language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class NavigationBar extends Component { render() { return ( <nav className={classes.NavBar}> <HorizontalNavigationBar /> <VerticalNavigationBar /> </nav> ); } }
JavaScript
class HomePage extends React.Component { constructor(props){ super(props); this.state = { user: { username: "", password: "", email: "", first_name: "", last_name: "", is_active: true, cellphone: "", position: "CLT" }, isAlertEmpty: false, isAlertSuccess: false, isBadinputs: false, credentials: cookie.get('notCredentials'), } } render() { const { t } = this.props return( <> <UVHeader/> <Container className="mt--7" fluid> <Card className="bg-secondary shadow"> <CardHeader className="bg-white border-0"> <center> <font size="5">Bienvenido</font> </center> </CardHeader> <center> <img alt="..." src={require("assets/img/theme/apple-icon.png")} /> </center> <CardBody> <center> <font size="5"> A su izquierda podra encontrar las funcionalidades del usuario ingresado </font> </center> </CardBody> </Card> </Container> </> ); } }
JavaScript
class Pool { constructor (func, ...args) { this.func = func this.args = args this.pool = [] } // 获取一个物体 getItem () { let Func = this.func let item = this.pool.pop() if (!item) item = new Func(this.args) return item } /** 回收 item * @param {(Object|Object[])} item item可以为数组 * @param {Boolean} isAll 默认只回收非enabled isAll 为 true 则强制回收全部 * @return {(Object|Object[])} 未被回收的项 */ recover (item, isAll) { if (item instanceof Array) { let res = [] for (let i = item.length - 1; i >= 0; i--) { let o = item[i] if (!o.enabled || isAll) { this.pool.push(o) } else res.push(o) } return res } else if (!item.enabled || isAll) { this.pool.push(item) return null } else return item } clear () { this.pool = [] } }
JavaScript
class FuroDataCollectionDropdown extends FuroSelectInput { constructor() { super(); this.error = false; this.disabled = false; this.displayField = 'display_name'; this.displaySubField = 'display_name'; this.valueField = 'id'; this.subField = 'data'; this.valueSubField = undefined; this.updateLock = false; /** * * @type {*[]} * @private */ this._dropdownList = []; /** * generated one element dropdown, which has only the data of the bounded DO * @type {*[]} * @private */ this._pseudoDropdownList = []; /** * injected dropdown elements which from a collection of response or in spec defined options * @type {*[]} * @private */ this._injectedDropdownList = []; /** * * @type {boolean} * @private */ this._valueFoundInList = true; this.addEventListener('value-changed', val => { if (this.binder.fieldNode) { // by valid input reset meta and constraints this._fieldNodeToUpdate._value = val.detail; if (this.subfield) { this._fieldDisplayNodeToUpdate._value = CollectionDropdownHelper.findDisplayNameByValue( this, val.detail, ); } } const selectedObj = this._dropdownList.find(obj => obj.id === this._fieldNodeToUpdate._value); CollectionDropdownHelper.notifiySelectedItem(this, selectedObj); }); this._initBinder(); /** * set option items by opening the dropdown if items are not set before */ this.addEventListener('focus', () => { // always use injected list by clicking the dropdown CollectionDropdownHelper.triggerSetOptionItem(this); }); } /** * inits the universalFieldNodeBinder. * Set the mapped attributes and labels. * @private */ _initBinder() { this.binder = new UniversalFieldNodeBinder(this); // set the attribute mappings this.binder.attributeMappings = { label: 'label', hint: 'hint', 'leading-icon': 'leadingIcon', 'trailing-icon': 'trailingIcon', errortext: 'errortext', }; // set the label mappings this.binder.labelMappings = { error: 'error', readonly: 'readonly', required: 'required', disabled: 'disabled', condensed: 'condensed', hidden: 'hidden', }; this.binder.fatAttributesToConstraintsMappings = { required: 'value._constraints.required.is', // for the fieldnode constraint 'min-msg': 'value._constraints.min.message', // for the fieldnode constraint message 'max-msg': 'value._constraints.max.message', // for the fieldnode constraint message }; this.binder.constraintsTofatAttributesMappings = { required: 'required', }; /** * check overrides from the used component, attributes set on the component itself overrides all */ this.binder.checkLabelandAttributeOverrrides(); // the extended furo-text-input component uses _value this.binder.targetValueField = '_value'; } /** * Updater for the list attr * @param value */ set list(value) { // map const arr = value.split(',').map(e => { const item = e.trim(); return { id: item, label: e, selected: this._fieldNodeToUpdate?._value === item, _original: item, }; }); this._notifyAndTriggerUpdate(arr); } /** * * @param arr * @private */ _notifyAndTriggerUpdate(arr) { if (arr.length > 0) { this._dropdownList = arr; // super.setOptions(arr); CollectionDropdownHelper.updateField(this); } } /** * Sets the field to readonly */ disable() { super.disable(); } /** * Makes the field writable. */ enable() { super.enable(); } static get properties() { return { /** * Overrides the label text from the **specs**. * * Use with caution, normally the specs defines this value. */ label: { type: String, reflect: true, }, /** * if you bind a complex type, declare here the field which gets updated of value by selecting an item. * * If you bind a scalar, you dont need this attribute. */ subfield: { type: String, }, /** * if you bind a complex type, declare here the field which gets updated of display_name by selecting an item. * * If you bind a scalar, you dont need this attribute. */ displaySubField: { type: String, attribute: 'display-sub-field', }, /** * The name of the field from the injected collection that contains the label for the dropdown array. */ displayField: { type: String, attribute: 'display-field', }, /** * The name of the field from the injected collection that contains the value you want to assign to the attribute value and the bounded field. */ valueField: { type: String, attribute: 'value-field', }, /** * The name of the field from the injected collection that contains the value you want to assign to the attribute value and the bounded field. */ valueSubField: { type: String, attribute: 'value-sub-field', }, autoSelectFirst: { type: Boolean, attribute: 'auto-select-first', }, /** * Overrides the hint text from the **specs**. * * Use with caution, normally the specs defines this value. */ hint: { type: String, reflect: true, }, readonly: { type: Boolean, reflect: true, }, /** * A Boolean attribute which, if present, means this field cannot be edited by the user. */ disabled: { type: Boolean, reflect: true, }, /** * Set this attribute to autofocus the input field. */ autofocus: { type: Boolean, reflect: true, }, /** * Icon on the left side */ leadingIcon: { type: String, attribute: 'leading-icon', reflect: true, }, /** * Icon on the right side */ trailingIcon: { type: String, attribute: 'trailing-icon', reflect: true, }, /** * html input validity */ valid: { type: Boolean, reflect: true, }, /** * The default style (md like) supports a condensed form. It is a little bit smaller then the default */ condensed: { type: Boolean, reflect: true, }, /** * Set a string list as options: * * "A, B, C" * * This will convert to options ["A","B","C"] by furo-select-input */ list: { type: String, reflect: true, }, /** * the dropdown list */ _dropdownList: { type: Array, }, /** * A Boolean attribute which, if present, means this field is not writeable for a while. */ _writeLock: { type: Boolean, }, }; } /** * Bind a entity field to the range-input. You can use the entity even when no data was received. * When you use `@-object-ready` from a `furo-data-object` which emits a EntityNode, just bind the field with `--entity(*.fields.fieldname)` * @param {Object|FieldNode} fieldNode a Field object */ bindData(fieldNode) { CollectionDropdownHelper.bindData(this, fieldNode); } /** * Sets the value for the field. This will update the fieldNode. * @param val */ setValue(val) { this.binder.fieldValue = val; } addItems(arr) { super.setOptions(arr); this.requestUpdate(); } /** * Build the dropdown list with given options from meta * @param {options} list of options with id and display_name * @private */ _buildListWithMetaOptions(options) { this._injectedDropdownList = CollectionDropdownHelper.mapDataToList(this, options.list); this._isMetaInjection = true; this._notifyAndTriggerUpdate(this._injectedDropdownList); } /** * Inject the array of a collection * @param entities */ injectEntities(entities) { CollectionDropdownHelper.injectList(this, entities); } }
JavaScript
class View6Free extends View { constructor(receiver) { super('view6-free', receiver); } linkElements() { showSplash(); setBackgroundColor('#CB563E1A', 'red'); this.arm = document.getElementById("view-6-character-arm"); this.body = document.getElementById('view-6-character-body'); this.body.src = window.colorPersoManager.getAsset().back; // Background elements this.dot1 = document.getElementById('view-6-free-red-ring'); this.dot2 = document.getElementById('view-6-free-green-dot'); this.dot6 = document.getElementById('view-6-free-white-ring'); this.dot4 = document.getElementById('view-6-free-green-tiny-dot'); // Parallax for background elements document.addEventListener('mousemove', (e) => { const x = e.clientX - window.innerWidth / 2; const y = e.clientY - window.innerHeight / 2; const angle = (e.clientX / window.innerWidth)*5; this.dot1.style.transform = `translateX(${x * -0.1}px) translateY(${y * -0.05}px)`; this.dot2.style.transform = `translateX(${x * -0.07}px) translateY(${y * 0.05}px)`; this.dot6.style.transform = `translateX(${x * -0.05}px) translateY(${y * -0.07}px)`; this.dot4.style.transform = `translateX(${x * 0.05}px) translateY(${y * 0.05}px)`; this.arm.style.transform = `translateX(-100%) rotate(${angle}deg)`; }); this.btNext = setOverlayButton('Voir l\'hôtel du Centre', false, 'sound/hover/voir_hotel_centre.mp3'); this.btNext.addEventListener('click', ()=>{ this.switchToViewPremium(); }); } async switchToViewPremium(){ transitionHorizontalInvert(this.view, View6Premium); } play() { window.soundManager.play('sound/Choix_1_liens_externes.mp3'); } }
JavaScript
class base_model { constructor(table) { this.table = table; }; get_all() { return db(this.table); }; async insert(data) { try { let [id] = await db(this.table).insert(data); return await this.find_by({id}) } catch (e) { console.log(e) return e } } async find_by(data) { try { return await db(this.table).select('*').where(data).first() } catch (e) { console.log(e); return e } }; async update(id, data) { try { await db(this.table).update(data).where({id: id}) return this.find_by({id}) } catch (e) { console.log(e.message) return e } }; }
JavaScript
class ApplicationError extends Error { constructor({ message, statusCode }) { super(message); this.name = 'ApplicationError'; this.statusCode = statusCode; Error.captureStackTrace(this, this.constructor); } }
JavaScript
class Directory extends Component { state = { result: [], filteredResult: [], search: "", // started: false }; // getStarted = () => { // this.setState({ started: true }); // started = true; // }; componentDidMount() { this.randomPerson(); // this.getStarted(); } randomPerson = () => { fetch("https://randomuser.me/api/?results=25") .then(res => res.json()) .then(response => { console.log("response", response); this.setState({ result: response.results }); }); }; globalSearch = () => { let { search, result } = this.state; console.log("search", search); console.log("before result", result); let filteredResult = result.filter(value => { return ( value.name.first.toLowerCase().includes(search.toLowerCase()) || value.name.last.toLowerCase().includes(search.toLowerCase()) || value.email.toLowerCase().includes(search.toLowerCase()) ); }); this.setState({ filteredResult }); console.log("filtered result", filteredResult); }; handleChange = event => { this.setState({ search: event.target.value }, () => { this.globalSearch(); filtered = true; }); }; formatBD = str => { const newDate = moment(str).format("LL"); // console.log("newDate", newDate); return newDate; }; render() { // ternary // console.log("started", this.state.started); return ( <div className="container"> {/* {!this.state.started ? ( <div className="jumbotron text-center"> <h1 className="display-4">Employee Directory</h1> <p className="lead"> Welcome to your Employee Directory! To find someone specific,{" "} <br /> simply type in the search bar to narrow the list down. </p> <hr className="my-4" /> <button type="button" className="btn btn-info" onChange={this.getStarted()} > Get Started! </button> </div> ) : ( */} <Container> <div className="jumbotron text-center"> <h1 className="display-4">Employee Directory</h1> <p className="lead"> Welcome to your Employee Directory! To find someone specific, simply start{" "} <br /> typing their name or email in the search bar to narrow the list down. </p> <hr className="my-4" /> <SearchBar name="search" value={this.state.search || ""} onChange={this.handleChange} label="Search" /> </div> <table className="table"> <thead> <tr> <th scope="col">Photo</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone #</th> <th scope="col">Birthdate</th> </tr> </thead> <tbody> {!filtered ? this.state.result.map(person => ( <TRow key={person.login.uuid} firstName={person.name.first} lastName={person.name.last} src={person.picture.thumbnail} email={person.email} phone={person.cell} birthdate={this.formatBD(person.dob.date)} /> )) : this.state.filteredResult.map(person => ( <TRow key={person.login.uuid} firstName={person.name.first} lastName={person.name.last} src={person.picture.thumbnail} email={person.email} phone={person.cell} birthdate={this.formatBD(person.dob.date)} /> ))} </tbody> </table> </Container> {/* )} */} </div> ); } }
JavaScript
class Creature { constructor( name, gender, species, say, legs=4 ) { this.species = species; this.name = name; this.gender = gender; this.legs = legs; this.say = say; this.friends = []; } addFriends(...args){ this.friends = [...args]; } toString() { return [ 'name', 'gender', 'species', 'say', 'legs' ] .map(key => `${key}: <strong>${this[key]}</strong>`) .concat(this.friends.map(friend => `<strong>${friend['name']}</strong>`)) .join('; '); } }
JavaScript
class MatrixDescriptionRow extends React.Component { render() { if (this.props.data[0] == 'noValue') { return } return <div className="Matrix_row Matrix_description_row"> {(() => { if (that.state.matrixYAxisDomain != 'deactivated') { return ( <MatrixDescriptionCell data={""} quantityList={this.props.quantityListX}/> ) } })()} {this.props.data.map((cell) => ( <MatrixDescriptionCell key={cell} data={cell} quantityList={this.props.quantityListX}/> ))} </div>; } }
JavaScript
class NotificationBar extends React.Component{ constructor(){ super(); this.state = { notifications : [], faded: false, hidden: true } this.closeHandler = this.closeHandler.bind(this) this.itemRemoveHandler = this.itemRemoveHandler.bind(this) this.hide = this.hide.bind(this) this.show = this.show.bind(this) } componentDidMount(){ this.timeout = setTimeout(this.show,10) } addNotification(notification){ if(notification.title && typeof notification.title == "string" && notification.body && typeof notification.body == "string"){ this.state.notifications.push(notification) } this.setState({ notifications: this.state.notifications }) } removeNotification(index){ this.state.notifications.splice(index,1) this.setState({ notifications: this.state.notifications }) if(this.state.notifications.length <= 0){ var hide = this.hide setTimeout(function(){ hide() },300) } } size(){ return this.state.notifications.length } componentClasses(){ var classes = ["NotificationBar"] if(this.state.faded){ classes.push("faded") } if(this.state.hidden){ classes.push("hidden") } return classes.join(" ") } hide(){ var thisComponent = this clearTimeout(this.timeout) this.setState({ faded:true }) this.timeout = setTimeout(()=>{ thisComponent.setState({ hidden:true }) },300) } show(){ var thisComponent = this clearTimeout(this.timeout) this.setState({ hidden:false }) this.timeout = setTimeout(()=>{ thisComponent.setState({ faded:false }) },10) } closeHandler(){ this.hide() } openHandler(){ this.show() } itemRemoveHandler(id){ this.removeNotification(id) } render(){ return React.createElement('div',{className:this.componentClasses()},( [ React.createElement('div',{key:'close-container',className:"text-right"},React.createElement(NotificationClose, {key:"close-button", closeHandler:this.closeHandler})), React.createElement(NotificationList, {key:"list", itemRemoveHandler:this.itemRemoveHandler, notifications: this.state.notifications}) ] )) } }
JavaScript
class TransactionStateError extends Exception { constructor(message) { super(message ? message : "Transaction state error."); } }
JavaScript
class Ship { constructor(type, pos, id = 999) { this.type = type; this.pos = pos; this.touchedPos = pos + 11; this.dmodel = ShipTypes[type].model; this.cmodel = this.dmodel; this.id = id; this.hp = ShipTypes.hp; this.rotation = 1; // this.prev = { rotation: 1, pos: pos + 11 }; } setRotation(r) { this.rotation = r; this.cmodel = rotateGrid(this.dmodel, this.rotation); } rotateBy(r) { this.rotation = (this.rotation + r) % 5; if (this.rotation <= 0) { this.rotation = 4; } this.cmodel = rotateGrid(this.dmodel, this.rotation); } setPos(pos, arr) { // this.prev.pos = this["pos"]; this.pos = pos; if (arr !== undefined) { return placeShip(arr, 10, this); } } }
JavaScript
class AsgardeoAuthClient { /** * This is the constructor method that returns an instance of the . * * @param {Store} store - The store object. * * @example * ``` * const _store: Store = new DataStore(); * const auth = new AsgardeoAuthClient<CustomClientConfig>(_store); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#constructor * @preserve */ constructor(store) { if (!AsgardeoAuthClient._instanceID) { AsgardeoAuthClient._instanceID = 0; } else { AsgardeoAuthClient._instanceID += 1; } this._dataLayer = new DataLayer(`instance_${AsgardeoAuthClient._instanceID}`, store); this._authenticationCore = new AuthenticationCore(this._dataLayer); } /** * * This method initializes the SDK with the config data. * * @param {AuthClientConfig<T>} config - The config object to initialize with. * * @example * const config = { * signInRedirectURL: "http://localhost:3000/sign-in", * clientID: "client ID", * serverOrigin: "https://localhost:9443" * } * * await auth.initialize(config); * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#initialize * * @preserve */ initialize(config) { return __awaiter(this, void 0, void 0, function* () { yield this._dataLayer.setConfigData(Object.assign(Object.assign({}, DefaultConfig), config)); }); } /** * This method returns the `DataLayer` object that allows you to access authentication data. * * @return {DataLayer} - The `DataLayer` object. * * @example * ``` * const data = auth.getDataLayer(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDataLayer * * @memberof AsgardeoAuthClient * * @preserve */ getDataLayer() { return this._dataLayer; } /** * This is an async method that returns a Promise that resolves with the authorization URL. * * @param {GetAuthURLConfig} config - (Optional) A config object to force initialization and pass * custom path parameters such as the fidp parameter. * * @return {Promise<string>} - A promise that resolves with the authorization URL. * * @example * ``` * auth.getAuthorizationURL().then((url)=>{ * // console.log(url); * }).catch((error)=>{ * // console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getAuthorizationURL * * @memberof AsgardeoAuthClient * * @preserve */ getAuthorizationURL(config) { return __awaiter(this, void 0, void 0, function* () { const authRequestConfig = Object.assign({}, config); authRequestConfig === null || authRequestConfig === void 0 ? true : delete authRequestConfig.forceInit; if (yield this._dataLayer.getTemporaryDataParameter(OP_CONFIG_INITIATED)) { return this._authenticationCore.getAuthorizationURL(authRequestConfig); } return this._authenticationCore.getOIDCProviderMetaData(config === null || config === void 0 ? void 0 : config.forceInit).then(() => { return this._authenticationCore.getAuthorizationURL(authRequestConfig); }); }); } /** * This is an async method that sends a request to obtain the access token and returns a Promise * that resolves with the token and other relevant data. * * @param {string} authorizationCode - The authorization code. * @param {string} sessionState - The session state. * * @return {Promise<TokenResponse>} - A Promise that resolves with the token response. * * @example * ``` * auth.requestAccessToken(authCode, sessionState).then((token)=>{ * // console.log(token); * }).catch((error)=>{ * // console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#requestAccessToken * * @memberof AsgardeoAuthClient * * @preserve */ requestAccessToken(authorizationCode, sessionState) { return __awaiter(this, void 0, void 0, function* () { if (yield this._dataLayer.getTemporaryDataParameter(OP_CONFIG_INITIATED)) { return this._authenticationCore.requestAccessToken(authorizationCode, sessionState); } return this._authenticationCore.getOIDCProviderMetaData(false).then(() => { return this._authenticationCore.requestAccessToken(authorizationCode, sessionState); }); }); } /** * This method clears all authentication data and returns the sign-out URL. * * @return {Promise<string>} - A Promise that resolves with the sign-out URL. * * @example * ``` * const signOutUrl = await auth.signOut(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#signOut * * @memberof AsgardeoAuthClient * * @preserve */ signOut() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.signOut(); }); } /** * This method returns the sign-out URL. * * **This doesn't clear the authentication data.** * * @return {Promise<string>} - A Promise that resolves with the sign-out URL. * * @example * ``` * const signOutUrl = await auth.getSignOutURL(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getSignOutURL * * @memberof AsgardeoAuthClient * * @preserve */ getSignOutURL() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getSignOutURL(); }); } /** * This method returns OIDC service endpoints that are fetched from the `.well-known` endpoint. * * @return {Promise<OIDCEndpoints>} - A Promise that resolves with an object containing the OIDC service endpoints. * * @example * ``` * const endpoints = await auth.getOIDCServiceEndpoints(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getOIDCServiceEndpoints * * @memberof AsgardeoAuthClient * * @preserve */ getOIDCServiceEndpoints() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getOIDCServiceEndpoints(); }); } /** * This method decodes the payload of the ID token and returns it. * * @return {Promise<DecodedIDTokenPayload>} - A Promise that resolves with the decoded ID token payload. * * @example * ``` * const decodedIdToken = await auth.getDecodedIDToken(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDecodedIDToken * * @memberof AsgardeoAuthClient * * @preserve */ getDecodedIDToken() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getDecodedIDToken(); }); } /** * This method returns the ID token. * * @return {Promise<string>} - A Promise that resolves with the ID token. * * @example * ``` * const idToken = await auth.getIDToken(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIDToken * * @memberof AsgardeoAuthClient * * @preserve */ getIDToken() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getIDToken(); }); } /** * This method returns the basic user information obtained from the ID token. * * @return {Promise<BasicUserInfo>} - A Promise that resolves with an object containing the basic user information. * * @example * ``` * const userInfo = await auth.getBasicUserInfo(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getBasicUserInfo * * @memberof AsgardeoAuthClient * * @preserve */ getBasicUserInfo() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getBasicUserInfo(); }); } /** * This method revokes the access token. * * **This method also clears the authentication data.** * * @return {Promise<AxiosResponse>} - A Promise that returns the response of the revoke-access-token request. * * @example * ``` * auth.revokeAccessToken().then((response)=>{ * // console.log(response); * }).catch((error)=>{ * // console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#revokeAccessToken * * @memberof AsgardeoAuthClient * * @preserve */ revokeAccessToken() { return this._authenticationCore.revokeAccessToken(); } /** * This method refreshes the access token and returns a Promise that resolves with the new access * token and other relevant data. * * @return {Promise<TokenResponse>} - A Promise that resolves with the token response. * * @example * ``` * auth.refreshAccessToken().then((response)=>{ * // console.log(response); * }).catch((error)=>{ * // console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#refreshAccessToken * * @memberof AsgardeoAuthClient * * @preserve */ refreshAccessToken() { return this._authenticationCore.refreshAccessToken(); } /** * This method returns the access token. * * @return {Promise<string>} - A Promise that resolves with the access token. * * @example * ``` * const accessToken = await auth.getAccessToken(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getAccessToken * * @memberof AsgardeoAuthClient * * @preserve */ getAccessToken() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getAccessToken(); }); } /** * This method sends a custom-grant request and returns a Promise that resolves with the response * depending on the config passed. * * @param {CustomGrantConfig} config - A config object containing the custom grant configurations. * * @return {Promise<TokenResponse | AxiosResponse>} - A Promise that resolves with the response depending * on your configurations. * * @example * ``` * const config = { * attachToken: false, * data: { * client_id: "{{clientID}}", * grant_type: "account_switch", * scope: "{{scope}}", * token: "{{token}}", * }, * id: "account-switch", * returnResponse: true, * returnsSession: true, * signInRequired: true * } * * auth.requestCustomGrant(config).then((response)=>{ * // console.log(response); * }).catch((error)=>{ * // console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#requestCustomGrant * * @memberof AsgardeoAuthClient * * @preserve */ requestCustomGrant(config) { return this._authenticationCore.requestCustomGrant(config); } /** * This method returns if the user is authenticated or not. * * @return {Promise<boolean>} - A Promise that resolves with `true` if the user is authenticated, `false` otherwise. * * @example * ``` * await auth.isAuthenticated(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isAuthenticated * * @memberof AsgardeoAuthClient * * @preserve */ isAuthenticated() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.isAuthenticated(); }); } /** * This method returns the PKCE code generated during the generation of the authentication URL. * * @return {Promise<string>} - A Promise that resolves with the PKCE code. * * @example * ``` * const pkce = await getPKCECode(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getPKCECode * * @memberof AsgardeoAuthClient * * @preserve */ getPKCECode() { return __awaiter(this, void 0, void 0, function* () { return this._authenticationCore.getPKCECode(); }); } /** * This method sets the PKCE code to the data store. * * @param {string} pkce - The PKCE code. * * @example * ``` * await auth.setPKCECode("pkce_code") * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#setPKCECode * * @memberof AsgardeoAuthClient * * @preserve */ setPKCECode(pkce) { return __awaiter(this, void 0, void 0, function* () { yield this._authenticationCore.setPKCECode(pkce); }); } /** * This method returns if the sign-out is successful or not. * * @param {string} signOutRedirectUrl - The URL to which the user has been redirected to after signing-out. * * **The server appends path parameters to the `signOutRedirectURL` and these path parameters * are required for this method to function.** * * @return {boolean} - `true` if successful, `false` otherwise. * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isSignOutSuccessful * * @memberof AsgardeoAuthClient * * @preserve */ static isSignOutSuccessful(signOutRedirectURL) { const url = new URL(signOutRedirectURL); const stateParam = url.searchParams.get("state"); const error = Boolean(url.searchParams.get("error")); return stateParam ? stateParam === SIGN_OUT_SUCCESS_PARAM && !error : false; } /** * This method updates the configuration that was passed into the constructor when instantiating this class. * * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with. * * @example * ``` * const config = { * signInRedirectURL: "http://localhost:3000/sign-in", * clientID: "client ID", * serverOrigin: "https://localhost:9443" * } * * await auth.updateConfig(config); * ``` * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#updateConfig * * @memberof AsgardeoAuthClient * * @preserve */ updateConfig(config) { this._authenticationCore.updateConfig(config); } }
JavaScript
class BlockChain { constructor() { this.bd = new LevelSandbox.LevelSandbox() this.generateGenesisBlock() .then(function(result) { console.log(result) }) .catch(function(err) { console.log(err) }) } // Promise => String // Create Genesis Block (always with height = 0) generateGenesisBlock() { let self = this // Return promise return new Promise(function(resolve, reject) { // Get chain height self.getBlockHeight() .then(function(height) { // If blocks not exist, create Genesis Block if (height == 0) { // Create Genesis Block return self.addBlock(new Block.Block('Genesis Block')) } else { resolve('Genesis Block already exists.') } }) .then(function(block) { resolve('Genesis Block Created.') }) .catch(function(err) { reject(err) }) }) } // Promise => Number // Get the height of the blockchain getBlockHeight() { let self = this // Return promise return new Promise(function(resolve, reject) { self.bd.getBlocksCount() .then(function(result) { resolve(result) }) .catch(function(err) { reject(err) }) }) } // Promise => Block Object // Add new block to the chain // Return block object addBlock(newBlock) { let self = this // Return promise return new Promise(function(resolve, reject) { // Get chain height self.getBlockHeight() .then(function(height) { // Configure new block height newBlock.height = height // Configure new block UTC timestamp newBlock.time = new Date().getTime().toString().slice(0,-3) // Get previous block return self.bd.getLevelDBData(height - 1) }) .then(function(block) { if (block) { // Configure new block's previous block hash newBlock.previousBlockHash = block.hash } else { // Configure new block's previous block hash newBlock.previousBlockHash = '' } // Block hash with SHA256 using newBlock and converting to a string newBlock.hash = SHA256(JSON.stringify(newBlock)).toString() // Add block to level db return self.bd.addLevelDBData(newBlock.height, JSON.stringify(newBlock)) }) .then(function(value) { resolve(newBlock) }) .catch(function(err) { reject(err) }) }) } // Promise => Block Object // Get Block By Height // Return block object or null getBlock(height) { let self = this // Return promise return new Promise(function(resolve, reject) { // Get block self.bd.getLevelDBData(height) .then(function(result) { resolve(result) }) .catch(function(err) { reject(err) }) }) } // Promise => Block Object // Get Block by hash // Return block object or null getBlockByHash(hash) { let self = this // Return promise return new Promise(function(resolve, reject) { // Get block self.bd.getLevelDBDataByHash(hash) .then(function(result) { resolve(result) }) .catch(function(err) { reject(err) }) }) } // Promise => [Block Object] // Get Block by wallet address // Return blocks array generated from this wallet address or [] getBlockByWalletAddress(address) { let self = this // Return promise return new Promise(function(resolve, reject) { // search for blocks self.bd.getLevelDBDataByAddress(address) .then(function(result) { resolve(result) }) .catch(function(err) { reject(err) }) }) } // Promise => Bool // Validates block // Return true if block is valid validateBlock(height) { let self = this // Return promise return new Promise(function(resolve, reject) { // Get block self.getBlock(height) .then(function(result) { // Block to be validated let block = result // Block hash let blockHash = block.hash // Remove hash block.hash = '' // Generate new hash let validHash = SHA256(JSON.stringify(block)).toString() // Validate if (blockHash === validHash) { resolve(true) } else { resolve(false) } }) .catch(function(err) { reject(err) }) }) } // Promise => [] // Validate Blockchain validateChain() { let self = this // Return promise return new Promise(function(resolve, reject) { // Array to log the errors let errorLog = [] // Get chain length self.getBlockHeight() .then(function(height) { let promiseArray = [] // Validate each individual block for (var i = 0; i < height; i++) { promiseArray.push(self.validateBlock(i)) } return Promise.all(promiseArray) }) .then(function(result) { // Log errors from block validation for (var i = 0; i < result.length; i++) { if (result[i] == false) { errorLog.push(`Block ${i} is not valid.`) } } // Validate links between blocks let promiseArray = [] for (var i = 0; i < result.length - 1; i++) { promiseArray.push(self.validateLink(i)) } return Promise.all(promiseArray) }) .then(function(result) { // Log errors from block links for (var i = 0; i < result.length; i++) { if (result[i] == false) { errorLog.push(`Link between blocks ${i} and ${i + 1} is not valid.`) } } // Resolve with error logs resolve(errorLog) }) .catch(function(err) { reject(err) }) }) } // Promise => Bool // Validates link between block at height and next block // Returns true if link is valid validateLink(height) { let self = this // Return promise return new Promise(function(resolve, reject) { let blockHash = '' // Get block self.getBlock(height) .then(function(block) { blockHash = block.hash // Get next block return self.getBlock(height + 1) }) .then(function(nextBlock) { // Compare hashes if (nextBlock.previousBlockHash !== blockHash) { resolve(false) } else { resolve(true) } }) .catch(function(err) { reject(err) }) }) } // Promise => Block Object // Utility method to tamper a block // This method is for testing purposes only _modifyBlock(height, block) { let self = this // Return promise return new Promise( (resolve, reject) => { self.bd.addLevelDBData(height, JSON.stringify(block).toString()) .then((blockModified) => { resolve(blockModified) }) .catch((err) => { reject(err) }) }) } }
JavaScript
class Marketplace extends Component { constructor(){ super(); this.state={ display: '' } this.handleClick = this.handleClick.bind(this); } handleClick(evt){ this.setState({display: evt.target.value}) } render() { return ( <div> <span> <button type="button" className="btn btn-success market-button" value="Grow" onClick={this.handleClick}>Grow</button> <button type="button" className="btn btn-success market-button" value="Labor" onClick={this.handleClick}>Labor</button> <button type="button" className="btn btn-success market-button" value="Exchange" onClick={this.handleClick}>Exchange</button> </span> {this.state.display === "Grow" ? (<div> <GrowTable user={this.props.user} sendMoney={this.props.sendMoney} address={this.props.address} /> <AddGrow /> </div>) : null} {this.state.display === "Labor" ? (<div>labor</div>) : null} {this.state.display === "Exchange" ? (<div>exchange</div>) : null} <button className="btn btn-success market-button" onClick={this.props.mintMoney}>Mint Money</button> </div> ) } }
JavaScript
class App extends Component { /** * The constructor. * * @param {object} props Object props. */ constructor( props ) { super( props ); // Initiate states. this.state = { tasks: MTStore.getAll(), }; // Events handler. this.onTasksUpdated = this.onTasksUpdated.bind( this ); } componentDidMount() { MTStore.addChangeListener( SUBMIT_TASK, this.onTasksUpdated ); MTStore.addChangeListener( COMPLETE_TASK, this.onTasksUpdated ); MTStore.addChangeListener( UPDATE_TASK, this.onTasksUpdated ); MTStore.addChangeListener( REMOVE_TASK, this.onTasksUpdated ); } componentWillUnmount() { MTStore.removeChangeListener( SUBMIT_TASK, this.onTasksUpdated ); MTStore.removeChangeListener( COMPLETE_TASK, this.onTasksUpdated ); MTStore.removeChangeListener( UPDATE_TASK, this.onTasksUpdated ); MTStore.removeChangeListener( REMOVE_TASK, this.onTasksUpdated ); } /** * Submit new task to the tasks list. * * @param {string} title New task title. */ onTasksUpdated() { // Add new task to the list (appending not mutating). this.setState({ tasks: MTStore.getAll(), }); } /** * Render TodoList to display tasks list. * * @return {string} TodoList HTML tags. */ render() { const tasks = this.state.tasks; return ( <div className="mt-container"> <MTAddTodo /> <MTTodoList tasks={tasks} completeTask={this.onTaskCompleted} updateTask={this.onTaskUpdated} removeTask={this.onTaskRemoved} /> </div> ); } }
JavaScript
class Pool extends EventEmitter { constructor(options) { super(); assert.equal(typeof options, 'object', 'options must be an object'); assert.equal(typeof options.acquire, 'function', 'options.acquire must be a function'); assert.equal(typeof options.dispose, 'function', 'options.dispose must be a function'); assertUnknownOptionsKeys(options, [ 'acquire', 'dispose', 'min', 'max', 'maxWaitingClients', 'acquireTimeoutMs', 'releaseTimeoutMs', 'fifo', ]); this._factory = { acquire: options.acquire.length === 1 ? options.acquire : asyncify(options.acquire), dispose: options.dispose.length === 2 ? options.dispose : asyncify(options.dispose), }; options = options || {}; this._options = { min: options.min || 0, max: options.max || 1, maxWaitingClients: options.maxWaitingClients || 10, fifo: options.fifo || false, acquireTimeoutMs: options.acquireTimeoutMs || 10000, releaseTimeoutMs: options.releaseTimeoutMs || 5000, }; this._rSet = new Set(); this._rDestroyed = new Map(); this._rBorrowed = new Map(); this._rAvailable = []; this._rReleased = []; this._ending = false; this._ended = false; this._queue = asyncQueue( (handler, next) => { this._getResource((err, resource) => { if (err) { handler(err); next(); } else { this._rBorrowed.set(resource, (cb) => { this._releaseResource(resource, (e) => { cb(e); next(); }); }); handler(null, resource); } }); }, this._options.max, ); this._queue.saturated = () => this.emit('saturated'); this._queue.unsaturated = () => this.emit('unsaturated'); this._queue.empty = () => this.emit('empty'); this._queue.drain = () => this.emit('drain'); this._queue.error = err => this.emit('error', err); this._acquire = timeout(this._acquire.bind(this), this._options.acquireTimeoutMs, 'Acquire timed out'); this._release = timeout(this._release.bind(this), this._options.releaseTimeoutMs, 'Release timed out'); } /** * @return {number} * Returns number of resources in the pool regardless of whether they are free or in use */ get size() { return this._rSet.size; } /** * @return {Number} * Returns number of unused resources in the pool */ get available() { return this._rAvailable.length; } /** * @return {number} * Returns number of resources that are currently acquired by userland code */ get borrowed() { return this._rBorrowed.size; } get stats() { return { size: this.size, available: this.available, borrowed: this.borrowed, }; } /** * Acquire a resource from the pool. * Calls to acquire after calling end will be rejected with the error "Pool is ending" * or "Pool is destroyed" once shutdown has completed. * * @param {function(err, resource:*)} [cb] * @returns {undefined|Promise} * Returns a promise if callback isn't provided. */ acquire(cb) { if (typeof cb !== 'function') { return this.acquireAsync(); } if (this._ending) { return cb(new Error('Pool is ending')); } if (this._ended) { return cb(new Error('Pool is destroyed')); } if (this._queue.length() >= this._options.maxWaitingClients) { return cb(new Error(`Max waiting clients count exceeded [${this._options.maxWaitingClients}]`)); } this._acquire(cb); } _acquire(cb) { this._queue.push(cb); } /** * Return a resource to the pool. * * @param {*} resource * @param {function(err)} [cb] * @returns {undefined|Promise} * Returns a promise if callback isn't provided. */ release(resource, cb) { if (typeof cb !== 'function') { return this.releaseAsync(resource); } this._release(resource, cb); } _release(resource, cb) { const releaseCb = this._rBorrowed.get(resource); if (releaseCb) { releaseCb(cb); } else { return cb(new Error(`Trying to release not acquired resource: ${inspect(resource)}`)); } } /** * Remove a resource from the pool gracefully. * * @param {*} resource * @param {function(err)} [cb] * @returns {undefined|Promise} * Returns a promise if callback isn't provided. */ destroy(resource, cb) { if (typeof cb !== 'function') { return this.destroyAsync(resource); } if (this._rSet.has(resource)) { this._rDestroyed.set(resource, (c) => { this._factory.dispose(resource, (err) => { this._deleteResource(resource); c(err); }); }); if (this._rBorrowed.has(resource)) { this.release(resource, cb); } else { const indexOfResource = this._rAvailable.indexOf(resource); this._rAvailable.splice(indexOfResource, 1); this._rDestroyed.get(resource)(cb); } } else { return cb(); } } /** * Attempt to gracefully close the pool. * * @param {boolean} force * @param {function(err)} cb * @returns {undefined|Promise} * Returns a promise if callback isn't provided. */ end(force, cb) { if (typeof force === 'function') { cb = force; } if (typeof cb !== 'function') { return this.endAsync(force); } this._ending = true; const onEnd = (err) => { this._ended = true; this._ending = false; cb(err); }; if (force && force !== cb) { asyncEach(Array.from(this._rSet.values()), (resource, c) => { this.destroy(resource, c); }, onEnd); } else { this._rAvailable.slice(0).forEach((resource) => { this.destroy(resource, noop); }); if (this._queue.idle()) { onEnd(); } else { this.once('drain', onEnd); } } } _releaseResource(resource, cb) { this._rBorrowed.delete(resource); const destroyCb = this._rDestroyed.get(resource); if (destroyCb) { destroyCb(cb); } else if (this._ending) { this.destroy(resource, cb); } else if (this._options.fifo) { this._rAvailable.unshift(resource); cb(); } else { this._rAvailable.push(resource); cb(); } } _deleteResource(resource) { this._rSet.delete(resource); this._rDestroyed.delete(resource); this._rBorrowed.delete(resource); } _getResource(cb) { if (this._rAvailable.length) { cb(null, this._rAvailable.pop()); } else { this._factory.acquire((err, resource) => { if (err) { cb(err); } else { this._rSet.add(resource); cb(null, resource); } }); } } }
JavaScript
class SqrtNode { constructor () { this.data = []; } }
JavaScript
class Url { constructor() { this.uri = new Uri(); this.string = this.uri.__toString(); } getString() { return this.string; } base(segments, query) { let uri = this.uri; if(typeof segments === 'undefined') { return this.string; } if(Array.isArray(segments)) { uri = this.uri.setSegments(segments); } else { uri = this.uri.setSegments(segments.split('/')); } if(query instanceof Object) { uri = uri.setQuery(query); } return uri.__toString(); } current(query) { if (query instanceof Object) { this.uri.withQuery(query); } return this.uri.__toString(); } redirect(segments, query) { let href = this.base(segments, query); window.location.href = href; } }
JavaScript
class ObjectAttributes extends EventEmitter { objects = {}; //getting all namespaces of src objects and arrays getKeysOfAllObjectsAndArrays = (obj, prefix = '') => { return Object.keys(obj).reduce((acc, el) => { if (Array.isArray(obj[el])) { const resKey = this.getKeysOfAllObjectsAndArrays( { ...obj[el] }, prefix + el + '.]' ); return [...acc, prefix + el, ...resKey]; } else if (typeof obj[el] === 'object' && obj[el] !== null) { const resKey = this.getKeysOfAllObjectsAndArrays( obj[el], prefix + el + '.]' ); return [...acc, prefix + el, ...resKey]; } return [...acc]; }, []); }; //toggling collapse of all src objects and arrays (collapse/expand all) toggleCollapseForAllObjectsAndArrays = ({ rjvId, collapsedState, value }) => { let expandedNamespaces = this.getKeysOfAllObjectsAndArrays(value, ''); expandedNamespaces = expandedNamespaces.map(namespace => { namespace = namespace.split('.]'); namespace = namespace.map(key => { if (parseInt(key) || key === '0') { return +key; } return key; }); return [false, ...namespace]; }); //To collapse -> expanded has to be false and vice versa //collapsedState toggles between 1 and false. If false then expanded has to be true. //If 1 then expanded has to be false. collapsedState = collapsedState !== 1; expandedNamespaces.forEach(key => { this.set(rjvId, key, 'expanded', collapsedState); this.emit('expanded-' + key.join(',')); }); }; set = (rjvId, name, key, value) => { if (this.objects[rjvId] === undefined) { this.objects[rjvId] = {}; } if (this.objects[rjvId][name] === undefined) { this.objects[rjvId][name] = {}; } this.objects[rjvId][name][key] = value; }; get = (rjvId, name, key, default_value) => { if ( this.objects[rjvId] === undefined || this.objects[rjvId][name] === undefined || this.objects[rjvId][name][key] === undefined ) { return default_value; } return this.objects[rjvId][name][key]; }; getSrcByNamespace = ({ rjvId, name, namespace, parent_type }) => { if ( this.objects[rjvId] === undefined || this.objects[rjvId][name] === undefined ) { return null; } namespace.shift(); //deep copy of src variable let updated_src = this.deepCopy(this.objects[rjvId].global.src, [ ...namespace ]); //point at current index let walk = updated_src; for (const idx of namespace) { walk = walk[idx]; } //return as array if parent is array (for slicing) return parent_type === 'object' ? { ...walk } : [...walk]; }; handleAction = action => { const { rjvId, data, name } = action; switch (name) { case 'RESET': this.emit('reset-' + rjvId); break; case 'VARIABLE_UPDATED': action.data.updated_src = this.updateSrc(rjvId, data); this.set(rjvId, 'action', 'variable-update', { ...data, type: 'variable-edited' }); this.emit('variable-update-' + rjvId); break; case 'VARIABLE_REMOVED': action.data.updated_src = this.updateSrc(rjvId, data); this.set(rjvId, 'action', 'variable-update', { ...data, type: 'variable-removed' }); this.emit('variable-update-' + rjvId); break; case 'VARIABLE_ADDED': action.data.updated_src = this.updateSrc(rjvId, data); this.set(rjvId, 'action', 'variable-update', { ...data, type: 'variable-added' }); this.emit('variable-update-' + rjvId); break; case 'VARIABLE_COPIED': this.emit('copied-' + rjvId); break; case 'ADD_VARIABLE_KEY_REQUEST': this.set(rjvId, 'action', 'new-key-request', data); this.emit('add-key-request-' + rjvId); break; case 'UPDATE_VARIABLE_KEY_REQUEST': this.set(rjvId, 'action', 'edit-key-request', data); this.emit('edit-key-request-' + rjvId); break; case 'VARIABLE_KEY_UPDATED': action.data.updated_src = this.updateSrc(rjvId, data); this.set(rjvId, 'action', 'variable-update', { ...data, type: 'variable-key-added' }); this.emit('variable-update-' + rjvId); break; case 'PASTE_ADD_KEY_REQUEST': this.set(rjvId, 'action', 'paste-add-key-request', data); this.emit('paste-add-key-request-' + rjvId); break; case 'VALIDATION-FAILURE': this.emit('validation-failure-' + rjvId); break; } }; updateSrc = (rjvId, request) => { let { name, namespace, new_value, variable_removed } = request; namespace.shift(); //deepy copy src let src = this.get(rjvId, 'global', 'src'); //deep copy of src variable let updated_src = this.deepCopy(src, [...namespace]); //point at current index let walk = updated_src; for (const idx of namespace) { walk = walk[idx]; } if (variable_removed) { if (toType(walk) === 'array') { walk.splice(name, 1); } else { delete walk[name]; } } else { //update copied variable at specified namespace if (name !== null && name) { walk[name] = new_value; } else { updated_src = new_value; } } this.set(rjvId, 'global', 'src', updated_src); return updated_src; }; deepCopy = (src, copy_namespace) => { const type = toType(src); let result; let idx = copy_namespace.shift(); if (type === 'array') { result = [...src]; } else if (type === 'object') { result = { ...src }; } if (idx !== undefined) { result[idx] = this.deepCopy(src[idx], copy_namespace); } return result; }; }
JavaScript
class Points { /** * Whether the Points Class has been Initialized * * @private * @type {boolean} */ static _initialized = false; /** * An EventEmitter Instance * * @private * @type {EventEmitter} */ static _emitter = undefined; /** * An Array of Subscriptions * * @private * @type {Object<number, {initializing: boolean, completed: boolean, pointIds: number[]}>} */ static _subscriptions = undefined; /** * An Array of PointModel Definitions * * @private * @type {Object<number, Object<number, PointModel>>} */ static _definitions = undefined; /** * An Array of Point Values * * @private * @type {Object<number, Object<number, Points.PointValueItem>>} */ static _values = undefined; /** * Initialize * * @static * @public * @package */ static initialize() { if(isDefined(Points._initialized) != true || Points._initialized != true) { if(isDefined(Points._emitter) != true) { Points._emitter = new EventEmitter(); } if(isDefined(Points._subscriptions) != true) { Points._subscriptions = {}; } if(isDefined(Points._definitions) != true) { Points._definitions = {}; } if(isDefined(Points._values) != true) { Points._values = {}; } WebSocketHelper.on('readpoints', (key, readPoints) => { if(isDefined(key) && key.includes('.') && readPoints.length > 0) { let keyId = key.split('.')[1]; let siteId = undefined; if(key.startsWith("site.")) { Points.log("Received `" + readPoints.length + "` Read Points for Site ID: " + keyId); siteId = Number(keyId); } else if(key.startsWith("rtu.")) { Points.log("Received `" + readPoints.length + "` Read Points for RTU ID: " + keyId); siteId = this.getDefaultSiteId(); } if(isDefined(siteId) && siteId > 0) { if((siteId in Points._values) != true) { Points._values[siteId] = {}; } let pointValueItems = []; readPoints.forEach((readPoint) => { if('id' in readPoint) { let pointId = Number(readPoint.id); if(pointId > 0 && 'value' in readPoint && 'timestamp' in readPoint) { /** * @type {Points.PointValueItem} */ let pointValueItem = { id: pointId, value: readPoint.value, timestamp: typeof readPoint.timestamp === 'string' ? new Date(readPoint.timestamp) : new Date(String(readPoint.timestamp)), }; Points._values[siteId][pointId] = pointValueItem; pointValueItems.push(pointValueItem); } } }); Points._emitter.emit('readpoints', siteId, pointValueItems); } } }); Points._initialized = true; } } /** * Returns the Initialized Status * * @static * @public * @returns {boolean} */ static isInitialized() { return isDefined(Points._initialized) && Points._initialized == true; } /** * Loggging * * @static * @private * @param {string} message - The Message to Log * @param {string} [type] - The Log Type (defaults to log) */ static log(message, type = 'log') { if(isDebugMode() == true) { switch(type) { case 'error': console.error('Points :: ' + message); break; case 'warn': case 'warning': console.warn('Points :: ' + message); break; case 'log': default: console.log('Points :: ' + message); break; } } } /** * Subscribe to a Site for Points * * @static * @public * @param {number} siteId - The Site ID * @return {Promise<boolean>} */ static subscribe(siteId) { if(Points.isInitialized() != true) { throw new Error("Points.subscribe cannot be called before the API Client has been Initialized"); } if(hasToken() != true) { throw new Error("Points.subscribe cannot be called before Authentication has been successful"); } if(siteId in Points._subscriptions) { if(Points._subscriptions[siteId].initializing == true) { throw new Error("Points.subscribe cannot not be called more than once while already Subscribing to the same Site ID"); } else if(Points._subscriptions[siteId].completed == true) { Points.log("Points.subscribe should not be called more than once for the same Site ID", 'warning'); return new Promise((resolve, reject) => { resolve(true); }); } } else { Points._subscriptions[siteId] = { initializing: true, completed: false, pointIds: [], }; } return new Promise((resolve, reject) => { Points.loadPointDefinitions(siteId) .then(() => { WebSocketHelper.subscribe('site.' + siteId); Points.loadPointValues(siteId) .then(() => { if(siteId in Points._subscriptions) { Points._subscriptions[siteId].initializing = false; Points._subscriptions[siteId].completed = true; } resolve(true); }) .catch(() => { if(siteId in Points._subscriptions) { Points._subscriptions[siteId].initializing = false; Points._subscriptions[siteId].completed = false; } reject(new Error("Failed to Subscribe to Site ID " + siteId + ". Unable to Fetch the Point Values")); }); }) .catch(() => { if(siteId in Points._subscriptions) { Points._subscriptions[siteId].initializing = false; Points._subscriptions[siteId].completed = false; } reject(new Error("Failed to Subscribe to Site ID " + siteId + ". Unable to Fetch the Point Definitions")); }); }); } /** * Unsubscribe from a Site for Points * * @static * @public * @param {number} siteId - The Site ID */ static unsubscribe(siteId) { if(Points.isInitialized() == true) { WebSocketHelper.unsubscribe('site.' + siteId); if(isDefined(Points._definitions) && siteId in Points._definitions) { delete Points._definitions[siteId]; } if(isDefined(Points._values) && siteId in Points._values) { delete Points._values[siteId]; } if(isDefined(Points._subscriptions) && siteId in Points._subscriptions) { delete Points._subscriptions[siteId]; } } else { throw new Error("Points.unsubscribe cannot be called before the API Client has been Initialized"); } } /** * Register Events Handler * * @static * @public * @param {string} event - The Event to Register a Handler for * @param {Points.eventCallback} handler - The Handler Callback */ static on(event, handler) { if(isDefined(Points._emitter) != true) { Points._emitter = new EventEmitter(); } Points._emitter.on(event, handler); } /** * Un-Register Events Handler * * @static * @public * @param {string} event - The Event to Un-Register a Handler from * @param {Points.eventCallback} handler - The Handler Callback */ static off(event, handler) { if(isDefined(Points._emitter)) { Points._emitter.off(event, handler); } } /** * Register 'readpoints' Event Handler * * @static * @public * @param {Points.readPointsCallback} handler - The Handler Callback */ static onReadPoints(handler) { Points.on('readpoints', handler); } /** * Un-Register 'readpoints' Event Handler * * @static * @public * @param {Points.readPointsCallback} handler - The Handler Callback */ static offReadPoints(handler) { Points.off('readpoints', handler); } /** * Get Point Definition * * @static * @public * @param {number} siteId - The Site ID * @param {number} pointId - The Point ID * @return {PointModel|undefined} - The Point Definition */ static getDefinition(siteId, pointId) { if(Points.isInitialized() != true) { return undefined; } if(siteId in Points._definitions && pointId in Points._definitions[siteId]) { return Points._definitions[siteId][pointId]; } return undefined; } /** * Get Point Value * * @static * @public * @param {number} siteId - The Site ID * @param {number} pointId - The Point ID * @return {Points.PointValueItem|undefined} - The Point Value */ static getValue(siteId, pointId) { if(Points.isInitialized() != true) { return undefined; } if(siteId in Points._values && pointId in Points._values[siteId]) { return Points._values[siteId][pointId]; } return undefined; } /** * Set Point Value * * @static * @public * @param {number} siteId - The Site ID * @param {number} pointId - The Point ID * @param {any} value - The Point Value to Write * @return {Promise<string>} */ static setValue(siteId, pointId, value) { return new Promise((resolve, reject) => { if(siteId <= 0) { reject(new Error("Invalid Site ID `" + siteId + "`")); } if(pointId <= 0) { reject(new Error("Invalid Point ID `" + pointId + "`")); } let pointDefinition = Points.getDefinition(siteId, pointId); if(isDefined(pointDefinition) != true || pointDefinition.id != pointId) { reject(new Error("Unknown Point ID `" + pointId + "` for Site ID `" + siteId + "`")); } WebSocketHelper.emit('createWritePoint', siteId, pointId, value, pointDefinition.valueType, false, (guid) => { resolve(guid); }); }); } /** * Load Point Definitions from the API * * @static * @private * @param {number} siteId - The Site ID to pull Point Definitions from * @return {Promise<boolean>} */ static loadPointDefinitions(siteId) { if((siteId in Points._definitions) != true) { Points._definitions[siteId] = {}; } return new Promise((resolve, reject) => { PointController.getAll(siteId) .then((points) => { if(siteId in Points._definitions) { points.forEach((point) => { Points._definitions[siteId][point.id] = point; }); resolve(true); } else { reject(new Error("Site ID is no longer Subscribed")); } }) .catch((error) => { Points.log(error, 'error'); reject(error); }); }); } /** * Load Point Values from the API * * @static * @private * @param {number} siteId - The Site ID to pull Point Values from * @return {Promise<boolean>} */ static loadPointValues(siteId) { if((siteId in Points._values) != true) { Points._values[siteId] = {}; } return new Promise((resolve, reject) => { PointController.getAllValues(siteId) .then((pointValues) => { if(siteId in Points._values) { let changedPoints = []; pointValues.forEach((pointValue) => { if(pointValue.id in Points._values[siteId]) { if(Points._values[siteId][pointValue.id].value != pointValue.value || Points._values[siteId][pointValue.id].timestamp != pointValue.timestamp) { changedPoints.push(pointValue); } Points._values[siteId][pointValue.id] = pointValue; } else { changedPoints.push(pointValue); Points._values[siteId][pointValue.id] = pointValue; } }); if(changedPoints.length > 0) { Points._emitter.emit('readpoints', siteId, changedPoints); } resolve(true); } else { reject(new Error("Site ID is no longer Subscribed")); } }) .catch((error) => { Points.log(error, 'error'); reject(error); }); }); } /** * Get Default Site ID * * @static * @private * @return {number|undefined} */ static getDefaultSiteId() { if(isDefined(Points._definitions) && Object.keys(Points._definitions).length > 0) { return Number(Object.keys(Points._definitions)[0]); } return undefined; } }
JavaScript
class ChallengeEndModal extends Component { state = { active: true, } dismiss = () => this.setState({active: false}) render() { return ( <Modal className="challenge-end-modal" contentClassName="mr-bg-blue-dark mr-w-sm" isActive={this.state.active} onClose={this.dismiss}> <div className="mr-bg-blue-dark mr-p-8"> <div className="mr-text-right mr-text-green-lighter" aria-label="close" > <button className="mr-text-green-lighter" onClick={this.dismiss}> <SvgSymbol sym="outline-close-icon" viewBox="0 0 20 20" className="icon mr-fill-current" /> </button> </div> <div className="mr-bg-blue-dark mr-text-white mr-text-center"> <div> <h2 className="mr-text-yellow mr-text-4xl mr-mb-4"> <FormattedMessage {...messages.header} /> </h2> <div className="form mr-mt-2 mr-py-4"> <p className="mr-mr-4 mr-text-lg"> <FormattedMessage {...messages.primaryMessage} /> </p> </div> </div> <div className="mr-text-center mr-mt-6"> <button className="mr-button" onClick={this.dismiss}> <FormattedMessage {...messages.dismiss} /> </button> </div> </div> </div> </Modal> ) } }
JavaScript
class TwingNodeVerbatim extends TwingNodeText { get type() { return type; } }
JavaScript
class LoaderInline extends RingComponent { render() { const classes = classNames( 'ring-loader-inline', this.props.className ); return ( <div {...this.props} className={classes} > <div className="ring-loader-inline__ball"></div> <div className="ring-loader-inline__ball ring-loader-inline__ball_second"></div> <div className="ring-loader-inline__ball ring-loader-inline__ball_third"></div> </div> ); } }
JavaScript
class TestWarning extends React.PureComponent { constructor(props){ super(props); this.handleClose = this.handleClose.bind(this); } handleClose(evt){ evt.preventDefault(); evt.stopPropagation(); if (typeof this.props.setHidden === 'function'){ this.props.setHidden(evt); return; } } render(){ const { visible } = this.props; if (!visible) return null; return ( <div className="test-warning"> <div className="container"> <div className="row"> <div className="col-10 text-container" style={{ fontSize : '13.5px' }}> <i className="icon fas icon-fw icon-info-circle circle-icon d-none d-md-inline-block"/> The data displayed on this page is not official and only for testing purposes. </div> <div className="col-2 close-button-container"> <a className="test-warning-close icon icon-times fas" title="Hide" onClick={this.handleClose}/> </div> </div> </div> </div> ); } }
JavaScript
class TwilioAdapter extends botbuilder_1.BotAdapter { /** * Create an adapter to handle incoming messages from Twilio's SMS service and translate them into a standard format for processing by your bot. * * Use with Botkit: *```javascript * const adapter = new TwilioAdapter({ * twilio_number: process.env.TWILIO_NUMBER, * account_sid: process.env.TWILIO_ACCOUNT_SID, * auth_token: process.env.TWILIO_AUTH_TOKEN, * validation_url: process.env.TWILIO_VALIDATION_URL * }); * const controller = new Botkit({ * adapter: adapter, * // ... other configuration options * }); * ``` * * Use with BotBuilder: *```javascript * const adapter = new TwilioAdapter({ * twilio_number: process.env.TWILIO_NUMBER, * account_sid: process.env.TWILIO_ACCOUNT_SID, * auth_token: process.env.TWILIO_AUTH_TOKEN, * validation_url: process.env.TWILIO_VALIDATION_URL * }); * // set up restify... * const server = restify.createServer(); * server.use(restify.plugins.bodyParser()); * server.post('/api/messages', (req, res) => { * adapter.processActivity(req, res, async(context) => { * // do your bot logic here! * }); * }); * ``` * * @param options An object containing API credentials, a webhook verification token and other options */ constructor(options) { super(); /** * Name used by Botkit plugin loader * @ignore */ this.name = 'Twilio SMS Adapter'; /** * A specialized BotWorker for Botkit that exposes Twilio specific extension methods. * @ignore */ this.botkit_worker = botworker_1.TwilioBotWorker; this.options = options; if (!options.twilio_number) { let err = 'twilio_number is a required part of the configuration.'; if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } if (!options.account_sid) { let err = 'account_sid is a required part of the configuration.'; if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } if (!options.auth_token) { let err = 'auth_token is a required part of the configuration.'; if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } if (this.options.enable_incomplete) { const warning = [ ``, `****************************************************************************************`, `* WARNING: Your adapter may be running with an incomplete/unsafe configuration. *`, `* - Ensure all required configuration options are present *`, `* - Disable the "enable_incomplete" option! *`, `****************************************************************************************`, `` ]; console.warn(warning.join('\n')); } try { this.api = Twilio(this.options.account_sid, this.options.auth_token); } catch (err) { if (err) { if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } } this.middlewares = { spawn: [ (bot, next) => __awaiter(this, void 0, void 0, function* () { bot.api = this.api; next(); }) ] }; } /** * Formats a BotBuilder activity into an outgoing Twilio SMS message. * @param activity A BotBuilder Activity object * @returns a Twilio message object with {body, from, to, mediaUrl} */ activityToTwilio(activity) { let message = { body: activity.text, from: this.options.twilio_number, to: activity.conversation.id, mediaUrl: undefined }; if (activity.channelData && activity.channelData.mediaUrl) { message.mediaUrl = activity.channelData.mediaUrl; } return message; } /** * Standard BotBuilder adapter method to send a message from the bot to the messaging API. * [BotBuilder reference docs](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/botadapter?view=botbuilder-ts-latest#sendactivities). * @param context A TurnContext representing the current incoming message and environment. (Not used) * @param activities An array of outgoing activities to be sent back to the messaging API. */ sendActivities(context, activities) { return __awaiter(this, void 0, void 0, function* () { const responses = []; for (var a = 0; a < activities.length; a++) { const activity = activities[a]; if (activity.type === botbuilder_1.ActivityTypes.Message) { const message = this.activityToTwilio(activity); const res = yield this.api.messages.create(message); responses.push({ id: res.sid }); } else { debug('Unknown message type encountered in sendActivities: ', activity.type); } } return responses; }); } /** * Twilio SMS adapter does not support updateActivity. * @ignore */ // eslint-disable-next-line updateActivity(context, activity) { return __awaiter(this, void 0, void 0, function* () { debug('Twilio SMS does not support updating activities.'); }); } /** * Twilio SMS adapter does not support deleteActivity. * @ignore */ // eslint-disable-next-line deleteActivity(context, reference) { return __awaiter(this, void 0, void 0, function* () { debug('Twilio SMS does not support deleting activities.'); }); } /** * Standard BotBuilder adapter method for continuing an existing conversation based on a conversation reference. * [BotBuilder reference docs](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/botadapter?view=botbuilder-ts-latest#continueconversation) * @param reference A conversation reference to be applied to future messages. * @param logic A bot logic function that will perform continuing action in the form `async(context) => { ... }` */ continueConversation(reference, logic) { return __awaiter(this, void 0, void 0, function* () { const request = botbuilder_1.TurnContext.applyConversationReference({ type: 'event', name: 'continueConversation' }, reference, true); const context = new botbuilder_1.TurnContext(this, request); return this.runMiddleware(context, logic); }); } /** * Accept an incoming webhook request and convert it into a TurnContext which can be processed by the bot's logic. * @param req A request object from Restify or Express * @param res A response object from Restify or Express * @param logic A bot logic function in the form `async(context) => { ... }` */ processActivity(req, res, logic) { return __awaiter(this, void 0, void 0, function* () { if ((yield this.verifySignature(req, res)) === true) { const event = req.body; const activity = { id: event.MessageSid, timestamp: new Date(), channelId: 'twilio-sms', conversation: { id: event.From }, from: { id: event.From }, recipient: { id: event.To }, text: event.Body, channelData: event, type: botbuilder_1.ActivityTypes.Message }; // Detect attachments if (event.NumMedia && parseInt(event.NumMedia) > 0) { // specify a different event type for Botkit activity.channelData.botkitEventType = 'picture_message'; } // create a conversation reference const context = new botbuilder_1.TurnContext(this, activity); context.turnState.set('httpStatus', 200); yield this.runMiddleware(context, logic); // send http response back res.status(context.turnState.get('httpStatus')); // Twilio requires a content type and throws errors without it. res.setHeader('content-type', 'application/xml'); if (context.turnState.get('httpBody')) { res.send(context.turnState.get('httpBody')); } else { res.end(); } } }); } /** * Validate that requests are coming from Twilio * @returns If signature is valid, returns true. Otherwise, sends a 400 error status via http response and then returns false. */ verifySignature(req, res) { return __awaiter(this, void 0, void 0, function* () { let twilioSignature; let validation_url; // Restify style if (!req.headers) { twilioSignature = req.header('x-twilio-signature'); validation_url = this.options.validation_url || (req.headers['x-forwarded-proto'] || (req.isSecure()) ? 'https' : 'http') + '://' + req.headers.host + req.url; } else { // express style twilioSignature = req.headers['x-twilio-signature']; validation_url = this.options.validation_url || ((req.headers['x-forwarded-proto'] || req.protocol) + '://' + req.hostname + req.originalUrl); } if (twilioSignature && Twilio.validateRequest(this.options.auth_token, twilioSignature, validation_url, req.body)) { return true; } else { debug('Signature verification failed, Ignoring message'); res.status(400); res.send({ error: 'Invalid signature.' }); return false; } }); } }
JavaScript
class ContractWrapper { /** * A new channel instance is created if channelId is null * otherwise use an existing channel. * @param {string} senderAddress The first number. * @param {string} receiverAddress The second number. * @param {number} web3 The second number. * @param {number} channelId The second number. */ constructor(senderAddress, receiverAddress, web3, channelId) { if (channelId === undefined) { this.channelId = '0x' + uuidv1() .split('-') .join(''); } else { this.channelId = channelId; } // TODO: Production code shouldn't have this. this.gasMultiplier = config.getGasMultiplier(); this.artifacts = new ContractArtifacts('Unidirectional'); this.senderAddress = senderAddress; this.receiverAddress = receiverAddress; this.web3 = web3; this.contract = new this.web3.eth.Contract(this.artifacts.contractAbi, this.artifacts.contractAddress); } /** * Gets a delegate to a method by name * @param {string} methodName the methods name from solidity * @return {*} the instance of the js wrapper methods */ methodNamefactory(methodName) { let method = methodName + '(' + this.artifacts.getParamsString(methodName) + ')'; return this.contract.methods[method]; } /** * handles promise and event sequence for web3 method.send * @param {string} methodName name for debug purposes * @param {*} parametered the delegate function to be called * @param {*} fromAddress Initiating wallet address * @param {*} value Tx value to be sent * @return {*} tx value */ bodyFactory(methodName, parametered, fromAddress, value) { return new Promise((resolve, reject) => { debug(methodName, this.channelId, fromAddress, value); parametered.estimateGas({value: value, from: fromAddress}) .then((gasAmount) => { debug(methodName + ': Estimated GAS: ' + gasAmount); return parametered .send({from: fromAddress, value: value, gas: parseInt(gasAmount * this.gasMultiplier, 10)}) .on('transactionHash', function(hash) { debugEvents(methodName + ': onTransactionHash: ' + hash); }) .on('confirmation', function(confirmationNumber, receipt) { debugEvents(methodName + ': onConfirmation: ' + confirmationNumber + ', ' + receipt.transactionHash); }) .on('receipt', function(receipt) { debugEvents(methodName + ': onReceipt: '); debugEvents(receipt); }); }) .then((value) => { debug(methodName + ': onValue: '); debug(value); resolve(value); }) .catch((reason) => { reject(reason); }); }); } // // Payable Functions // // TODO: We already have receiverAddress in the constructor! /** * See solidity * @param {*} receiverAddress * @param {*} settlingPeriod * @param {*} initialValue * @return {*} */ open(receiverAddress, settlingPeriod, initialValue) { // TODO: Validate input paramets let methodName = 'open'; let parametered = this.methodNamefactory(methodName)(this.channelId, receiverAddress, settlingPeriod); return this.bodyFactory(methodName, parametered, this.senderAddress, initialValue); } /** * See solidity * @param {*} depositValue * @return {*} */ deposit(depositValue) { // TODO: Validate input paramets let methodName = 'deposit'; let parametered = this.methodNamefactory(methodName)(this.channelId); return this.bodyFactory(methodName, parametered, this.senderAddress, depositValue); } /** * See solidity * @param {*} payment * @param {*} signature * @return {*} */ claim(payment, signature) { // TODO: Validate input paramet let methodName = 'claim'; let parametered = this.methodNamefactory(methodName)(this.channelId, payment, signature); return this.bodyFactory(methodName, parametered, this.receiverAddress, 0); } /** * See solidity * @return {*} */ settle() { // TODO: Validate input paramets let methodName = 'settle'; let parametered = this.methodNamefactory(methodName)(this.channelId); return this.bodyFactory(methodName, parametered, this.senderAddress, 0); } /** * See solidity * @return {*} */ startSettling() { // TODO: Validate input paramets let methodName = 'startSettling'; let parametered = this.methodNamefactory(methodName)(this.channelId); return this.bodyFactory(methodName, parametered, this.senderAddress, 0); } // // View Functions // /** * See solidity * @return {*} */ isAbsent() { // TODO: perform input validation. return this.contract.methods.isAbsent(this.channelId).call(); } /** * See solidity * @return {*} */ isPresent() { // TODO: perform input validation. return this.contract.methods.isPresent(this.channelId).call(); } /** * See solidity * @return {*} */ isSettling() { // TODO: perform input validation. return this.contract.methods.isSettling(this.channelId).call(); } /** * See solidity * @return {*} */ isOpen() { // TODO: perform input validation. return this.contract.methods.isOpen(this.channelId).call(); } /** * See solidity * @param {*} originAddress * @return {*} */ canDeposit(originAddress) { // TODO: perform input validation. return this.contract.methods.canDeposit(this.channelId, originAddress).call(); } /** * See solidity * @param {*} originAddress * @return {*} */ canStartSettling(originAddress) { // TODO: perform input validation. return this.contract.methods.canStartSettling(this.channelId, originAddress).call(); } /** * See solidity * @return {*} */ canSettle() { // TODO: perform input validation. return this.contract.methods.canSettle(this.channelId).call(); } /** * See solidity * @param {*} payment * @param {*} originAddress * @param {*} signature * @return {*} */ canClaim(payment, originAddress, signature) { // TODO: perform input validation. debug('a: ' + this.channelId + 'p: ' + payment); return this.contract.methods.canClaim(this.channelId, payment, originAddress, signature).call({from: this.receiverAddress}); } /** * See solidity * @param {*} payment * @return {*} */ paymentDigest(payment) { // TODO: perform input validation. return this.contract.methods.paymentDigest(this.channelId, payment).call(); } }
JavaScript
class Bounce extends Component { static propTypes = { onPress: PropTypes.func, //Optional function to be excecuted after succesful press level: PropTypes.number // Maximum scale of animation }; static defaultProps = { level: 1.1 }; constructor(props) { super(props); this.state = { scale: new Animated.Value(1) }; } panResponder = {}; componentWillMount() { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: (evt, gestureState) => true, onStartShouldSetPanResponderCapture: (evt, gestureState) => true, onMoveShouldSetPanResponder: (evt, gestureState) => true, onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderTerminationRequest: (evt, gestureState) => true, onPanResponderTerminate: (evt, gestureState) => {}, onPanResponderGrant: (evt, gestureState) => { Animated.timing(this.state.scale, { toValue: this.props.level, friction: 1, duration: 200 }).start(); }, onPanResponderRelease: (evt, gestureState) => { if ( gestureState.dy > moveTolerance || gestureState.dy < -moveTolerance || gestureState.dx > moveTolerance || gestureState.dx < -moveTolerance ) { // Do nothing } else { setTimeout(() => { // 50ms delay makes press response more natural Animated.spring(this.state.scale, { toValue: 1, friction: 1, duration: 200 }).start(); if (this.props.onPress) { this.props.onPress(); } }, 50); } } }); } render() { return ( <Animated.View style={[ { transform: [ { scale: this.state.scale } ] }, this.props.style ]} > <View {...this._panResponder.panHandlers}> <View>{this.props.children}</View> </View> </Animated.View> ); } }
JavaScript
class SignInController { constructor() { } }
JavaScript
class TrafficFunctions { /** * @param {object} store * @param {string} apiKey * @param {string} baseUrl * @param {object} origin * @param {string} origin.latitude * @param {string} origin.longitude * @param {object} destination * @param {string} destination.latitude * @param {string} destination.longitude */ constructor(store, apiKey, baseUrl, origin, destination) { this.store = store; this.apiKey = apiKey; this.baseURL = baseUrl; this.origin = origin; this.destination = destination; } /** * @description Sends a propery formatted GET request for HERE API * @param {string} transportMode * @returns {Promise<TrafficResponse>} response */ async GetTraffic(transportMode) { const url = this.baseURL + `/routes?transportMode=${transportMode}&origin=${this.origin.latitude},${this.origin.longitude}&destination=${this.destination.latitude},${this.destination.longitude}&apiKey=${this.apiKey}`; const response = await axios.get(url); return response; } /** * @description Iterates over on travel modes from config.js. In every * iteration it executes GetTraffic with a different transport mode. * Afterwards result stored in a new Array then set to vuex store * @returns {Promise<void>} */ async GetTrafficByMultipleTravelMode() { let responseList = []; for (const mode of traffic.travelModes) { const response = await this.GetTraffic(mode); responseList.push(response?.data?.routes[0]?.sections[0]); } this.CreateTrafficStateFromResponseList(responseList); return void 0; } /** * @description Creates a new array of objects from forecast response * Result list stored in vuex store * @param {Array<Section>} list * @returns {void} */ CreateTrafficStateFromResponseList(list) { if (!list || !Array.isArray(list)) return; let result = list.map(m => { return { type: m?.transport?.mode, departureTime: m?.departure?.time, arrivalTime: m?.arrival?.time, }; }); this.store.dispatch('traffic/SET_TRAFFIC', result); return void 0; } }
JavaScript
class TextField extends Component { state = { isFocused: false, }; floatingSpring = new Spring(1, 0.3); constructor (props) { super(props); this.floatingSpring.tolerance = 1 / 60; } /// Input ID, used for the `for` attribute on the `<label>` if `id` is not given. inputID = `text-field-${inputIDCounter++}`; labelID = this.inputID + '-label'; errorID = this.inputID + '-error'; node = null; /// The `<input>` node. inputNode = null; /// The leading container node. leadingNode = null; onFocus = e => { if (this.props.onFocus) this.props.onFocus(e); if (!e.defaultPrevented) this.setState({ isFocused: true }); }; onBlur = e => { if (this.props.onBlur) this.props.onBlur(e); if (!e.defaultPrevented) this.setState({ isFocused: false }); this.underlineX = null; }; onInputMouseDown = e => { if (this.props.onMouseDown) this.props.onMouseDown(e); if (!e.defaultPrevented && !this.state.isFocused) { const nodeRect = this.node.getBoundingClientRect(); this.underlineX = (e.clientX - nodeRect.left) / nodeRect.width; } }; onInputTouchStart = e => { if (this.props.onTouchStart) this.props.onTouchStart(e); if (!e.defaultPrevented && !this.state.isFocused) { const nodeRect = this.node.getBoundingClientRect(); this.underlineX = (e.touches[0].clientX - nodeRect.left) / nodeRect.width; } }; /// Calls `focus()` on the input node. focus () { this.inputNode.focus(); } /// Sets the target of the floating spring according to the current state. updateFloatingSpring () { this.floatingSpring.target = (this.state.isFocused || this.props.value) ? 1 : 0; if (this.floatingSpring.wantsUpdate()) this.floatingSpring.start(); } componentDidMount () { this.updateFloatingSpring(); this.floatingSpring.finish(); this.forceUpdate(); } componentDidUpdate (prevProps) { this.updateFloatingSpring(); if (prevProps.label !== this.props.label) { // label width changed; decorations need to be updated this.floatingSpring.start(); } } render () { let className = (this.props.class || '') + ' paper-text-field'; if (this.state.isFocused) className += ' is-focused'; if (this.props.error) className += ' has-error'; if (this.props.disabled) className += ' is-disabled'; if (this.props.center) className += ' centered'; if (this.state.isFocused || this.props.value) className += ' floating'; if (!this.props.label) className += ' no-label'; if (this.props.leading) className += ' has-leading'; if (this.props.trailing) className += ' has-trailing'; const props = { ...this.props }; delete props.class; delete props.outline; delete props.label; delete props.value; delete props.leading; delete props.trailing; delete props.center; delete props.error; delete props.helperLabel; const outline = !!this.props.outline; if (!outline) className += ' filled-style'; return ( <span class={className} ref={node => this.node = node}> <span class="p-contents"> <span class="p-leading" ref={node => this.leadingNode = node}> {this.props.leading} </span> <input autoComplete="off" {...props} id={this.props.id || this.inputID} class="p-input" onFocus={this.onFocus} onBlur={this.onBlur} onMouseDown={this.onInputMouseDown} onTouchStart={this.onInputTouchStart} ref={node => this.inputNode = node} value={this.props.value} placeholder={this.props.placeholder} disabled={this.props.disabled} aria-labelledby={this.labelID} aria-invalid={!!this.props.error} aria-errormessage={this.props.error && this.errorID} onInput={e => this.props.onChange && this.props.onChange(e)} /> <span class="p-trailing"> {this.props.trailing} </span> </span> <TextFieldDecoration floatingSpring={this.floatingSpring} id={this.props.id || this.inputID} labelID={this.labelID} label={this.props.label} inputNode={this.inputNode} leadingNode={this.leadingNode} outline={outline} center={this.props.center} underlineX={this.underlineX} /> <label class="p-error-label" id={this.errorID}>{this.props.error}</label> <label class="p-helper-label">{this.props.helperLabel}</label> </span> ); } }
JavaScript
class TextFieldDecoration extends Component { state = { float: 0, }; /// The `<label>` node. labelNode = null; /// Returns the styles for the label node and layout info for the outline break. getLabelStyleAndBreakStyle () { // return dummy value if refs haven’t been populated yet if (!this.labelNode) return [{}, {}]; const labelWidth = this.labelNode.offsetWidth; const labelHeight = this.labelNode.offsetHeight; const inputStyle = getComputedStyle(this.props.inputNode); const floatingY = this.props.outline ? -labelHeight * FLOATING_LABEL_SCALE / 2 : 0; const fixedY = (parseInt(inputStyle.paddingTop) + parseInt(inputStyle.paddingBottom)) / 2; const leadingWidth = this.props.leadingNode.offsetWidth; let x = this.props.center ? (this.props.inputNode.offsetWidth - lerp(labelWidth, labelWidth * FLOATING_LABEL_SCALE, this.state.float)) / 2 : parseInt(inputStyle.paddingLeft); if (!this.props.outline) x += leadingWidth; const y = lerp(fixedY, floatingY, this.state.float); const scale = lerp(1, FLOATING_LABEL_SCALE, this.state.float); const breakX = this.props.center ? (this.props.inputNode.offsetWidth - labelWidth * FLOATING_LABEL_SCALE) / 2 - 2 : x - 2; const breakWidth = labelWidth ? labelWidth * FLOATING_LABEL_SCALE + 4 : 0; let labelX = x; const easeOutSine = t => Math.sin(Math.PI / 2 * t); if (this.props.outline) labelX += leadingWidth * easeOutSine(1 - this.state.float); return [ { transform: `translate(${labelX}px, ${y}px) scale(${scale})`, }, { // scale (of the two border lines, indicated by +++ here) // v------ // .------- ++++ ++++ -------- // | · · // | left · break · right // | · · // '------- -------------- -------- // |------------| // | width // x x: breakX, width: breakWidth, scale: 1 - this.state.float, }, ]; } componentDidMount () { this.props.floatingSpring.on('update', this.onUpdate); } componentWillUnmount () { this.props.floatingSpring.removeListener('update', this.onUpdate); } onUpdate = float => this.setState({ float }); render () { const [labelStyle, breakStyle] = this.getLabelStyleAndBreakStyle(); return ( <span class="p-decoration"> <label class="p-label" id={this.props.labelID} for={this.props.id} style={labelStyle} ref={node => this.labelNode = node}> {this.props.label} </label> {this.props.outline ? ( <div class="p-outline"> <div class="outline-left" style={{ width: breakStyle.x }}></div> <div class="outline-break" style={{ width: breakStyle.width }}> <div class="break-left" style={{ transform: `scaleX(${breakStyle.scale})` }} /> <div class="break-right" style={{ transform: `scaleX(${breakStyle.scale})` }} /> <div class="break-bottom" /> </div> <div class="outline-right"></div> </div> ) : ( <div class="p-underline"> <div class="p-underline-inner" style={{ transformOrigin: `${Number.isFinite(this.props.underlineX) ? (this.props.underlineX * 100) : 50}% 100%`, }} /> </div> )} </span> ); } }
JavaScript
class Category extends Model { /** * Initialization function. * * @param sequelize * @returns {Model} */ static init(sequelize) { return super.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, name: { type: DataTypes.STRING, allowNull: false, unique: true, }, description: DataTypes.STRING, }, { sequelize, updatedAt: false, }); } /** * Set associations for the model */ static associate({ FeedObject }) { this.belongsToMany(FeedObject, { through: 'feedObjectCategoryWrappers', foreignKey: 'categoryId' }); } }
JavaScript
class BhairaviTemplate extends PlantWorksBaseTemplate { // #region Constructor constructor(parent, loader) { super(parent, loader); } // #endregion // #region Protected methods - need to be overriden by derived classes /** * @async * @function * @override * @instance * @memberof BhairaviTemplate * @name _addRoutes * * @returns {undefined} Nothing. * * @summary Adds routes to the Koa Router. */ async _addRoutes() { await super._addRoutes(); const path = require('path'); const serveStatic = require('koa-static'); const dirPath = path.join(path.dirname(path.dirname(require.main.filename)), 'node_modules/ember-source/dist'); this.$router.use(serveStatic(dirPath)); if(!this.$statciServers) { // eslint-disable-line curly this.$statciServers = {}; } this.$router.get('*', async (ctxt, next) => { let staticServer = null; try { const tenantTemplatePath = path.dirname(path.join(ctxt.state.tenant['template']['tenant_domain'], ctxt.state.tenant['template']['tmpl_name'], ctxt.state.tenant['template']['path_to_index'])); const tmplStaticAssetPath = path.join(path.dirname(path.dirname(require.main.filename)), 'tenant_templates', tenantTemplatePath); // eslint-disable-next-line security/detect-object-injection if(this.$statciServers[tmplStaticAssetPath]) { // eslint-disable-next-line security/detect-object-injection staticServer = this.$statciServers[tmplStaticAssetPath]; } else { staticServer = serveStatic(tmplStaticAssetPath); // eslint-disable-next-line security/detect-object-injection this.$statciServers[tmplStaticAssetPath] = staticServer; } } catch(err) { console.error(`${err.message}\n${err.stack}`); await next(); return; } await staticServer(ctxt, next); }); // If it gets till here... must be a SPA asking for a client-side defined route // Let the client-side router handle the transition. We'll treat it as if 'GET /' // was requested this.$router.get('*', async (ctxt, next) => { try { await this._serveTenantTemplate(ctxt, next); } catch(err) { console.error(`${err.message}\n${err.stack}`); throw err; } }); return null; } // #endregion // #region Properties /** * @override */ get basePath() { return __dirname; } // #endregion }
JavaScript
class VigenereCipheringMachine { constructor(param){ if (param==false) { this.param=false } else this.param=true } encrypt(message, key) { if(!message || !key){ throw new Error('Incorrect arguments!'); } else{ message = message.toUpperCase(); key= key.toUpperCase() } let kf=Math.ceil(message.length / key.length); key = key.repeat(kf); let result = [] let abcCount = 26; let countKey=0 for (let i=0; i<message.length; i++){ if(message[i].charCodeAt(0)<65 || message[i].charCodeAt(0)>90){ result.push(message[i]) } else { let codeA = 'A'.charCodeAt(0); let shift = key.charCodeAt(countKey) - codeA; let letterIndex = message.charCodeAt(i) - codeA; let newSymbol = String.fromCharCode( codeA + (letterIndex + shift) % abcCount) result.push(newSymbol) countKey++ } } if(this.param == true) return result.join(''); else return result.reverse().join(''); } decrypt(message, key) { if(!message || !key){ throw new Error ('Incorrect arguments!'); } else{ message = message.toUpperCase(); key= key.toUpperCase() } let kf=Math.ceil(message.length / key.length); key = key.repeat(kf); let result = [] let abcCount = 26; let countKey=0 for (let i=0; i<message.length; i++){ if(message[i].charCodeAt(0)<65 || message[i].charCodeAt(0)>90){ result.push(message[i]) } else { let codeA = 'A'.charCodeAt(0); let shift = key.charCodeAt(countKey) - codeA; let letterIndex = message.charCodeAt(i) - codeA; let newSymbol = String.fromCharCode( codeA + (letterIndex - shift + abcCount) % abcCount) result.push(newSymbol) countKey++ } } if(this.param == true) return result.join(''); else return result.reverse().join(''); } }
JavaScript
class Home extends React.Component { componentWillMount() { const { setName } = this.props; setName("Otro") } render(){ const { classes, history, session } = this.props; return ( <AppLayout title={title} > <h2>{session.name}</h2> </AppLayout> ) } }
JavaScript
class CreateSeatModalContainer extends React.Component { constructor(props, context) { super(props, context); this.handleClose = this.handleClose.bind(this); this.handleChange = this.handleChange.bind(this); this.changeColor = this.changeColor.bind(this); this.changeSlider = this.changeSlider.bind(this); this.saveSeat = this.saveSeat.bind(this); } handleClose() { this.props.actions.toggleCreateSeatModal(false); } handleChange(event) { const seat = {...this.props.seat}; const field = event.target.name; seat[field] = event.target.value; this.props.actions.updateSeatFormData(seat); } changeColor(color) { this.props.actions.updateSeatFormData({ ...this.props.seat, color: color.hex }); } changeSlider(value) { this.props.actions.updateSeatFormData({ r: value }); } saveSeat() { const {x, y} = this.props.point; this.props.actions.createSeat(this.props.roomId, { ...this.props.seat, x, y }); } render() { const {seat} = this.props; return ( <Modal show={this.props.showCreateSeatModal} onHide={this.handleClose}> <Modal.Header closeButton> <Modal.Title>Thêm ghế</Modal.Title> </Modal.Header> <Modal.Body> <FormGroup controlId="seat-name"> <ControlLabel>Tên chỗ ngồi</ControlLabel> <FormControl type="text" name="name" value={seat.name || name} placeholder="Tên chỗ ngồi" onChange={this.handleChange} /> </FormGroup> <FormGroup> <ControlLabel> <span style={{marginRight: 5}}>Kích thước ghế</span> <Badge>{parseInt(seat.r || 1)}</Badge> </ControlLabel> <Slider onChange={this.changeSlider} step={1} value={seat.r || 1} min={1} max={10}/> </FormGroup> <FormGroup> <ControlLabel>Màu ghế</ControlLabel> <CirclePicker width="100%" color={seat.color || ""} onChangeComplete={this.changeColor}/> </FormGroup> </Modal.Body> <Modal.Footer> <Button onClick={this.saveSeat} className="btn btn-rose"> Lưu </Button> </Modal.Footer> </Modal> ); } }
JavaScript
class WowzaAPI { constructor(options) { this.wowzaAdress = options.wowzaAdress || 'localhost'; this.application = options.application || 'live'; this.streamFile = options.streamFile || 'myStream.stream'; this.appInstance = options.appInstance || '_definst_'; this.mediaCasterType = options.mediaCasterType || 'rtp'; this.commonRequestUrl = `http://${this.wowzaAdress}:8087`; this.authEnabled = false; this.autOptions = options.username + ':' + options.password; /*if ( options.username != '' && options.password != '' ){ console.log("using digest library"); this.authEnabled = true; http = httpClient(options.username, options.password); } else { console.log("using native library"); http = require("http"); }*/ this.httpOptions = { host: this.wowzaAdress, port: '8087', path: '/v2/servers/_defaultServer_/vhosts/_defaultVHost_', method: 'PUT', headers: { 'Accept': 'application/json; charset=utf-8', 'Content-Type': 'application/json; charset=utf-8' } } } /** *Get a list of streamfiles * * @function getStreamFilesList * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve by object which contains array of streamFiles and it's confifurations * * @example * wowza.getStreamFilesList({application: 'webrtc', streamFile: 'ipCamera'}) * .then( responseMsg => console.log(responseMsg)) * .catch( errorMsg => console.log(errorMsg)); * * // Wowza answer example: * //{serverName: '_defaultServer_', streamFiles: [{id: 'ipCamera2', href: '/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/webrtc/streamfiles/ipCamera2'}]} */ getStreamFilesList(options) { let application = this.application; if (options && options.application) application = options.application; return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/streamfiles`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Ability to update the existing stream file parameters * * @function updateStreamFileOptions * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {Object} [options] * @return {Promise} promise which resolve by object which contains a resposne that looks like this: { "success": true, "message:" "", "data": null } */ updateStreamFileOptions(options, streamFileAppConfig){ let application = this.application; let streamFile = this.streamFile; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'PUT'; options.path = `${this.httpOptions.path}/applications/${application}/streamfiles/${streamFile}`; options.body = JSON.stringify(streamFileAppConfig); //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Ability to update the existing stream file parameters * * @function updateAdvancedStreamFileOptions * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {Object} [options] * @return {Promise} promise which resolve by object which contains a resposne that looks like this: { "success": true, "message:" "", "data": null } * @example this is what a streamFileAppConfigAdv looks like { "sourceControlDriver": "", //optional "advancedSettings": [ { "sectionName": "", "canRemove": false, "defaultValue": "", "documented": false, "name": "", "section": "", "type": "", "value": "", "enabled": false } ], //required should be _defaultServer_ unless changed "serverName": "", //optional "saveFieldList": [ "" ], //optional "version": "" } */ updateAdvancedStreamFileOptions(options, streamFileAppConfigAdv){ let application = this.application; let streamFile = this.streamFile; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'PUT'; options.body = JSON.stringify(streamFileAppConfigAdv); options.path = `${this.httpOptions.path}/applications/${application}/streamfiles/${streamFile}/adv`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Adds a stream file to a given application * * @function addStreamFile * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve by object which contains array of streamFiles and it's confifurations * */ addStreamFile(options, streamFileAppConfig){ let application = this.application; if (options) { application = options.application || this.application; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'POST'; options.path = `${this.httpOptions.path}/applications/${application}/streamfiles`; //the http library can be digest or non-digest, options.body allows digest to properly process the request options.body = JSON.stringify(streamFileAppConfig); this.makeNetworkRequest(options, resolve, reject); }); } deleteStreamFile(options){ let application = this.application; let streamFile = this.streamFile; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'DELETE'; options.path = `${this.httpOptions.path}/applications/${application}/streamfiles/${streamFile}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } getApplicationConfig(options) { let application = this.application; if (options) { application = options.application || this.application; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Get specific stream configuration * * @function getStreamFileConfiguration * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.streamFile = 'myStream.stream'] name of a streamfile (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve by stream configurations object * */ getStreamFileConfiguration(options) { let application = this.application; let streamFile = this.streamFile; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/streamfiles/${streamFile}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Create Recorder * * @method createRecorder * @param {Object} recorderParametres * @param {string} recorderParametres.restURI * @param {string} recorderParametres.recorderName * @param {string} recorderParametres.instanceName * @param {string} recorderParametres.recorderState * @param {boolean} recorderParametres.defaultRecorder * @param {string} recorderParametres.segmentationType * @param {string} recorderParametres.outputPath default value is [] and wowza should save files in [install-dir]/content, not tested * @param {string} recorderParametres.baseFile default is [], and wowza should name file as a streamfile name, not tested * @param {string} recorderParametres.fileFormat * @param {string} recorderParametres.fileVersionDelegateName * @param {string} recorderParametres.fileTemplate * @param {number} recorderParametres.segmentDuration * @param {number} recorderParametres.segmentSize * @param {string} recorderParametres.segmentSchedule * @param {boolean} recorderParametres.recordData * @param {boolean} recorderParametres.startOnKeyFrame * @param {boolean} recorderParametres.splitOnTcDiscontinuity * @param {number} recorderParametres.backBufferTime * @param {string} recorderParametres.option should to work with one of: version | append | overwrite, but not tested * @param {boolean} recorderParametres.moveFirstVideoFrameToZero * @param {number} recorderParametres.currentSize * @param {number} recorderParametres.currentDuration * @param {string} recorderParametres.recordingStartTime * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.streamFile = 'myStream.stream'] name of a streamfile (default value can be another if it was passed to the class constructor) * @param {string} [options.appInstance = '_definst_'] name of an instance (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve when rec will start * @example * wowza.createRecorder({ * "restURI": "http://192.168.1.15:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/webrtc/instances/_definst_/streamrecorders/ipCamera.stream", * "recorderName": "ipCameraRecorder", * "instanceName": "_definst_", * "recorderState": "Waiting for stream", * "defaultRecorder": true, * "segmentationType": "None", * "outputPath": "", // default value is [] and wowza save files in [install-dir]/content, not tested * "baseFile": "myrecord2.mp4", // default is [], and wowza will name file as a streamfile name, not tested * "fileFormat": "MP4", * "fileVersionDelegateName": "com.wowza.wms.livestreamrecord.manager.StreamRecorderFileVersionDelegate", * "fileTemplate": "${BaseFileName}_${RecordingStartTime}_${SegmentNumber}", * "segmentDuration": 900000, * "segmentSize": 10485760, * "segmentSchedule": "0 * * * * *", * "recordData": true, * "startOnKeyFrame": true, * "splitOnTcDiscontinuity": false, * "backBufferTime": 3000, * "option": "Version existing file", //should to work with one of: version | append | overwrite, but not tested * "moveFirstVideoFrameToZero": true, * "currentSize": 0, * "currentDuration": 0, * "recordingStartTime": "" * },{ * streamFile: 'ipCamera', * application: 'webrtc', * appIstance: '_definst_' * }) * .then(response => console.log(response)) * .catch(errorMsg => console.log(errorMsg)); * // Wowza answer example: * //{ success: true, message: 'Recorder Created', data: null } */ createRecorder(recorderParametres, options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'POST'; options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/streamrecorders/${streamFile}`; options.body = JSON.stringify(recorderParametres); //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Stop recording * * @method stopRecording * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.streamFile = 'myStream.stream'] name of a streamfile (default value can be another if it was passed to the class constructor) * @param {string} [options.appInstance = '_definst_'] name of an instance (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve when rec will stop * @example * wowza.stopRecording({ * streamFile: 'ipCamera', * application: 'webrtc', * appIstance: '_definst_' * }).then(response => console.log(response)).catch(errorMsg => console.log(errorMsg)); * // Wowza answer example: * // { success: true, message: 'Recording (ipCamera) stopped', data: null } */ stopRecording(options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'PUT'; options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/streamrecorders/${streamFile}/actions/stopRecording`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Updates an existing stream target * * @method deleteStreamTarget * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [entryName] * @return {Promise} promise which resolve by object contains recorders params array */ deleteStreamTarget(options, entryName) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = "DELETE"; options.path = `${this.httpOptions.path}/applications/${application}/pushpublish/mapentries/${entryName}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Updates an existing stream target * * @method setStreamTargetOption * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [entryName] * @param {string} [action] * @return {Promise} promise which resolve by object contains recorders params array */ setStreamTargetOption(options, entryName, action) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = "PUT"; options.path = `${this.httpOptions.path}/applications/${application}/pushpublish/mapentries/${entryName}/actions/${action}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Updates an existing stream target * * @method setStreamTarget * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {Object} [config] * @return {Promise} promise which resolve by object contains recorders params array */ setStreamTarget(options, config) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = (config.actionType == "update" ? 'PUT' : 'POST'); options.path = `${this.httpOptions.path}/applications/${application}/pushpublish/mapentries/${config.entryName}`; options.body = JSON.stringify(config); //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Get a list of stream targets * * @method getStreamTargets * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve by object contains recorders params array * @example * wowza.getStreamTargets({ * application: 'webrtc', * appIstance: '_definst_' * }).then( response => console.log(response)).catch( errorMsg => console.log(errorMsg)); */ getStreamTargets(options) { let application = this.application; let appInstance = this.appInstance; if (options) { application = options.application || this.application; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/pushpublish/mapentries`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Get a list of recorders * * @method getRecordersList * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.appInstance = '_definst_'] name of an instance (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve by object contains recorders params array * @example * wowza.getRecordersList({ * application: 'webrtc', * appIstance: '_definst_' * }).then( response => console.log(response)).catch( errorMsg => console.log(errorMsg)); * // Wowza answer example: * //{ serverName: '_defaultServer_', * // instanceName: '_definst_', * // streamrecorder: * // [ { recorderName: 'ipCamera', * // instanceName: '_definst_', * // recorderState: 'Waiting for stream', * // defaultRecorder: false, * // segmentationType: 'None', * // outputPath: '/usr/local/WowzaStreamingEngine/content/records', * // baseFile: 'myrecord2.mp4', * // fileFormat: 'MP4', * // fileVersionDelegateName: 'com.wowza.wms.livestreamrecord.manager.StreamRecorderFileVersionDelegate', * // fileTemplate: '${BaseFileName}_${RecordingStartTime}_${SegmentNumber}', * // segmentDuration: 900000, * // segmentSize: 10485760, * // segmentSchedule: '0 * * * * *', * // recordData: true, * // startOnKeyFrame: true, * // splitOnTcDiscontinuity: false, * // backBufferTime: 3000, * // option: 'Version existing file', * // moveFirstVideoFrameToZero: true, * // currentSize: 0, * // currentDuration: 0, * // recordingStartTime: '' } ] } */ getRecordersList(options) { let application = this.application; let appInstance = this.appInstance; if (options) { application = options.application || this.application; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/streamrecorders`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** *Connect a existing streamfile * * @method connectStreamFile * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.streamFile = 'myStream.stream'] name of a streamfile (default value can be another if it was passed to the class constructor) * @param {string} [options.appInstance = '_definst_'] name of an instance (default value can be another if it was passed to the class constructor) * @param {string} [options.mediaCasterType = 'rtp'] caster type (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve when stream will connect * @example * wowza.connectStreamFile({ * streamFile: 'ipCamera', * application: 'webrtc', * appIstance: '_definst_' * }).then( response => console.log(response)).catch( errorMsg => console.log(errorMsg)); * //Wowza answer example: * //{ success: true, message: 'Publish stream successfully started [webrtc/_definst_]: mp4:ipCamera.stream', data: null } */ connectStreamFile(options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; let mediaCasterType = this.mediaCasterType; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; mediaCasterType = options.mediaCasterType || this.mediaCasterType; } return new Promise((resolve, reject) => { //getting request query string let data = querystring.stringify({ connectAppName: application, appInstance: appInstance, mediaCasterType: mediaCasterType }); //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.path = `${this.httpOptions.path}/streamfiles/${ this._checkStreamFileName(streamFile) }/actions/connect?${data}`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } getIncomingStreamInfo(options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/incomingstreams/${streamFile}.stream`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } getIncomingStreamStats(options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.method = 'GET'; options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/incomingstreams/${streamFile}.stream/monitoring/current`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } /** * Disconnect a existing stream file * * @method disconnectStreamFile * @param {Object} [options] * @param {string} [options.application = 'live'] name of an application (default value can be another if it was passed to the class constructor) * @param {string} [options.streamFile = 'myStream.stream'] name of a streamfile (default value can be another if it was passed to the class constructor) * @param {string} [options.appInstance = '_definst_'] name of an instance (default value can be another if it was passed to the class constructor) * @param {string} [options.mediaCasterType = 'rtp'] caster type (default value can be another if it was passed to the class constructor) * @return {Promise} promise which resolve when stream will connect * @example * wowza.disconnectStreamFile({ * streamFile: 'ipCamera.stream', * application: 'webrtc', * appIstance: '_definst_' * }).then( response => console.log(response)).catch( errorMsg => console.log(errorMsg)); * //Wowza answer example: * //{ success: true, message: ''Publish stream successfully stopped [webrtc/_definst_]: mp4:ipCamera.stream'',data: null } */ disconnectIncomingStream(options) { let application = this.application; let streamFile = this.streamFile; let appInstance = this.appInstance; let mediaCasterType = this.mediaCasterType; if (options) { application = options.application || this.application; streamFile = options.streamFile || this.streamFile; appInstance = options.appInstance || this.appInstance; mediaCasterType = options.mediaCasterType || mediaCasterType; } return new Promise((resolve, reject) => { //getting a clone of the common httpOptions object and change it's path to necessary let options = Object.assign({}, this.httpOptions); options.path = `${this.httpOptions.path}/applications/${application}/instances/${appInstance}/incomingstreams/${streamFile}/actions/disconnectStream`; //getting request object this.makeNetworkRequest(options, resolve, reject); }); } makeTestNetworkRequest(options, resolve, reject){ var req, body; console.log(9); try { if ( options.body && this.authEnabled == false ){ body = options.body; delete options.body; } console.log(12, options); req = http.request(options, this.testResponseHandler(resolve, reject), reject); if ( body && this.authEnabled == false ){ req.write(body); } req.on('error', reject); req.end(); } catch(e){ console.log(11); reject(e); } console.log(10); return req; } makeNetworkRequest(options, resolve, reject){ var req, body; /*try { if ( options.body && this.authEnabled == false ){ body = options.body; delete options.body; } req = http.request(options, this.responseHandler(resolve, reject), reject); if ( body && this.authEnabled == false ){ req.write(body); } req.on('error', reject); req.end(); } catch(e){ reject(e); }*/ let shellParams = [ '-X', options.method, '--digest', '-u', this.autOptions, '-H', 'Accept:application/json; charset=utf-8', '-H', 'Content-Type:application/json; charset=utf-8' ]; if(options.body) { shellParams.push('-d') shellParams.push(options.body), shellParams.push('http://' + options.host + ':' + options.port + options.path) } const ls = spawn('curl', [ '-X', options.method, '--digest', '-u', this.autOptions, '-H', 'Accept:application/json; charset=utf-8', '-H', 'Content-Type:application/json; charset=utf-8', '-d', options.body, 'http://' + options.host + ':' + options.port + options.path ]); let curlRes = []; ls.stdout.on('data', (data) => { //console.log(`stdout: ${data}`); curlRes.push(`${data}`); }); ls.stderr.on('data', (data) => { //curlRes.push(`${data}`); }); ls.on('close', (code) => { //console.log(`child process exited with code ${code}`); resolve(curlRes.join('')) }); return req; } // handler for responses from wowza engine, if wowza response status 200 handler resolve promise responseHandler(resolve, reject) { return (res) => { if (res.statusCode < 300) { let responseData = ""; res.on('data', (chunk) => { responseData += chunk; }); res.on('end', () => { resolve(JSON.parse(responseData)); }); } else { reject(res.statusMessage); } } } // for debugging with write a data to console testResponseHandler(resolve, reject) { return (res) => { //console.log(res.getHeaders()); console.log('status'); console.log(res.statusCode); //if (res.statusCode < 300) { console.log(res.statusMessage); let responseData = ""; res.on('data', (chunk) => { console.log('DATA', chunk.length); responseData+=chunk; }); res.on('end', () => { console.log('END RESPONSE', res.req.path, res.req._header, responseData); resolve(JSON.parse(responseData)); }); /*} else { reject(res.statusMessage); }*/ } } // Connect streamfile wowza http method works only for streamfiles which name pattern is: [name].stream, // and URL connect stream method need only [name] part for identificate streamfile. // others URL methods works with all named streamfils and need full name in params. // This way, necessary checking '.stream' at the end of the streamFile while connect to streamfile. _checkStreamFileName(streamFile) { let splitted = streamFile.split('.'); return splitted.pop() === 'stream' ? splitted.join('.') : streamFile; } }
JavaScript
class Body { constructor(x, y) { this.comp = new Array(); this.pos = new Vector(x, y); this.m = 0; this.inv_m = 0; this.inertia = 0; this.inv_inertia = 0; this.elasticity = 1; this.friction = 0; this.angFriction = 0; this.maxSpeed = 0; this.color = ""; this.fill = true; this.layer = 0; this.up = false; this.down = false; this.left = false; this.right = false; this.action = false; this.vel = new Vector(0, 0); this.acc = new Vector(0, 0); this.keyForce = 1; this.angKeyForce = 0.1; this.angle = 0; this.angVel = 0; this.player = false; this.collides = true; this.images = Array(); this.actionImage = new Image(); BODIES.push(this); } render() { for (let i in this.comp) { this.comp[i].draw(this.color, this.fill, this.images[i], this.angle, this.up, this.actionImage); } } reposition() { this.acc = this.acc.unit().mult(this.keyForce); this.vel = this.vel.add(this.acc); this.vel = this.vel.mult(1 - this.friction); if (this.vel.mag() > this.maxSpeed && this.maxSpeed !== 0) { this.vel = this.vel.unit().mult(this.maxSpeed); } //this.angVel *= (1-this.angFriction); this.angVel = this.angVel * (1 - this.angFriction); } keyControl() { } remove() { if (BODIES.indexOf(this) !== -1) { BODIES.splice(BODIES.indexOf(this), 1); } } setCollisions(value) { this.collides = value; } setMass(m) { this.m = m; if (this.m === 0) { this.inv_m = 0; } else { this.inv_m = 1 / this.m; } } setImages(urls) { for (let url of urls) { const image = new Image(); image.src = url; this.images.push(image); } } setActionImage(url) { this.actionImage = new Image(); this.actionImage.src = url; } }
JavaScript
class Cassandra { /** * Get instance method of cassandra. * * @returns {Promise<*>} */ async getInstance() { const configStrategyProvider = require(rootPrefix + '/lib/providers/configStrategy'); const cassandraConfigResponse = await configStrategyProvider.getConfigForKind(configStrategyConstants.cassandra); if (cassandraConfigResponse.isFailure()) { return cassandraConfigResponse; } const cassandraConfig = cassandraConfigResponse.data[configStrategyConstants.cassandra]; const cassandraConfigStrategy = { contactPoints: cassandraConfig.contactPoints, localDataCenter: cassandraConfig.localDataCenter, authProvider: new CassandraClient.auth.PlainTextAuthProvider(cassandraConfig.username, cassandraConfig.password), encoding: { set: Set } }; return new CassandraClient.Client(cassandraConfigStrategy); } }
JavaScript
class SwaggerRouterHelper { /** * The main method for the SwaggerRouterHelper class. * * The object returned is in the form: * { * SomeControllerName: [contents of the controller file via REQUIRE], * SomeOtherControllerName: [contents of the controller file via REQUIRE] * } * * @param controllersPath - relative to the location of "this" helper! * @returns {*|{}} */ static enumerateControllers(controllersPath = '../controllers/') { // Properly resolve the path that contains the Controllers const controllerRootPath = path.join(__dirname, controllersPath); // Start with an empty object let controllersObject = {}; // Enumerate by parsing into the main Controllers Path controllersObject = SwaggerRouterHelper.parseDirectories( controllerRootPath, controllersObject ); // Return the object return controllersObject; } /** * A recursive method that crawls a directory looking for JS files and * adds them to an object that lists them all together. * * This was inspired by https://github.com/DanWahlin/express-convention-routes * * The main flow of this method is: * - Inspect the directory passed (always starts with a directory) * - Enumerate each "item" in that directory * - If the item is a file that ends in '.js', adds it to the list of controllers * - If the item is a directory, recursively scans into that directory looking for more controllers * * @param directoryPath * @param controllersObject * @returns {*} */ static parseDirectories(directoryPath, controllersObject) { // Iterate over each item in the passed directory fs.readdirSync(directoryPath).forEach(function (fileListItem) { // Prepares the full name for the file (including the directory) let fullName = path.join(directoryPath, fileListItem); // Is the item a directory? let stat = fs.lstatSync(fullName); if (stat.isDirectory()) { // It is a directory, so recursively walk into it! controllersObject = SwaggerRouterHelper.parseDirectories( fullName, controllersObject ); } else if (path.extname(fileListItem) === '.js') { // Otherwise, found a .js controller fileListItem so register it controllersObject = { ...controllersObject, [path.basename(fullName, '.js')]: require(fullName), }; } }); // return the enumerated controllers up the chain return controllersObject; } }
JavaScript
class App extends Component { /** * Default places. */ basicPlaces = [ {id: 0, name: 'Castle in Lublin', lat: 51.2504931, lng: 22.5702397, customIcon: false}, {id: 1, name: 'Old Town', lat: 51.24875, lng: 22.568635, customIcon: false}, {id: 2, name: 'Plac Litewski', lat: 51.2481725, lng: 22.5595155, customIcon: false}, {id: 3, name: 'State Park', lat: 51.2485435, lng: 22.5481983, customIcon: false}, {id: 4, name: 'Centrum Spotkania Kultur', lat: 51.2470124, lng: 22.5489064, customIcon: false} ] /** * Places stored here after using search filter. */ filteredPlaces = [] /** * @property {object} this.state - The default values for state. * @property {array} state.places - The array of default places. * @property {string} state.infoName - The default value of name in Information about the location. * @property {string} state.infoAddr - The default value of address in Information about the location. */ state = { places: this.basicPlaces, infoName: '', infoAddr: '' } /** * Filter places after using search filter */ filterPlaces=(filterKey) => { // If input is not empty if(filterKey.length > 0) { // Filter this.basicPlaces and put results to this.filteredPlaces then update state this.filteredPlaces = this.basicPlaces.filter((el) => el.name.toLowerCase().includes(filterKey.toLowerCase())); this.setState((state) => { return {places: this.filteredPlaces}; }); } else { // Use basic places instead this.filteredPlaces = this.basicPlaces; this.setState({ places: this.filteredPlaces }); } } /** * Change marker when clicked button in search panel */ markerCheck=(id)=> { // name and address are loading this.setState({ infoName: 'loading...', infoAddr: 'loading...' }); // set react-foursquare basic parameters params['ll'] = `${this.state.places[id].lat},${this.state.places[id].lng}`; params['query'] = this.state.places[id].name; // fetch data from Foursquare API foursquare.venues.getVenues(params) .then(res => { // name and address temporary strings let infoNameTemp = '', infoAddrTemp = ''; // name and address are updated res.response.venues[0].name ? infoNameTemp = res.response.venues[0].name : infoNameTemp = ''; res.response.venues[0].location.address ? infoAddrTemp = res.response.venues[0].location.address : infoAddrTemp = ''; // name and address are are updated by state in React way this.setState({ infoName: infoNameTemp, infoAddr: infoAddrTemp }); }); // if this.filteredPlaces is empty use this.basicPlaces array of places if(this.filteredPlaces.length > 0) { this.filteredPlaces.forEach((el) => el.customIcon = false); this.filteredPlaces[id].customIcon = true; } else { this.basicPlaces.forEach((el) => el.customIcon = false); this.basicPlaces[id].customIcon = true; } } /** * Render view of this component. */ render() { return ( <div className="App"> <div> <Search places = {this.state.places} basicPlaces = {this.basicPlaces} filterPlaces = {this.filterPlaces} markerCheck = {this.markerCheck} infoName = {this.state.infoName} infoAddr = {this.state.infoAddr} ></Search> </div> <div style={{ height: '100vh', width: '100%' }}> <MapContainer places = {this.state.places} ></MapContainer> </div> </div> ); } }
JavaScript
class BlobsStorage { /** * Constructs a BlobsStorage instance. * * @param {string} connectionString Azure Blob Storage connection string * @param {string} containerName Azure Blob Storage container name * @param {BlobsStorageOptions} options Other options for BlobsStorage */ constructor(connectionString, containerName, options) { this._concurrency = Infinity; z.object({ connectionString: z.string(), containerName: z.string() }).parse({ connectionString, containerName, }); this._containerClient = new storage_blob_1.ContainerClient(connectionString, containerName, options === null || options === void 0 ? void 0 : options.storagePipelineOptions); // At most one promise at a time to be friendly to local emulator users if (connectionString.trim() === 'UseDevelopmentStorage=true;') { this._concurrency = 1; } } // Protects against JSON.stringify cycles toJSON() { return { name: 'BlobsStorage' }; } _initialize() { if (!this._initializePromise) { this._initializePromise = this._containerClient.createIfNotExists(); } return this._initializePromise; } /** * Loads store items from storage. * * @param {string[]} keys Array of item keys to read * @returns {Promise<StoreItems>} The fetched [StoreItems](xref:botbuilder-core.StoreItems) */ read(keys) { return __awaiter(this, void 0, void 0, function* () { z.object({ keys: z.array(z.string()) }).parse({ keys }); yield this._initialize(); return (yield p_map_1.default(keys, (key) => __awaiter(this, void 0, void 0, function* () { const result = { key, value: undefined }; const blob = yield ignoreError_1.ignoreError(this._containerClient.getBlobClient(sanitizeBlobKey_1.sanitizeBlobKey(key)).download(), ignoreError_1.isStatusCodeError(404)); if (!blob) { return result; } const { etag: eTag, readableStreamBody: stream } = blob; if (!stream) { return result; } const contents = yield get_stream_1.default(stream); const parsed = JSON.parse(contents); result.value = Object.assign(Object.assign({}, parsed), { eTag }); return result; }), { concurrency: this._concurrency, })).reduce((acc, { key, value }) => (value ? Object.assign(Object.assign({}, acc), { [key]: value }) : acc), {}); }); } /** * Saves store items to storage. * * @param {StoreItems} changes Map of [StoreItems](xref:botbuilder-core.StoreItems) to write to storage * @returns {Promise<void>} A promise representing the async operation */ write(changes) { return __awaiter(this, void 0, void 0, function* () { z.record(z.unknown()).parse(changes); yield this._initialize(); yield p_map_1.default(Object.entries(changes), (_a) => { var [key, _b] = _a, { eTag = '' } = _b, change = __rest(_b, ["eTag"]); const blob = this._containerClient.getBlockBlobClient(sanitizeBlobKey_1.sanitizeBlobKey(key)); const serialized = JSON.stringify(change); return blob.upload(serialized, serialized.length, { conditions: typeof eTag === 'string' && eTag !== '*' ? { ifMatch: eTag } : {}, }); }, { concurrency: this._concurrency, }); }); } /** * Removes store items from storage. * * @param {string[]} keys Array of item keys to remove from the store * @returns {Promise<void>} A promise representing the async operation */ delete(keys) { return __awaiter(this, void 0, void 0, function* () { z.object({ keys: z.array(z.string()) }).parse({ keys }); yield this._initialize(); yield p_map_1.default(keys, (key) => ignoreError_1.ignoreError(this._containerClient.deleteBlob(sanitizeBlobKey_1.sanitizeBlobKey(key)), ignoreError_1.isStatusCodeError(404)), { concurrency: this._concurrency, }); }); } }
JavaScript
class AdminHome extends Component { constructor (props) { super(props) this.state = { username: this.props.username } } componentWillMount () { this.setState({ username: this.props.username }) this.props.getUserProfile({ username: this.props.username }) } componentDidUpdate (prevProps, prevState) { if (!_.isEqual(prevProps.username, this.props.username)) { this.props.getUserProfile({ username: this.props.username }) this.setState({ username: this.props.username }) } } componentDidMount () { // this.props.fetchUser({id: this.props.loginToken}) } render () { return ( <div> <Segment style={{ padding: '8em 0em', minHeight: window.innerHeight }} vertical> <Grid container stackable verticalAlign='middle'> <Grid.Row> <Grid.Column width={8}> <p>Admin Home</p> </Grid.Column> </Grid.Row> </Grid> </Segment> <Segment inverted vertical style={{ padding: '5em 0em' }}> {/* <FooterContainer /> */} </Segment> </div> ) } }
JavaScript
class CanvasApiClient { /** * Create a new API client instance * @param {String} baseUrl Root URL of the Canvas instance * @param {String} apiKey Permanent OAuth API key to use for authenticating requests */ constructor(baseUrl, apiKey) { // Create the Request HTTP client this.client = Request.defaults({ baseUrl: baseUrl, headers: { Authorization: `Bearer ${apiKey}` }, json: true, simple: true, time: true, timeout: 20000, transform: (body, response, resolveWithFullResponse) => { // Track Canvas API usage Logger.info(`Canvas API usage`, { rateLimitRemain: parseFloat(response.headers['x-rate-limit-remaining']), requestCost: parseFloat(response.headers['x-request-cost']) }); return (resolveWithFullResponse) ? response : body; } }); } /** * User accounts */ /** * Lookup a user account profile in Canvas. * @param {String} sisLoginId Banner login identity for the person * @returns {Promise} Resolved with the Canvas user profile object */ getUser(userId, type='sis_user_id:') { return this.client({ method: `GET`, uri: `/users/${type}${userId}/profile`, headers: { Accept: 'application/json+canvas-string-ids' } }) .promise() .catch(error => { if(error.statusCode === 404) { Logger.verbose(`Could not find user profile in Canvas`, {type: type, userId: userId}); return null; } return Promise.reject(error); }); } /** * Create or update a user account in Canvas with the minimum viable * attributes for the SIS login ID, first name, last name, and a contact * e-mail address. Tries to avoid unnecessary operations if the Canvas * account already appears to be in sync with the values provided. * @param {String} sisLoginId Banner login identity for the person * @param {String} firstName First name from Banner * @param {String} lastName Last name from Banner * @param {String} email Contact e-mail address from Banner * @returns {Promise} Resolved with the Canvas user profile object after the update */ async syncUser(person) { let parent = this; Logger.info(`Preparing to sync Canvas account`, { campusId: person.sisLoginId, firstName: person.firstName, lastName: person.lastName, email: person.email }); // Validate the e-mail address (this can be sticky issue if // the address appears corrupt) if(person.email === undefined || person.email === null) { throw new Error(`Cannot synchronize ${person.sisLoginId} because e-mail address is missing. Please verify the source SIS data is correct`); } else if(Email.validate(person.email) === false) { throw new Error(`Cannot synchronize ${person.sisLoginId} because e-mail address '${person.email}' failed to validate. Please verify the source SIS data is correct`); } // Fetch user profile from Canvas let profile = await this.getUser(person.sisLoginId); // Evaluate result to determine next action if(profile === null) { // Create new account return parent.createUser(person); } else if(profile.name !== `${person.firstName} ${person.lastName}` || profile.sortable_name !== `${person.lastName}, ${person.firstName}`) { // Sync account due to name change return parent.updateUser(person); } else if(profile.primary_email !== person.email) { // Sync account due to e-mail change return parent.updateUser(person); } return profile; } createUser(person) { Logger.info(`Creating new Canvas account`, { sisLoginId: person.sisLoginId, firstName: person.firstName, lastName: person.lastName, email: person.email }); return this.client({ method: `POST`, uri: `/accounts/1/users`, form: { 'user[name]': `${person.firstName} ${person.lastName}`, 'user[short_name]': `${person.firstName} ${person.lastName}`, 'user[sortable_name]': `${person.lastName}, ${person.firstName}`, 'user[skip_registration]': 'true', 'user[terms_of_use]': 'true', 'pseudonym[unique_id]': person.sisLoginId, 'pseudonym[sis_user_id]': person.sisLoginId, 'pseudonym[skip_confirmation]': 'true', 'pseudonym[integration_id]': (person.cccId) ? person.cccId : undefined, 'enable_sis_reactivation': 'true', 'communication_channel[address]': (person.email) ? person.email : '[email protected]', 'communication_channel[type]': 'email', 'communication_channel[skip_confirmation]': 'true' } }) .catch(error => { Logger.error(`Failed to create new Canvas account`, [error, { sisLoginId: person.sisLoginId, firstName: person.firstName, lastName: person.lastName, email: person.email }]); if(error.message.includes('ID already in use')) { return Promise.reject(new Error(`Failed to create new Canvas account for ${person.sisLoginId}, ${person.lastName}, ${person.firstName}. An existing account was already found in Canvas with ${person.sisLoginId} for the username.`)); } else { return Promise.reject(error); } }); } updateUser(person) { Logger.info(`Updating existing Canvas accont`, { sisLoginId: person.sisLoginId, firstName: person.firstName, lastName: person.lastName, email: person.email }); return this.client({ method: `PUT`, uri: `/users/sis_user_id:${person.sisLoginId}`, form: { 'user[name]': person.firstName + ' ' + person.lastName, 'user[short_name]': person.firstName + ' ' + person.lastName, 'user[sortable_name]': person.lastName + ', ' + person.firstName, 'user[email]': (person.email) ? person.email : '[email protected]' } }) .catch(error => { Logger.error(`Failed to update existing Canvas account` [error, { sisLoginId: person.sisLoginId, firstName: person.firstName, lastName: person.lastName, email: person.email }]); return Promise.reject(error); }); } /** * Courses */ /** * Get a course object from Canvas by its unique ID * @param {String|Number} id Canvas course ID * @returns {Promise} Resolved with the requested object */ getCourse(id) { return this.client .get(`/courses/${id}`) .promise(); } /** * Create a new course in Canvas with parameters set by the provided * object map. * @param {Object} payload Object of key-value properties following the Instructure API documentation * @returns {Promise} Resolved with the newly created Canvas course object */ createCourse(payload) { return this.client({ method: `POST`, uri: `/accounts/1/courses`, form: payload }) .promise() .tap(course => { Logger.verbose('Created new Canvas course', course); }); } /** * Delete an existing course in Canvas by its unique ID. * @param {String|Number} id Canvas course ID * @returns {Promise} Resolved with the now deleted Canvas course object */ deleteCourse(id) { return this.getCourse(id) .tap(course => { return this.client({ method: `DELETE`, uri: `/courses/${course.id}`, useQuerystring: true, qs: { 'event': 'delete' } }); }) .tap(course => { Logger.info('Deleted Canvas course', course); }); } /** * Get a list of the Canvas courses that a user is associated with, * filtered by the SIS ID for a specific enrollment term. * @param {String} termCode Banner term code * @param {String} sisLoginId Banner login identity for the person * @param {Boolean} [withSections=false] If true, perform a secondary lookup and get the Canvas section objects for the course * @returns {Promise} Resolved with an array of Course objects * */ getCoursesForUser(termCode, sisLoginId, withSections=false, enrollmentType=['student']) { let parent = this; return Promise.all([ this.getEnrollmentTermBySisId(termCode), this.requestWithPagination({ method: 'GET', uri: `/users/sis_user_id:${sisLoginId}/courses`, useQuerystring: true, qs: { 'state[]': ['unpublished', 'available'], 'enrollment_type': enrollmentType, 'per_page': '100' } })]) .spread((enrollmentTerm, courses) => { // Filter result courses by enrollment term ID return courses.filter(course => { return course.enrollment_term_id === enrollmentTerm.id; }); }) .map(course => { // Skip section transform if not requested if(!(withSections)) { return course; } // Add promise to be fufilled with info about course sections // Filter objects that do not have an SIS ID (these are typically the root course in the site) course.sections = parent.client .get(`/courses/${course.id}/sections`) .promise() .filter(section => section.sis_section_id !== null); // Transform course with pending promises return Promise.props(course); }); } async getCoursesForEnrollmentTerm(enrollmentTermId, state=['created', 'claimed', 'available']) { // Execute request using internal pagination helper function return await this.requestWithPagination({ method: 'GET', uri: `/accounts/1/courses`, useQuerystring: true, qs: { 'per_page': '100', 'completed': 'false', 'enrollment_term_id': enrollmentTermId, 'state[]': state } }); } /** * Enrollment Terms */ /** * Get all enrollment terms defined in a Canvas college account. * @returns {Promise} Resolved with an array of EnrollmentTerm objects * */ getEnrollmentTerms() { return this.client .get(`/accounts/1/terms`) .then(response => { return response.enrollment_terms; }); } /** * Get a specific Canvas enrollment term by its native ID. * @param {Number} id Enrollment term ID * @returns {Promise} Resolved with the matching EnrollmentTerm object, or an empty array if not found */ getEnrollmentTerm(id) { return this .getEnrollmentTerms() .reduce((result, enrollmentTerm) => { if(enrollmentTerm.id === id) { return enrollmentTerm; } return result; }); } /** * Get a specific Canvas enrollment term by its SIS ID. * @param {String} sisId Banner term code * @returns {Promise} Resolved with the matching EnrollmentTerm object, or undefined if not found */ async getEnrollmentTermBySisId(sisId) { let enrollmentTerms = await this.getEnrollmentTerms(); // Iterate enrollment term objects, find one to match the SIS ID for(let term of enrollmentTerms) { if(term.sis_term_id === sisId) { // Terminate the loop and return the identified enrollment term return term; } } return undefined; } /** * Get a list of enrollments for a specific user, for a specific Banner * SIS term, and optionally filtered by an enrollment status other than * 'active'. * @param {String} termCode Banner term code * @param {String} sisLoginId Banner login identity for the person * @param {String} [state=active] Enrollment state to filter to further narrow results */ getEnrollmentsForUser(termCode, sisLoginId, state='active') { return this.client .get(`/users/sis_user_id:${sisLoginId}/enrollments`) .promise() .map(enrollment => { // If possible, parse Banner SIS section ID to get the term and CRN if(enrollment.sis_section_id) { let parsedSectionId = Common.parseSisSectionId(enrollment.sis_section_id); // Decorate enrollment enrollment.bannerTerm = parsedSectionId.term; enrollment.bannerCrn = parsedSectionId.crn; } // Return object return enrollment; }) // Filter by specific Banner term and enrollment state .filter(enrollment => enrollment.bannerTerm === termCode && enrollment.enrollment_state === state); } /** * Sections */ /** * Get a Canvas section by its unique ID * @param {String|Number} id Canvas section ID * @returns {Promise} Resolved with the Section object if found */ getSection(id) { return this.client .get(`/sections/${id}`) .catch(error => { if(error.statusCode === 404) { Logger.verbose(`Could not find section ${id} in Canvas`); return null; } return Promise.reject(error); }); } async getSectionsForCourse(courseId) { return await this.client .get(`/courses/${courseId}/sections`); } /** * Create a new Canvas section in an existing course. * @param {String|Number} courseId ID for the Canvas course where the section will be created * @param {String} name Name of the section (will be visible to users) * @param {String} term Banner term (used in the SIS section ID) * @param {String} crn Banner section CRN (used in the SIS section ID) * @returns {Promise} Resolved with the newly created Section object */ createSection(courseId, name, term, crn) { let generatedSisId = `${term}:${crn}:${Random.number(4)}`; return this.client({ method: `POST`, uri: `/courses/${courseId}/sections`, form: { 'course_section[name]': name, 'course_section[sis_section_id]': generatedSisId, 'course_section[integration_id]': generatedSisId } }) .promise() .tap(section => { // Audit log Logger.verbose(`Created new Canvas section`, [{term: term, crn: crn}, section]); }); } /** * Delete an existing Canvas section. <em>Note: this function does not take * care of any enrolled students in the section. These must be deleted * from the section prior to calling this API.</em> * @param {String|Number} id Canvas section ID * @returns {Promise} Resolved with the now deleted Section object */ deleteSection(id) { return this.client .del(`/sections/${id}`) .promise() .tap(section => { // Audit log Logger.verbose(`Deleted Canvas section`, section); }); } /** * Enrollments */ /** * Get an Enrollment object from Canvas. * @param {String|Number} id Canvas enrollment ID * @returns {Promise} Resolved with the Enrollment object if found */ getEnrollment(id) { return this.client .get(`/accounts/1/enrollments/${id}`) .promise(); } /** * Get all Enrollment objects for a Canvas course. By default, the * result is limited to only active students in a course. * @param {String|Number} id Canvas course ID * @returns {Promise} Resolved with an array of Enrollment objects */ async getCourseEnrollment(id, type=['StudentEnrollment'], state=['active']) { // Execute request using internal pagination helper function return await this.requestWithPagination({ method: 'GET', uri: `/courses/${id}/enrollments`, useQuerystring: true, qs: { 'per_page': `100`, 'type[]': type, 'state[]': state, 'role[]': 'StudentEnrollment' } }); } /** * Get all student Enrollment objects for an existing Canvas section. * @param {String|Number} id Canvas section ID * @returns {Promise} Resolved with an array of Enrollment objects */ async getSectionEnrollment(id, type=['StudentEnrollment'], state=['active']) { // Execute request using internal pagination helper function return await this.requestWithPagination({ method: 'GET', uri: `/sections/${id}/enrollments`, useQuerystring: true, qs: { 'per_page': `100`, 'type[]': type, 'state[]': state } }); } /** * Enroll an instructor into an existing Canvas course. * @param {String|Number} courseId Canvas course ID * @param {String|Number} userId Canvas user account ID * @returns {Promise} Resolved with the new instructor Enrollment object */ enrollInstructor(courseId, userId) { return this.client({ method: `POST`, uri: `/courses/${courseId}/enrollments`, form: { 'enrollment[user_id]': userId, 'enrollment[type]': 'TeacherEnrollment', 'enrollment[enrollment_state]': 'active', 'enrollment[notify]': 'false' } }) .promise() .tap(enrollment => { Logger.verbose(`Enrolled instructor into Canvas course`, enrollment); }); } enrollInstructorSection(sectionId, userId) { return this.client({ method: `POST`, uri: `/sections/${sectionId}/enrollments`, form: { 'enrollment[user_id]': userId, 'enrollment[type]': 'TeacherEnrollment', 'enrollment[enrollment_state]': 'active', 'enrollment[notify]': 'false' } }) .promise() .tap(enrollment => { Logger.verbose(`Enrolled instructor into Canvas section`, enrollment); }); } /** * Enroll a student into an existing Canvas section. * @param {String|Number} sectionId Canvas section ID * @param {String|Number} userId Canvas user account ID * @returns {Promise} Resolved with the new student Enrollment object */ enrollStudent(sectionId, userId) { return this.client({ method: `POST`, uri: `/sections/${sectionId}/enrollments`, form: { 'enrollment[user_id]': userId, 'enrollment[type]': 'StudentEnrollment', 'enrollment[enrollment_state]': 'active', 'enrollment[notify]': 'false' } }) .promise() .tap(enrollment => { Logger.verbose(`Enrolled student into Canvas course`, enrollment); }); } /** * Drop a student from an existing Canvas section. Dropping a student means * inactivating their enrollment in Canvas. This leaves the door open for * a student to be re-enrolled in the class without losing any prior work. * @param {Object} enrollment The enrollment in Canvas to inactivate * @returns {Promise} Resolved with now inactivated student Enrollment object */ dropStudent(enrollment) { // Execute enrollment inactivate API call return this.client({ method: 'DELETE', uri: `/courses/${enrollment.course_id}/enrollments/${enrollment.id}`, form: { 'task': 'inactivate' } }) .promise() .tap(enrollment => { Logger.verbose(`Dropped student from Canvas section`, enrollment); }); } /** * Delete a student from an existing Canvas section. Deleting a student * means any of record of them in the section, including prior work, is * completely removed and cannot be restored. * @param {Object} enrollment The enrollment in Canvas to delete * @returns {Promise} Resolved with now deleted student Enrollment object */ deleteStudent(enrollment) { // Execute enrollment delete API call return this.client({ method: 'DELETE', uri: `/courses/${enrollment.course_id}/enrollments/${enrollment.id}`, form: { 'task': 'delete' } }) .promise() .tap(enrollment => { Logger.verbose(`Dropped student from Canvas section`, enrollment); }); } /** * Mark a student enrollment concluded in a Canvas course. Does not delete * the student from the course, and puts their access to the course into * read-only mode. * @param {Object} enrollment The enrollment in Canvas to conclude * @returns {Promise} Resolved when operation is complete */ async concludeStudent(enrollment) { await this.client({ method: 'DELETE', uri: `/courses/${enrollment.course_id}/enrollments/${enrollment.id}`, form: { 'task': 'conclude' } }); Logger.verbose(`Concluded student enrollment`, enrollment); } /** * Helper function to look up and delete all active student enrollments * from an existing Canvas section. * @param {String} id Canvas section object ID * @returns {Promise} Resolved with an array of the deleted student Enrollment objects */ deleteSectionEnrollments(id) { let parent = this; // Step 1: List all student enrollments for the section return this.getSectionEnrollment(id) .promise() // Step 2: Remove each enrollment from the section .map(enrollment => { return parent.deleteStudent(enrollment); }, Common.concurrency.MULTI) .tap(enrollments => { // Validate that enrollment objects existed if(enrollments.length > 0) { // Audit log Logger.info(`Completed removal of all enrolled students from Canvas section`, { count: enrollments.length, sisCourseId: enrollments[0].sis_course_id, sisSectionId: enrollments[0].sis_section_id }); } }); } /** * Student Grading and Scoring * */ /** * Lookup all of the student enrollments in a course, and return only * relevant student information along with their final score or grade. * @param {String} id Canvas course ID to lookup. */ async getFinalCourseGrades(id) { // Get enrollment records let enrollments = await this.getCourseEnrollment(id); // Limit to only records that contain valid data return enrollments.filter(enrollment => enrollment.grades.final_score > 0 && enrollment.sis_user_id !== null); } /* async getFinalSectionGrades(id) { // TODO: Develop later } */ /** * User custom data */ async setCustomData(userId, namespace, scope, data) { await this.client({ method: 'PUT', uri: `/users/59/custom_data/${scope}`, form: { ns: namespace, data: data } }); } async getCustomData(userId, namespace, scope) { try { // Execute GET request to fetch custom data let result = await this.client({ method: 'GET', uri: `/users/59/custom_data/${scope}`, qs: { ns: namespace } }); // Return data field return result.data; } catch(error) { // If the custom data point is missing, simply return null to the caller if(error.error.message === 'no data for scope') { return null; } // Raise an error condition for every other outcome throw error; } } /* * Content Migrations */ /** * Get a list of courses owned by a user that would make for ideal sources * for setting up an automatic content migration into a new course. * @param {String} sisLoginId Banner login identity for the person * @returns {Promise|Array} Resolved with a list of potential courses */ listMigrationSources(sisLoginId) { return this.client({ method: `GET`, uri: `/users/sis_user_id:${sisLoginId}/courses`, qs: { 'include[]': 'term', 'state[]': ['unpublished', 'available'], 'per_page': '250', } }) .promise(); } /** * List active migration tasks for a Canvas course. Active means the workflow * status is not "completed". * @param {String} courseId Canvas course ID * @returns {Promise|Array} Resolved with list of active migration tasks */ listActiveMigrations(courseId) { return this.client .get(`/courses/${courseId}/content_migrations`) .promise() .filter(migration => migration.workflow_state !== 'completed'); } /** * Create a new migration task using an existing course site as the course, * and targeting another existing course site that is presumed empty. * @param {String} fromCourseId Canvas course ID for the source * @param {String} toCourseId Canvas course ID for the target * @returns {Promise} Resolved when the migration task was created */ createMigration(fromCourseId, toCourseId) { return this.client({ method: `POST`, uri: `/courses/${toCourseId}/content_migrations`, form: { 'migration_type': 'course_copy_importer', 'settings[source_course_id]': fromCourseId } }) .promise(); } async requestWithPagination(requestOpts) { let finalResult = []; let hasPagesRemaining = false; // REM let paginationUrl = null; let requestedPageCount = 0; let totalPages = 1; // Parse page count from request if(requestOpts.qs['per_page']) { requestedPageCount = parseInt(requestOpts.qs['per_page']); } else if(requestOpts.form['per_page']) { requestedPageCount = parseInt(requestOpts.form['per_page']); } // Fetch the initial page let pageResponse = await this.client( // Enforce sensible defaults so that pagination can function properly Object.assign(requestOpts, { resolveWithFullResponse: true, })); // Append internal result array finalResult = finalResult.concat(pageResponse.body); Logger.debug(`Fetched page ${totalPages}, entry count: ${pageResponse.body.length}, page count per request: ${requestedPageCount}`); // Parse pagination orders let paginationOrders = this.parseCanvasPagination(pageResponse.headers.link); hasPagesRemaining = paginationOrders.next !== undefined; // Continue fetching additional pages if possible while(hasPagesRemaining) { Logger.debug(`Next page still available`, { hasPagesRemaining: hasPagesRemaining, orders: paginationOrders }); totalPages++; // Fetch next page pageResponse = await this.client({ method: requestOpts.method, baseUrl: null, uri: paginationOrders.next, resolveWithFullResponse: true }); // Append internal result array finalResult = finalResult.concat(pageResponse.body); Logger.debug(`Fetched page ${totalPages}, entry count: ${pageResponse.body.length}, page count per request: ${requestedPageCount}`); // Parse pagination orders paginationOrders = this.parseCanvasPagination(pageResponse.headers.link); hasPagesRemaining = paginationOrders.next !== undefined; } Logger.debug(`Completed fetching pages`); return finalResult; } /** * Utility function to parse content from a standard formatted HTTP Link * header, and transform the output into a simple key-value object * where rel: url. * @param {String} linkHeader String content of the Link header from an HTTP request * @returns {Object} One or more links mapped to the rel name */ parseCanvasPagination(linkHeader) { return HttpLinkHeader .parse(linkHeader) .refs .reduce((result, ref) => { result[ref.rel] = ref.uri; return result; }, {}); } }
JavaScript
class Force extends React.Component { state = { force: [], forcewidgets: [], forcefeatures: [], forcebackgroundimage: [], error: null, }; componentDidMount = async () => { document.documentElement.scrollTop = 0; document.scrollingElement.scrollTop = 0; this.refs.main.scrollTop = 0; const parseJSON = resp => (resp.json ? resp.json() : resp); const checkStatus = resp => { if (resp.status >= 200 && resp.status < 300) { return resp; } return parseJSON(resp).then(resp => { throw resp; }); }; const headers = { 'Content-Type': 'application/json', }; try { const force = await fetch(`${appConfig.apiURL}/force`, { method: 'GET', headers: headers, }) .then(checkStatus) .then(parseJSON); this.setState({ force, forcebackgroundimage: force.image, forcefeatures: force.featuresarray.features }); } catch (error) { this.setState({ error }); } try { const forcewidgets = await fetch(`${appConfig.apiURL}/forcewidgets`, { method: 'GET', headers: headers, }) .then(checkStatus) .then(parseJSON); this.setState({ forcewidgets }); } catch (error) { this.setState({ error }); } }; handleEndReached = () => { console.log("load more"); }; render() { const { error, force, forcewidgets, forcefeatures} = this.state; console.log(force); // Print errors if any if (error) { return <div>An error occured: {error.message}</div>; } return ( <> <DemoNavbar /> <main ref="main"> <div className="position-relative"> {/* shape Hero */} <section className="section section-lg section-shaped pb-250"> <div className="shape shape-default" style= {{ backgroundPosition: "center", backgroundImage: `url(${require('assets/img/theme/force-device-on-wooden-texture-with-layer-min-final.jpg')})` //backgroundImage:`url("${forcebackgroundimage.url}")`, }}> <span /> <span /> <span /> <span /> <span /> <span /> <span /> <span /> <span /> </div> <Container className="py-lg-md d-flex"> <div className="col px-0"> <Row> <Col lg="8"> <div> <h1 className="display-1 text-white text-lead" style={{ textAlign : "left" ,fontFamily: "Noto Sans JP", fontSize: "48px", fontWeight: "900", marginTop: "90px" , lineHeight: "125%" }}> {/*Empowered to save Power*/}{force.Title}</h1><br /> <h3 className="display-4 text-info mt-2" style={{ textAlign : "left" , marginBottom : "90px" }}> {/*Force is a smart, dual-action device which helps both increase the flow of electricity, and absorb any electrical losses. It's installed next to your electricity meter.*/} {force.subtitle} </h3> </div> </Col> </Row> </div> </Container> {/* SVG separator */} <div className="separator separator-bottom separator-skew"> <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="fill-white" points="2560 0 2560 100 0 100" /> </svg> </div> </section> {/* 1st Hero Variation */} </div> <section className="section section-lg pt-lg-0 mt--200"> <Container> <Row className="justify-content-center"> <Col lg="12"> <Row className="row-grid"> {forcewidgets.map(widgets => ( <Col lg="4" key={widgets.id}> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4"> <div className=" rounded-circle mb-2"> <img alt="..." className="rounded-circle img-center img-fluid" src={`${widgets.image.url}`} style={{ width: "100px" }}/> </div> <h6 className={"text-" + widgets.classname + " text-uppercase text-center"}> {/*About Company*/} {widgets.Title} </h6> <p className="description mt-3" style={{ textAlign : "left" }}> {widgets.description} </p> </CardBody> </Card> </Col> ))} {/*<Col lg="4"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4"> <div className=" rounded-circle mb-2"> <img alt="..." className="rounded-circle img-center img-fluid" src={`${require("assets/img/theme/force_1_ceb4e9e6.png")}`} style={{ width: "100px" }}/> </div> <h6 className="text-success text-uppercase text-center"> Environmentally Friendly </h6> <p className="description mt-3" style={{ textAlign : "left" }}> FORCE uses eco-friendly technology to save electricity. It uses the naturally occurring material tourmaline, which helps generate anions. </p> </CardBody> </Card> </Col> <Col lg="4"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4"> <div className=" rounded-circle mb-2"> <img alt="..." className="rounded-circle img-center img-fluid" src={`${require("assets/img/theme/force_2.128f9e8d.png")}`} style={{ width: "100px" }}/> </div> <h6 className="text-info text-uppercase text-center"> Safe </h6> <p className="description mt-3" style={{ textAlign : "left" }}> FORCE does not require a separate power supply, making it safe to install when the power is off. It's both easy to install and use.</p> </CardBody> </Card> </Col> <Col lg="4"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4"> <div className=" rounded-circle mb-2"> <img alt="..." className="rounded-circle img-center img-fluid" src={`${require("assets/img/theme/force_3.f7979078.png")}`} style={{ width: "100px" }}/> </div> <h6 className="text-primary text-uppercase text-center"> Versatile </h6> <p className="description mt-3" style={{ textAlign : "left" }}> FORCE can make a difference for virtually any use of electricity throughout your property. <br /><br /></p> </CardBody> </Card> </Col>*/} </Row> </Col> </Row> </Container> </section> <section className="section pb-0 bg-gradient-default"> <Container> <Row className="row-grid"> <Col lg="12"> <h1 className="display-3 text-white justify-content-center" style={{ textAlign : "left" , fontSize: "48px", fontWeight: "800px"}}> {/*Features*/}{force.featuresheading}</h1> </Col> </Row> <Row className="row-grid"> <Col lg="1"> </Col> {forcefeatures.map(feature => ( <Col lg="2" key={feature.id}> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-3"> <div className={"icon icon-shape icon-shape-"+feature.classname+" rounded-circle mb-4 text-dark"}> {feature.id} </div> <h6 className="text-dark"> <ReactMarkdown source={feature.feature} allowDangerousHtml={true} /> </h6> </CardBody> </Card> </Col> ))} </Row> {/*<Row className="row-grid"> <Col lg="1"> </Col> <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4 text-center"> <div className="icon icon-shape icon-shape-danger rounded-circle mb-4 text-dark"> 1 </div> <h6 className="text-dark"> Saves electricity by 5-15%<br /><br /> </h6> </CardBody> </Card> </Col> <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4 text-center"> <div className="icon icon-shape icon-shape-darker rounded-circle mb-4 text-dark"> 2 </div> <h6 className="text-dark"> Prolongs the life span of your appliances </h6> </CardBody> </Card> </Col> <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4 text-center"> <div className="icon icon-shape icon-shape-warning rounded-circle mb-4 text-dark"> 3 </div> <h6 className="text-dark"> Reduces harmonic distortion<br /><br /> </h6> </CardBody> </Card> </Col> <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4 text-center"> <div className="icon icon-shape icon-shape-primary rounded-circle mb-4 text-dark"> 4 </div> <h6 className="text-dark"> Increases conductivity<br /><br /><br /> </h6> </CardBody> </Card> </Col> <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4 text-center"> <div className="icon icon-shape icon-shape-success rounded-circle mb-4 text-dark"> 5 </div> <h6 className="text-dark"> Reduces impedance<br /><br /><br /> </h6> </CardBody> </Card> </Col> {/*} <Col lg="2"> <Card className="card-lift--hover shadow border-0"> <CardBody className="py-4"> <div className="icon icon-shape icon-shape-success rounded-circle mb-4 text-dark"> 6 </div> <h6 className="text-dark"> Force don't consume any power by itself. </h6> </CardBody> </Card> </Col> </Row>*/}<br /><br /> </Container> <div className="separator separator-bottom separator-skew zindex-100"> <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="fill-white" points="2560 0 2560 100 0 100" /> </svg> </div> </section> {/*} <section className="section pb-0 bg-gradient-default"> <Container > <h3 className="text-white">Brilliant Benefits</h3> <Row className="row-grid align-items-center"> <Col className="order-md-1" lg="6"> <div className="pr-md-5"> <ul className="list-unstyled mt-5"> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="primary"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Eco Friendly</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="danger"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white">Highly Safe</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="info"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Easy to install</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="success"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Versatile</h6> </div> </div> </li> </ul></div></Col> <Col className="order-md-1" lg="6"> <div className="pr-md-5"> <ul className="list-unstyled mt-5"> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="danger"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Energy saver</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="success"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Excellent technology</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="warning"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> Economically viable solution</h6> </div> </div> </li> <li className="py-2"> <div className="d-flex align-items-center"> <div> <Badge className="badge-circle mr-3" color="info"> <i className="ni ni-settings-gear-65" /> </Badge> </div> <div> <h6 className="mb-0 text-white"> High reliability</h6> </div> </div> </li> </ul> </div> </Col> </Row><br /> </Container>*/} {/* SVG separator */} {/* <div className="separator separator-bottom separator-skew zindex-100"> <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="fill-white" points="2560 0 2560 100 0 100" /> </svg> </div> </section>*/} </main> <CardsFooter /> </> ); } }
JavaScript
class BlockCodeEditor extends Component { constructor(props) { super(props); } static propTypes = { lidlAst: PropTypes.array.isRequired, onChange: PropTypes.func.isRequired }; state = { code: this.props.lidlAst }; // handleChange(newVal) { // // console.log("change Container : " +JSON.stringify(newVal)); // this.setState({ // code: newVal // }); // } /*style={{ overflow: 'auto', display: 'inline-block', verticalAlign: 'top' }}*/ render() { // console.log(this.props.value[0]) // TODO here we render only the first interaction : this.state.code[0] if(this.props.lidlAst===null || this.props.lidlAst===undefined) { return <div style={{textAlign:'center'}}><CircularProgress style={{margin:"20px"}} mode="indeterminate" /></div>; }else { return ( <div> <Interaction onChange = {this.props.onChange} val={this.props.lidlAst[0].interaction}/> </div> );} } }
JavaScript
class HomeContainer extends React.Component { render() { return ( <Panel> <Row> <Col xs={12} md={6}> <PocketCalculator /> </Col> <Col xs={12} md={6}> <div className="song_lyrics"> <p> I'm the operator<br/> With my pocket calculator<br/> I'm the operator<br/> With my pocket calculator </p> <p> I am adding<br/> And subtracting<br/> I'm controlling<br/> And composing </p> <p> By pressing down a special key<br/> It plays a little melody<br/> By pressing down a special key<br/> It plays a little melody </p> </div> <div className="song_byline"> <p>- Kraftwerk</p> </div> </Col> </Row> </Panel> ); } }
JavaScript
class Component { /** * @constructor */ constructor() { /** * @description * ID of the component. * @type {number} */ this.id = uid(); /** * @description * Container for the component. * @type {JQuery} */ this.container = null; /** * @readonly * @description * If `true` the component is currently visible. * @type {boolean} */ this.visible = false; /** * @description * Set to `true` to keep the component hidden. * @type {boolean} */ this.hidden = false; } /** * @description * Load the component and append to `container`. * @param {JQuery} container Container to load into. * @returns {Component|JQueryPromise} Returns itself for chaining. */ load(container) { const $ = getJQuery(); this.container = $('<div />').appendTo(container); return this; } /** * @description * Update the component with a data source. * @param {object} data Data to bind to the component. * @returns {Component|JQueryPromise} Returns itself for chaining. */ update(data) { return this; } /** * @description * Unload the component. * @returns {void} */ unload() { if (this.container) this.container.remove(); this.container = null; } /** * @description * Show the component if `hide` is `false`. * @returns {Component} Returns itself for chaining. */ show() { if (this.container && !this.hidden) this.container.show(); this.visible = false; return this; } /** * @description * Hide the component. * @returns {Component} Returns itself for chaining. */ hide() { if (this.container && !this.hidden) this.container.hide(); this.visible = !this.hidden; return this; } }
JavaScript
class HasManyQueryClient { constructor(relation, parent, client) { this.relation = relation; this.parent = parent; this.client = client; } /** * Generate a related query builder */ static query(client, relation, row) { const query = new QueryBuilder_1.HasManyQueryBuilder(client.knexQuery(), client, row, relation); typeof relation.onQueryHook === 'function' && relation.onQueryHook(query); return query; } /** * Generate a related eager query builder */ static eagerQuery(client, relation, rows) { const query = new QueryBuilder_1.HasManyQueryBuilder(client.knexQuery(), client, rows, relation); query.isRelatedPreloadQuery = true; typeof relation.onQueryHook === 'function' && relation.onQueryHook(query); return query; } /** * Returns an instance of the sub query */ static subQuery(client, relation) { const query = new SubQueryBuilder_1.HasManySubQueryBuilder(client.knexQuery(), client, relation); typeof relation.onQueryHook === 'function' && relation.onQueryHook(query); return query; } /** * Returns instance of query builder */ query() { return HasManyQueryClient.query(this.client, this.relation, this.parent); } /** * Save related model instance */ async save(related) { await utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); this.relation.hydrateForPersistance(this.parent, related); related.$trx = trx; await related.save(); }); } /** * Save related model instance */ async saveMany(related) { const parent = this.parent; await utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await parent.save(); for (let row of related) { this.relation.hydrateForPersistance(this.parent, row); row.$trx = trx; await row.save(); } }); } /** * Create instance of the related model */ async create(values) { return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); const valuesToPersist = Object.assign({}, values); this.relation.hydrateForPersistance(this.parent, valuesToPersist); return this.relation.relatedModel().create(valuesToPersist, { client: trx }); }); } /** * Create instance of the related model */ async createMany(values) { const parent = this.parent; return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await parent.save(); const valuesToPersist = values.map((value) => { const valueToPersist = Object.assign({}, value); this.relation.hydrateForPersistance(this.parent, valueToPersist); return valueToPersist; }); return this.relation.relatedModel().createMany(valuesToPersist, { client: trx }); }); } /** * Get the first matching related instance or create a new one */ async firstOrCreate(search, savePayload) { return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); const valuesToPersist = Object.assign({}, search); this.relation.hydrateForPersistance(this.parent, valuesToPersist); return this.relation .relatedModel() .firstOrCreate(valuesToPersist, savePayload, { client: trx }); }); } /** * Update the existing row or create a new one */ async updateOrCreate(search, updatePayload) { return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); const valuesToPersist = Object.assign({}, search); this.relation.hydrateForPersistance(this.parent, valuesToPersist); return this.relation .relatedModel() .updateOrCreate(valuesToPersist, updatePayload, { client: trx }); }); } /** * Fetch the existing related rows or create new one's */ async fetchOrCreateMany(payload, predicate) { return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); payload.forEach((row) => { this.relation.hydrateForPersistance(this.parent, row); }); predicate = Array.isArray(predicate) ? predicate : predicate ? [predicate] : []; return this.relation .relatedModel() .fetchOrCreateMany(predicate.concat(this.relation.foreignKey), payload, { client: trx, }); }); } /** * Update the existing related rows or create new one's */ async updateOrCreateMany(payload, predicate) { return utils_1.managedTransaction(this.parent.$trx || this.client, async (trx) => { this.parent.$trx = trx; await this.parent.save(); payload.forEach((row) => { this.relation.hydrateForPersistance(this.parent, row); }); predicate = Array.isArray(predicate) ? predicate : predicate ? [predicate] : []; return this.relation .relatedModel() .updateOrCreateMany(predicate.concat(this.relation.foreignKey), payload, { client: trx, }); }); } }
JavaScript
class StringUtils { /** * Converts a given regex from string to a native RegExp object. * * @param {string} string A string containing the regex to convert. * * @returns {RegExp} The converted RegExp object. * * @throws {InvalidArgumentException} If an invalid string is given. * @throws {InvalidArgumentException} If an invalid regex representation is given. */ static toRegExp(string){ if ( string === '' || typeof string !== 'string' ){ throw new InvalidArgumentException('Invalid string.', 1); } const components = string.match(new RegExp('^/(.*?)/([gimy]*)$')); if ( components === null ){ throw new InvalidArgumentException('Invalid regex representation.', 2); } return new RegExp(components[1], components[2]); } }
JavaScript
class VueInitializer { constructor(routes, components, middleware = () => {}){ this.setupVuePlugins(); this.registerComponents(components); router = this.setupRouting(routes, middleware); Vue.mixin({ data(){ return { RouteNames, NETWORKS, }}, computed:{ ...mapState([ 'iv', 'selectedNetwork', 'balance', 'activeAccount', 'tokenMeta', ]), hbarBalance(){ if(!this.balance) return null; if(!parseFloat(this.balance.hbars.toTinybars().toString())){ return parseFloat(0).toFixed(8); } else { return parseFloat(this.balance.hbars.toTinybars() / 100000000).toFixed(8); } }, tokenBalances(){ if(!this.balance) return null; const json = JSON.parse(this.balance.tokens.toString()); return Object.keys(json).map(tokenId => { // Merging in meta data with balances const meta = this.tokenMeta.hasOwnProperty(tokenId) ? this.tokenMeta[tokenId] : { symbol:null, name:null, decimals:null }; return Object.assign({id:tokenId, balance:json[tokenId]}, meta); }); }, hasAccount(){ return !!this.activeAccount; } }, mounted(){ this.sanitizeVuex(); }, methods: { async getTokenMeta(){ store.dispatch('setTokenMeta', await InternalMessage.signal(InternalMessageTypes.GET_TOKEN_META).send()); }, async setTokenMeta(id, query){ const meta = { name:query.name, symbol:query.symbol, decimals:query.decimals, } // Soft save (prevents having to go back to IPC to update local refs const clone = JSON.parse(JSON.stringify(this.tokenMeta)); clone[id] = meta; store.dispatch('setTokenMeta', clone); this.$forceUpdate(); // Hard save return InternalMessage.payload(InternalMessageTypes.SET_TOKEN_META, {id, meta}).send(); }, async checkActiveAccount(){ if(this.activeAccount) return; if(!this.iv) return; let account = await InternalMessage.signal(InternalMessageTypes.GET_ACTIVE_ACCOUNT).send(); if(!account) { account = this.iv.keychain.accounts[0]; if(account) await InternalMessage.payload(InternalMessageTypes.SET_ACTIVE_ACCOUNT, account).send(); } if(!account) return; console.log('setting active account', account); store.dispatch('setActiveAccount', account); }, async setSelectedNetwork(network){ store.dispatch('setSelectedNetwork', network); }, async regenerateIVData(){ return store.dispatch('setIV', await InternalMessage.signal(InternalMessageTypes.GET_DATA).send()); }, sanitizeVuex(){ // Removes pesky __vue__ exposure from elements. const all = document.querySelectorAll("*"); for (let i=0, max=all.length; i < max; i++) { if(all[i].hasOwnProperty('__vue__')) delete all[i].__vue__; } }, getClient(){ if(!this.activeAccount) return; const client = Client[`for${this.activeAccount.network}`](); client.setOperatorWith( this.activeAccount.name, this.activeAccount.publicKey, async buf => { const signature = await InternalMessage.payload(InternalMessageTypes.INTERNAL_SIGN, {data:buf, account:this.activeAccount}).send(); return Buffer.from(signature, 'hex'); } ); return client; }, async getAccountInfo(){ if(!this.activeAccount) return; const client = Client[`for${this.activeAccount.network}`](); const accountBalance = await new AccountBalanceQuery() .setAccountId(this.activeAccount.name) .execute(client).catch(err => { console.error("Error getting account balance", err); return null; }); if(accountBalance){ store.dispatch('setBalance', accountBalance); this.$forceUpdate(); } }, formatNumber(num){ if(!num) return 0; let precision = num.toString().split('.')[1]; precision = precision ? precision.length : 0; const [whole, decimal] = num.toString().split('.'); const formatted = whole.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); if(!decimal || parseInt(decimal) === 0) return formatted; return `${formatted}.${decimal}`; }, }, }) this.setupVue(router); return router; } setupVuePlugins(){ Vue.use(VueRouter); Vue.use(VTooltip, { defaultOffset:5, defaultDelay: 0, defaultContainer: '#app', }); } registerComponents(components){ components.map(component => { Vue.component(component.tag, component.vue); }); } setupRouting(routes, middleware){ const router = new VueRouter({ routes, // mode: 'history', linkExactActiveClass: 'active', }); router.beforeEach((to, from, next) => { return middleware(to, next) }); return router; } setupVue(router){ const app = new Vue({ router, store, render: h => h(App) }); app.$mount('#app'); } }
JavaScript
class Score { constructor(initialscore) { this.element = document.createElement("DIV"); this.element.innerText = initialscore; document.body.appendChild(this.element); // possible styling for container to put above div into this.element.style.display = "hidden"; this.element.style.width = "16px"; this.element.style.height = "150px"; this.element.style.border = "1px solid #cdcdcd"; this.element.style.position = "absolute"; this.element.style.top = "50%"; this.element.style.left = "50%"; this.element.style.transform = "translate(-2500%, -50%)"; this.element.style['align-items'] = "flex-end"; // div styling // this.element.style.display = "block"; // this.element.style.width = "16px"; this.element.style['background-color'] = "aqua"; this.element.style.border = "1px solid #000000"; // this.element.style.margin = "0 auto"; // this.element.style['vertical-align'] = "bottom" // this.element.style.height = "0px"; this.element.style['text-align'] = "center"; // this.element.style.top = "50%"; // this.element.style.left = "50%"; // this.element.style.transform = "translate(-2500%, -50%)"; // this.element.style['align-items'] = "flex-end"; } showScore() { this.element.style.display = "block"; } updateScore(newScore) { this.element.innerText = newScore; } }
JavaScript
class CountryFlagsProvider extends React.PureComponent { registered = 0 getChildContext () { return { registerFlag: this.registerFlag, unregisterFlag: this.unregisterFlag } } componentDidMount () { this.mounted = true this.load(this.props.url) } componentWillUnmount () { this.mounted = false this.unload() } componentWillReceiveProps (props) { this.load(props.url) } registerFlag = () => { this.registered++ if (this.mounted) { this.load(this.props.url) } } unregisterFlag = () => { this.registered = Math.min(0, this.registered - 1) } load (url) { if (this.registered <= 0) { return } if (this.loadedUrl === url) { return } this.unload() this.loadedUrl = url this.abortRequest = load(url, (err, content) => { if (!err) { this.attach(content) } }) } attach (svg) { this.unload() this.element = document.createElement('div') this.element.innerHTML = svg this.element.style.width = '1px' this.element.style.height = '1px' this.element.style.margin = '-1px' this.element.style.padding = '0' this.element.style.border = '0' this.element.style.clip = 'rect(0 0 0 0)' this.element.style.position = 'absolute' this.element.style.whiteSpace = 'nowrap' this.element.style.overflow = 'hidden' document.body.insertBefore(this.element, document.body.childNodes[0]) } unload () { if (this.abortRequest) { this.abortRequest() } if (this.element && this.element.parentNode) { this.element.parentNode.removeChild(this.element) } } /** * Render children. */ render () { return this.props.children } }
JavaScript
class ThetaLiveVR { constructor(container, canvas, streamURI) { this.container = container; this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.img = new Image(); this.img.src = streamURI; this.clock = new THREE.Clock(); } init() { this.renderer = new THREE.WebGLRenderer(); this.element = this.renderer.domElement; this.container.appendChild(this.element); this.effect = new StereoEffect(this.renderer); this.camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700); this.camera.position.set(0, 10, 0); this.texture = new THREE.Texture(this.canvas); this.texture.minFilter = THREE.LinearFilter; this.texture.magFilter = THREE.LinearFilter; let material = new THREE.MeshBasicMaterial({ map: this.texture, side: THREE.BackSide }); let mesh = new THREE.Mesh(tv.createGeometry(), material); this.scene = new THREE.Scene(); this.scene.add(mesh); this.scene.add(this.camera); this.controls = new OrbitControls(this.camera, this.element); this.controls.target.set( this.camera.position.x + 0.1, this.camera.position.y, this.camera.position.z ); this.controls.enableZoom = false; this.controls.enablePan = false; let setOrientationControls = (e) => { if (!e.alpha) { return; } this.controls = orientationControls(this.camera); this.controls.connect(); this.controls.update(); window.addEventListener('orientationchange', () => alert('1'), false); window.addEventListener('deviceorientation', () => alert('2'), false); this.element.addEventListener('click', () => this.fullscreen() , false); window.removeEventListener('deviceorientation', setOrientationControls, true); } window.addEventListener('deviceorientation', setOrientationControls, true); window.addEventListener('resize', () => this.resize, false); this.animate(); } resize() { let width = this.container.offsetWidth; let height = this.container.offsetHeight; this.camera.aspect = width / height; this.camera.updateProjectionMatrix(); this.renderer.setSize(width, height); this.effect.setSize(width, height); } update(dt) { this.resize(); this.camera.updateProjectionMatrix(); this.controls.update(dt); } render() { this.effect.render(this.scene, this.camera); } animate() { this.update(this.clock.getDelta()); this.updateCanvas(); this.texture.needsUpdate = true; this.render(); requestAnimationFrame(() => this.animate()); } fullscreen() { if (this.container.requestFullscreen) { this.container.requestFullscreen(); } else if (this.container.msRequestFullscreen) { this.container.msRequestFullscreen(); } else if (this.container.mozRequestFullScreen) { this.container.mozRequestFullScreen(); } else if (this.container.webkitRequestFullscreen) { this.container.webkitRequestFullscreen(); } } updateCanvas() { this.ctx.drawImage(this.img, 0, 0); } }
JavaScript
class TextTools { constructor() { } // static get defaultTextureManager() { // return defaultTextManager; // } // // static set defaultTextureManager(t) { // defaultTextManager = t; // } static get TEMP_CANVAS() { return TEMP_CANVAS; } static get SPACE_CHAR_CODE() { return SPACE_CHAR_CODE; } static isNewLineChar(char) { return _newlines.indexOf(char) != -1; } static isSpacesChar(char) { return _breakingSpaces.indexOf(char) != -1; } static get BASELINE_ALPHABETIC() { return BASELINE_ALPHABETIC; } static get BASELINE_TOP() { return BASELINE_TOP; } static get ALIGN_CENTER() { return ALIGN_CENTER; } static createTextlines(text, fontSize, fontFamily, fontWeight, fontStyle, textureManager) { if(textureManager == null) return null; // textureManager = textureManager || this.defaultTextureManager; let stringArray = TextTools.splitTextWithNewlineChar(text); let lineArray = []; let lineMaxWidth = 0; let fontMetrics = this.measureFont(fontFamily, fontWeight); for (let i = 0; i < stringArray.length; i++) { let line = {lineWidth: 0, textures: [], scale: 1}; lineArray.push(line); let s = stringArray[i]; for (let j = 0; j < s.length; j++) { let code = s.charCodeAt(j); if (TextTools.isNewLineChar(code)) { code = TextTools.SPACE_CHAR_CODE; } if (TextTools.isSpacesChar(code)) { let spaceWidth = fontMetrics.spaceCharWidthCent[code] * fontSize; line.lineWidth += Math.floor(spaceWidth); //之前的计算都是四舍五入,这里截断,有可能会缩小误差哟 line.textures.push(spaceWidth); continue; } let char = String.fromCharCode(code); let textureId = char + "@" + fontMetrics.id + "_" + fontSize.toString(); let texture = null; if (textureManager != null) texture = textureManager.getTextureById(textureId); if (texture == null) { if (textureManager != null) { let result = TextTools.draw2dText(char, fontSize, fontFamily, fontWeight, fontStyle); texture = textureManager.createTexture(result.canvas, textureId); texture.textWidth = result.textWidth; } } if(texture != null){ line.textures.push(texture); line.lineWidth += texture.textWidth; } } lineMaxWidth = Math.max(lineMaxWidth, line.lineWidth); } return {lineMaxWidth: lineMaxWidth, lineArray: lineArray}; } static getFontString(fontSize, fontFamily, fontWeight, fontStyle) { fontSize = (fontSize != null) ? fontSize : 32; fontFamily = fontFamily || "arial"; fontFamily = fontFamily.trim().toLocaleLowerCase(); fontWeight = fontWeight || ""; fontWeight = fontWeight.trim().toLocaleLowerCase(); fontStyle = fontStyle || ""; fontStyle = fontStyle.trim().toLocaleLowerCase(); let font = ""; if (fontStyle !== "") { font = font + fontStyle + " "; } if (fontWeight !== "") { font = font + fontWeight + " "; } font = font + fontSize.toString() + "px "; if (fontFamily !== "") { font = font + fontFamily; } return font; } static getStartPointOffset(baseLine, textAlign, fontSize, textMetric, width) { baseLine = baseLine.toLowerCase().trim(); textAlign = textAlign.toLowerCase().trim(); let offset = {x: 0, y: 0}; if (textAlign === ALIGN_LEFT || textAlign === ALIGN_START) { } if (textAlign === ALIGN_END || textAlign === ALIGN_RIGHT) { offset.x = -width; } if (textAlign === ALIGN_CENTER) { offset.x = (-width) / 2; } if (baseLine === BASELINE_ALPHABETIC) { offset.y -= textMetric.ascent * fontSize; } if (baseLine === BASELINE_HANGING) { offset.y -= textMetric.hangingBaseline * fontSize; } if (baseLine === BASELINE_TOP) { offset.y -= textMetric.topBaseline * fontSize; } if (baseLine === BASELINE_BOTTOM) { offset.y -= textMetric.fontSize * fontSize; } if (baseLine === BASELINE_IDEOGRAPHICS) { offset.y -= textMetric.fontSize * fontSize; offset.y += textMetric.ideographicBaseline * fontSize; } if (baseLine === BASELINE_MIDDLE) { offset.y -= textMetric.middle * fontSize; } return offset; } static splitTextWithNewlineChar(string) { return string.split('\n'); } static draw2dText(text, fontSize, fontFamily, fontWeight, fontStyle) { let canvas = TEMP_CANVAS; let textMetrics = TextTools.measureText(text, fontSize, fontFamily, fontWeight, fontStyle); let width = textMetrics.width; if (fontStyle != null) fontStyle = fontStyle.trim().toLowerCase(); if (fontStyle === 'italic') { width += textMetrics.extendWidth * fontSize; } canvas.width = Math.ceil(width); canvas.height = Math.round(textMetrics.fontSize * fontSize); if (canvas.width === 0 || canvas.height === 0) return; let ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.fillStyle = "#FFFFFF";//必须白色 ctx.font = textMetrics.font; ctx.textAlign = ALIGN_LEFT; ctx.textBaseline = BASELINE_ALPHABETIC; ctx.fillText(text, 0, textMetrics.ascent * fontSize); ctx.restore(); return {canvas: TEMP_CANVAS, textWidth: textMetrics.width}; } static measureText(text, fontSize, fontFamily, fontWeight, fontStyle) { let canvas = TEMP_CANVAS; let font = this.getFontString(fontSize, fontFamily, fontWeight, fontStyle); let fontProperties = this.measureFont(fontFamily, fontWeight); let copyProperties = {}; for (let p in fontProperties) { copyProperties[p] = fontProperties[p]; } let ctx = canvas.getContext('2d'); ctx.font = font; copyProperties.width = ctx.measureText(text).width; copyProperties.font = font; return copyProperties; } static measureFont(fontFamily, fontWeight) { let canvas = TEMP_CANVAS; let fontSize = 100; fontFamily = fontFamily || DEFAULT_FONTFAMILY; // fontFamily = fontFamily.trim().toLocaleLowerCase(); fontWeight = fontWeight || ""; // fontWeight = fontWeight.trim().toLocaleLowerCase(); let fontStyle = ITALIC_FONTSTYLE; let font = ""; let fontKey = ""; if (fontStyle !== "") { font = font + fontStyle + " "; } if (fontWeight !== "") { font = font + fontWeight + " "; fontKey = fontKey + fontWeight; } font = font + fontSize.toString() + "px "; if (fontFamily !== "") { font = font + fontFamily; fontKey = fontKey + "_" + fontFamily; } let properties = _fontMetricsCatch[fontKey]; if (properties != null) return properties; properties = {}; let ctx = canvas.getContext('2d'); ctx.save(); ctx.font = font; let spaceCharWidthMap = {}; for (let i = 0; i < _breakingSpaces.length; i++) { let spaceChar = String.fromCharCode(_breakingSpaces[i]); spaceCharWidthMap[_breakingSpaces[i]] = ctx.measureText(spaceChar).width / 100; } properties.spaceCharWidthCent = spaceCharWidthMap; let textMetric = ctx.measureText(TEST_CHAR); let width = Math.ceil(textMetric.width * 2); let height = Math.ceil(textMetric.width * 3); canvas.width = width; canvas.height = height; ctx.font = font; ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "#000000"; ctx.textBaseline = BASELINE_BOTTOM; ctx.fillText(TEST_CHAR, 0, height); let imageData = ctx.getImageData(0, 0, width, height).data; let i = height - 1; let j = 0; let stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } let extendWidthStart = j; let extendWidthEnd = extendWidthStart; let bottom = i + 1; for (; i >= 0; i--) { stop = true; for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = false; extendWidthEnd = j; break; } } if (stop) break; } let top = i + 1; stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } let head = i + 1; for (; i >= 0; i--) { stop = true; for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = false; break; } } if (stop) break; } let begin = i + 1; properties.fontSize = height - begin + 1; properties.ascent = bottom - begin + 1; properties.extendWidth = (extendWidthEnd - extendWidthStart + 1) / (bottom - top + 1) * properties.fontSize; properties.alphabeticBaseline = properties.ascent; canvas.width = width; height = properties.fontSize; canvas.height = height; ctx.font = font; //计算尾部离bottom的距离: ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "#000000"; ctx.textBaseline = BASELINE_BOTTOM; ctx.fillText("j", textMetric.width / 2, height); imageData = ctx.getImageData(0, 0, width, height).data; i = height - 1; stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } let bottomSpace = height - i; ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "#000000"; ctx.textBaseline = BASELINE_TOP; ctx.fillText("j", textMetric.width / 2, 0); imageData = ctx.getImageData(0, 0, width, height).data; i = height - 1; stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } properties.topBaseline = height - i - bottomSpace; properties.emHeight = properties.fontSize - properties.topBaseline; properties.middleBaseline = properties.emHeight / 2 + properties.topBaseline; ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "#000000"; ctx.textBaseline = BASELINE_HANGING; ctx.fillText("j", textMetric.width / 2, 0); imageData = ctx.getImageData(0, 0, width, height).data; i = height - 1; stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } properties.hangingBaseline = height - i - bottomSpace; ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "#000000"; ctx.textBaseline = BASELINE_IDEOGRAPHICS; ctx.fillText("j", textMetric.width / 2, height); imageData = ctx.getImageData(0, 0, width, height).data; i = height - 1; stop = false; for (; i >= 0; i--) { for (j = 0; j < width; j++) { let index = i * width + j; index *= 4; if (imageData[index] !== 255) { stop = true; break; } } if (stop) break; } let deltaHeight = height - i - bottomSpace; properties.ideographicsBaseline = -deltaHeight; for (let p in properties) { if (typeof properties[p] !== "object") properties[p] = properties[p] / fontSize; } properties.id = fontKey; properties.fontFamily = fontFamily; properties.fontWeight = fontWeight; // let finalProperties = {}; // Tools.createReadOnlyObject(properties, finalProperties); ctx.restore(); _fontMetricsCatch[fontKey] = properties; return properties; } }
JavaScript
class Poll { /** * Periodically call a function. If the polling period is faster than the iteration rate, * then the interation rate will slow polling so that no buffering is required. Because of * this, when the iterating code stops, calls to asyncFunction will also stop. However, you * should call the `done` method so that any `finally` expressions can run. * * @param {Function|AsyncFunction} fn - synchronous or async function that takes no parameters * @param {Number} period - call fn every period milliseconds * @param {Number} initialWait - make first function call immediately if zero, otherwise wait * `initialWait` millisceonds before making first call. Defaults to zero. * @returns {AsyncGenerator} - provides the stream of poll results * @example * // iteration potentially faster than polling period: * const poller = poll(async () => '42', 720) * for await (const value of poller) { * console.log(value) // prints '42' once every 720ms * } * // iteration slower than polling period: * const fastPoller = poll(() => 'A', 100) * const slowIterator = throttle(500, true, fastPoller) // maximum iteration rate of 500ms * for await (const value of slowIterator) { * console.log(value) // prints 'A' once every 500ms, even though period is 100ms * } * // polling stops when iteration stops * // but iteration won't complete until you call done() * const limitedPolls = take(5, poll(async () => 'B', 420)) * for await (const value of limitedPolls) { * console.log(value) // prints 'B' 5 times, and only calls the async function 5 times * } */ constructor (fn, period, initialWait = 0) { this.fn = fn this.period = period this.initialWait = initialWait this.isDone = false } /** * Stops polling */ done () { this.isDone = true } async * [Symbol.asyncIterator] () { if (this.initialWait !== 0) { await wait(this.initialWait) } while (!this.isDone) { // eslint-disable-line const startTime = Date.now() yield await Promise.resolve(this.fn()) const yieldDuration = Date.now() - startTime if (yieldDuration < this.period) { await wait(this.period - yieldDuration) } } } }
JavaScript
class KeeperApi { constructor (client) { this.client = client // Dynamic loading API... fs.readdirSync(__dirname).forEach((file) => { if (/^[a-z]+\.api\.js$/.test(file)) { const name = path.basename(file, '.api.js') // this.client.logger.debug('Loading %s API...', name) const Api = require(path.join(__dirname, file)) this[name] = new Api(this.client) } }) } }
JavaScript
class TaskEasy { constructor(compare_func, max_queue_size = 100) { this.tasks = []; this.taskRunning = false; if (typeof compare_func !== "function") throw new Error( `Task Easy Comparison Function must be of Type <function> instead got ${typeof compare_func}` ); if (typeof max_queue_size !== "number") throw new Error( `Task Easy Max Queue Size must be of Type <Number> instead got ${typeof number}` ); if (max_queue_size <= 0) throw new Error("Task Easy Max Queue Size must be greater than 0"); this.compare = compare_func; this.max = max_queue_size; } /** * Schedules a new "Task" to be Performed * * @param {function} task - task to schedule * @param {Array} args - array of arguments to pass to task * @param {object} priority_obj - object that will be passed to comparison handler provided in the constructor * @returns * @memberof TaskQueue */ schedule(task, args, priority_obj) { if (typeof task !== "function") throw new Error(`Scheduler Task must be of Type <function> instead got ${typeof task}`); if (!Array.isArray(args)) throw new Error(`Scheduler args must be of Type <Array> instead got ${typeof args}`); if (typeof priority_obj !== "object") throw new Error( `Scheduler Task must be of Type <Object> instead got ${typeof priority_obj}` ); if (this.tasks.length >= this.max) throw new Error(`Micro Queue is already full at size of ${this.max}!!!`); // return Promise to Caller return new Promise((resolve, reject) => { // Push Task to Queue if (this.tasks.length === 0) { this.tasks.unshift({ task, args, priority_obj, resolve, reject }); this._reorder(0); this._next(); } else { this.tasks.unshift({ task, args, priority_obj, resolve, reject }); this._reorder(0); } }); } /** * Swaps the tasks with the specified indexes * * @param {number} ix * @param {number} iy * @memberof TaskEasy */ _swap(ix, iy) { const temp = this.tasks[ix]; this.tasks[ix] = this.tasks[iy]; this.tasks[iy] = temp; } /** * Recursively Reorders from Seed Index Based on Outcome of Comparison Function * * @param {number} index * @memberof TaskQueue */ _reorder(index) { const { compare } = this; const size = this.tasks.length; const l = index * 2 + 1; const r = index * 2 + 2; let swap = index; if (l < size && compare(this.tasks[l].priority_obj, this.tasks[swap].priority_obj)) swap = l; if (r < size && compare(this.tasks[r].priority_obj, this.tasks[swap].priority_obj)) swap = r; if (swap !== index) { this._swap(swap, index); this._reorder(swap); } } /** * Executes Highest Priority Task * * @memberof TaskQueue */ _runTask() { this._swap(0, this.tasks.length - 1); const job = this.tasks.pop(); const { task, args, resolve, reject } = job; this._reorder(0); this.taskRunning = true; task(...args) .then((...args) => { resolve(...args); this.taskRunning = false; this._next(); }) .catch((...args) => { reject(...args); this.taskRunning = false; this._next(); }); } /** * Executes Next Task in Queue if One Exists and One is Currently Running * * @memberof TaskQueue */ _next() { if (this.tasks.length !== 0 && this.taskRunning === false) { this._runTask(); } } }
JavaScript
class EventEmitter { constructor() { this.events = {} } /** * add new event * * @param {string} type - event name * @param {function} callback */ on(type, callback) { this.events[type] = this.events[type] || []; this.events[type].push(callback); } /** * calls event * * @param {string} type - event name * @param {*} arg - argument for methods */ emit(type, arg) { if (this.events[type]) { this.events[type].forEach(callback => { callback(arg); }); } } }
JavaScript
class ActorRdfResolveQuadPatternFederated extends bus_rdf_resolve_quad_pattern_1.ActorRdfResolveQuadPatternSource { constructor(args) { super(args); this.emptyPatterns = new Map(); } async test(action) { const sources = this.getContextSources(action.context); if (!sources) { throw new Error('Actor ' + this.name + ' can only resolve quad pattern queries against a sources array.'); } return true; } async getSource(context) { return new FederatedQuadSource_1.FederatedQuadSource(this.mediatorResolveQuadPattern, context, this.emptyPatterns, this.skipEmptyPatterns); } async getOutput(source, pattern, context) { // Attach metadata to the output const output = await super.getOutput(source, pattern, context); output.metadata = () => new Promise((resolve, reject) => { output.data.on('error', reject); output.data.on('end', () => reject(new Error('No metadata was found'))); output.data.on('metadata', (metadata) => { resolve(metadata); }); }); return output; } }
JavaScript
class LandingScreen extends Component { /** * @constructor * @param {object} props * @param {object} props.navigation the navigation object provided by 'react-navigation' */ constructor(props) { super(props) } render() { return ( <View style={localStyle.wrapper}> {/* loading spinner */} <Spinner visible={this.props.loading} /> {/* banner */} <Banner nav={this.props.navigation} title={config.text.login.landing.title} subTitle={config.text.login.landing.subTitle} noWayBack noMenu /> {/* scrollIndicator */} <View style={{ ...localStyle.flexi, ...localStyle.wrapper }}> <ScrollIndicatorWrapper contentData={ <View style={localStyle.wrapper}> {/* top elements title & text */} <View style={localStyle.top}> <Text style={localStyle.titleText}>{config.text.login.landing.welcomeTitle}</Text> <Text style={localStyle.infoText}>{config.text.login.landing.text}</Text> </View> {/* bottom login button */} <View style={localStyle.bottom}> <TouchableOpacity style={localStyle.button} onPress={() => { this.props.navigation.navigate('Login') }} accessibilityLabel={config.text.login.landing.buttonText} accessibilityRole={config.text.accessibility.types.button} accessibilityHint={config.text.accessibility.loginHint} > <Text style={localStyle.buttonLabel}> {config.text.login.landing.buttonText} </Text> </TouchableOpacity> </View> </View> } /> </View> </View> ) } }
JavaScript
class BoldItalicUnderlineHandler { rawEditor; constructor({rawEditor}) { this.rawEditor = rawEditor; } isHandlerFor(event) { return event.type == "keydown" && ["b","i","u"].includes(event.key) && (event.ctrlKey || event.metaKey); } handleEvent(event) { let property; switch(event.key) { case "b": property = boldProperty; break; case "u": property = underlineProperty; break; case "i": property = italicProperty; break; } const range = this.rawEditor.currentSelection; const selection = this.rawEditor.selectCurrentSelection(); this.rawEditor.toggleProperty(selection, property); // set cursor at end of selection, TODO: check what other editors do but this feels natural this.rawEditor.setCurrentPosition(range[1]); return HandlerResponse.create({ allowBrowserDefault: false, allowPropagation: false }); } }
JavaScript
class RenderVisioDocumentFigures { static async Run() { let fileInfo = new viewer_cloud.FileInfo(); fileInfo.filePath = "SampleFiles/sample.vssx"; let viewOptions = new viewer_cloud.ViewOptions(); viewOptions.fileInfo = fileInfo; viewOptions.viewFormat = viewer_cloud.ViewOptions.ViewFormatEnum.PNG; viewOptions.renderOptions = new viewer_cloud.ImageOptions(); viewOptions.renderOptions.visioRenderingOptions = new viewer_cloud.VisioRenderingOptions(); viewOptions.renderOptions.visioRenderingOptions.renderFiguresOnly = true; viewOptions.renderOptions.visioRenderingOptions.figureWidth = 250; let request = new viewer_cloud.CreateViewRequest(viewOptions); let response = await viewApi.createView(request); console.log("RenderVisioDocumentFigures completed: " + response.pages.length); } }
JavaScript
class Router { constructor(window=null) { this.registry = new Registry(this); this._events = new events.EventEmitter(); this.HASH_CHANGED = 'hashchange'; if(window != null) window.addEventListener(this.HASH_CHANGED, this); } handleEvent(e) { var hash = (window.location.hash) ? window.location.hash.replace(/^#/, '/'). replace(/\/\//g, '/'). split('?'): '/'; this.registry.run(hash[0], hash[1] || null); } on() { this._events.on.apply(this._events, arguments); return this; } once() { this._events.once.apply(this._events, arguments); return this; } emit() { this._events.emit.apply(this._events, arguments); return this; } /** * get queues up a route to be executed. * @param {string|Regexp} path The path to activate the handler on * @param {handler} cb */ get(path, cb) { this.registry.register(path, (typeof cb === 'object') ? cb.onActive.bind(cb) : cb); return this; } /** * use sets up middleware for all routes * @param {handler} cb */ use(cb) { this.registry.register(null, (typeof cb === 'object') ? cb.onActive.bind(cb) : cb); return this; } }
JavaScript
class Mixin { /** * Property on the source object that the mixin will be namespaced under. * * For example, a `_namespace` value of `event` will be attahced to the source object as `<Object>.event`. * * @memberof Whirl.mixins.Mixin * @type {string} * @abstract */ static _namespace = null; /** * The source object that this mixin instance is applied to. * * @memberof Whirl.mixins.Mixin * @type {object} */ _source; constructor(source) { this._source = source; } /** * Apply mixins to a given object. * * "Applied" means that the mixin is constructed and added to the object under a key defined by its namespace. * * The source object must have an instance variable called `mixins` that contains an array of mixins to apply. Mixins are applied in the order that they are given. * * Every class in the array must inherit from `Mixin` class and override its `_namespace` property. * * After every mixin has been applied, the `mixin` property will be deleted from the source object. * * @method Whirl.mixins.Mixin.apply * * @param {object} object Instance of an object to apply the set of mixins to. * @param {Whirl.mixins.Mixin[]} [mixins] Provide the array of mixins explicitly instead of looking for the `mixins` property on the source object. * * @example * const {mixins: {Mixin, Event}} = Whirl; * * // Add the `Event` mixin to `MyObject` * class MyObject { * mixins = [Event]; * * constructor() { * Mixin.apply(this); * } * } * * @example * const {mixins: {Mixin, Event}} = Whirl; * * // Add the `Event` mixin to `MyObject` explicitly * class MyObject { * constructor() { * Mixin.apply(this, [Event]); * } * } */ static apply(object, mixinList) { const mixins = mixinList || object.mixins; if (!mixins || !Array.isArray(mixins) || !mixins.every((m) => m.prototype instanceof Mixin)) { throw new Error("Whirl | Invalid mixin type and/or format provided to `Mixin.apply`."); } mixins.forEach((mixin) => { // Enforce namespace if (!mixin._namespace) { throw new Error(`Whirl | Mixin "${mixin.name}" has no namespace.`); } // Create and add mixin instance to object under its namespace object[mixin._namespace] = new mixin(object); }); // Remove unused 'mixins' property if it exists delete object.mixins; } }
JavaScript
class DropDown extends Component { // onSelect = e => { // console.log(e.target.value); // } onChange(e) { console.log(e); this.props.history.push(`/${e.target.value}`); } constructor(props) { super(props); this.onChange = this.onChange.bind(this); console.log(this.props) } render() { return ( <select onChange={this.onChange}> <option value="stuff">Nasdaq</option> <option value="second-route">S&P 500</option> </select> ); } }
JavaScript
class PopupBaseModel extends Model { constructor() { super(); this.addProperty('show', false); this.addProperty('overlay', false); this.addProperty('opacity', 0); } }
JavaScript
class Hooks { /** * Allowed hook types * @memberof Hooks * @type {Array} * @private */ types = HOOK_TYPES constructor() { this._registeredHooks = {} /** * Creates helpers for registering hooks * @memberof Hooks * @function * @public * @param {function} method - Function to be registered to the hook. They will be called when the runner runs a feature * @example * const hooks = new Hooks() * hooks.beforeAll(() => setupEnvironment()) * * @returns {void} */ this.types.map(type => { this[type] = clientHookFn => { if (!isFunc(clientHookFn)) return this._registeredHooks[type] = clientHookFn } }) } /** * @param {string} type * @return {Function} the function registered to the hook type, or a noOp function by default */ getRegistered = type => { return this.types.includes(type) ? this._registeredHooks[type] || noOp : throwInvalidHookType(HOOK_TYPES.join(', '), type) } }
JavaScript
class AboutStepper extends React.Component { // This component keeps track of which step is active so that each step can be linked to the one before it and the one after it for navigation purposes state = { activeStep: 0, }; // Increment step state by 1 to move to next step handleNext = () => { this.setState(state => ({ activeStep: state.activeStep + 1, })); }; // Decrement by 1 to move back a step handleBack = () => { this.setState(state => ({ activeStep: state.activeStep - 1, })); }; // Reset reverts to first step handleReset = () => { this.setState({ activeStep: 0, }); }; render() { const { classes } = this.props; const steps = getSteps(); const { activeStep } = this.state; return ( <div className="aboutStepper"> <div className={classes.root}> <Stepper style={style} activeStep={activeStep} orientation="vertical"> {steps.map((label, index) => ( <Step key={label} style={style}> <StepLabel className="stepLabel" style={labelStyle}>{label}</StepLabel> <StepContent style={style}> <Typography style={style} className="textBody">{getStepContent(index)}</Typography> <div className={classes.actionsContainer}> <div> <Button disabled={activeStep === 0} onClick={this.handleBack} className={classes.button} > ← </Button> <Button variant="contained" onClick={this.handleNext} className={classes.button} > {activeStep === steps.length - 1 ? '→' : '→'} </Button> </div> </div> </StepContent> </Step> ))} </Stepper> {activeStep === steps.length && ( <Paper style={style} square elevation={0} className={classes.resetContainer}> <Typography className={classes.typography}>―――――</Typography> <Button onClick={this.handleReset} className={classes.topButton}> top ↑ </Button> </Paper> )} </div> </div> ); } }
JavaScript
class Grid extends ConcreteCell { constructor(props, ...args){ super(props, ...args); // Bind context to methods this.makeHeaders = this.makeHeaders.bind(this); this.makeRows = this.makeRows.bind(this); } _computeFillSpacePreferences() { return {horizontal: true, vertical: true}; } build(){ let topTableHeader = null; if(this.props.hasTopHeader){ topTableHeader = h('th'); } return ( h('table', { id: this.getElementId(), "data-cell-id": this.identity, "data-cell-type": "Grid", class: "cell table-sm table-striped cell-grid" }, [ h('thead', {}, [ h('tr', {}, [topTableHeader, ...this.makeHeaders()]) ]), h('tbody', {}, this.makeRows()) ]) ); } makeHeaders(){ return this.renderChildrenNamed('headers').map((headerEl, colIdx) => { return ( h('th', {key: `${this.identity}-grid-th-${colIdx}`}, [ headerEl ]) ); }); } makeRows(){ let rowLabels = this.renderChildrenNamed('rowLabels'); return this.renderChildrenNamed('dataCells').map((dataRow, rowIdx) => { let columns = dataRow.map((column, colIdx) => { return( h('td', {key: `${this.identity}-grid-col-${rowIdx}-${colIdx}`}, [ column ]) ); }); let rowLabelEl = null; if(this.namedChildren.rowLabels && this.namedChildren.rowLabels.length > 0){ rowLabelEl = h('th', {key: `${this.identity}-grid-col-${rowIdx}`}, [ rowLabels[rowIdx] ]); } return ( h('tr', {key: `${this.identity}-grid-row-${rowIdx}`}, [ rowLabelEl, ...columns ]) ); }); } }
JavaScript
class Book { constructor(bookName, author, bookType){ this.bookName = bookName this.author = author this.bookType = bookType } getAuthor(){ return this.author } getBookName(){ return this.bookName } }
JavaScript
class VirtualUtils { constructor(options, updateCallBack) { this._initialize(options, updateCallBack); } /** * @param {Object} options * @param {Number} options.keeps threshhold to how many elements to be rendered at a any given time * @param {Number} options.buffer to be substracted to estimate starting point * @param {Array} options.uniqueIds of data to calculate length * @param {String} options.pageMode indicates if scroll method is on whole page or on specific container * @param {Function} updateCallBack */ _initialize(options, updateCallBack) { // param data this._options = options; this._updateCallBack = updateCallBack; // size data this._sizes = new Map(); this._firstRangeTotalSize = 0; this._firstRangeAverageSize = 0; this._wrapperOffsetWidth = 0; this._lastCalcIndex = 0; this._fixedSizeValue = 0; this._calcType = CALC_TYPE.INIT; // scroll data this._offset = 0; this._direction = ''; // range data this._range = {}; this._estimatedDocumentPosition = 0; if (options) { this._checkRange(0, options.keeps - 1); } } /** * reset internal objects and variables */ destroy() { this._initialize(null, null); } /** * Get current range values * @returns {Object} range */ getRange() { const range = {}; range.start = this._range.start; range.end = this._range.end; range.padFront = this._range.padFront; range.padBehind = this._range.padBehind; range.uniqueIds = this._options.uniqueIds; return range; } /** * Calculate estimated starting index based on scroll */ _getViewportStartIndex() { const offset = this._offset - (this._options.pageMode && this._estimatedDocumentPosition); if (offset <= 0) { return 0; } if (this._isFixedType()) { return Math.floor(offset / this._fixedSizeValue); } let low = 0; let middle = 0; let middleOffset = 0; let high = this._options.uniqueIds.length; while (low <= high) { middle = low + Math.floor((high - low) / 2); middleOffset = this._getIndexOffset(middle); if (middleOffset === offset) { return middle; } else if (middleOffset < offset) { low = middle + 1; } else if (middleOffset > offset) { high = middle - 1; } } return low > 0 ? --low : 0; } /** * @param {Number} givenIndex * @returns {Number} offset */ _getIndexOffset(givenIndex) { if (!givenIndex) { return 0; } let offset = 0; let indexSize = 0; for (let index = 0; index < givenIndex; index++) { indexSize = this._sizes.get(this._options.uniqueIds[index]); offset = offset + (indexSize || this.getEstimateSize()); } // store last calculated index this._lastCalcIndex = Math.max(this._lastCalcIndex, givenIndex - 1); this._lastCalcIndex = Math.min( this._lastCalcIndex, this._getUniqueIdsLastIndex() ); return offset; } isDownward() { return this._direction === DIRECTION_TYPE.DOWN_SCROLL; } isForward() { return this._direction === DIRECTION_TYPE.TOP_SCROLL; } /** * @param {*} key * @param {*} value data/footer offset height size */ updateParam(key, value) { if (this._options && key in this._options) { this._options[key] = value; } } /** * @param {Id} id of the element * @param {Number} size of the element * store element size */ saveSize(id, size, rootElPosition) { this._estimatedDocumentPosition = rootElPosition; this._sizes.set(id, size); if (this._calcType === CALC_TYPE.INIT) { this._fixedSizeValue = size; this._calcType = CALC_TYPE.FIXED; } else if ( this._calcType === CALC_TYPE.FIXED && this._fixedSizeValue !== size ) { this._calcType = CALC_TYPE.DYNAMIC; delete this._fixedSizeValue; } // calculate the average size only in the first range if (this._sizes.size <= this._options.keeps) { this._firstRangeTotalSize = this._firstRangeTotalSize + size; this._firstRangeAverageSize = Math.round( this._firstRangeTotalSize / this._sizes.size ); } else { delete this._firstRangeTotalSize; } } /** * render next range including buffer depending on the current scroll direction (up/down) */ dataListChangeEvent() { let start = this._range.start; if (this.isForward()) { start = start - START_LEADING_BUFFER; } else if (this.isDownward()) { start = start + START_LEADING_BUFFER; } start = Math.max(start, 0); this._updateRange(this._range.start, this._getEndByStart(start)); } /** * Re-calculate starting point of index and update range */ footerSizeChangeEvent() { this.dataListChangeEvent(); } /** * @param {Number} offset of current scrolling position */ handleScroll(offset) { this._direction = offset < this._offset ? DIRECTION_TYPE.TOP_SCROLL : DIRECTION_TYPE.DOWN_SCROLL; this._offset = offset; if (this._direction === DIRECTION_TYPE.TOP_SCROLL) { this._handleTopScroll(); } else if (this._direction === DIRECTION_TYPE.DOWN_SCROLL) { this._handleDownScroll(); } } /** * check if type is fixed * @returns {Boolean} CalculationType */ _isFixedType() { return this._calcType === CALC_TYPE.FIXED; } /** * total top padding * @return {TotalPadTop} */ _getPadTop() { if (this._isFixedType()) { return this._fixedSizeValue * this._range.start; } else { return this._getIndexOffset(this._range.start); } } /** * Validate range on top scroll */ _handleTopScroll() { const overs = this._getViewportStartIndex(); // should not change range if start doesn't exceed overs if (overs > this._range.start) { return; } // move up start by a buffer length, and make sure its valid const start = Math.max(overs - this._options.buffer, 0); this._checkRange(start, this._getEndByStart(start)); } /** * Validate range on down scroll */ _handleDownScroll() { const overs = this._getViewportStartIndex(); // range stays the same if within buffer value if (overs < this._range.start + this._options.buffer) { return; } this._checkRange(overs, this._getEndByStart(overs)); } /** * total bottom padding * @return {Number} TotalPadBottom */ _getPadDown() { const end = this._range.end; const lastIndex = this._getUniqueIdsLastIndex(); if (this._isFixedType()) { return (lastIndex - end) * this._fixedSizeValue; } // if lasCalcIndex is equals then calculate the relevant padding \ if (this._lastCalcIndex === lastIndex) { return this._getIndexOffset(lastIndex) - this._getIndexOffset(end); } else { // if not, use a estimated value return (lastIndex - end) * this.getEstimateSize(); } } /** * set the start and end point of the index * * @param {Number} start index of the data array * @param {Number} end index of the data array */ _checkRange(start, end) { const keeps = this._options.keeps; const total = this._options.uniqueIds.length; // data size is less than keeps, render all if (total <= keeps) { start = 0; end = this._getUniqueIdsLastIndex(); } else if (end - start < keeps - 1) { // if current range is more than the allowed keeps then assign start to previous end start = end - keeps + 1; } if (this._range.start !== start) { this._updateRange(start, end); } } /** * set start and end point of the index and calculated paddings * * @param {Number} start index of data array * @param {Number} end index of data array */ _updateRange(start, end) { this._range.start = start; this._range.end = end; this._range.padFront = this._getPadTop(); this._range.padBehind = this._getPadDown(); this._updateCallBack(this.getRange()); } /** * Calculate end index * * @param {Number} start index of data array * @returns {Number} estimated ending index of data array */ _getEndByStart(start) { const end = start + this._options.keeps; const calcEnd = Math.min(end, this._getUniqueIdsLastIndex()); return calcEnd; } getEstimateSize() { return this._firstRangeAverageSize || 0; } _getUniqueIdsLastIndex() { return this._options.uniqueIds.length - 1; } /** * Calculate position of a specific element * * @param {Number} start index of data array * @returns {Number} offset value from the start index provided */ getOffset(start) { return ( (start < 1 ? 0 : this._getIndexOffset(start)) + this._estimatedDocumentPosition ); } }
JavaScript
class TagController { /** * Show a list of all tags. * GET tags * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index({auth}) { return await Tag.query().where('user_id', `${auth.user.id}`).orderBy('name').fetch() } /** * search tags. * GET tags/:name * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async search({ params, auth, response }) { const tag = _.get(params, 'name', '') // assuming bad data can be sent here. Raw should parameterize input // https://security.stackexchange.com/q/172297/35582 const tagQuery = await Tag.query().whereRaw('name LIKE ?', `${tag}%`).andWhere('user_id', `${auth.user.id}`).orderBy('name').fetch() if (tagQuery.toJSON().length < 1) { return response.status(204).send({ message: 'no results found' }) } return tagQuery } /** * Update tag details. * PUT or PATCH tags/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update({ params, auth, request, response }) { const { name } = request.post() // places are on their own URI. Tags can be in the illustration post let tag = await Tag.find(params.id) if (!tag.toJSON()[0] && tag.user_id != auth.user.id) { return response.status(403).send({ message: 'You do not have permission to access this resource' }) } tag.name = name await tag.save() return response.send({message: 'Updated successfully'}) } /** * Delete a tag with id. * DELETE tags/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy({ params, auth, response }) { let tag = await Tag.find(params.id) if (!tag.toJSON()[0] && tag.user_id != auth.user.id) { return response.status(403).send({ message: 'You do not have permission to access this resource' }) } await tag.delete() return response.send({message: `Deleted tag id: ${tag.id}`}) } }
JavaScript
class ComPriFacNotConcept { /** * en: Constructor. * de: Konstruktor. */ constructor() { } /** * :en: Getter for {@link cvAliasDigits}. * :de: Getter für {@link cvAliasDigits}. * * @returns {string} {@link cvAliasDigits} * @see cvAliasDigits * @see aliasDigits * @since 1.3, 2021-12-13 */ static get aliasDigits() { return ComPriFacNotConcept.cvAliasDigits; } /** * :en: Getter for {@link cvAliasDigitsJsonUrl}. * :de: Getter für {@link cvAliasDigitsJsonUrl}. * * @returns {string} {@link cvAliasDigitsJsonUrl} * @see cvAliasDigitsJsonUrl * @since 1.3, 2021-12-13 */ static get aliasDigitsJsonUrl() { return ComPriFacNotConcept.cvAliasDigitsJsonUrl; } /** * :en: Getter for {@link cvAliasDigitsMap}. * :de: Getter für {@link cvAliasDigitsMap}. * * @returns {Map<string, string>} {@link cvAliasDigitsMap} * @see cvAliasDigitsMap * @see aliasDigitsMap * @since 1.3, 2021-12-13 */ static get aliasDigitsMap() { return ComPriFacNotConcept.cvAliasDigitsMap; } /** * :en: Getter for {@link cvAliasDigitsValues}. * :de: Getter für {@link cvAliasDigitsValues}. * * @returns {Array<string>} {@link cvAliasDigitsValues} * @see cvAliasDigitsValues * @see aliasDigitsValues * @since 1.3, 2021-12-13 */ static get aliasDigitsValues() { return ComPriFacNotConcept.cvAliasDigitsValues; } /** * :en: Getter for {@link cvBasicDigits}. * :de: Getter für {@link cvBasicDigits}. * * @returns {string} {@link cvBasicDigits} * @see cvBasicDigits * @see basicDigits * @since 1.2, 2021-12-12 */ static get basicDigits() { return ComPriFacNotConcept.cvBasicDigits; } /** * :en: Getter for {@link cvBasicDigitsJsonUrl}. * :de: Getter für {@link cvBasicDigitsJsonUrl}. * * @returns {string} {@link cvBasicDigitsJsonUrl} * @see cvBasicDigitsJsonUrl * @since 1.2, 2021-12-12 */ static get basicDigitsJsonUrl() { return ComPriFacNotConcept.cvBasicDigitsJsonUrl; } /** * :en: Getter for {@link cvBasicDigitsMap}. * :de: Getter für {@link cvBasicDigitsMap}. * * @returns {Map<string, number>} {@link cvBasicDigitsMap} * @see cvBasicDigitsMap * @see basicDigitsMap * @since 1.2, 2021-12-12 */ static get basicDigitsMap() { return ComPriFacNotConcept.cvBasicDigitsMap; } /** * :en: Getter for {@link cvBasicDigitsValues}. * :de: Getter für {@link cvBasicDigitsValues}. * * @returns {Array<number>} {@link cvBasicDigitsValues} * @see cvBasicDigitsValues * @see basicDigitsValues * @since 1.2, 2021-12-12 */ static get basicDigitsValues() { return ComPriFacNotConcept.cvBasicDigitsValues; } /** * :en: Getter for {@link cvBasicDigitsValuesMap}. * :de: Getter für {@link cvBasicDigitsValuesMap}. * * @returns {Map<number, string>} {@link cvBasicDigitsValuesMap} * @see cvBasicDigitsValuesMap * @see basicDigitsValuesMap * @since 1.5, 2021-12-16 */ static get basicDigitsValuesMap() { return ComPriFacNotConcept.cvBasicDigitsValuesMap; } /** * :en: Getter for {@link cvExponentSupers}. * :de: Getter für {@link cvExponentSupers}. * * @returns {string} {@link cvExponentSupers} * @see cvExponentSupers * @since 1.5, 2021-12-16 */ static get exponentSupers() { return ComPriFacNotConcept.cvExponentSupers; } /** * :en: Getter for {@link cvInitializationThrowable}. * :de: Getter für {@link cvInitializationThrowable}. * * @returns {any} {@link cvInitializationThrowable} * @see cvInitializationThrowable * @see initializationThrowable * @since 1.2, 2021-12-12 */ static get initializationThrowable() { return ComPriFacNotConcept.cvInitializationThrowable; } /** * :en: Getter for {@link cvCurrentScriptSrc}. * :de: Getter für {@link cvCurrentScriptSrc}. * * @returns {string} {@link cvCurrentScriptSrc} * @see cvCurrentScriptSrc * @see currentScriptSrc * @since 1.3, 2021-12-13 */ static get currentScriptSrc() { return ComPriFacNotConcept.cvCurrentScriptSrc; } /** * :en: Initializes this class and calls a call-back-function afterwards. * :de: Initialisiert diese Klasse und ruft anschließend eine Call-Back-Funktion auf. * * @param {() => any} pvCallBack Call-back-function */ static initialize(pvCallBack) { const lcCurrentScript = document.currentScript; if (!(lcCurrentScript instanceof HTMLScriptElement)) { const lcMessage = "Initialization error: currentScript not instanceof HTMLScriptElement!"; const lcError = new Error(lcMessage); ComPriFacNotConcept.initializationThrowable = lcError; pvCallBack(); } else { const lcSrc = lcCurrentScript.src; ComPriFacNotConcept.currentScriptSrc = lcSrc; // must be saved before asynch call const lcBasicDigitsJsonUrl = ComPriFacNotConcept.basicDigitsJsonUrl; ComPriFacNotConcept.loadJson(lcBasicDigitsJsonUrl, function (pvBasicJsonContent) { // Basic digits JSON could be loaded successfully const lcBasicDigitsDupels = JSON.parse(pvBasicJsonContent); const lcBasicDigitsMap = new Map(); const lcBasicDigitsArray = new Array(); const lcBasicDigitsValues = new Array(); const lcBasicDigitsValuesMap = new Map(); let i = -1; for (const lcBasicDigitsDupel of lcBasicDigitsDupels) { i++; const lcBasicDigit = lcBasicDigitsDupel[0]; const lcBasicDigitValue = lcBasicDigitsDupel[1]; lcBasicDigitsMap.set(lcBasicDigit, lcBasicDigitValue); lcBasicDigitsValuesMap.set(lcBasicDigitValue, lcBasicDigit); lcBasicDigitsArray[i] = lcBasicDigit; lcBasicDigitsValues[i] = lcBasicDigitValue; } const lcBasicDigitsString = lcBasicDigitsArray.join(""); ComPriFacNotConcept.basicDigits = lcBasicDigitsString; ComPriFacNotConcept.basicDigitsValues = lcBasicDigitsValues; ComPriFacNotConcept.basicDigitsMap = lcBasicDigitsMap; ComPriFacNotConcept.basicDigitsValuesMap = lcBasicDigitsValuesMap; const lcAliasDigitsJsonUrl = ComPriFacNotConcept.aliasDigitsJsonUrl; ComPriFacNotConcept.loadJson(lcAliasDigitsJsonUrl, function (pvAliasJsonContent) { // Alias digits JSON could be loaded successfully const lcAliasDigitsDupels = JSON.parse(pvAliasJsonContent); const lcAliasDigitsMap = new Map(); const lcAliasDigitsArray = new Array(); const lcAliasDigitsValues = new Array(); const lcAliasDigitsValuesMap = new Map(); let i = -1; for (const lcAliasDigitsDupel of lcAliasDigitsDupels) { i++; const lcAliasDigit = lcAliasDigitsDupel[0]; const lcAliasDigitValue = lcAliasDigitsDupel[1]; lcAliasDigitsMap.set(lcAliasDigit, lcAliasDigitValue); lcAliasDigitsValuesMap.set(lcAliasDigitValue, lcAliasDigit); lcAliasDigitsArray[i] = lcAliasDigit; lcAliasDigitsValues[i] = lcAliasDigitValue; } const lcAliasDigitsString = lcAliasDigitsArray.join(""); ComPriFacNotConcept.aliasDigits = lcAliasDigitsString; ComPriFacNotConcept.aliasDigitsValues = lcAliasDigitsValues; ComPriFacNotConcept.aliasDigitsMap = lcAliasDigitsMap; /* ComPriFacNotConcept.aliasDigitsValuesMap = lcAliasDigitsValuesMap; // TODO for future use (?) */ pvCallBack(); }, function () { // Alias digits JSON could not be loaded successfully pvCallBack(); }); }, function () { // Basic digits JSON could not be loaded successfully pvCallBack(); }); } } /** * :en: Loads JSON (asynch) and calls call-back-function. * :de: Lädt JSON (asynchron) und ruft Call-Back-Funktion. * * @param {string} pvJsonUrl URL for JSON * @param {(pvJsonContent: string) => any} pvOnSuccess Call-back-function on success * @param {() => any} pvOnError Call-back-function on error * @since 1.3, 2021-12-13 */ static loadJson(pvJsonUrl, pvOnSuccess, pvOnError) { const lcCurrentScriptSrc = ComPriFacNotConcept.currentScriptSrc; const lcUrl = lcCurrentScriptSrc + "/../" + pvJsonUrl; const lcRequest = new Request(lcUrl); const lcFetchPromise = fetch(lcRequest); lcFetchPromise.then(pvResponse => { try { const lcResponseOk = pvResponse.ok; if (lcResponseOk) { const lcResponseTextPromise = pvResponse.text(); // JSON with comments (.jsonc) lcResponseTextPromise.then(pvResponseText => { const lcFirstBracket = pvResponseText.indexOf("["); // Start of data const lcJson = pvResponseText.substring(lcFirstBracket); pvOnSuccess(lcJson); }); } else { const lcStatus = pvResponse.status; const lcMessage = "Initialization error: Load of JSON " + pvJsonUrl + " failed: HTTP-Status expected: 200; " + "HTTP-Status actual: " + lcStatus; const lcError = new Error(lcMessage); ComPriFacNotConcept.initializationThrowable = lcError; pvOnError(); } } catch (lcError) { ComPriFacNotConcept.initializationThrowable = lcError; pvOnError(); } }, (pvReason) => { ComPriFacNotConcept.initializationThrowable = pvReason; pvOnError(); }); } /** * :en: Setter for {@link #cvAliasDigits}. * :de: Setter für {@link #cvAliasDigits}. * * @param {string} pvAliasDigits {@link #cvAliasDigits} * @see cvAliasDigits * @see aliasDigits * @since 1.3, 2021-12-13 */ static set aliasDigits(pvAliasDigits) { ComPriFacNotConcept.cvAliasDigits = pvAliasDigits; } /** * :en: Getter for {@link cvAliasDigitsMap}. * :de: Getter für {@link cvAliasDigitsMap}. * * @param {Map<string, string>} pvAliasDigitsMap {@link cvAliasDigitsMap} * @see cvAliasDigitsMap * @see aliasDigitsMap * @since 1.3, 2021-12-13 */ static set aliasDigitsMap(pvAliasDigitsMap) { ComPriFacNotConcept.cvAliasDigitsMap = pvAliasDigitsMap; } /** * :en: Setter for {@link cvAliasDigitsValues}. * :de: Setter für {@link cvAliasDigitsValues}. * * @param {Array<string>} pvAliasDigitsValues {@link cvAliasDigitsValues} * @see cvAliasDigitsValues * @see aliasDigitsValues * @since 1.3, 2021-12-13 */ static set aliasDigitsValues(pvAliasDigitsValues) { ComPriFacNotConcept.cvAliasDigitsValues = pvAliasDigitsValues; } /** * :en: Setter for {@link #cvBasicDigits}. * :de: Setter für {@link #cvBasicDigits}. * * @param {string} pvBasicDigits {@link #cvBasicDigits} * @see cvBasicDigits * @see basicDigits * @since 1.2, 2021-12-12 */ static set basicDigits(pvBasicDigits) { ComPriFacNotConcept.cvBasicDigits = pvBasicDigits; } /** * :en: Getter for {@link cvBasicDigitsMap}. * :de: Getter für {@link cvBasicDigitsMap}. * * @param {Map<string, number>} pvBasicDigitsMap {@link cvBasicDigitsMap} * @see cvBasicDigitsMap * @see basicDigitsMap * @since 1.2, 2021-12-12 */ static set basicDigitsMap(pvBasicDigitsMap) { ComPriFacNotConcept.cvBasicDigitsMap = pvBasicDigitsMap; } /** * :en: Setter for {@link cvBasicDigitsValues}. * :de: Setter für {@link cvBasicDigitsValues}. * * @param {Array<number>} pvBasicDigitsValues {@link cvBasicDigitsValues} * @see cvBasicDigitsValues * @see basicDigitsValues * @since 1.2, 2021-12-12 */ static set basicDigitsValues(pvBasicDigitsValues) { ComPriFacNotConcept.cvBasicDigitsValues = pvBasicDigitsValues; } /** * :en: Setter for {@link cvBasicDigitsValuesMap}. * :de: Setter für {@link cvBasicDigitsValuesMap}. * * @param {Map<number, string>} pvBasicDigitsValuesMap {@link cvBasicDigitsValuesMap} * @see cvBasicDigitsValuesMap * @see basicDigitsValuesMap * @since 1.5, 2021-12-16 */ static set basicDigitsValuesMap(pvBasicDigitsValuesMap) { ComPriFacNotConcept.cvBasicDigitsValuesMap = pvBasicDigitsValuesMap; } /** * :en: Setter for {@link cvCurrentScriptSrc}. * :de: Setter für {@link cvCurrentScriptSrc}. * * @param {string} pvCurrentScriptSrc {@link cvCurrentScriptSrc} * @see cvCurrentScriptSrc * @see currentScriptSrc * @since 1.3, 2021-12-13 */ static set currentScriptSrc(pvCurrentScriptSrc) { ComPriFacNotConcept.cvCurrentScriptSrc = pvCurrentScriptSrc; } /** * :en: Setter for {@link cvInitializationThrowable}. * :de: Setter für {@link cvInitializationThrowable}. * * @param {any} pvInitializationThrowable {@link cvInitializationThrowable} * @see cvInitializationThrowable * @see initializationThrowable * @since 1.2, 2021-12-12 */ static set initializationThrowable(pvInitializationThrowable) { ComPriFacNotConcept.cvInitializationThrowable = pvInitializationThrowable; } }
JavaScript
class BaseScorePanel { static CONFIG = CONFIG.SCENES.GAME.GAME.SCORE; /** * Creates an instance of BaseScorePanel * @param {Phaser.Scene} scene - The Scene to which this Player belongs */ constructor(scene) { this.scene = scene; this.isFlashing = false; this.flashTween = this.createFlashTween(); // set maxScore to 10^MAX_LENGTH - 1 e.g. MAX_LENGTH = 5 so maxScore = 10^5 - 1 = 99_999 this.maxScoreLength = BaseScorePanel.CONFIG.MAX_LENGTH; this.maxScore = 10 ** (this.maxScoreLength - 1) - 1; this.defaultString = ''; // Register event handlers this.scene.events.on(CONFIG.EVENTS.GAME_START, this.onStart, this); this.scene.events.on(CONFIG.EVENTS.GAME_RESTART, this.onRestart, this); this.scene.events.on(CONFIG.EVENTS.GAME_OVER, this.onGameOver, this); this.createScoreText(); } /** * Create {Phaser.GameObjects. BitmapText} `scoreText` * @abstract * @throws Will throw an error if not implemented */ // eslint-disable-next-line class-methods-use-this createScoreText() { // create scoreText: BitmapText var here throw new Error('Method must be implemented by subclass'); } /** * Create score text flash tween * @param {number} duration - Tween duration * @param {number} iterations - Tween iterations * @param {function} [onStart=() => {}] - A function to be executed when tween starts * @param {function} [onComplete=() => {}] - A function to be executed when tween completes * @returns {Phaser.Tweens.Tween} Created Tween object */ createFlashTween(duration, iterations, onStart = () => {}, onComplete = () => {}) { return this.scene.tweens.create({ targets: this.scoreText, duration: 0, alpha: { start: 1, to: 10e-3, }, repeat: iterations, repeatDelay: duration, yoyo: true, hold: duration, completeDelay: duration, onStart: () => { this.isFlashing = true; onStart(); }, onComplete: () => { this.isFlashing = false; this.scoreText.setAlpha(1); onComplete(); }, }); } /** * Update score panel * @param {number} score - Current game score */ update(score) { if (score >= this.maxScore) { this.maxScoreLength += 1; this.maxScore = 10 ** (this.maxScoreLength - 1) - 1; } } /** * Set score * @param {number} score - Current game score */ setScore(score) { // create score string and padStart it to MAX_LENGTH with zeros // e.g. MAX_LENGTH = 5 and score = 418, so scoreString will be '00418' const scoreString = this.defaultString + score.toString().padStart(this.maxScoreLength, '0'); this.scoreText.setText(scoreString); } /** * Clear score */ clearScore() { this.setScore(0); } /** * Flash score text */ flashScore() { this.flashTween = this.createFlashTween(); this.flashTween.play(); } /** * Reset score panel */ reset() { this.flashTween.complete(); } /** * Handle game start */ // eslint-disable-next-line class-methods-use-this onStart() {} /** * Handle game restart */ onRestart() { this.isFlashing = false; this.flashTween = this.createFlashTween(); this.maxScoreLength = BaseScorePanel.CONFIG.MAX_LENGTH; this.maxScore = 10 ** (this.maxScoreLength - 1) - 1; } /** * Handle gameover */ onGameOver() { this.reset(); } }
JavaScript
class SuggestedParamsRequest extends jsonrequest_1.default { /* eslint-disable class-methods-use-this */ path() { return '/v2/transactions/params'; } prepare(body) { return { flatFee: false, fee: body.fee, firstRound: body['last-round'], lastRound: body['last-round'] + 1000, genesisID: body['genesis-id'], genesisHash: body['genesis-hash'], }; } }
JavaScript
class CleanFaction { /** * Constructor. * * @param {PlayerDeck} playerDesk * @param {string} factionNsidName - name portion "token.command:base/jolnar" -> "jolnar" */ constructor(playerDesk, factionNsidName) { assert(playerDesk instanceof PlayerDesk); assert(typeof factionNsidName === "string"); this._playerSlot = playerDesk.playerSlot; this._factionNsidName = factionNsidName; this._faction = Faction.getByNsidName(factionNsidName); assert(this._faction); this._extraNsids = new Set(); const extra = this._faction.raw.unpackExtra; if (extra) { extra.forEach((extra) => { if (extra.tokenNsid) { this._extraNsids.add(extra.tokenNsid); } if (extra.bagNsid) { this._extraNsids.add(extra.bagNsid); } }); } } /** * Remove the constructor-specified faction from the player desk/table. * This is only intended as an undo immediately after faction unpacking, * it should not be used once a game is in progress. */ clean() { // Scan objects, look inside decks. for (const obj of world.getAllObjects()) { if (obj.getContainer()) { continue; } // Clean owner tokens on table. if (ObjectNamespace.isControlToken(obj)) { if (obj.getOwningPlayerSlot() === this._playerSlot) { obj.destroy(); } } // Otherwise restrict to player desk. const closestDesk = PlayerDesk.getClosest(obj.getPosition()); if (closestDesk.playerSlot !== this._playerSlot) { continue; } if (obj instanceof Card && obj.getStackSize() > 1) { // Cards in a deck are not objects, pull them out. const nsids = ObjectNamespace.getDeckNsids(obj); for (let i = nsids.length - 1; i >= 0; i--) { const nsid = nsids[i]; if (this._shouldClean(nsid)) { let cardObj; if (obj.getStackSize() > 1) { //console.log(`${nsid}: ${i}/${obj.getStackSize()}`); cardObj = obj.takeCards(1, true, i); } else { cardObj = obj; // cannot take final card } assert(cardObj instanceof Card); cardObj.destroy(); } } } else { const nsid = ObjectNamespace.getNsid(obj); if (this._shouldClean(nsid)) { obj.destroy(); } } } } _shouldClean(nsid) { console.log("candidate " + nsid); const parsed = ObjectNamespace.parseNsid(nsid); // Placeholder faction sheet used during testing. // Remove this when real faction sheets are ready. if (nsid === "sheet.faction:base/???") { return true; } // Sheet ("sheet.faction:base/x"). if (nsid.startsWith("sheet.faction")) { const factionSlot = parsed.name.split(".")[0]; return factionSlot === this._factionNsidName; } // Tech ("card.technology.red.muaat"). if (nsid.startsWith("card.technology")) { const factionSlot = parsed.type.split(".")[3]; return factionSlot === this._factionNsidName; } // Promissory ("card.promissory.jolnar"). if (nsid.startsWith("card.promissory")) { const factionSlot = parsed.type.split(".")[2]; return factionSlot === this._factionNsidName; } // Leader ("card.leader.agent.x"). if (nsid.startsWith("card.leader")) { const factionSlot = parsed.type.split(".")[3]; return factionSlot === this._factionNsidName; } // Alliance "card.alliance:pok/faction" if (nsid.startsWith("card.alliance")) { const factionSlot = parsed.name.split(".")[0]; return factionSlot === this._factionNsidName; } // Command, control tokens. if ( nsid.startsWith("token.command") || nsid.startsWith("token.control") ) { const factionSlot = parsed.name.split(".")[0]; return factionSlot === this._factionNsidName; } // Command, control token bags. These are generic! if ( nsid.startsWith("bag.token.command") || nsid.startsWith("bag.token.control") ) { return true; } return this._extraNsids.has(nsid); } }
JavaScript
class AllocationDriverBase { /** * @param deviceConfig { Object } * @return {Promise<DeviceCookie>} */ async allocate(deviceConfig) {} // eslint-disable-line no-unused-vars /** * @param cookie { DeviceCookie } * @param options { DeallocOptions } * @return {Promise<void>} */ async free(cookie, options) {} // eslint-disable-line no-unused-vars }
JavaScript
class AuthenticatedRoute extends Component { componentWillMount() { let {check, login} = this.props; this.allowed = isUserAuthenticated(); if (!this.allowed) route(login || '/'); } render({ check, login, route: Route, ...props }) { return <div>{this.allowed && <Route {...props}/>}</div>; } }
JavaScript
class NetCordaCoreCryptoTransactionSignature { /** * Constructs a new <code>NetCordaCoreCryptoTransactionSignature</code>. * @alias module:io.generated.model/NetCordaCoreCryptoTransactionSignature * @param bytes {File} * @param by {String} Base 58 Encoded Public Key */ constructor(bytes, by) { NetCordaCoreCryptoTransactionSignature.initialize(this, bytes, by); } /** * 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, bytes, by) { obj['bytes'] = bytes; obj['by'] = by; } /** * Constructs a <code>NetCordaCoreCryptoTransactionSignature</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:io.generated.model/NetCordaCoreCryptoTransactionSignature} obj Optional instance to populate. * @return {module:io.generated.model/NetCordaCoreCryptoTransactionSignature} The populated <code>NetCordaCoreCryptoTransactionSignature</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new NetCordaCoreCryptoTransactionSignature(); if (data.hasOwnProperty('bytes')) { obj['bytes'] = ApiClient.convertToType(data['bytes'], File); } if (data.hasOwnProperty('by')) { obj['by'] = ApiClient.convertToType(data['by'], 'String'); } if (data.hasOwnProperty('signatureMetadata')) { obj['signatureMetadata'] = NetCordaCoreCryptoSignatureMetadata.constructFromObject(data['signatureMetadata']); } if (data.hasOwnProperty('partialMerkleTree')) { obj['partialMerkleTree'] = NetCordaCoreCryptoPartialMerkleTree.constructFromObject(data['partialMerkleTree']); } } return obj; } }
JavaScript
class TrainingTracker extends Component { constructor(props){ super(props) this.state = { nextWorkout: null, trackerData: {}, trackerOpen: false, tracker: null, workoutStarted: false, workoutEnded: false, workoutTime: 0, workoutName: null, activeDay: null, timerOn: false, timerStart: 0, timerTime: 0 } } componentDidMount() { //this.props.fetchPlanTemps() this.props.fetchActiveTrainingPlan() } startWorkout = () => { this.setState({trackerOpen:!this.state.trackerOpen}) } getWorkoutDayOrUndefined = () => { return Object.keys(this.props.activePlan.days[0]).find(date => new Date(date).toDateString() === new Date().toDateString()) } startTimer = async (workoutName) => { await this.setState({ timerOn: true, workoutStarted: true, workoutName: workoutName, timerTime: this.state.timerTime, timerStart: Date.now() - this.state.timerTime//moment().subtract( 'seconds', this.state.timerTime.getSecon) }) this.timer = setInterval(() => { this.setState({ timerTime: Date.now() - this.state.timerStart//moment().subtract('seconds', this.state.timerStart.seconds()).format('HH:mm') }) }, 10) } setNextWorkout = () =>{ //TODO: Refactor to include modal let eMap = [] let day = Object.keys(this.props.activePlan.days[0]).find(date => new Date(date).toDateString() === new Date().toDateString()) let updateData = (workout, value, type, set) => { //Assumes you won't do the same exercise twice in a workout let name = workout.split(' ').join('_') let trackerData = this.state.trackerData if (!trackerData[name]) trackerData[name] = {} if (!trackerData[name][set]) trackerData[name][set] = {} trackerData[name][set][type] = value this.setState({trackerData}) } if (!day) return <h5>Rest Up!</h5> else { this.props.activePlan.days[0][day].exercises.map((e,k)=>{ if (e) { eMap.push( <> <ListGroupItem style={{borderRadius:'10px'}} className='bg-dark text-white m-2'> <h6><strong>{e.name}</strong>{ ': ' + e.sets + ' x ' + e.reps}</h6> { e.note? <p className='mb-0'>Exercise note: {e.note}</p> : null } <Button color={this.state.tracker === k ? 'warning' : 'light'} size='sm' className='mb-2' onClick={()=>this.setState({tracker: this.state.tracker === k?null:k})}>Track Stats</Button> <Collapse isOpen={this.state.tracker===k}> {[...Array(parseInt(e.sets)).keys()].map(i=>{ return( <> <Label className='m-0'><strong>Set #{i+1}</strong></Label> <InputGroup className='my-2'> <InputGroupAddon addonType="prepend"> <InputGroupText>Weight Used(lb)</InputGroupText> </InputGroupAddon> <Input onChange={(event)=> updateData(e.name, event.target.value, 'weight',i+1)} placeholder='(optional)'/> </InputGroup> <InputGroup className='mb-3'> <InputGroupAddon addonType="prepend"> <InputGroupText>Reps Achieved </InputGroupText> </InputGroupAddon> <Input onChange={(event)=> updateData(e.name, event.target.value, 'reps', i+1)} placeholder='(optional)'/> </InputGroup> </>) })} </Collapse> </ListGroupItem> </> ) } }) } return( <ListGroup style={{maxHeight:'50vh', overflowY:'scroll'}}> {eMap} </ListGroup> ) } renderWorkoutStart = () => { let day = Object.keys(this.props.activePlan.days[0]).find(date => new Date(date).toDateString() === new Date().toDateString()) return ( <Row> <Collapse isOpen={this.state.workoutStarted} tag="h5" className="mt-2 col-md"> <ListGroupItemText> <Label>Timer</Label> <h4><Badge color="info" id='timer' pill> <Timer id='timer'> <Timer.Hours /> hr : <Timer.Minutes /> min : <Timer.Seconds /> sec </Timer> {/* {moment(this.state.timerTime).format('HH:mm')} */} </Badge></h4> </ListGroupItemText> </Collapse> <ButtonGroup className='justify-content-center col-md'> <Button onClick={()=>{ this.startTimer(this.props.activePlan.days[0][day].title) // this.setState({ workoutName:this.props.activePlan.days[0][day].title}) }} color='success'>Start Workout</Button> <Button disabled={!this.state.timerOn} onClick={()=>this.sendTrackerData()} color='danger'>End Workout</Button> </ButtonGroup> </Row> ) } sendTrackerData = async () => { let totalTime = document.getElementById('timer').innerText //HACK: let workoutData = { workoutName: this.state.workoutName, date: new Date(), totalTime, trackerData: this.state.trackerData } // console.log(workoutData) await this.props.sendWorkoutTrackerData(workoutData) alert('Workout completed!') this.setState({trackerOpen:false}) } /** * * * @memberof TrainingTracker */ renderTracker = () => { return ( <Modal isOpen={this.state.trackerOpen} toggle={this.startWorkout}> {/* <ModalHeader toggle={this.startWorkout}>{<h3>{this.props.activePlan.days[0][this.getWorkoutDayOrUndefined()].title }</h3>}</ModalHeader> */} <ModalBody> {/* {For loop here of current workout sets/reps/ note and optional place to fill in weights/reps achieved } */} {this.props.activePlan ? this.setNextWorkout() : null} </ModalBody> <ModalFooter style={{padding:'0.5rem'}}> {this.getWorkoutDayOrUndefined() ? this.renderWorkoutStart() : null} {/* <Button color="secondary" onClick={()=>this.setState({trackerOpen:false})}>Cancel</Button> */} </ModalFooter> </Modal> ) } render() { console.log(this.state) return ( <React.Fragment> {this.renderTracker()} <Button onClick={()=>this.setState({trackerOpen:true})}>View Workout</Button> </React.Fragment> ) } }
JavaScript
class GRpcClient { /** * Creates an instance of GRpcClient, and generate transaction sending and receiving methods * * @param {object|string} config - config object, if a string passed, will be used as the endpoint * @param {string} [config.endpoint="tcp://127.0.0.1:28210"] - grpc endpoint the client can connect to * @param {string} [config.chainId=""] - chainId used to construct transaction * @see GRpcClient.getRpcMethods */ constructor(config = 'tcp://127.0.0.1:28210') { let endpoint = ''; let chainId = ''; if (typeof config === 'string') { endpoint = config; } else { // eslint-disable-next-line prefer-destructuring endpoint = config.endpoint; // eslint-disable-next-line prefer-destructuring chainId = config.chainId; } if (!endpoint) { throw new Error('GRpcClient requires a valid `endpoint` to initialize'); } this._endpoint = endpoint; this._chainId = chainId; this._initRpcClients(); this._initRpcMethods(); createExtensionMethods(this, { encodeTxAsBase64: false }); } /** * Initialize grpc-node clients for each rpc service, lazy connection under the surface * * @private */ _initRpcClients() { const socket = this._endpoint.split('//').pop(); this.clients = Object.keys(rpcs).reduce((acc, x) => { debug('initRpcClient', x); acc[x] = new rpcs[x](socket, grpc.credentials.createInsecure()); return acc; }, {}); } /** * Initialize standard rpc methods defined in protobuf * * @private */ _initRpcMethods() { const groups = Object.keys(rpcs); groups.forEach(x => Object.keys(rpcs[x].methods).forEach(m => this._initRpcMethod(x, m))); } _initRpcMethod(group, method) { const client = this.clients[group]; const rpc = client[method].bind(client); const spec = rpcs[group].methods[method]; const { requestStream = false, responseStream = false, requestType, responseType } = spec; // debug('_initRpcMethod', { method, requestStream, responseStream, requestType, responseType }); let fn = null; // unary call, return Promise if (requestStream === false && responseStream === false) { fn = params => new Promise((resolve, reject) => { const request = this._createRequest(requestType, params); rpc(request, this._createResponseHandler({ method, resolve, reject, responseType })); }); // response streaming: return EventEmitter } else if (requestStream === false && responseStream) { fn = params => { const request = this._createRequest(requestType, params); const stream = rpc(request); const emitter = this._createStreamHandler({ method, stream, responseType }); return emitter; }; // request streaming: return Promise } else if (requestStream && responseStream === false) { fn = params => new Promise((resolve, reject) => { const stream = rpc(this._createResponseHandler({ method, resolve, reject, responseType })); (Array.isArray(params) ? params : [params]).forEach(x => { const request = this._createRequest(requestType, x); stream.write(request); }); stream.end(); }); // request & response streaming: return EventEmitter } else { fn = params => { const stream = rpc(); const emitter = this._createStreamHandler({ method, stream, responseType }); (Array.isArray(params) ? params : [params]).forEach(x => { debug('stream request', { method, requestType, x }); const request = this._createRequest(requestType, x); stream.write(request); }); stream.end(); return emitter; }; } fn.rpc = true; fn.meta = { group, requestStream, responseStream, requestType, responseType }; fn.$format = data => formatMessage(responseType, data); attachExampleFn(requestType, fn, '$requestExample'); attachExampleFn(responseType, fn, '$responseExample'); this[camelCase(method)] = fn; } /** * List standard rpc methods * * @returns {object} */ getRpcMethods() { return Object.keys(this) .filter(x => typeof this[x] === 'function' && this[x].rpc) .reduce((acc, x) => { acc[x] = this[x].meta; return acc; }, {}); } /** * Create an request object from params object * * @private * @param {String} requestType * @param {Object} [params={}] */ _createRequest(type, _params) { const { fn: Message, fields } = getMessageType(type); if (!Message) { throw new Error(`Unsupported messageType: ${type}`); } if (!fields) { throw new Error(`Unsupported messageFields: ${type}`); } const request = createMessage(type, _params || {}); debug('_createRequest', { type, request: request.toObject() }); return request; } /** * Create unary response handler * * @private * @param {*} method * @param {*} resolve * @param {*} reject */ _createResponseHandler({ method, resolve, reject, responseType }) { return (err, response) => { if (err) { return reject(err); } const res = response.toObject(); debug('Rpc Response', method, res); if (res.code) { return reject(this._createResponseError(res.code, method)); } attachFormatFn(responseType, res); return resolve(res); }; } /** * Create stream response handler * * @private * @param {*} method * @param {*} stream */ _createStreamHandler({ method, stream, responseType }) { const emitter = new EventEmitter(); stream .on('data', response => { const res = response.toObject(); if (res.code) { emitter.emit('error', this._createResponseError(res.code, method)); return; } attachFormatFn(responseType, res); emitter.emit('data', res); }) .on('error', err => emitter.emit('error', err)) .on('close', () => emitter.emit('close', undefined)) .on('end', () => emitter.emit('end', undefined)); return emitter; } _createResponseError(status, method) { const code = messages.StatusCode[status].toLowerCase(); if (errorCodes[code]) { const type = snakeCase(method); const message = (errorCodes[code][type] || errorCodes[code].default || code).trim(); const error = new Error(`${method} failed with status ${code}, possible reason: ${message}`); error.code = code; error.type = type; return error; } const error = new Error(`gRPC response error: ${code}, method: ${method}`); error.errcode = code; error.errno = status; return error; } /** * Prepare an declare transaction when the chain has enabled restricted declare * * @memberof GRpcClient * @function * @param {object} params * @param {string} params.moniker - account moniker * @param {string} params.issuer - issuer address * @param {string} params.delegator - the delegator address * @param {WalletObject} params.wallet - the wallet that want to do the declare * @param {object} extra - other param to underlying client implementation * @returns {Promise} the `transaction` object once resolved */ // prepareDeclareNode({ moniker, issuer, wallet, data, delegator = '' }, extra) { // return this.signDeclareTx( // { // tx: { // itx: { // moniker, // issuer, // data, // }, // }, // delegator, // wallet, // }, // extra // ); // } /** * Finalize an declare transaction using the issuer's account * * @memberof GRpcClient * @function * @param {object} params * @param {object} params.tx - the transaction object from `prepareExchange` * @param {string} params.delegator - who authorized this transaction * @param {object} params.data - extra data in the multi sig * @param {WalletObject} params.wallet - issuer's wallet * @param {object} extra - other param to underlying client implementation * @returns {Promise} the `transaction` object once resolved */ // finalizeDeclareNode({ tx, delegator = '', data, wallet }, extra) { // return this.multiSignDeclareTx( // { // tx, // delegator, // data, // wallet, // }, // extra // ); // } }
JavaScript
class SpecEvent { constructor (attr) { this.id = attr.id this.coreContext = attr.coreContext } specStart (specContext) { console.info('start running case \'' + specContext.description + '\'') } specDone (specContext) { // 获取报告打印服务 let reportService = this.coreContext.getDefaultService('report') if (specContext.error) { reportService.formatPrint('fail', specContext.description) reportService.formatPrint('failDetail', specContext.error) } else if (specContext.result) { if (specContext.result.failExpects.length > 0) { reportService.formatPrint('fail', specContext.description) specContext.result.failExpects.forEach(failExpect => { const msg = failExpect.message || ('expect ' + failExpect.actualValue + ' ' + failExpect.checkFunc + ' ' + (failExpect.expectValue || '')) reportService.formatPrint('failDetail', msg) }) } else { reportService.formatPrint('pass', specContext.description) } } } }
JavaScript
class RedditFetcher { constructor(bot) { this.bot = bot; this.subreddits = []; } // Fetch new posts (every 1 minute) async fetchPosts() { setInterval(async () => { for (const { subredditName: sub, channelIDs } of this.subreddits) { const resp = await fetch(`https://www.reddit.com/r/${sub}/new.json`).then(res => res.json()); if (resp.data?.children) { for (const { data } of resp.data.children.reverse()) { if (date <= data.created_utc) { if (debug) this.bot.logger.debug(`Recieved new ${data.subreddit} post: ${data.title}.`); const Post = new RedditPost(data); const embed = new MessageEmbed() .setTitle(`New post from r/${Post.subreddit}`) .setURL(Post.link) .setImage(Post.imageURL); if (Post.text) embed.setDescription(Post.text); channelIDs.forEach((id) => { this.bot.addEmbed(id, embed);}); } } } } date = Math.floor(Date.now() / 1000); }, 60000); } // Updates subreddit list every 5 minutes async updateSubredditList() { // fetch reddit data from database const subreddits = await RedditSchema.find({}); if (!subreddits[0]) return this.bot.logger.error('Reddit: No subreddits to load.'); this.subreddits = []; for (const subreddit of subreddits) { if (subreddit.channelIDs.length >= 1) { this.bot.logger.log(`Reddit: Added ${subreddit.subredditName} to the watch list.`); this.subreddits.push(subreddit); } else { await RedditSchema.findOneAndRemove({ subredditName: subreddit.subredditName }, (err) => { if (err) console.log(err); }); } } } // init the class async init() { this.bot.logger.log('Reddit: Loading module...'); await this.updateSubredditList(); await this.fetchPosts(); this.bot.logger.ready('Reddit: Loaded module.'); // Update subreddit list every 5 minutes setInterval(async () => { await this.updateSubredditList(); }, 5 * 60000); } }
JavaScript
class Welcome extends Component{ render(){ return( <div> <h1>Welcome Props in class component {this.props.name}</h1> </div> ) } }
JavaScript
class Level { constructor(config = {},logger) { logger.info('[level-auth] initialized'); config.file = isAbsolute(config.file) ? config.file: resolve(dirname(config.self_path),config.file); config.max_users = config.max_users === undefined ? Infinity : config.max_users; this.logger = logger; this.config = config; assert(this.config.file, 'missing "file" in config'); this.db = new Db(this.config.file,this.logger); } _genErr(msg, status) { const err = new Error(msg); err.status = status; return err; } async _check(obj, action) { let verified, user; if (!obj.username || !obj.password) { return this._genErr('username and password is required', 400); } if (action === 'register') { user = await this.db.getUser(obj.username); if (user) { return this._genErr('username is already registered', 409); } if (this.config.max_users < 0) { return this._genErr('user registration disabled', 409); } const count = await this.db.getCount(); if (count >= this.config.max_users) { return this._genErr('maximum amount of users reached', 403); } } else if (action === 'authenticate' || action === 'edit') { user = await this.db.getUser(obj.username); if (!user) { return this._genErr('username not found', 409); } verified = await this.db.verifyUser(obj.username, obj.password); if (!verified) { return this._genErr('unauthorized access', 401); } } return null; } /** * authenticate - Authenticate user. * @param {string} user * @param {string} password * @param {function} cb * @returns {function} */ authenticate(user, password, cb) { this.logger.info('[level-plugin] authenticate:',user); this._check({ username: user, password }, 'authenticate').then((err) => { if (err) { this.logger.error('[level-plugin] authenticate:',err.message); return cb(err); } // TODO: support usergroups return cb(null,[user]); }).catch((err) => { this.logger.error('[level-plugin] authenticate:',err.message); return cb(err); }); } /** * adds a user * * @param {string} user * @param {string} password * @param {function} realCb * @returns {function} */ adduser(user, password, cb) { this.logger.info('[level-plugin] adduser:',user); this._check({ username: user, password }, 'register').then((err) => { if (err) { this.logger.error('[level-plugin] adduser:',err.message); return cb(err); } this.db.addUser(user, password).then(() => { return cb(null,true); }).catch((err) => { this.logger.error('[level-plugin] adduser:',err.message); return cb(err); }); }).catch((err) => { this.logger.error('[level-plugin] adduser:',err.message); return cb(err); }); } /** * changePassword - change password for existing user. * @param {string} user * @param {string} password * @param {function} cd * @returns {function} */ changePassword(user, password, newpassword, cb) { this.logger.info('[level-plugin] changePassword:',user); this._check({ username: user, password }, 'edit').then((err) => { if (err) { this.logger.error('[level-plugin] changePassword:',err.message); return cb(err); } this.db.addUser(user, password).then(() => { return cb(null,true); }).catch((err) => { this.logger.error('[level-plugin] changePassword:',err.message); return cb(err); }); }).catch((err) => { this.logger.error('[level-plugin] changePassword:',err.message); return cb(err); }); } }
JavaScript
class Main extends PlantWorksBaseComponent { // #region Constructor constructor(parent, loader) { super(parent, loader); } // #endregion // #region Protected methods - need to be overriden by derived classes /** * @async * @function * @override * @instance * @memberof Main * @name _addRoutes * * @returns {undefined} Nothing. * * @summary Adds routes to the Koa Router. */ async _addRoutes() { try { this.$router.get('/users/:user_id', this.$parent._rbac('registered'), this._getProfile.bind(this)); this.$router.patch('/users/:user_id', this.$parent._rbac('registered'), this._updateProfile.bind(this)); this.$router.del('/users/:user_id', this.$parent._rbac('registered'), this._deleteProfile.bind(this)); this.$router.get('/get-image', this.$parent._rbac('registered'), this._getProfileImage.bind(this)); this.$router.post('/upload-image', this.$parent._rbac('registered'), this._updateProfileImage.bind(this)); this.$router.post('/changePassword', this.$parent._rbac('registered'), this._changePassword.bind(this)); this.$router.post('/user-contacts', this.$parent._rbac('registered'), this._addContact.bind(this)); this.$router.del('/user-contacts/:user_contact_id', this.$parent._rbac('registered'), this._deleteContact.bind(this)); await super._addRoutes(); return null; } catch(err) { throw new PlantWorksComponentError(`${this.name}::_addRoutes error`, err); } } // #endregion // #region Route Handlers async _getProfile(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const userData = await apiSrvc.execute('Main::getProfile', ctxt); ctxt.status = 200; ctxt.body = userData.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error retrieving profile data`, err); } } async _updateProfile(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const userData = await apiSrvc.execute('Main::updateProfile', ctxt); ctxt.status = 200; ctxt.body = userData.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error updating profile data`, err); } } async _deleteProfile(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; await apiSrvc.execute('Main::deleteProfile', ctxt); ctxt.status = 204; return null; } catch(err) { throw new PlantWorksComponentError(`Error deleting profile`, err); } } async _getProfileImage(ctxt) { try { const path = require('path'); const send = require('koa-send'); const apiSrvc = this.$dependencies.ApiService; let userData = await apiSrvc.execute('Main::getProfile', ctxt); userData = userData.shift(); const profileImageFolder = this.$parent.$config.profileImagePath; const profileImagePath = path.join(profileImageFolder, `${userData.data.attributes.profile_image}.png`); const profileImageExists = await this._exists(profileImagePath); if(profileImageExists) await send(ctxt, profileImagePath); else await send(ctxt, path.join(profileImageFolder, 'anonymous.jpg')); return null; } catch(err) { throw new PlantWorksComponentError(`Error retrieving profile image`, err); } } async _updateProfileImage(ctxt) { try { const fs = require('fs'); const path = require('path'); const promises = require('bluebird'); const uuid = require('uuid/v4'); const filesystem = promises.promisifyAll(fs); const apiSrvc = this.$dependencies.ApiService; let userData = await apiSrvc.execute('Main::getProfile', ctxt); userData = userData.shift(); const currentImageId = userData.data.attributes.profile_image, image = ctxt.request.body.image.replace(/' '/g, '+').replace('data:image/png;base64,', ''), imageId = uuid().toString(); let profileImageFolder = this.$parent.$config.profileImagePath; if(!path.isAbsolute(profileImageFolder)) profileImageFolder = path.join(path.dirname(path.dirname(require.main.filename)), profileImageFolder); const profileImagePath = path.join(profileImageFolder, `${imageId}.png`); await filesystem.writeFileAsync(profileImagePath, Buffer.from(image, 'base64')); ctxt.request.body = { 'data': { 'id': ctxt.state.user.user_id, 'type': 'profile/users', 'attributes': { 'profile_image': imageId, 'profile_image_metadata': ctxt.request.body.metadata } } }; await apiSrvc.execute('Main::updateProfile', ctxt); ctxt.status = 200; ctxt.body = { 'status': true, 'responseText': 'Profile Image Updated succesfully' }; if(!currentImageId) return null; if(currentImageId === 'f8a9da32-26c5-495a-be9a-42f2eb8e4ed1') return null; const currentImageExists = await this._exists(path.join(profileImageFolder, `${currentImageId}.png`)); if(currentImageExists) await filesystem.unlinkAsync(path.join(profileImageFolder, `${currentImageId}.png`)); return null; } catch(err) { throw new PlantWorksComponentError(`Error updating profile image`, err); } } async _changePassword(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const status = await apiSrvc.execute('Main::changePassword', ctxt); ctxt.status = 200; ctxt.body = status.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error updating password`, err); } } async _addContact(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; const status = await apiSrvc.execute('Main::addContact', ctxt); ctxt.status = 200; ctxt.body = status.shift(); return null; } catch(err) { throw new PlantWorksComponentError(`Error adding contact`, err); } } async _deleteContact(ctxt) { try { const apiSrvc = this.$dependencies.ApiService; await apiSrvc.execute('Main::deleteContact', ctxt); ctxt.status = 204; return null; } catch(err) { throw new PlantWorksComponentError(`Error deleting contact`, err); } } // #endregion // #region Properties /** * @override */ get dependencies() { return ['ApiService'].concat(super.dependencies); } /** * @override */ get basePath() { return __dirname; } // #endregion }
JavaScript
class WeatherService { /** * Set up WeatherService * @param {Object} $http * @param {Object} WEATHER_CONFIG */ constructor($http, WEATHER_CONFIG, ecCalloutService) { /** * @typedef {Object} weatherData * @property {boolean} geolocationEnabled Whether the geo loc is enabled or not * @property {string} name Location name * @property {Object} main Object containing data about weather, such as pressure, humidity and temp * @property {Array} weather Containing objects with data related to the weather icon displayed */ this.weatherData = { geolocationEnabled: true } this.$http = $http; this.WEATHER_CONFIG = WEATHER_CONFIG; this.CalloutService = ecCalloutService; } /** * @returns {weatherData} Object containing weather data */ getWeatherData() { return this.weatherData; } /** * Sets weather data * @param {weatherData} weatherData Object containing weather data */ setWeatherData(weatherData) { // Assign properties from response.data to weatherData for(var key in weatherData) this.weatherData[key] = weatherData[key]; } /** * Gets weather using provided params * @param {Object} params The parameters provided by a user * @param {string} params.latitude * @param {string} params.longitude * @param {string} params.zip The city ZIP code * @param {string} params.country The country code (CZ, GB, ...) */ getWeather(params) { return this.$http({ method: 'GET', url: this.WEATHER_CONFIG.API_URL, params: { lat: params.latitude, lon: params.longitude, // zip must be in format: zip,countryCode zip: params.zip && params.country ? params.zip.toLowerCase().replace(/\s/g, "") + ',' + params.country.toLowerCase().replace(/\s/g, "") : '', units: 'metric', APPID: this.WEATHER_CONFIG.APP_ID } }).then( function fulfilled(response) { // Check for response.data.cod property // If it's not 200, the response is not successful // This happens when API's response status is 200 (which is basically // success and therefore handled here), yet the API responded // with data containing cod: "404", which is an error if(response.data.cod != 200) { // Disable geolocation in order for the manual form to be displayed this.disableGeolocation(response.data.message); // Otherwise, if it's cod: "200", we have successful response and can handle the data } else { // Assign properties from response.data to weatherData this.setWeatherData(response.data); // Send a notification about success this.CalloutService.notify({ type: 'success', message: 'Weather data successfully fetched', img: 'https://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/svgs/fi-check.svg', timeout: 2000 }); } }.bind(this), /** * If there was an error during the process, log it */ function rejected(error) { console.error(error); } ); } disableGeolocation(error = 'There was an error while retrieving your location, please provide details to display weather') { this.weatherData.geolocationEnabled = false; // Notify this.CalloutService.notify({ type: 'alert', message: error, img: 'https://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/svgs/fi-alert.svg', timeout: 4000 }); } }
JavaScript
class APIBase { /** * @param {string} distDir - Directory path of distributed resources. */ constructor(distDir) { /** * Directory path of model files * @type{string} * @protected */ this.modelDir = `${distDir}/model` /** * Topology data converter with data cache function. * @type {CacheRfcTopologyDataConverter} * @protected */ this.converter = new CacheRfcTopologyDataConverter(this.modelDir, distDir) } /** * Get all model file information * @see static/model/_index.json * @returns {Promise<null|Object>} - Model file indexes (`_index.json`) * @public */ async getModels() { const modelsFile = `${this.modelDir}/_index.json` try { const buffer = await asyncReadFile(modelsFile) return JSON.parse(buffer.toString()) } catch (error) { console.log(error) return null } } /** * Read graph layout data from layout file. * @param {string} jsonName - File name of layout file (json). * @returns {Promise<null|LayoutData>} Layout data. * @protected */ async readLayoutJSON(jsonName) { try { const baseName = jsonName.split('.').shift() const layoutJsonName = `${this.modelDir}/${baseName}-layout.json` const buffer = await asyncReadFile(layoutJsonName) return JSON.parse(buffer.toString()) } catch (error) { console.log(`Layout file correspond with ${jsonName} was not found.`) // layout file is optional. // when found (layout file was not found), use default layout. return null } } /** * Convert rfc-topology data to topology data to draw diagram. * @param {string} jsonName - File name of rfc-topology data. * @returns {Promise<ForceSimulationTopologyData>} topology data for force-simulation diagram. * @protected */ toForceSimulationTopologyData(jsonName) { return this.converter.toForceSimulationTopologyData(jsonName) } /** * Convert rfc-topology data to topology data for dependency diagram. * @param {string} jsonName - file name of rfc-topology data. * @param {Request|proto.netoviz.GraphRequest} req - HTTP/gRPC request. * @returns {Promise<DependencyTopologyData>} Graph data object for nested graph. * @abstract * @protected */ async toDependencyTopologyData(jsonName, req) { /** * @typedef {Object} DependencyGraphQuery * @prop {string} target * @prop {ForceSimulationTopologyData} topologyData */ } /** * Convert rfc-topology data to topology data for nested diagram. * @param {string} jsonName - file name of rfc-topology data. * @param {Request|proto.netoviz.GraphRequest} req - HTTP/gRPC request. * @returns {Promise<NestedTopologyData>} Graph data object for nested graph. * @abstract * @protected */ async toNestedTopologyData(jsonName, req) { /** * @typedef {Object} NestedGraphQuery * @prop {boolean} reverse * @prop {number} depth * @prop {string} target * @prop {string} layer * @prop {boolean} aggregate * @prop {ForceSimulationTopologyData} topologyData * @prop {LayoutData} layoutData */ } /** * Convert rfc-topology data to topology data for distance diagram. * @param {string} jsonName - file name of rfc-topology data. * @param {Request|proto.netoviz.GraphRequest} req - HTTP/gRPC request. * @returns {Promise<DistanceTopologyData>} Graph data object for distance graph. * @abstract * @protected */ async toDistanceTopologyData(jsonName, req) { /** * @typedef {Object} DistanceGraphQuery * @prop {string} target * @prop {string} layer * @prop {ForceSimulationTopologyData} topologyData */ } /** * Get converted graph data for web-frontend visualization. * @param {string} graphName - Graoh name (type). * @param {string} jsonName - Topology data file name (json). * @param {Request|proto.netoviz.GraphRequest} req - HTTP/gRPC request. * @returns {Promise<string>} Graph data as JSON format string. * @public */ async getGraphData(graphName, jsonName, req) { try { let data = { error: 'invalid graph name', graphName } // default if (graphName === 'forceSimulation') { data = await this.toForceSimulationTopologyData(jsonName) } else if (graphName === 'dependency') { data = await this.toDependencyTopologyData(jsonName, req) } else if (graphName === 'nested') { data = await this.toNestedTopologyData(jsonName, req) } else if (graphName === 'distance') { data = await this.toDistanceTopologyData(jsonName, req) } return JSON.stringify(data) } catch (error) { // catch-up all exceptions about target/cache file handling. console.error(error) return JSON.stringify({ error: 'invalid data file', jsonName }) } } // delegate splitAlertHost(alertHost) { return splitAlertHost(alertHost) } }
JavaScript
class Formatter { constructor(template) { this.template = template; } /** * @arg {Logger} log * @return {String} */ static format(log, formatter) { const tmpltType = typeof formatter.template; if (!(tmpltType === 'string')) { throw Error('options.formatter should be type: "string", not: "' + tmpltType + '"'); } let transformed = splitAndJoin( formatter.template, / [-|,] /g, (seg) => format(seg, log) ); return transformed; } }
JavaScript
class HTMLReport { print(report) { const html = ` <div> <h1>Analysis Output</h1> <div> <p>${report}</p> </div> </div> `; fs_1.default.writeFileSync('reports.html', html); } }
JavaScript
class Chat extends Component { renderMessages(message, key) { const { message: msg, orign: author } = message return ( <div key={key}> {author === 'user' && <span> <Badge color="primary"> voce disse: </Badge> <Alert color="primary">{msg} </Alert> </span>} {author === 'bot' && <span> <Badge color="warning"> Bot disse:</Badge> <Alert color="warning"> {msg}</Alert> </span>} </div> ) } render() { return ( <div className="chat-conversa"> { Object.keys(this.props.messages).map(key => this.renderMessages(this.props.messages[key], key)) } </div> ) } }
JavaScript
class Alien { constructor(x,y,width=40,height=40,hitten=0, color='pink', moving=0.25) { this.x = x; this.y = y; this.width = width; this.height = height; this.hitten = hitten; this.color = color this.moving = moving; } show() { ctx.drawImage(virus, this.x, this.y, this.width, this.height); } move() { this.x += this.moving; if (this.y >= (spaceShip.y-spaceShip.height)) { spaceShip.lives = 0 //if the viruses reach the player game over } } }
JavaScript
class Endgegner extends Alien { constructor(x,y,width=240,height=240,hitten=0,color,moving=0.8 ) { super(x,y,width,height,hitten,color,moving) } showEnd() { ctx.drawImage(virus2, this.x, this.y, this.width, this.height); //the picture } moveEnd() { //the moving into the screen and the normal moving if (this.y <= 30) {this.y += this.moving} else { this.x += this.moving } // the Instance speeds up after hitten switch (this.hitten) { case 5 : this.hitten++; this.moving = 1.3; this.y += 10; break; case 10: this.hitten++ this.moving = 2; this.y += 2; break; case 20: this.hitten++ this.moving = 3; this.y += 2; break; } } //Instance shoots in several time fight() { if (timer === 4) { // the time intervall of shooting is depending on the hitten number (doubling after 10 hits) this.hitten <= 10 ? timer=0 : timer =2; // shot is created (instance of class backfire) let shoot = new Backfire(this.x+spaceShip.width/2,this.y+240,0); // the shot is directed to player depending on the relative postion of the player vs the endgegner shoot.direction = (spaceShip.x-this.x)/44 // the instance is pushed into array of backshots backfire.push(shoot); } } }
JavaScript
class PitchToggle { //create a class that has the pitch and bearing constructor({ bearing = 0, pitch = 60, minpitchzoom = null }) { this._bearing = bearing; this._pitch = pitch; this._minpitchzoom = minpitchzoom; } onAdd(map) { this._map = map; let _this = this; this._btn = document.createElement('button');// create the 3d button this._btn.className = 'mapboxgl-ctrl-icon mapboxgl-ctrl-pitchtoggle-3d';// set the class name for css styling this._btn.type = 'button'; this._btn['aria-label'] = 'Toggle Pitch';//not sure this._btn.onclick = function () { //when the button is clicked if (map.getPitch() === 0) {// if the pitch is 0 then run this let options = { pitch: _this._pitch, bearing: _this._bearing };// grab the pitch & bearing from the class constructor // if (_this._minpitchzoom && map.getZoom() > _this._minpitchzoom) {//dont really need // options.zoom = _this._minpitchzoom; // } map.easeTo(options); _this._btn.className = 'mapboxgl-ctrl-icon mapboxgl-ctrl-pitchtoggle-2d';//change button to show 2d after change } else { map.easeTo({ pitch: 0, bearing: 0 });// reset back to 2D if the pitch is not 0 _this._btn.className = 'mapboxgl-ctrl-icon mapboxgl-ctrl-pitchtoggle-3d';//change button to show 3d after change } }; this._container = document.createElement('div');// create a div this._container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group'; this._container.appendChild(this._btn); return this._container; } onRemove() { this._container.parentNode.removeChild(this._container); this._map = undefined; } }
JavaScript
class StateArtists extends Component { state = { savedCheck: true, search: '', currentPage: 1, }; //load data if no artists async componentDidMount() { window.scroll(0, 0); const currentState = this.props.match.params.state; if ( this.props.stateArtists.length === 0 || this.props.stateArtists[0].stateAbbrev !== currentState ) { await this.props.fetchStateArtists(currentState); } } componentWillUnmount() { if (this.state.currentPage !== 1) { this.props.fetchStateArtists(this.props.match.params.state); } } componentDidUpdate() { this.saved(); } saved = () => { if ( this.props.isLoggedIn && this.props.savedArtists.length === 0 && this.state.savedCheck ) { this.props.fetchSaved(); this.setState({ savedCheck: false }); } }; incrementPage = async () => { try { await this.props.fetchStateArtists( this.props.match.params.state, this.state.currentPage + 1, this.state.search ); this.setState((prevState) => ({ currentPage: prevState.currentPage + 1, })); window.scroll(0, 0); } catch (err) { console.error(err); } }; decrementPage = async () => { try { await this.props.fetchStateArtists( this.props.match.params.state, this.state.currentPage - 1, this.state.search ); this.setState((prevState) => ({ currentPage: prevState.currentPage - 1, })); window.scroll(0, 0); } catch (err) { console.error(err); } }; jumpToPage = async (page) => { try { await this.props.fetchStateArtists( this.props.match.params.state, page, this.state.search ); this.setState({ currentPage: page }); window.scroll(0, 0); } catch (err) { console.error(err); } }; searchForArtists = async (evt) => { evt.preventDefault(); const name = evt.target.name.value; await this.props.fetchStateArtists(this.props.match.params.state, 1, name); this.setState({ search: name }); }; render() { return ( //if there are no artists in this state load informative message this.props.stateArtists.length === 0 ? ( <div className="noStateArtistsContainer"> <div className="noStateArtists"> <h1>Searching...</h1> </div> </div> ) : ( <div className="stateArtistsDiv"> <h1 className="stateArtistsTitle"> {getStateFullName( this.props.stateArtists[0].stateAbbrev ).toUpperCase()} </h1> <Search onSubmit={this.searchForArtists} label={'Search Artists'} placeholder={'Name'} /> <div className="stateArtistsContainer"> {this.props.stateArtists.map((artist) => ( //map over artists and display link for their individual page <div key={artist.id}> <Link className="stateArtistPic" to={`/RapMap/${artist.stateAbbrev}/${ artist.name.split(' ').join('') + `_${artist.id}` }`} > <div className="stateArtistName"> <div className="stateArtistNameText">{artist.name}</div> </div> <img src={artist.imageURL} /> </Link> </div> ))} </div> {new Array(Math.ceil(this.props.numArtists / 50)).length > 1 && ( <Pagination totalPages={new Array(Math.ceil(this.props.numArtists / 50)).fill( null )} currentPage={this.state.currentPage} incrementPage={this.incrementPage} decrementPage={this.decrementPage} jumpToPage={this.jumpToPage} /> )} </div> ) ); } }
JavaScript
class Header { constructor(el, data) { this.el = el; this.data = data; //this.$el= $(el) this.initListeners(); } initListeners(){ } }
JavaScript
class UserDataHandler { /** *Creates an instance of UserDataHandler. * @memberof UserDataHandler */ constructor () { this.users = [] } /** * A method for loading users data from the server * @return {Promise} if successful updates users array of the calass instance * @memberof UserDataHandler */ async loadUsers () { const response = await axios.get('http://localhost:3000/users').catch(err => { throw new Error(`Failed to load users data: ${err}`) }) this.users = response.data } /** * * A method for creating a string containing al user emails * @return {String} a string containing all the users emails separated by a semicolon * @memberof UserDataHandler */ getUserEmailsList () { if (this.users.length === 0) throw new Error('No users loaded!') const arrayOfEmails = this.users.map(user => user.email) const listOfUSerEmails = arrayOfEmails.join(';') return listOfUSerEmails } /** * * A method for retrieving number of current users * @return {Number} current number of users in class instance * @memberof UserDataHandler */ getNumberOfUsers () { return this.users.length } /** * * * @param {Object} user user object to be checked * @param {Object} searchParamsObject object containing search parameters in key-value pairs * @return {Boolean} returns true if user object matches all provided search parameters * @memberof UserDataHandler */ isMatchingAllSearchParams (user, searchParamsObject) { let isMatching = true for (const searchParam in searchParamsObject) { if (user[searchParam] !== searchParamsObject[searchParam]) { isMatching = false } if (isMatching === false) break } return isMatching } /** * * * @param {Object} searchParamsObject object containing search parameters in key-value pairs * @return {Array<Object>} array of objects that match provided search parameters * @memberof UserDataHandler */ findUsers (searchParamsObject) { if (!searchParamsObject) throw new Error('No search parameters provoded!') if (this.users.length === 0) throw new Error('No users loaded!') const matchingUsers = this.users.filter(user => this.isMatchingAllSearchParams(user, searchParamsObject)) if (matchingUsers.length === 0) throw new Error('No matching users found!') return matchingUsers } }