language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class TokenUser { get createdOstStatus() { return 'CREATED'; } get activatingOstStatus() { return 'ACTIVATING'; } get activatedOstStatus() { return 'ACTIVATED'; } get ostStatuses() { const oThis = this; return { '1': oThis.createdOstStatus, '2': oThis.activatingOstStatus, '3': oThis.activatedOstStatus }; } get invertedOstStatuses() { const oThis = this; if (invertedOstStatuses) { return invertedOstStatuses; } invertedOstStatuses = util.invert(oThis.ostStatuses); return invertedOstStatuses; } get airdropDoneProperty() { return 'AIRDROP_DONE'; } get airdropStartedProperty() { return 'AIRDROP_STARTED'; } get airdropFailedProperty() { return 'AIRDROP_FAILED'; } get tokenHolderDeployedProperty() { return 'TOKEN_HOLDER_DEPLOYED'; } get properties() { const oThis = this; if (!propertiesHash) { propertiesHash = { '1': oThis.tokenHolderDeployedProperty, '2': oThis.airdropStartedProperty, '4': oThis.airdropDoneProperty, '8': oThis.airdropFailedProperty }; } return propertiesHash; } get validPropertiesArray() { const oThis = this; return [ oThis.tokenHolderDeployedProperty, oThis.airdropStartedProperty, oThis.airdropDoneProperty, oThis.airdropFailedProperty ]; } get invertedProperties() { const oThis = this; if (!invertedPropertiesHash) { invertedPropertiesHash = util.invert(oThis.properties); } return invertedPropertiesHash; } }
JavaScript
class RegisterBlock extends Component { constructor(props){ super(props); this.state = { User: {}, usernameState: STATUS.NO_INPUT, emailState: STATUS.NO_INPUT, passwordState: STATUS.NO_INPUT, passwordSuggestState: { status: STATUS.VALID, eightCharacters: STATUS.NO_INPUT, oneUpperCase: STATUS.NO_INPUT, oneLowerCase: STATUS.NO_INPUT, oneNumber: STATUS.NO_INPUT, oneSpecial: STATUS.NO_INPUT }, confirmState: STATUS.NO_INPUT, verifyState: STATUS.NO_INPUT, recaptchaState: STATUS.NO_INPUT, verify: false, username: "", email: "", password: "", passwordConfirm: "", recaptcha: "", registrationStatus: STATUS.WAITING, store_in_keystore: true } this.register = this.register.bind(this); this.updateUsername = this.updateUsername.bind(this); this.updateEmail = this.updateEmail.bind(this); this.updatePassword = this.updatePassword.bind(this); this.updatePasswordConfirm = this.updatePasswordConfirm.bind(this); this.updateVerify = this.updateVerify.bind(this); this.recaptcha = this.recaptcha.bind(this); this.loginClick = this.loginClick.bind(this); this.handleStorageClick = this.handleStorageClick.bind(this) } componentWillUnmount(){ this.showRecaptcha = false; } componentDidMount(){ this.showRecaptcha = true; } handleStorageClick(e) { this.setState({store_in_keystore: ((e.target.name === "keystore"))}) } register(){ this.setState({registrationStatus: STATUS.PENDING}); let abort = false; if (this.state.usernameState !== STATUS.VALID){ abort = true; this.setState({usernameState: STATUS.INVALID}); } if (this.state.emailState !== STATUS.VALID){ abort = true; this.setState({emailState: STATUS.INVALID}); } if (this.state.passwordState !== STATUS.VALID){ abort = true; this.setState({passwordState: STATUS.INVALID}); } if (this.state.confirmState !== STATUS.VALID){ abort = true; this.setState({confirmState: STATUS.INVALID}); } if (!this.state.verify){ abort = true; this.setState({verifyState: STATUS.INVALID}); } if (this.state.recaptcha === ""){ abort = true; this.setState({verifyState: STATUS.INVALID}); } // If we are not ready, abort. if (abort){ this.setState({registrationStatus: STATUS.WAITING}); } this.props.accountRegister(this.state.email, this.state.password, {store_in_keystore: this.state.store_in_keystore}) } updateUsername(){ let newState = STATUS.VALID; if (this.username.value === "") newState = STATUS.NO_INPUT; this.setState({username: this.username.value, usernameState: newState}); } updateEmail(){ let newState = this.state.emailState; let isEmail = validator.isEmail(this.email.value); newState = isEmail ? STATUS.VALID : STATUS.INVALID; if (this.email.value === "") newState = STATUS.NO_INPUT; this.setState({email: this.email.value, emailState: newState}); } updatePassword(){ let newState = STATUS.VALID; if (this.password.value === "") newState = STATUS.NO_INPUT; function hasDigit(str) { return (/^(?=.*\d)/.test(str)); } function hasLowerCase(str) { return (/^(?=.*[a-z])/.test(str)); } function hasUpperCase(str) { return (/^(?=.*[A-Z])/.test(str)); } function hasSpecialCharacter(str) { return (/[^A-Za-z0-9]/.test(str)); } function isAtLeastEight(str){ return str.length >= 8; } var uppercase = hasUpperCase(this.password.value); var lowercase = hasLowerCase(this.password.value); var number = hasDigit(this.password.value); var specialCharacter = hasSpecialCharacter(this.password.value); var atLeastEight = isAtLeastEight(this.password.value); var newStatus = STATUS.INVALID; // If we are all good, or if there is no input, then hide the suggester if ((uppercase && lowercase && number && specialCharacter && atLeastEight) || newState === STATUS.NO_INPUT) newStatus = STATUS.VALID this.setState({password: this.password.value, passwordState: newState, passwordSuggestState: { status: newStatus, eightCharacters: atLeastEight ? STATUS.VALID : STATUS.INVALID, oneUpperCase: uppercase ? STATUS.VALID : STATUS.INVALID, oneLowerCase: lowercase ? STATUS.VALID : STATUS.INVALID, oneNumber: number ? STATUS.VALID : STATUS.INVALID, oneSpecial: specialCharacter ? STATUS.VALID : STATUS.INVALID }}); // Only set password confirm to "invalid" if the user has typed anything in. if (this.state.passwordConfirm !== "") this.updatePasswordConfirm(); } updatePasswordConfirm(){ let newState = STATUS.INVALID; if (this.passwordConfirm.value === this.password.value) newState = STATUS.VALID; if (this.passwordConfirm.value === "") newState = STATUS.NO_INPUT; this.setState({passwordConfirm: this.passwordConfirm.value, confirmState: newState}); } updateVerify(verify_state){ this.setState({verify: verify_state }); } recaptcha(response){ if (response) this.setState({recaptcha: response, recaptchaState: STATUS.VALID}) else this.setState({recaptcha: response, recaptchaState: STATUS.INVALID}) } loginClick(){ this.setState({redirectToLogin: true}) } render() { var RegisterBtnTxt = "Register"; if (this.props.Account.registerFetching){ RegisterBtnTxt = "Registering..." } else if (this.props.Account.registerSuccess){ RegisterBtnTxt = "Register Success!" } else if (this.props.Account.registerFailure){ RegisterBtnTxt = "Register Error!" } return ( <div> <h2>Please Register</h2> <hr className="" /> <div className="form-group"> <input ref={username => this.username = username} onInput={this.updateUsername} type="text" className={"form-control input-lg" + (this.state.usernameState === STATUS.INVALID ? " is-invalid" : "") + (this.state.usernameState === STATUS.VALID ? " is-valid" : "")} placeholder="Username*" tabIndex="1" /> {this.state.usernameState === STATUS.INVALID ? <div className="invalid-feedback" id="feedback_username"> Please choose a Username </div> : ""} </div> <div className="form-group"> <input ref={email => this.email = email} onInput={this.updateEmail} type="email" className={"form-control input-lg" + (this.state.emailState === STATUS.INVALID ? " is-invalid" : "") + (this.state.emailState === STATUS.VALID ? " is-valid" : "")} placeholder="Email Address" tabIndex="2" /> {this.state.emailState === STATUS.INUSE ? <div className="invalid-feedback"> That email is already in use, please try another one </div> : ""} {this.state.emailState === STATUS.INVALID ? <div className="invalid-feedback"> That email does not seem valid, please try another one </div> : ""} </div> <div className="row"> <div className="col-xs-12 col-sm-6 col-md-6"> <div className="form-group"> <input ref={password => this.password = password} onInput={this.updatePassword} type="password" className={"form-control input-lg" + (this.state.passwordState === STATUS.INVALID ? " is-invalid" : "") + (this.state.passwordState === STATUS.VALID ? " is-valid" : "")} placeholder="Password*" tabIndex="3" /> </div> </div> <div className="col-xs-12 col-sm-6 col-md-6"> <div className="form-group"> <input ref={passwordConfirm => this.passwordConfirm = passwordConfirm} onInput={this.updatePasswordConfirm} type="password" className={"form-control input-lg" + (this.state.confirmState === STATUS.INVALID ? " is-invalid" : "") + (this.state.confirmState === STATUS.VALID ? " is-valid" : "")} placeholder="Confirm Password*" tabIndex="4" /> {this.state.confirmState === STATUS.INVALID ? <div className="invalid-feedback" id="feedback_password_confirmation"> Your passwords do not match </div> : ""} </div> </div> <div className="col-12"> {this.state.passwordSuggestState.status === STATUS.INVALID ? <div className="warning-feedback"> We suggest your password contain a minimum of: <ul style={{listStyle: "none"}}> <li className={ this.state.passwordSuggestState.eightCharacters === STATUS.VALID ? "text-success" : this.state.passwordSuggestState.eightCharacters === STATUS.INVALID ? "text-danger" : "text-warning" }> <span className={this.state.passwordSuggestState.eightCharacters === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 8 Characters </li> <li className={ this.state.passwordSuggestState.oneUpperCase === STATUS.VALID ? "text-success" : this.state.passwordSuggestState.oneUpperCase === STATUS.INVALID ? "text-danger" : "text-warning" }> <span className={this.state.passwordSuggestState.oneUpperCase === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Uppercase Letter </li> <li className={ this.state.passwordSuggestState.oneLowerCase === STATUS.VALID ? "text-success" : this.state.passwordSuggestState.oneLowerCase === STATUS.INVALID ? "text-danger" : "text-warning" }> <span className={this.state.passwordSuggestState.oneLowerCase === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Lowercase Letter </li> <li className={ this.state.passwordSuggestState.oneNumber === STATUS.VALID ? "text-success" : this.state.passwordSuggestState.oneNumber === STATUS.INVALID ? "text-danger" : "text-warning" }> <span className={this.state.passwordSuggestState.oneNumber === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Number </li> <li className={ this.state.passwordSuggestState.oneSpecial === STATUS.VALID ? "text-success" : this.state.passwordSuggestState.oneSpecial === STATUS.INVALID ? "text-danger" : "text-warning" }> <span className={this.state.passwordSuggestState.oneSpecial === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Special Character </li> </ul> </div> : ""} </div> </div> <div className="row d-flex justify-content-center"> <button name="local" type="button" onClick={this.handleStorageClick} className={"btn btn" + (this.state.store_in_keystore ? "-outline-success" : "-success") + " btn-sm m-2"}>Store locally</button> <button name="keystore" type="button" onClick={this.handleStorageClick} className={"btn btn" + (this.state.store_in_keystore ? "-info" : "-outline-info") + " btn-sm m-2"}>Store in keystore</button> </div> <div className="row"> <div className="col-12 text-center" style={{fontSize: "13.5px", padding: "0px"}}> <p> Save your password now! <br /> <strong>Password recovery is NOT possible</strong> <br /> (We never see your password!) </p> </div> <div className="col-12" style={{margin: "0px 0px"}}> <center> <ButtonCheckbox color={"secondary"} onChange={this.updateVerify} text={"I have taken responsibility for my password"} style={{fontSize: "12px", width: "300px", height: "50px"}} iconStyle={{fontSize: "25px", verticalAlign: "-5px"}} /> {this.state.verifyState === STATUS.INVALID ? <p id="passwordResponsibilityCheckbox" style={{color: "#dc3545", fontSize: "13.5px", marginTop: "5px", marginBottom: "0px"}}>Please agree that you have saved your password safely!</p> : ""} </center> </div> </div> <div className="row"> <div style={{margin: "0px auto", marginTop: "10px", marginBottom: "-5px"}}> {this.showRecaptcha ? <ReCAPTCHA sitekey="6LdZnGgUAAAAALEwTXUJ9xzm30Ny_jqmgtKDYBo6" onChange={this.recaptcha} /> : ""} {this.state.recaptchaState === STATUS.INVALID ? <p style={{color: "#dc3545", fontSize: "13.5px", marginTop: "5px", marginBottom: "0px"}}>Your recaptcha is invalid!</p> : ""} </div> </div> <br /> <div className="row"> <div className="col-12" style={{fontSize: "13.5px", margin: "0px 0px", marginBottom: "-10px"}}> By <strong>Registering</strong>, you agree to the <a href="/terms_and_conditions" data-toggle="modal" data-target="#t_and_c_m" data-ytta-id="-">Terms and Conditions</a>, including our Cookie Use.<p></p> </div> </div> <hr className="" /> {this.props.Account.registerFailure ? this.props.Account.registerErrorMessage : null} <div className="row"> <div className="col-xs-12 col-md-3 order-2 order-sm-1"><button className="btn btn-outline-secondary btn-block btn-lg" onClick={this.props.onLoginClick}>Login</button></div> <div className="col-xs-12 col-md-9 order-1 order-sm-2"><button id="register" className={"btn btn" + (this.props.Account.registerFailure ? "-danger" : "-success") + " btn-block btn-lg"} onClick={this.register} tabIndex="5">{RegisterBtnTxt}</button></div> </div> </div> ); } }
JavaScript
class MatRowHarness extends _MatRowHarnessBase { constructor() { super(...arguments); this._cellHarness = MatCellHarness; } /** * Gets a `HarnessPredicate` that can be used to search for a table row with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options = {}) { return new HarnessPredicate(MatRowHarness, options); } }
JavaScript
class MatHeaderRowHarness extends _MatRowHarnessBase { constructor() { super(...arguments); this._cellHarness = MatHeaderCellHarness; } /** * Gets a `HarnessPredicate` that can be used to search for * a table header row with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options = {}) { return new HarnessPredicate(MatHeaderRowHarness, options); } }
JavaScript
class MatFooterRowHarness extends _MatRowHarnessBase { constructor() { super(...arguments); this._cellHarness = MatFooterCellHarness; } /** * Gets a `HarnessPredicate` that can be used to search for * a table footer row cell with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options = {}) { return new HarnessPredicate(MatFooterRowHarness, options); } }
JavaScript
class Cursor { // DOM elements DOM = { // Main element (.cursor) el: null, } // Properties that will change renderedStyles = { // With interpolation, we can achieve a smooth animation effect when moving the cursor. // The "previous" and "current" values are the values that will interpolate. // The returned value will be one between these two (previous and current) at a specific increment. // The "amt" is the amount to interpolate. // As an example, the following formula calculates the returned translationX value to apply: // this.renderedStyles.tx.previous = lerp(this.renderedStyles.tx.previous, this.renderedStyles.tx.current, this.renderedStyles.tx.amt); // Cursor translation in the x-axis tx: {previous: 0, current: 0, amt: 0.4}, // Cursor translation in the y-axis ty: {previous: 0, current: 0, amt: 0.4}, // Scale up the cursor scale: {previous: 1, current: 1, amt: 0.2}, // Fade out the cursor opacity: {previous: 1, current: 1, amt: 0.3} }; // Size and position bounds; /** * Constructor. * @param {Element} DOM_el - The .cursor element * @param {String} triggerSelector - Selector for all the elements that when hovered trigger the cursor enter/leave methods. Default is all <a>. */ constructor(DOM_el, triggerSelector = 'a') { this.DOM = {el: DOM_el}; // Hide initially this.DOM.el.style.opacity = 0; // Calculate size and position this.bounds = this.DOM.el.getBoundingClientRect(); // Mousemove event: // Start tracking the cursor position as soon as the user moves the cursor and fede in the cursor element. this.onMouseMoveEv = () => { // Set up the initial values to be the same this.renderedStyles.tx.previous = this.renderedStyles.tx.current = cursor.x - this.bounds.width/2; this.renderedStyles.ty.previous = this.renderedStyles.ty.previous = cursor.y - this.bounds.height/2; // Fade in gsap.to(this.DOM.el, {duration: 0.9, ease: 'Power3.easeOut', opacity: 1}); // Start loop requestAnimationFrame(() => this.render()); // Remove the mousemove event window.removeEventListener('mousemove', this.onMouseMoveEv); }; window.addEventListener('mousemove', this.onMouseMoveEv); [...document.querySelectorAll(triggerSelector)].forEach(link => { link.addEventListener('mouseenter', () => this.enter()); link.addEventListener('mouseleave', () => this.leave()); }); } /** * Mouseenter event * Scale up and fade out. */ enter() { this.renderedStyles['scale'].current = 2; this.renderedStyles['opacity'].current = 0.8; } /** * Mouseleave event * Reset scale and opacity. */ leave() { this.renderedStyles['scale'].current = 1; this.renderedStyles['opacity'].current = 1; } /** * Shows the cursor */ show() { this.renderedStyles['opacity'].current = 1; } /** * Hides the cursor */ hide() { this.renderedStyles['opacity'].current = 0; } /** * Loop */ render() { // New cursor positions this.renderedStyles['tx'].current = cursor.x - this.bounds.width/2; this.renderedStyles['ty'].current = cursor.y - this.bounds.height/2; // Interpolation for (const key in this.renderedStyles ) { this.renderedStyles[key].previous = lerp(this.renderedStyles[key].previous, this.renderedStyles[key].current, this.renderedStyles[key].amt); } // Apply interpolated values (smooth effect) this.DOM.el.style.transform = `translateX(${(this.renderedStyles['tx'].previous)}px) translateY(${this.renderedStyles['ty'].previous}px) scale(${this.renderedStyles['scale'].previous})`; this.DOM.el.style.opacity = this.renderedStyles['opacity'].previous; // loop... requestAnimationFrame(() => this.render()); } }
JavaScript
class HttpMethod { /** * Instance an object * @param methods array to list all avaiable http methods * @param checked determines the current selected http methods by user * @param subPrefix DOM id, needed to access the sub contents from the current method. */ constructor(methods, checked, subPrefix) { $.each(methods, function (index, value) { value = value.toUpperCase(); }); this.methods = methods; this.subPrefix = subPrefix; this.methodString = checked.toUpperCase(); } /** * httpMethod.method = "text" * Trying to set the method property (methodString) of httpMethod with String "text". * If "text" does not match with the kown methods (set by constructor) the set attempt will be ignored. * If "text" is the same as last time, the sub content for that methods is toogled * else the new set methods subcontent will be visible and the replaced one will be hidden. * @param input should be a value from listed methods */ set method(input) { input = input.toUpperCase(); var i; for (i = 0; i < this.methods.length; i++) { if (input == this.methods[i]) { if (input == this.methodString) { this.toggleMethod(); } else { this.hideMethod(); this.methodString = input; this.showMethod(); } break; } } } /** * xyz = httpMethod.method * @return methodString value will be returned as the method property */ get method() { return this.methodString; } /** * Hides the outer div container from the subcontent for the current method property. */ hideMethod() { if (this.methodString != "") { $("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).hide(); } } /** * Shows the outer div container from the subcontent for the current method property. */ showMethod() { if (this.methodString != "") { $("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).show(); } } /** * Toggles the outer div container from the subcontent for the current method property. */ toggleMethod() { if (this.methodString != "") { $("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).toggle(); } } }
JavaScript
class ModelSet extends BaseClass { constructor(iterable) { this._size = 0; if(iterable) { this.addObjects(iterable); } } get size() { return this._size; } /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var models = new ModelSet([post1, post2, post3]); models.size; // 3 models.clear(); models.size; // 0 ``` @method clear @return {ModelSet} An empty Set */ clear() { var len = this._size; if (len === 0) { return this; } var guid; for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } this._size = 0; return this; } add(obj) { var guid = guidFor(obj), idx = this[guid], len = this._size; if (idx>=0 && idx<len && (this[idx] && this[idx].isEqual(obj))) { // overwrite the existing version if(this[idx] !== obj) { this[idx] = obj; } return this; // added } len = this._size; this[guid] = len; this[len] = obj; this._size = len+1; return this; } delete(obj) { var guid = guidFor(obj), idx = this[guid], len = this._size, isFirst = idx === 0, isLast = idx === len-1, last; if (idx>=0 && idx<len && (this[idx] && this[idx].isEqual(obj))) { // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; this._size = len-1; return true; } return false; } has(obj) { return this[guidFor(obj)]>=0; } copy(deep=false) { var C = this.constructor, ret = new C(), loc = this._size; ret._size = loc; while(--loc>=0) { ret[loc] = deep ? this[loc].copy() : this[loc]; ret[guidFor(this[loc])] = loc; } return ret; } forEach(callbackFn, thisArg = undefined) { for (var i=0; i < this._size; i++) { callbackFn.call(thisArg, this[i], this[i], this); } } toString() { var len = this.size, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return `ModelSet<${array.join(',')}>`; } get(model) { var idx = this[guidFor(model)]; if(idx === undefined) return; return this[idx]; } getForClientId(clientId) { var idx = this[clientId]; if(idx === undefined) return; return this[idx]; } *values() { for (var i=0; i < this._size; i++) { yield this[i]; } } /** Adds the model to the set or overwrites the existing model. */ addData(model) { var existing = this.getModel(model); var dest; if(existing) { dest = existing.copy(); model.copyTo(dest); } else { // copy since the dest could be the model in the session dest = model.copy(); } this.add(dest); return dest; } // // Backwards compat. methods // addObjects(iterable) { if(typeof iterable.forEach === 'function') { iterable.forEach(function(item) { this.add(item); }, this); } else { for (var item of iterable) { this.add(item); } } return this; } removeObjects(iterable) { if(typeof iterable.forEach === 'function') { iterable.forEach(function(item) { this.delete(item); }, this); } else { for (var item of iterable) { this.delete(item); } } return this; } toArray() { return array_from(this); } }
JavaScript
class XwInvalidStateError extends Error { /** * @constructor * @param {string} [reason] Reason related to the invalid state */ constructor(reason) { const _reason = xw.defaultable(reason); super(_formatMessage(_reason)); this.reason = _reason; } }
JavaScript
class ReservedInstances { /** * Constructs a new <code>ReservedInstances</code>. * Describes a Reserved Instance. * @alias module:model/ReservedInstances */ constructor() { ReservedInstances.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>ReservedInstances</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ReservedInstances} obj Optional instance to populate. * @return {module:model/ReservedInstances} The populated <code>ReservedInstances</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ReservedInstances(); if (data.hasOwnProperty('AvailabilityZone')) { obj['AvailabilityZone'] = ApiClient.convertToType(data['AvailabilityZone'], 'String'); } if (data.hasOwnProperty('CurrencyCode')) { obj['CurrencyCode'] = CurrencyCodeValues.constructFromObject(data['CurrencyCode']); } if (data.hasOwnProperty('Duration')) { obj['Duration'] = ApiClient.convertToType(data['Duration'], 'Number'); } if (data.hasOwnProperty('End')) { obj['End'] = ApiClient.convertToType(data['End'], 'Date'); } if (data.hasOwnProperty('FixedPrice')) { obj['FixedPrice'] = ApiClient.convertToType(data['FixedPrice'], 'Number'); } if (data.hasOwnProperty('InstanceCount')) { obj['InstanceCount'] = ApiClient.convertToType(data['InstanceCount'], 'Number'); } if (data.hasOwnProperty('InstanceTenancy')) { obj['InstanceTenancy'] = Tenancy.constructFromObject(data['InstanceTenancy']); } if (data.hasOwnProperty('InstanceType')) { obj['InstanceType'] = InstanceType.constructFromObject(data['InstanceType']); } if (data.hasOwnProperty('OfferingClass')) { obj['OfferingClass'] = OfferingClassType.constructFromObject(data['OfferingClass']); } if (data.hasOwnProperty('OfferingType')) { obj['OfferingType'] = OfferingTypeValues.constructFromObject(data['OfferingType']); } if (data.hasOwnProperty('ProductDescription')) { obj['ProductDescription'] = RIProductDescription.constructFromObject(data['ProductDescription']); } if (data.hasOwnProperty('RecurringCharges')) { obj['RecurringCharges'] = ApiClient.convertToType(data['RecurringCharges'], [RecurringCharge]); } if (data.hasOwnProperty('ReservedInstancesId')) { obj['ReservedInstancesId'] = ApiClient.convertToType(data['ReservedInstancesId'], 'String'); } if (data.hasOwnProperty('Scope')) { obj['Scope'] = Scope.constructFromObject(data['Scope']); } if (data.hasOwnProperty('Start')) { obj['Start'] = ApiClient.convertToType(data['Start'], 'Date'); } if (data.hasOwnProperty('State')) { obj['State'] = ReservedInstanceState.constructFromObject(data['State']); } if (data.hasOwnProperty('Tags')) { obj['Tags'] = ApiClient.convertToType(data['Tags'], [Tag]); } if (data.hasOwnProperty('UsagePrice')) { obj['UsagePrice'] = ApiClient.convertToType(data['UsagePrice'], 'Number'); } } return obj; } }
JavaScript
class Terminal { constructor(selector, words) { this.wordbank = words; this.terminal = document.querySelector(selector); this.prompt = new Prompt('#answers'); this.MAX_TOTAL_CHARS = 12 * 32; this.MAX_HALF_CHARS = 12 * 16; } /** * Displays the terminal or displays the end game messages, dependin on the value * of displayTerminal * * @param {boolean} displayTerminal if true, displays the terminal * @memberof Terminal */ toggleGrid(displayTerminal) { const terminal = document.querySelector('.terminal-body'); const message = document.querySelector('.terminal-message'); if(displayTerminal) { terminal.style.display = 'grid'; message.style.display = 'none'; } else { terminal.style.display = 'none'; message.style.display = 'grid'; } } /** * Starts the game. Destroys old terminals and values and builds a new one. * * @param {string} level novice advance expert master * @memberof Terminal */ play(level) { // set the difficulty const difficulty = { novice: { min: 4, max: 5}, advanced: { min: 6, max: 8 }, expert: { min: 9, max: 10 }, master: { min: 11, max: 12 } } this.wordLength = random(difficulty[level].max + 1, difficulty[level].min); // get the words const words = this.wordbank.filter(word => word.length === this.wordLength).map(word => word.toUpperCase()); // use a set to avoid duplicates this.words = new Set(); while(this.words.size !== 10) { this.words.add(words[random(words.length)]); } // turn it into an array to allow for array methods this.words = Array.from(this.words); // set the properties this.password = this.words[random(this.words.length)]; this.cursor = 0; this.chars = []; this.attempts = 5; // build the coolumns; document.querySelectorAll('.terminal-col-narrow, .terminal-col-wide') .forEach(col => col.innerHTML = ''); this.prompt.wipeLog(); this.prompt.createLog(); this.setAttempts(this.attempts); this.toggleGrid(true); this.populateSideColumns(); this.populateGrid(); // first item is always selected this.prompt.setPrompt(this.chars[0].char); } deselectAll() { this.chars.forEach(char=> char.deselect()); } /** * Moves the cursor from grid to grid * * @param {Event} event * @memberof Terminal */ moveCursor(event) { event.preventDefault(); const arrows = [ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight" ]; if(arrows.includes(event.key)) { /** * Calculates the new position or doesn't move if new position is invalid. * * @param {number} position starting position * @param {number} direction should be 1 (down and right) or -1 (up or left) * @param {number} amt should be 1 (left or right) or 12 (up or down) or distance to other grid */ const calcPosition = (position, direction, amt) => { const newPosition = position + (amt * direction); if(newPosition < 0 || newPosition >= (32 * 12)) { return position; } return newPosition; } // holds movement functions // key values match event.key for arrow presses // ArrowLeft and ArrowRight also have ability to jump across to other side const move = { ArrowUp: (position)=> { return calcPosition(position, -1, 12); }, ArrowDown: (position)=> { return calcPosition(position, 1, 12); }, ArrowLeft: (position)=> { const edges = []; for(let i = 16; i < 32; i++) { edges.push(i * 12); } const distance = edges.includes(position) ? (12 * 15) + 1 : 1; return calcPosition(position, -1, distance); }, ArrowRight: (position)=> { const edges = []; for(let i = 0; i < 16; i++) { edges.push((i * 12) + 11); } const distance = edges.includes(position) ? (12 * 15) + 1 : 1; return calcPosition(position, 1, distance); }, } // helper function for the .forEach calls later on const selectAll = (char)=> char.select(); this.cursor = move[event.key](this.cursor); this.deselectAll(); const selectedChar = this.chars[this.cursor]; // if there's a wordData object, select the word if(selectedChar.wordData) { selectedChar.select(); const word = selectedChar.wordData.word; this.chars.filter(char => char.wordData && char.wordData.word === word) .forEach(selectAll); this.prompt.setPrompt(word); // if there's a bracketData object, select the bracket pair } else if(selectedChar.bracketData) { const id = selectedChar.bracketData.id; const bracket = this.chars.filter(char => char.bracketData && char.bracketData.id === id); bracket.forEach(selectAll); this.prompt.setPrompt(bracket.map(char=> char.char).join('')); // otherwise just select the character } else { selectedChar.select(); this.prompt.setPrompt(selectedChar.char); } } else if(event.key === "Enter") { this.submitPrompt(this.chars[this.cursor]); } } /** * Ends the game, displays a message and sets up for the next game * * @param {String} msg message to be displayed * @memberof Terminal */ endGame(msg) { setTimeout(()=> { this.prompt.wipeLog(); this.toggleGrid(false); document.getElementById('display').innerHTML = msg; }, 1000) } /** * Sends the selected character to the prompter * Performs the appropriate action if it recieves a char, bracket or word * * @param {Char} char * @memberof Terminal */ submitPrompt(char) { if(char.wordData) { const matches = compare(char.wordData.word, this.password); // if the selected word is the password, win the game if(matches === 'match') { this.prompt.setPrompt(char.wordData.word, true); this.prompt.setPrompt('Entry granted!', true); this.endGame('User Authenticated') // or, reduce the attempts and lose if attempts is at zero } else { this.prompt.setPrompt(char.wordData.word, true); this.prompt.setPrompt('Entry denied.', true); this.prompt.setPrompt(`Likeness=${matches}`, true); this.attempts -= 1; this.setAttempts(this.attempts); if(this.attempts === 0) { this.prompt.setPrompt('Initializing Lockout', true); this.endGame('System locked out') } } } else if(char.bracketData) { if(char.bracketData.func === 'reset') { this.setAttempts(5); this.prompt.setPrompt('Tries reset.', true); } else { let dud = this.words.filter(word => word !== this.password)[random(this.words.length - 1)]; let chars = this.chars.filter(char => char.wordData && char.wordData.word === dud); chars.forEach(char => { char.wordData = null; char.setChar('.'); }); this.words = this.words.filter(word => word !== dud); this.prompt.setPrompt('Dud removed.', true); } let bracketId = char.bracketData.id; this.chars.filter(char => char.bracketData && char.bracketData.id === bracketId) .forEach(char => char.bracketData = null); } else { this.prompt.setPrompt(char.char, true); this.prompt.setPrompt('Error', true); } } /** * Sets the number of attempts remaining, starting at 5. * * @param {number} amt * @memberof Terminal */ setAttempts(amt) { if(amt < 0) { amt = 0; } const attempts = document.getElementById('attempts'); attempts.innerHTML = '▉ '.repeat(amt); this.attempts = amt; } /** * Populates the side columns with hex values that start at a random number * and increment by 12. * I guess they're just to make them look like memory addresses * * @memberof Terminal */ populateSideColumns() { const [ side1, side2 ] = document.querySelectorAll('.hex'); [side1, side2].forEach(side => side.innerHTML = ''); let MIN = 4096; let MAX = 65535 - (32 * 12); let start = random(MAX, MIN); for(let i = 0; i < 32; i++) { let side = i < 16 ? side1 : side2; const line = document.createElement('div'); line.innerHTML = '0x' + (start.toString(16)); side.appendChild(line); start += 12; } } /** * Populates the grid with special characters * Once it does that, it adds words * Once it does that, it adds matched brackets * Once it does that, it adds unmatched brackets * @memberof Terminal */ populateGrid() { const SPECIAL = `!@#$%^&*_+-=\`\\|;':".,/?`.split(''); const BRACKETS = `{}[]<>()`.split(''); const [ side1, side2 ] = document.querySelectorAll('.code'); [side1, side2].forEach(side => side.innerHTML = ''); const usedPositions = new Set(); const usedRows = new Set(); // fetches an unused row from either half of the grid const getUnusedRow = (i, half)=> { let row; do { row = i < half ? ROWS[random(ROWS.length / 2)] : ROWS[random(ROWS.length, (ROWS.length / 2) + 1)]; } while(usedRows.has(row)); usedRows.add(row); return row; } // generates an array of rows (multiples of 12) const ROWS = []; for(let i = 0; i < 32; i++) { ROWS.push(i * 12); } // fill out the grid with special characters for(let i = 0; i < this.MAX_TOTAL_CHARS; i++) { let side = i < this.MAX_HALF_CHARS ? side1 : side2; const character = SPECIAL[random(SPECIAL.length)]; const char = new Char(character, i); this.chars.push(char); side.appendChild(char.div); } // add the words at random this.words.forEach((word, i) => { // find an unused row let row = getUnusedRow(i, this.words.length / 2); // calculate the starting position let position; do { position = row + random(12); } while(position + this.wordLength > this.MAX_TOTAL_CHARS || usedPositions.has(position)); // add the word to that position character by character word.split('').forEach(character => { this.chars[position].setWord(character, { word, position }); usedPositions.add(position); //if a word spills into another row, add that row to used rows const currentRow = Math.floor(position / 12) * 12; if(!usedRows.has(currentRow)) { usedRows.add(currentRow); } position += 1; }); }); // add the bracket pairs let functions = arrayshuffle(['reset', 'dud', 'dud', 'dud', 'dud']); for(let i = 0; i < 5; i++) { let func = functions[i]; let row = getUnusedRow(i, 3); const start = row + random(11); const end = start + random(12 - (start % 12)); const index = random(4) * 2; const [ open, close ] = [ BRACKETS[index], BRACKETS[index + 1] ]; let id = i; this.chars[start].setBracket(open, { start, end, id, func }); for(let i = start; i < end; i++) { this.chars[i].setBracket(this.chars[i].char, { start, end, id, func}); } this.chars[end].setBracket(close, { start, end, id, func }); } // finally, sprinkle in some random unbalanced brackets const numBrackets = random(20,15); for(let i = 0; i < numBrackets;) { let char = this.chars[random(this.chars.length)]; if(!char.wordData && !char.bracketData) { char.setChar(BRACKETS[random(BRACKETS.length)]); i++; } } } }
JavaScript
class Chart { /** * Constructor. * * @param {selection} parent The selected D3 parent element container * @param {Configuration} configuration The application configuration */ constructor(parent, configuration) { this._configuration = configuration; this._parent = parent; this._hierarchy = new Hierarchy(this._configuration); this._data = {}; } /** * Returns the SVG instance. * * @return {Svg} */ get svg() { return this._svg; } /** * Update/Calculate the viewBox attribute of the SVG element. * * @private */ updateViewBox() { // Get bounding boxes let svgBoundingBox = this._svg.visual.node().getBBox(); let clientBoundingBox = this._parent.node().getBoundingClientRect(); // View box should have at least the same width/height as the parent element let viewBoxWidth = Math.max(clientBoundingBox.width, svgBoundingBox.width); let viewBoxHeight = Math.max(clientBoundingBox.height, svgBoundingBox.height, MIN_HEIGHT); // Calculate offset to center chart inside svg let offsetX = (viewBoxWidth - svgBoundingBox.width) / 2; let offsetY = (viewBoxHeight - svgBoundingBox.height) / 2; // Adjust view box dimensions by padding and offset let viewBoxLeft = Math.ceil(svgBoundingBox.x - offsetX - MIN_PADDING); let viewBoxTop = Math.ceil(svgBoundingBox.y - offsetY - MIN_PADDING); // Final width/height of view box viewBoxWidth = Math.ceil(viewBoxWidth + (MIN_PADDING * 2)); viewBoxHeight = Math.ceil(viewBoxHeight + (MIN_PADDING * 2)); // Set view box attribute this._svg.get() .attr("viewBox", [ viewBoxLeft, viewBoxTop, viewBoxWidth, viewBoxHeight ]); // Add rectangle element // this._svg // .insert("rect", ":first-child") // .attr("class", "background") // .attr("width", "100%") // .attr("height", "100%") // .style("fill", "none") // .style("pointer-events", "all"); // // // Adjust rectangle position // this._svg // .select("rect") // .attr("x", viewBoxLeft) // .attr("y", viewBoxTop); } /** * Returns the chart data. * * @return {Object} */ get data() { return this._data; } /** * Sets the chart data. * * @param {Object} value The chart data */ set data(value) { this._data = value; // Create the hierarchical data structure this._hierarchy.init(this._data); } /** * This method draws the chart. */ draw() { // Remove previously created content this._parent.html(""); // Create the <svg> element this._svg = new Svg(this._parent, this._configuration); // Overlay must be placed after the <svg> element this._overlay = new Overlay(this._parent); // Init the <svg> events this._svg.initEvents(this._overlay); let personGroup = this._svg.get().select("g.personGroup"); let gradient = new Gradient(this._svg, this._configuration); let that = this; personGroup .selectAll("g.person") .data(this._hierarchy.nodes, (d) => d.data.id) .enter() .append("g") .attr("class", "person") .attr("id", (d) => "person-" + d.data.id); // Create a new selection in order to leave the previous enter() selection personGroup .selectAll("g.person") .each(function (d) { let person = d3.select(this); if (that._configuration.showColorGradients) { gradient.init(d); } new Person(that._svg, that._configuration, person, d); }); this.bindClickEventListener(); this.updateViewBox(); } /** * This method bind the "click" event listeners to a "person" element. */ bindClickEventListener() { let persons = this._svg.get() .select("g.personGroup") .selectAll("g.person") .filter((d) => d.data.xref !== "") .classed("available", true); // Trigger method on click persons.on("click", this.personClick.bind(this)); } /** * Method triggers either the "update" or "individual" method on the click on an person. * * @param {Event} event The current event * @param {Object} data The D3 data object * * @private */ personClick(event, data) { // Trigger either "update" or "redirectToIndividual" method on click depending on person in chart (data.depth === 0) ? this.redirectToIndividual(data.data.url) : this.update(data.data.updateUrl); } /** * Redirects to the individual page. * * @param {String} url The individual URL * * @private */ redirectToIndividual(url) { window.location = url; } /** * Updates the chart with the data of the selected individual. * * @param {String} url The update URL */ update(url) { let update = new Update(this._svg, this._configuration, this._hierarchy); update.update(url, () => this.bindClickEventListener()); } }
JavaScript
class Bridge { constructor (socket, app) { this.didAuth = false this.sessionId = '' this.checkSession = app.get('checkSession') this.changeSessionState = app.get('changeSessionState') this.socket = socket this.udp = null socket.on('message', this.clientToGrid.bind(this)) socket.on('close', this.onSocketClose.bind(this)) } authenticate (sessionId) { try { const state = this.checkSession(sessionId) if (state === 'inactive') { // Session has no active socket -> open this.didAuth = true this.changeSessionState(sessionId, 'active') this.sessionId = sessionId const udp = dgram.createSocket('udp4') this.udp = udp udp.bind() udp.on('message', this.gridToClient.bind(this)) udp.on('close', this.onUDPClose.bind(this)) this.socket.send('ok') } else { // session did close or has an active socket -> close this socket this.socket.close(1008, 'already active socket open') } } catch (err) { // handle error if (err.status === pouchdbErrors.INVALID_REQUEST.status) { this.socket.close(1011, err.message) } else { this.socket.close(1008, 'wrong session id') } } } clientToGrid (message) { if (message instanceof Buffer && this.didAuth) { const ip = message.readUInt8(0) + '.' + message.readUInt8(1) + '.' + message.readUInt8(2) + '.' + message.readUInt8(3) const port = message.readUInt16LE(4) const buffy = message.slice(6) this.udp.send(buffy, 0, buffy.length, port, ip) } else if (!this.didAuth && typeof message === 'string') { this.authenticate(message) } } gridToClient (message, rinfo) { const buffy = Buffer.concat([ Buffer.alloc(6), message ]) // add IP address const ipParts = rinfo.address.split('.') for (let i = 0; i < 4; i++) { buffy.writeUInt8(Number(ipParts[i]), i) } // add port buffy.writeUInt16LE(rinfo.port, 4) this.socket.send(buffy, { binary: true }) } onSocketClose (code, reason) { if (this.socket && this.sessionId !== '') { const nextState = code === 1000 ? 'end' : 'inactive' try { this.changeSessionState(this.sessionId, nextState) } catch (err) { console.error(err) } } if (this.socket) { this.socket = undefined } if (this.udp) { this.udp.close() this.udp = undefined } } onUDPClose () { if (this.udp) { this.udp = undefined } if (this.socket) { this.socket.close(1012, 'udp did close') this.socket = undefined } } }
JavaScript
class BusinessDashboardParent extends React.Component{ /* ----------------------------------------------------------------------------- Constructor is used for state design, modularized to pass as props ----------------------------------------------------------------------------- */ constructor(props){ super(props); this.state = { // Values for the parent currentLocation: '', session: '', currentStore: '', currentMessage: 'Success!', currentStatus: 'good', load: () => { //BE Call: On page load let base = 'https://fuo-backend.herokuapp.com/business/printalllocation/'; let id = this.state.session; let url = base + id; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("bad loading"); } }) .then(data => { this.setState({locations: data, locationBg: ''}); }) .catch(error => { console.log('caught load'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); base = 'https://fuo-backend.herokuapp.com/business/numoflocations/'; url = base + this.state.session; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("bad loading"); } }) .then(data => this.setState({totalLocations: data})) .catch(error => { console.log('caught numLocations'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); base = 'https://fuo-backend.herokuapp.com/business/getbusinessname/'; url = base + this.state.session; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("bad loading"); } }) .then(data => this.setState({companyName: data.name})) .catch(error => { console.log('caught numLocations'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); }, // Props for LeftSideBar ------------------------------------------------- logout: () => { localStorage.clear(); window.location.assign('https://corona-food.herokuapp.com/landing.html'); }, companyName: '', totalLocations: '', addLocation: () => { this.setState({formClass: this.state.formClass==="off"?"on":"off"}); }, // Props for LocationSearchBar ------------------------------------------- search: (e) => { if(e === ''){ let base = 'https://fuo-backend.herokuapp.com/business/printalllocation/'; let id = this.state.session; let url = base + id; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("bad loading"); } }) .then(data => {this.setState({locations: data, locationBg: ''})}) .catch(error => { console.log('caught load'); console.log(error); }); } else{ let base = 'https://fuo-backend.herokuapp.com/business/searchlocation/'; let id = this.state.session + '/'; let arg = e; let url = base + id + arg; console.log(url); fetch(url) .then(res => { if(res.status === 200){ return res.json() } else{ throw new Error("bad search"); } }) .then(data => { this.setState({locations: data, locationBg: (data.length===0?'empty':'')}); }) .catch(error => { console.log("caught search"); console.log(error); this.setState({locations: [], locationBg: 'empty'}); }); } }, // Props for Location ---------------------------------------------------- locations: [], locationBg: 'empty', selectLocation: (sel) => { //Error when selection not found if(sel === null){ alert("Select Location failed"); return } //BE Call: On store get let base = 'https://fuo-backend.herokuapp.com/product/printallproduct/'; let id = sel.store_id; let url = base + id; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("Unable to get store"); } }) .then(data => { let currentList = []; for(let i = 0; i < data.length; i++){ currentList.push({ image: data[i].product_img, category: data[i].category, name: data[i].product_name, amount: data[i].stock_amount, price: data[i].price, rate: data[i].coupon, product_id: data[i].product_id, expiration: data[i].expire_date }); } let list = []; for(let i = 0; i < currentList.length; i++){ list.push(this.state.fillListing(currentList[i], 7)); } this.setState({ right: { address: sel.address, totalProducts: data.length, productsList: data }, updateListings: currentList, list: list, currentLocation: sel.address, currentStore: sel.store_id }); }) .catch(error => { console.log('caught store get'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); }, //Props for LocationInfo ------------------------------------------------- right: { address: 'No Selection', totalProducts: 0, productsList: [] }, rightControls: { updateProducts: () => { if(this.state.currentStore !== ''){ this.setState({updateClass: this.state.updateClass==="off"?"on":"off"}); } else{ alert("No location selected"); } }, deleteLocation: (e) => { //BE Call: On location Delete const method = {method: 'DELETE'}; let base = 'https://fuo-backend.herokuapp.com/business/deletelocation/'; let id = this.state.session + '/'; this.setState({currentStatus:''}); let arg = this.state.currentStore; let url = base + id + arg; if( this.state.currentStore!==''){ fetch(url, method) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("Delete failed"); } }) .then(data => { base = 'https://fuo-backend.herokuapp.com/business/printalllocation/'; id = this.state.session; url = base + id; this.state.load(); this.setState({ currentStore: '', right: { address: "No Selection", totalProducts: 0, productsList: [] }, updateListings: [], list: [], currentStatus: 'good', currentMessage: 'Success!' }); } ) .catch(error => { console.log('caught delete'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); } else{ alert("No location selected"); } }, }, // Props for AddLocation-------------------------------------------------- formClass: "off", form: { submitNewLocation: (location) => { //BE Call: On location add this.setState({currentStatus:''}); const method = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: location.street + '.' + location.city + ',' + location.state + ' ' + location.zip, name: location.name }) }; let base = 'https://fuo-backend.herokuapp.com/business/addlocation/'; let id = this.state.session; let url = base + id; fetch(url, method) .then(res => { if(res.status === 200){ return res.json(); } else{ throw new Error('Add location failed'); } }) .then(data => { base = 'https://fuo-backend.herokuapp.com/business/printalllocation/'; id = this.state.session; url = base + id; this.state.load(); this.setState({currentMessage: 'Success!', currentStatus:'good'}) } ) .catch(error => { console.log('caught add'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); }, closeForm: (e) => { this.setState({formClass: this.state.formClass==="off"?"on":"off"}); }, }, //Props for UpdateListings------------------------------------------------ updateListings: [], removeListings: [], list: [], idx: -1, key: 0, updateClass: "off", formControl: { remove: (idx) => { //find and remove by idx let listings = this.state.updateListings; let list = this.state.list; let remove = this.state.removeListings; let rem = null; for(let i = 0; i < list.length; i++){ if(list[i].props.data.idx === idx){ rem = i; break; } } //Not found error if(rem === null){ alert("Remove failed: could not find item"); return; } //Remove remove.push(listings[rem]); listings.splice(rem, 1); list.splice(rem, 1); //reset state this.setState({updateListings: listings, list: list, removeListings: remove}); }, onChange: (idx, obj, focus) => { //find and change by index let listings = this.state.updateListings; let list = this.state.list; let mod = null; for(let i = 0; i < listings.length; i++){ if(list[i].props.data.idx === idx){ mod = i; break; } } //Not found error if(mod === null){ alert("Change failed: could not find item"); return; } //Modify listings[mod] = obj; list[mod] = this.state.fillListing(listings[mod], focus); this.setState({updateListings: listings, list: list}); } }, update: { submitUpdate: () => { //Repackage listings for HTTP request let list = JSON.parse(JSON.stringify(this.state.updateListings)); if(!this.validate(list)){return false;} let body = []; let ids = []; for(let i = 0; i < list.length; i++){ body.push({ product_name: list[i].name, product_img: list[i].image, category: list[i].category, price: list[i].price, expire_date: list[i].expiration, stock_amount: list[i].amount, coupon: list[i].rate }); ids.push(list[i].product_id); } //BE Call: On products upsert let method = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: {} }; let base = 'https://fuo-backend.herokuapp.com/product/upsert/'; let id = this.state.currentStore + '/'; this.setState({currentStatus:''}); for(let i = 0 ; i < body.length; i++){ let arg = ids[i]; let url = base + id + arg; method.body = JSON.stringify(body[i]); fetch(url, method) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("bad upload"); } }) .then(data => { this.state.refreshCurrent(); this.setState({currentMessage: 'Success!', currentStatus:'good'}); }) .catch(error => { console.log('caught upload'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); } //BE Call: On products delete list = JSON.parse(JSON.stringify(this.state.removeListings)); this.setState({removeListings: []}); method = { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, } base = 'https://fuo-backend.herokuapp.com/product/delete/'; id = this.state.currentStore + '/'; let url = ''; for(let i = 0; i < list.length; i++){ if(list[i].product_id !== '0'){ url = base + id + list[i].product_id; fetch(url, method) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("Delete item failed"); } }) .then(data => { this.state.refreshCurrent(); this.setState({currentMessage: 'Success!', currentStatus:'good'}); }) .catch(error => { console.log('caught delete'); console.log(error); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); } } this.state.update.closeForm(); }, addListing: (e) => { let listings = this.state.updateListings; let list = this.state.list; let newListing = { image:'', category:'None', name: '', amount: '', price: '', rate: '', product_id: '0', expiration: '', idx: this.state.idx, remove: this.state.formControl.remove, onChange: this.state.formControl.onChange, linkError: '', nameError: '', amountError: '', priceError: '', discountError: '', expirationError: '', } let newList = (<ListingForm data={newListing} key={this.state.key} action={this.state.formControl} focus={7}/>) listings.push(newListing); list.push(newList); this.setState({updateListings: listings, list: list, key: this.state.key+1, idx: this.state.idx-1}); }, closeForm: (e) => { try{ e.preventDefault(); } catch(e){ console.log("saved!");} this.setState({updateClass: this.state.updateClass==="off"?"on":"off"}); }, }, fillListing: (list, focus) => { let newListing = { image: list.image===null?'':list.image, category: list.category, name: list.name, amount: list.amount, price: list.price, rate: list.rate, product_id: list.product_id, expiration: list.expiration, product_id: list.product_id, idx: this.state.idx, remove: this.state.formControl.remove, onChange: this.state.formControl.onChange } let fill = <ListingForm data={newListing} key={this.state.key} action={this.state.formControl} focus={focus}/>; this.setState({key: this.state.key+1, idx: this.state.idx-1}); return fill; }, refreshCurrent:()=>{ let base = 'https://fuo-backend.herokuapp.com/product/printallproduct/'; let id = this.state.currentStore; let url = base + id; fetch(url) .then(res => { if( res.status === 200){ return res.json(); } else{ throw new Error("Failed to get new listings"); } }) .then(data => { let currentList = []; for(let i = 0; i < data.length; i++){ currentList.push({ image: data[i].product_img, category: data[i].category, name: data[i].product_name, amount: data[i].stock_amount, price: data[i].price, rate: data[i].coupon, product_id: data[i].product_id, expiration: data[i].expire_date }); } let list = []; for(let i = 0; i < currentList.length; i++){ list.push(this.state.fillListing(currentList[i], 7)); } this.setState({ right: { address: this.state.currentLocation, totalProducts: data.length, productsList: data }, updateListings: currentList, list: list, }); }) .catch(error => { console.log('caught'); console.log(error); }); } }; //binding this.validate = this.validate.bind(this); } /** validation for all listings are filled in */ validate = (list) => { for (let i = 0; i < list.length; i++) { if ( (list[i].image && !list[i].image.includes('.')) || (!list[i].name ) || (!list[i].amount || !Number(list[i].amount) ) || (!list[i].price || !Number(list[i].price) || Number(list[i].price) > 1000) || (!list[i].rate || !Number(list[i].rate)) || (!list[i].expiration || new Date(list[i].expiration) < new Date().setDate(new Date().getDate() - 1)) ) { alert('Please provide all required details.') return false; } } return true; }; /* ----------------------------------------------------------------------------- Assemble page, pass state values into props Action | Child functionality implemented in parent, then passed down Data | Read only propss Initial | Starter data that may get changed ----------------------------------------------------------------------------- */ render(){ return( <div> <LeftSideBar action={this.state.addLocation} data={this.state.logout} name={this.state.companyName} num={this.state.totalLocations}/> <LocationSearchBar action={this.state.search} /> <Locations action={this.state.selectLocation} data={this.state.locations} initial={this.state.locationBg} /> <LocationInfo action={this.state.rightControls} data={this.state.right} /> <AddLocation action={this.state.form} data={this.state.formClass} /> <UpdateListings action={this.state.update} data={this.state.updateClass} initial={this.state.list}/> <Status message={this.state.currentMessage} status={this.state.currentStatus}/> </div> ); } /* ----------------------------------------------------------------------------- After Render ----------------------------------------------------------------------------- */ componentDidMount(){ //Alert logins on small bad screen sizes if(window.innerWidth / window.innerHeight < 1.3 || window.innerHeight < 720){ alert("Layout has not been optimized for small screens. Please log in with a larger device."); } let body = { token: localStorage.getItem("fuo-b") }; fetch('https://fuo-backend.herokuapp.com/users/me/from/token/business', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) .then(res => { if(res.status === 200){ return res.json() } else{ window.location.assign('https://corona-food.herokuapp.com/'); throw new Error('There is no session'); } }) .then(data => { this.setState({session: data.user.business_id}); this.state.load(); }) .catch(err => { console.log("caught b login"); console.log(err); window.location.assign('https://corona-food.herokuapp.com/'); this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'}); }); } }
JavaScript
class CoreBadge extends HTMLElement { /** * Initialize private fields, shadowRoot and the view */ constructor() { super(); // Initialize all private fields this._value = this.getAttribute('value') || undefined; this._max = this.getAttribute('max') || undefined; this._isDot = this.hasAttribute('is-dot') || false; this._hidden = this.hasAttribute('hidden') || false; this._type = this.getAttribute('type') || undefined; // Initialize the shadowRoot this.attachShadow({mode: 'open'}); this.shadowRoot.appendChild(template.content.cloneNode(true)); this.shadowRoot.appendChild(style.cloneNode(true)); // Add 'change' event listener to this element so that // every time a 'change' event is observed, update the view const config = {attributes: false, childList: true, subtree: true}; const observer = new MutationObserver(this._updateTemplate.bind(this)); observer.observe(this, config); this.addEventListener('change', this._updateTemplate.bind(this)); // Initialize the view this._updateTemplate(); } get max() { return this._max; } /** * The maximum number that can be put in the badge * <br>If the value field is a number larger than max field, * `${max}+` will be displayed in the badge * @param {number} val */ set max(val) { if (typeof val === 'number') { this._max = val; this.setAttribute('max', val); } else { this._max = undefined; this.removeAttribute('max'); } this._updateTemplate(); } get isDot() { return this._isDot; } /** * If a little dot is displayed instead of the value * @param {boolean} val */ set isDot(val) { if (val === true) { this._isDot = true; this.setAttribute('is-dot', ''); } else { this._isDot = false; this.removeAttribute('is-dot'); } this._updateTemplate(); } get hidden() { return this._hidden; } /** * If the badge is displayed or not. * @param {boolean} val */ set hidden(val) { if (val === true) { this._hidden = true; this.setAttribute('hidden', ''); } else { this._hidden = false; this.removeAttribute('hidden'); } this._updateTemplate(); } get value() { return this._value; } /** * The content that the badge tries to display but may not be the same as the acutal displayed content * when the value is a number larger than max field. * @param {number|string} val */ set value(val) { if (typeof val === 'string' || typeof val === 'number') { this._value = val; this.setAttribute('value', val); } else { this._value = undefined; this.removeAttribute('value'); } this._updateTemplate(); } get type() { return this._type; } /** * The type of the badge chosen from [primary, success, warning, info, danger] * @param {string} val */ set type(val) { if (['primary', 'success', 'warning', 'info', 'danger'].indexOf(val) > -1) { this._type = val; this.setAttribute('type', val); } else { this._type = undefined; this.removeAttribute('type'); } this._updateTemplate(); } /** * The actual content to be displayed. It may be different from the given value because of max field. */ get content() { if (this.isDot) return ''; const value = this.value; const max = this.max; const valueNum = parseInt(value); const maxNum = parseInt(max); if (!isNaN(valueNum) && !isNaN(maxNum)) { return maxNum < valueNum ? `${maxNum}+` : valueNum; } return value; } /** * Update the content of the transition element inside our template */ _updateTemplate() { const update = !this.hidden && (this.content || this.content === 0 || this.isDot) ? ` <sup class="el-badge__content ${'el-badge__content--' + (this.type === null ? undefined : this.type)} ${this.innerHTML ? 'is-fixed' : ''} ${this.isDot ? 'is-dot' : ''}"> ${this.content} </sup> ` : ''; this.shadowRoot.querySelector('transition').innerHTML = update; } }
JavaScript
class StatusMessage { /** * * @param {Integer} pProgress * @param {String} pMessage * @constructor */ constructor( pProgress, pMessage=""){ this.progress = pProgress; this.msg = pMessage; this.extra = null; Logger.debug('<status message> : NEW : ',pMessage); } /** * To create a messsage with "error" flag * @param {Integer} pProgress * @param {String} pMessage * @returns {StatusMessage} * @static */ static newError( pProgress, pMessage){ let m = new StatusMessage(pProgress, pMessage); m.extra = "error"; Logger.debug('<status message> : ERROR : ',pMessage); return m; } /** * To create a message with "success" flag * * @param {String} pMessage * @returns {StatusMessage} * @static */ static newSuccess( pMessage){ let m = new StatusMessage(100, pMessage); m.extra = "success"; Logger.debug('<status message> : SUCCESS : ',pMessage); return m; } /** * * @param {*} pMsg * @method */ append( pMsg){ return this.msg+"\n"+pMsg; } /** * @method */ getProgress(){ return this.progress; } /** * @method */ getMessage(){ return this.msg; } /** * @method */ getExtra(){ return this.extra; } /** * To export to a poor object, ready to be serialized into JSON format * * @method */ toJsonObject(){ let o = new Object(); o.progress = this.progress; o.msg = this.msg; o.extra = this.extra; return o; } }
JavaScript
class ToStringBuilder { constructor(object, style, buffer) { if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((buffer != null && (buffer instanceof Object)) || buffer === null)) { let __args = arguments; if (this.buffer === undefined) { this.buffer = null; } if (this.object === undefined) { this.object = null; } if (this.style === undefined) { this.style = null; } if (style == null) { style = ToStringBuilder.getDefaultStyle(); } if (buffer == null) { buffer = { str: "", toString: function () { return this.str; } }; } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && buffer === undefined) { let __args = arguments; { let __args = arguments; let buffer = null; if (this.buffer === undefined) { this.buffer = null; } if (this.object === undefined) { this.object = null; } if (this.style === undefined) { this.style = null; } if (style == null) { style = ToStringBuilder.getDefaultStyle(); } if (buffer == null) { buffer = { str: "", toString: function () { return this.str; } }; } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } if (this.buffer === undefined) { this.buffer = null; } if (this.object === undefined) { this.object = null; } if (this.style === undefined) { this.style = null; } } else if (((object != null) || object === null) && style === undefined && buffer === undefined) { let __args = arguments; { let __args = arguments; let style = null; let buffer = null; if (this.buffer === undefined) { this.buffer = null; } if (this.object === undefined) { this.object = null; } if (this.style === undefined) { this.style = null; } if (style == null) { style = ToStringBuilder.getDefaultStyle(); } if (buffer == null) { buffer = { str: "", toString: function () { return this.str; } }; } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } if (this.buffer === undefined) { this.buffer = null; } if (this.object === undefined) { this.object = null; } if (this.style === undefined) { this.style = null; } } else throw new Error('invalid overload'); } static defaultStyle_$LI$() { if (ToStringBuilder.defaultStyle == null) { ToStringBuilder.defaultStyle = org.openprovenance.apache.commons.lang.builder.ToStringStyle.DEFAULT_STYLE_$LI$(); } return ToStringBuilder.defaultStyle; } /** * <p>Gets the default <code>ToStringStyle</code> to use.</p> * * <p>This method gets a singleton default value, typically for the whole JVM. * Changing this default should generally only be done during application startup. * It is recommended to pass a <code>ToStringStyle</code> to the constructor instead * of using this global default.</p> * * <p>This method can be used from multiple threads. * Internally, a <code>volatile</code> variable is used to provide the guarantee * that the latest value set using {@link #setDefaultStyle} is the value returned. * It is strongly recommended that the default style is only changed during application startup.</p> * * <p>One reason for changing the default could be to have a verbose style during * development and a compact style in production.</p> * * @return {org.openprovenance.apache.commons.lang.builder.ToStringStyle} the default <code>ToStringStyle</code>, never null */ static getDefaultStyle() { return ToStringBuilder.defaultStyle_$LI$(); } /** * <p>Sets the default <code>ToStringStyle</code> to use.</p> * * <p>This method sets a singleton default value, typically for the whole JVM. * Changing this default should generally only be done during application startup. * It is recommended to pass a <code>ToStringStyle</code> to the constructor instead * of changing this global default.</p> * * <p>This method is not intended for use from multiple threads. * Internally, a <code>volatile</code> variable is used to provide the guarantee * that the latest value set is the value returned from {@link #getDefaultStyle}.</p> * * @param {org.openprovenance.apache.commons.lang.builder.ToStringStyle} style the default <code>ToStringStyle</code> * @throws IllegalArgumentException if the style is <code>null</code> */ static setDefaultStyle(style) { if (style == null) { throw Object.defineProperty(new Error("The style must not be null"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] }); } ToStringBuilder.defaultStyle = style; } static reflectionToString$java_lang_Object(object) { return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object(object); } static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style) { return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style); } static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean(object, style, outputTransients) { return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$boolean$java_lang_Class(object, style, outputTransients, false, null); } static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$java_lang_Class(object, style, outputTransients, reflectUpToClass) { return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$boolean$java_lang_Class(object, style, outputTransients, false, reflectUpToClass); } /** * <p>Uses <code>ReflectionToStringBuilder</code> to generate a * <code>toString</code> for the specified object.</p> * * @param {*} object the Object to be output * @param {org.openprovenance.apache.commons.lang.builder.ToStringStyle} style the style of the <code>toString</code> to create, may be <code>null</code> * @param {boolean} outputTransients whether to include transient fields * @param {*} reflectUpToClass the superclass to reflect up to (inclusive), may be <code>null</code> * @return {string} the String result * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class) * @since 2.0 */ static reflectionToString(object, style, outputTransients, reflectUpToClass) { if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((typeof outputTransients === 'boolean') || outputTransients === null) && ((reflectUpToClass != null && (reflectUpToClass["__class"] != null || ((t) => { try { new t; return true; } catch (_a) { return false; } })(reflectUpToClass))) || reflectUpToClass === null)) { return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$java_lang_Class(object, style, outputTransients, reflectUpToClass); } else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((typeof outputTransients === 'boolean') || outputTransients === null) && reflectUpToClass === undefined) { return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean(object, style, outputTransients); } else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && outputTransients === undefined && reflectUpToClass === undefined) { return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style); } else if (((object != null) || object === null) && style === undefined && outputTransients === undefined && reflectUpToClass === undefined) { return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object(object); } else throw new Error('invalid overload'); } append$boolean(value) { this.style.append$java_lang_StringBuffer$java_lang_String$boolean(this.buffer, null, value); return this; } append$boolean_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$byte(value) { this.style.append$java_lang_StringBuffer$java_lang_String$byte(this.buffer, null, value); return this; } append$byte_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$char(value) { this.style.append$java_lang_StringBuffer$java_lang_String$char(this.buffer, null, value); return this; } append$char_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$double(value) { this.style.append$java_lang_StringBuffer$java_lang_String$double(this.buffer, null, value); return this; } append$double_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$float(value) { this.style.append$java_lang_StringBuffer$java_lang_String$float(this.buffer, null, value); return this; } append$float_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$int(value) { this.style.append$java_lang_StringBuffer$java_lang_String$int(this.buffer, null, value); return this; } append$int_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$long(value) { this.style.append$java_lang_StringBuffer$java_lang_String$long(this.buffer, null, value); return this; } append$long_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$java_lang_Object(obj) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, null, obj, null); return this; } append$java_lang_Object_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$short(value) { this.style.append$java_lang_StringBuffer$java_lang_String$short(this.buffer, null, value); return this; } append$short_A(array) { this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, null, array, null); return this; } append$java_lang_String$boolean(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$boolean(this.buffer, fieldName, value); return this; } append$java_lang_String$boolean_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$boolean_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param {string} fieldName the field name * @param {boolean[]} array the array to add to the <code>toString</code> * @param {boolean} fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this */ append(fieldName, array, fullDetail) { if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'boolean'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$boolean_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$byte_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'string'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$char_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$double_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$float_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$int_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$long_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (array[0] != null))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$java_lang_Object_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$short_A$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) { return this.append$java_lang_String$java_lang_Object$boolean(fieldName, array, fullDetail); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'boolean'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$boolean_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$byte_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'string'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$char_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$double_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$float_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$int_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$long_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (array[0] != null))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$java_lang_Object_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$short_A(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'boolean') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$boolean(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$byte(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'string') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$char(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$short(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$int(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$long(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$float(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) { return this.append$java_lang_String$double(fieldName, array); } else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null) || array === null) && fullDetail === undefined) { return this.append$java_lang_String$java_lang_Object(fieldName, array); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'boolean'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$boolean_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$byte_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'string'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$char_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$double_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$float_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$int_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$long_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (fieldName[0] != null))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$java_lang_Object_A(fieldName); } else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$short_A(fieldName); } else if (((typeof fieldName === 'boolean') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$boolean(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$byte(fieldName); } else if (((typeof fieldName === 'string') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$char(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$short(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$int(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$long(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$float(fieldName); } else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$double(fieldName); } else if (((fieldName != null) || fieldName === null) && array === undefined && fullDetail === undefined) { return this.append$java_lang_Object(fieldName); } else throw new Error('invalid overload'); } append$java_lang_String$byte(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$byte(this.buffer, fieldName, value); return this; } append$java_lang_String$byte_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$byte_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$char(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$char(this.buffer, fieldName, value); return this; } append$java_lang_String$char_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$char_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$double(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$double(this.buffer, fieldName, value); return this; } append$java_lang_String$double_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$double_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$float(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$float(this.buffer, fieldName, value); return this; } append$java_lang_String$float_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$float_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$int(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$int(this.buffer, fieldName, value); return this; } append$java_lang_String$int_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$int_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$long(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$long(this.buffer, fieldName, value); return this; } append$java_lang_String$long_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$long_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$java_lang_Object(fieldName, obj) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, fieldName, obj, null); return this; } append$java_lang_String$java_lang_Object$boolean(fieldName, obj, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, fieldName, obj, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$java_lang_Object_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$java_lang_Object_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } append$java_lang_String$short(fieldName, value) { this.style.append$java_lang_StringBuffer$java_lang_String$short(this.buffer, fieldName, value); return this; } append$java_lang_String$short_A(fieldName, array) { this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, fieldName, array, null); return this; } append$java_lang_String$short_A$boolean(fieldName, array, fullDetail) { this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail)); return this; } /** * <p>Appends with the same format as the default <code>Object toString() * </code> method. Appends the class name followed by * {@link System#identityHashCode(Object)}.</p> * * @param {*} object the <code>Object</code> whose class name and id to output * @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this * @since 2.0 */ appendAsObjectToString(object) { org.openprovenance.apache.commons.lang.ObjectUtils.identityToString$java_lang_StringBuffer$java_lang_Object(this.getStringBuffer(), object); return this; } /** * <p>Append the <code>toString</code> from the superclass.</p> * * <p>This method assumes that the superclass uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If <code>superToString</code> is <code>null</code>, no change is made.</p> * * @param {string} superToString the result of <code>super.toString()</code> * @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this * @since 2.0 */ appendSuper(superToString) { if (superToString != null) { this.style.appendSuper(this.buffer, superToString); } return this; } /** * <p>Append the <code>toString</code> from another object.</p> * * <p>This method is useful where a class delegates most of the implementation of * its properties to another class. You can then call <code>toString()</code> on * the other class and pass the result into this method.</p> * * <pre> * private AnotherObject delegate; * private String fieldInThisClass; * * public String toString() { * return new ToStringBuilder(this). * appendToString(delegate.toString()). * append(fieldInThisClass). * toString(); * }</pre> * * <p>This method assumes that the other object uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>toString</code> is <code>null</code>, no change is made.</p> * * @param {string} toString the result of <code>toString()</code> on another object * @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this * @since 2.0 */ appendToString(toString) { if (toString != null) { this.style.appendToString(this.buffer, toString); } return this; } /** * <p>Returns the <code>Object</code> being output.</p> * * @return {*} The object being output. * @since 2.0 */ getObject() { return this.object; } /** * <p>Gets the <code>StringBuffer</code> being populated.</p> * * @return {{ str: string, toString: Function }} the <code>StringBuffer</code> being populated */ getStringBuffer() { return this.buffer; } /** * <p>Gets the <code>ToStringStyle</code> being used.</p> * * @return {org.openprovenance.apache.commons.lang.builder.ToStringStyle} the <code>ToStringStyle</code> being used * @since 2.0 */ getStyle() { return this.style; } /** * <p>Returns the built <code>toString</code>.</p> * * <p>This method appends the end of data indicator, and can only be called once. * Use {@link #getStringBuffer} to get the current string state.</p> * * <p>If the object is <code>null</code>, return the style's <code>nullText</code></p> * * @return {string} the String <code>toString</code> */ toString() { if (this.getObject() == null) { /* append */ (sb => { sb.str += this.getStyle().getNullText(); return sb; })(this.getStringBuffer()); } else { this.style.appendEnd(this.getStringBuffer(), this.getObject()); } return /* toString */ this.getStringBuffer().str; } }
JavaScript
class RestMetaCollection { /** * Constructs a new <code>RestMetaCollection</code>. * @alias module:model/RestMetaCollection * @class */ constructor() { } /** * Constructs a <code>RestMetaCollection</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/RestMetaCollection} obj Optional instance to populate. * @return {module:model/RestMetaCollection} The populated <code>RestMetaCollection</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new RestMetaCollection(); if (data.hasOwnProperty('NodePath')) { obj['NodePath'] = ApiClient.convertToType(data['NodePath'], 'String'); } if (data.hasOwnProperty('Metadatas')) { obj['Metadatas'] = ApiClient.convertToType(data['Metadatas'], [RestMetadata]); } } return obj; } /** * @member {String} NodePath */ NodePath = undefined; /** * @member {Array.<module:model/RestMetadata>} Metadatas */ Metadatas = undefined; }
JavaScript
class RootReference { constructor(env) { this.env = env; this.children = dict(); this.tag = CONSTANT_TAG; } get(key) { // References should in general be identical to one another, so we can usually // deduplicate them in production. However, in DEBUG we need unique references // so we can properly key off them for the logging context. if (DEBUG) { // We register the template debug context now since the reference is // created before the component itself. It shouldn't be possible to cause // errors when accessing the root, only subproperties of the root, so this // should be fine for the time being. The exception is helpers, but they // set their context earlier. // // TODO: This points to a need for more first class support for arguments in // the debugRenderTree. The fact that we can't accurately relate an argument // reference to its component is problematic for debug tooling. if (!this.didSetupDebugContext) { this.didSetupDebugContext = true; this.env.setTemplatePathDebugContext(this, this.debugLogName || 'this', null); } return new PropertyReference(this, key, this.env); } else { let ref = this.children[key]; if (ref === undefined) { ref = this.children[key] = new PropertyReference(this, key, this.env); } return ref; } } }
JavaScript
class PropertyReference { constructor(parentReference, propertyKey, env) { this.parentReference = parentReference; this.propertyKey = propertyKey; this.env = env; this.children = dict(); this.lastRevision = null; if (DEBUG) { env.setTemplatePathDebugContext(this, propertyKey, parentReference); } let valueTag = this.valueTag = createUpdatableTag(); let parentReferenceTag = parentReference.tag; this.tag = combine([parentReferenceTag, valueTag]); } value() { let { tag, lastRevision, lastValue, parentReference, valueTag, propertyKey } = this; if (lastRevision === null || !validateTag(tag, lastRevision)) { let parentValue = parentReference.value(); if (isDict(parentValue)) { let combined = track(() => { lastValue = this.env.getPath(parentValue, propertyKey); }, DEBUG && this.env.getTemplatePathDebugContext(this)); updateTag(valueTag, combined); } else { lastValue = undefined; } this.lastValue = lastValue; this.lastRevision = valueForTag(tag); } return lastValue; } get(key) { // References should in general be identical to one another, so we can usually // deduplicate them in production. However, in DEBUG we need unique references // so we can properly key off them for the logging context. if (DEBUG) { return new PropertyReference(this, key, this.env); } else { let ref = this.children[key]; if (ref === undefined) { ref = this.children[key] = new PropertyReference(this, key, this.env); } return ref; } } [UPDATE_REFERENCED_VALUE](value) { let { parentReference, propertyKey } = this; let parentValue = parentReference.value(); this.env.setPath(parentValue, propertyKey, value); } } //////////
JavaScript
class IterationItemReference { constructor(parentReference, itemValue, itemKey, env) { this.parentReference = parentReference; this.itemValue = itemValue; this.env = env; this.tag = createUpdatableTag(); this.children = dict(); if (DEBUG) { env.setTemplatePathDebugContext(this, debugToString(itemKey), parentReference); } } value() { return this.itemValue; } update(value) { dirtyTag(this.tag); this.itemValue = value; } get(key) { // References should in general be identical to one another, so we can usually // deduplicate them in production. However, in DEBUG we need unique references // so we can properly key off them for the logging context. if (DEBUG) { return new PropertyReference(this, key, this.env); } else { let ref = this.children[key]; if (ref === undefined) { ref = this.children[key] = new PropertyReference(this, key, this.env); } return ref; } } }
JavaScript
class Recurring { /** * Init * @param {UnzerSimple} unzer Unzer main class */ constructor(unzer) { this._urlpath = '/types'; this._unzer = unzer; } /** * GET recurring state * * @link https://docs.unzer.com/reference/api/#get-/v1/types/{methodid}/recurring * @param {string} methodId Id of Payment method * @return {Promise<Object>} Unzer response */ async get(methodId) { let url = this._urlpath + '/' + methodId + '/recurring'; return this._unzer.get(url); } /** * Set reccuring state for given UUID * @link https://docs.unzer.com/reference/api/#post-/v1/types/recurring * @param {string} uuid UUID of payment method * @return {Promise<Object>} */ async postUuid(uuid) { let url = this._urlpath + '/recurring'; return this._unzer.post(url, {uuid: uuid}); } /** * Set recurring state for given method id * @link https://docs.unzer.com/reference/api/#post-/v1/types/{methodid}/recurring * @param {string} methodId payment method id * @param {object} payload post body payload * @return {Promise<Object>} */ async postMethodId(methodId, payload) { let url = this._urlpath + '/' + methodId + '/recurring'; return this._unzer.post(url, payload, {}, true); } }
JavaScript
class Grid3D extends Grid { /** Constructor of the Grid3D object. * @param {GridSize} extents - the size of the grid in each dimension * @param {boolean[]} [torus = [true,true,true]] - should the borders of * the grid be linked, so that a cell moving out on the left reappears on * the right? */ constructor( extents, torus = [true,true,true] ){ super( extents, torus ) // Check that the grid size is not too big to store pixel ID in 32-bit number, // and allow fast conversion of coordinates to unique ID numbers. /** @ignore */ this.Z_BITS = 1+Math.floor( Math.log2( this.extents[2] - 1 ) ) if( this.X_BITS + this.Y_BITS + this.Z_BITS > 32 ){ throw("Field size too large -- field cannot be represented as 32-bit number") } /** @ignore */ this.Z_MASK = (1 << this.Z_BITS)-1 /** @ignore */ this.Z_STEP = 1 /** @ignore */ this.Y_STEP = 1 << (this.Z_BITS) /** @ignore */ this.X_STEP = 1 << (this.Z_BITS +this.Y_BITS) /** Array with values for each pixel stored at the position of its * {@link IndexCoordinate}. E.g. the value of pixel with coordinate i * is stored as this._pixelArray[i]. * Note that this array is accessed indirectly via the * {@link _pixels} set- and get methods. * @private * @type {Uint16Array} */ this._pixelArray = new Uint16Array(this.p2i(extents)) this.datatype = "Uint16" } /** Method for conversion from an {@link ArrayCoordinate} to an * {@link IndexCoordinate}. * * See also {@link Grid3D#i2p} for the backward conversion. * * @param {ArrayCoordinate} p - the coordinate of the pixel to convert * @return {IndexCoordinate} the converted coordinate. * * @example * let grid = new CPM.Grid3D( [100,100,100], [true,true,true] ) * let p = grid.i2p( 5 ) * console.log( p ) * console.log( grid.p2i( p )) */ p2i( p ){ return ( p[0] << ( this.Z_BITS + this.Y_BITS ) ) + ( p[1] << this.Z_BITS ) + p[2] } /** Method for conversion from an {@link IndexCoordinate} to an * {@link ArrayCoordinate}. * * See also {@link Grid3D#p2i} for the backward conversion. * * @param {IndexCoordinate} i - the coordinate of the pixel to convert * @return {ArrayCoordinate} the converted coordinate. * * @example * let grid = new CPM.Grid3D( [100,100,100], [true,true,true] ) * let p = grid.i2p( 5 ) * console.log( p ) * console.log( grid.p2i( p )) */ i2p( i ){ return [i >> (this.Y_BITS + this.Z_BITS), ( i >> this.Z_BITS ) & this.Y_MASK, i & this.Z_MASK ] } /** This iterator returns locations and values of all non-zero pixels. * Whereas the {@link pixels} generator yields only non-background pixels * and specifies both their {@link ArrayCoordinate} and value, this * generator yields all pixels by {@link IndexCoordinate} and does not * report value. * * @return {IndexCoordinate} for each pixel, return its * {@link IndexCoordinate}. * * * @example * let CPM = require( "path/to/build" ) * // make a grid and set some values * let grid = new CPM.Grid3D( [100,100,100], [true,true,true] ) * grid.setpixi( 0, 1 ) * grid.setpixi( 1, 5 ) * * // iterator * for( let i of grid.pixelsi() ){ * console.log( i ) * } */ * pixelsi() { let ii = 0, c = 0 for( let i = 0 ; i < this.extents[0] ; i ++ ){ let d = 0 for( let j = 0 ; j < this.extents[1] ; j ++ ){ for( let k = 0 ; k < this.extents[2] ; k ++ ){ yield ii ii++ } d += this.Y_STEP ii = c + d } c += this.X_STEP ii = c } } /** This iterator returns locations and values of all non-zero pixels. * @return {Pixel} for each pixel, return an array [p,v] where p are * the pixel's array coordinates on the grid, and v its value. * * @example * let CPM = require( "path/to/build" ) * // make a grid and set some values * let grid = new CPM.Grid3D( [100,100,100], [true,true,true] ) * grid.setpix( [0,0,0], 1 ) * grid.setpix( [0,0,1], 5 ) * * // iterator * for( let p of grid.pixels() ){ * console.log( p ) * } */ * pixels() { let ii = 0, c = 0 for( let i = 0 ; i < this.extents[0] ; i ++ ){ let d = 0 for( let j = 0 ; j < this.extents[1] ; j ++ ){ for( let k = 0 ; k < this.extents[2] ; k ++ ){ //noinspection JSUnresolvedVariable let pixels = this._pixels if( pixels[ii] > 0 ){ yield [[i,j,k], pixels[ii]] } ii++ } d += this.Y_STEP ii = c + d } c += this.X_STEP ii = c } } /** Return array of {@link IndexCoordinate} of the Moore neighbor pixels * of the pixel at coordinate i. This function takes the 3D equivalent of * the 2D Moore-8 neighborhood, excluding the pixel itself. * @see https://en.wikipedia.org/wiki/Moore_neighborhood * @param {IndexCoordinate} i - location of the pixel to get neighbors of. * @param {boolean[]} [torus=[true,true,true]] - does the grid have linked * borders? Defaults to the setting on this grid, see {@link torus} * @return {IndexCoordinate[]} - an array of coordinates for all the * neighbors of i. */ neighi( i, torus = this.torus ){ let p = this.i2p(i) let xx = [] for( let d = 0 ; d <= 2 ; d ++ ){ if( p[d] === 0 ){ if( torus[d] ){ xx[d] = [p[d],this.extents[d]-1,p[d]+1] } else { xx[d] = [p[d],p[d]+1] } } else if( p[d] === this.extents[d]-1 ){ if( torus[d] ){ xx[d] = [p[d],p[d]-1,0] } else { xx[d] = [p[d],p[d]-1] } } else { xx[d] = [p[d],p[d]-1,p[d]+1] } } let r = [], first=true for( let x of xx[0] ){ for( let y of xx[1] ){ for( let z of xx[2] ){ if( first ){ first = false } else { r.push( this.p2i( [x,y,z] ) ) } } } } return r } }
JavaScript
class Event { /** * Initializes a new Event * * @param {Object} config Event configuration object * @param {String} config.name Event name * @param {String} [config.discordEventName = ''] Name of discord.js event that triggers this Event * @param {Function} config.handler Event function * @param {String} [config.type = 'discord'] Event type * @param {String} [config.description = ''] Event description * @param {String} [config.context = 'global'] Event context * @param {String} [config.interval = '1d'] Event interval * @param {Function} [config.enable = () => {}] function that runs before enabling the Event for a context * @param {Function} [config.disable = () => {}] function that runs before disabling the Event for a context * @param {String} sourcePath full path of Event source file * @constructor */ constructor ({ name, discordEventName = '', handler, type = 'discord', description = '', context = 'global', interval = '1d', enable = () => {}, disable = () => {} }, sourcePath) { this.name = name this.discordEventName = (discordEventName.length > 0 ? discordEventName : name) this.handler = handler this.type = type this.description = description this.context = context this.interval = interval this.enable = enable this.disable = disable this.sourcePath = sourcePath } }
JavaScript
class CreatePodForm extends Component { initialState = { name: "", description: "", }; constructor(props) { super(props); this.state = this.initialState; // any method using this keyword must bind // example: this.method = this.method.bind(this) } componentDidMount() { // Things to do when the component is first rendered into the dom } componentWillUnmount() { // Things to do when the component is removed } handleChange = (event) => { const { name, value } = event.target; this.setState({ [name]: value, }); }; submitForm = () => { this.props.handleSubmit(this.state); this.setState(this.initialState); }; render() { return ( <div className="CreatePodForm"> <h3>Name: {this.state.name}</h3> <h3>Description: {this.state.description}</h3> <form className="form my-4"> <div class="form-group"> <label for="name">Project Name:</label> <input type="text" class="form-control" placeholder="Enter Project Name" name="name" value={this.state.name} onChange={this.handleChange} required /> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> </div> <div class="form-group"> <label for="description">Project Description:</label> <input type="text" class="form-control" placeholder="Enter Project Description" name="description" value={this.state.description} onChange={this.handleChange} required /> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> </div> <input type="button" value="submit" class="btn btn-primary" onClick={this.submitForm} /> </form> </div> ); } }
JavaScript
class Tab extends Node { /** * @param {string} label - text label for the tab * @param {EnumerationProperty.<PreferencesDialog.<PreferencesTab>} property * @param {PreferencesDialog.PreferencesTab} value - PreferencesTab shown when this tab is selected */ constructor( label, property, value ) { const textNode = new Text( label, PreferencesDialog.TAB_OPTIONS ); // background Node behind the Text for layout spacing, and to increase the clickable area of the tab const backgroundNode = new Rectangle( textNode.bounds.dilatedXY( 15, 10 ), { children: [ textNode ] } ); const underlineNode = new Line( 0, 0, textNode.width, 0, { stroke: FocusHighlightPath.INNER_FOCUS_COLOR, lineWidth: 5, centerTop: textNode.centerBottom.plusXY( 0, 5 ) } ); super( { children: [ backgroundNode, underlineNode ], cursor: 'pointer', // pdom tagName: 'button', innerContent: label, ariaRole: 'tab', focusable: true, containerTagName: 'li' } ); // @public {PreferenceTab} this.value = value; // voicing this.initializeVoicing(); this.voicingNameResponse = StringUtils.fillIn( preferencesTabResponsePatternString, { title: label } ); const buttonListener = new PressListener( { press: () => { property.set( value ); // speak the object response on activation this.voicingSpeakNameResponse(); }, // phet-io - opting out for now to get CT working tandem: Tandem.OPT_OUT } ); this.addInputListener( buttonListener ); Property.multilink( [ property, buttonListener.isOverProperty ], ( selectedTab, isOver ) => { textNode.opacity = selectedTab === value ? 1 : isOver ? 0.8 : 0.6; this.focusable = selectedTab === value; underlineNode.visible = selectedTab === value; } ); } }
JavaScript
class BaseModel { constructor() { /** @const the underlying mongoose model used for queries */ this.mongooseModel_ = this.createMongooseModel_() } /** * Returns the model schema. The child class must implement the static schema * property. * @return {string} the models schema */ getSchema() { if (!this.constructor.schema) { throw new Error("Schema not defined") } return this.constructor.schema } /** * Returns the model name. The child class must implement the static modelName * property. * @return {string} the name of the model */ getModelName() { if (!this.constructor.modelName) { throw new Error("Every model must have a static modelName property") } return this.constructor.modelName } /** * Returns the schema options defined in child class. * @return {object} the schema options */ getSchemaOptions() { if (!this.constructor.schemaOptions) { return {} } return this.constructor.schemaOptions } /** * @private * Creates a mongoose model based on schema, schema options and model name. * @return {Mongooose.Model} the mongoose model */ createMongooseModel_() { const schema = this.getSchema() const options = this.getSchemaOptions() const mongooseSchema = new mongoose.Schema(schema, options) return mongoose.model(this.getModelName(), mongooseSchema) } /** */ startSession() { return this.mongooseModel_.startSession() } /** * Queries the mongoose model via the mongoose's findOne. * @param query {object} a mongoose selector query * @param options {?object=} mongoose options * @return {?mongoose.Document} the retreived mongoose document or null. */ findOne(query, options = {}) { return this.mongooseModel_.findOne(query, options).lean() } /** * Queries the mongoose model via the mongoose's find. * @param query {object} a mongoose selector query * @param options {?object=} mongoose options * @return {Array<mongoose.Document>} the retreived mongoose documents or * an empty array */ find(query, options, offset, limit) { return this.mongooseModel_ .find(query, options) .skip(offset) .limit(limit) .lean() } count() { return this.mongooseModel_.count({}) } /** * Update a model via the mongoose model's updateOne. * @param query {object} a mongoose selector query * @param update {object} mongoose update object * @param options {?object=} mongoose options * @return {object} mongoose result */ updateOne(query, update, options = {}) { options.new = true return this.mongooseModel_.findOneAndUpdate(query, update, options).lean() } /** * Update a model via the mongoose model's update. * @param query {object} a mongoose selector query * @param update {object} mongoose update object * @param options {?object=} mongoose options * @return {object} mongoose result */ update(query, update, options) { return this.mongooseModel_.update(query, update, options) } /** * Creates a document in the mongoose model's collection via create. * @param object {object} the value of the document to be created * @param options {?object=} mongoose options * @return {object} mongoose result */ create(object, options) { return this.mongooseModel_.create(object, options) } /** * Deletes a document in the mongoose model's collection * @param query {object} the value of the document to be created * @param options {?object=} mongoose options * @return {object} mongoose result */ deleteOne(query, options) { return this.mongooseModel_.deleteOne(query, options) } /** * Deletes many document in the mongoose model's collection * @param query {object} the value of the document to be created * @param options {?object=} mongoose options * @return {object} mongoose result */ delete(query, options) { return this.mongooseModel_.deleteMany(query, options) } }
JavaScript
class State { /** * Set page map * @param {PageMap} pageMap - page map * @example State.setPageMap(new PageMap()); */ static setPageMap(pageMap) { this.pageMap = pageMap; } /** * Set current page by Name * @param {string} pageName - name of page ot set * @example State.setPage("YourPage"); */ static setPage(pageName) { this.page = this.pageMap.getPage(pageName).pageObject; } /** * Get current page * @return {AbstractPage} - current page * @throws {Error} * @example State.getPage(); */ static getPage() { if (this.page) { return this.page; } else { throw new Error("Current page is not defined") } } }
JavaScript
class PieceState { // creates a new piece with a given color and id constructor(color, id) { this._color = color this._id = id this._state = State.HOME this._location = null this._capturer = null this.selected = false } get color() { return this._color } get id() { return this._id } isHome() { return this._state === State.HOME } isOut() { return this._state === State.OUT } moveOut() { const new_piece = new PieceState(this._color, this._id) new_piece._state = State.OUT new_piece._location = { track: this._color, position: KEY_POSITION.START, } return new_piece } isCaptured() { return this._state === State.CAPTURED } makeCaptured(capturerColor) { if (!this.isOut()) { throw new Error("a piece can only be captured if out") } const new_piece = new PieceState(this._color, this._id) new_piece._state = State.CAPTURED new_piece._capturer = capturerColor return new_piece } capturerColor() { if (!this.isCaptured()) { throw new Error("this piece is not captured") } return this._capturer } makeReleased() { if (!this.isCaptured()) { throw new Error("a piece can only be released if captured") } return new PieceState(this._color, this._id) } isGraduating() { if (!this.isOut()) { return false } return this._location.track === 'graduation_lane' } isGraduated() { return this._state === State.GRADUATED } makeGraduated() { if (!this.isGraduating()) { throw new Error("a piece can only graduate if it's graduating") } const new_piece = new PieceState(this._color, this._id) new_piece._state = State.GRADUATED return new_piece } /** * Return an object with fields "track" which is either * 'graduation_lane' or <color>. If 'graduation_lane' * 'position' is one of 1 through 5 or 6 (depending on the * rules) and it will be located on its color's track. if * <color> (which is one of our four colors), position * represents the cell they are in. cell 0 represents the * most counterclockwise position of that color. (e.g., * for RED that positon is the color that is connected to * the BLUE HOME and the RED graduation triangle). */ location() { if (!this.isOut()) { throw new Error("This piece is not out, so it doesn't have a location") } return { track: this._location.track, position: this._location.position, } } isAboutToEnterGraduationLane() { if (!this.isOut()) { return false } if (this._location.track !== this._color) { return false } return this._location.position === KEY_POSITION.GRADUATE } forward(count, stop_at_graduation_entrance=false) { if (!this.isOut()) { throw new Error("This piece can't move forward because it's not out") } const new_piece = new PieceState(this._color, this._id) new_piece._state = State.OUT const new_position = this._location.position + count if (this.isGraduating()) { if (new_position > KEY_POSITION.LAST_GRAD) { throw new Error("Cannot exceed graduation") } new_piece._location = { track: GRAD_TRACK, position: new_position } return new_piece } // TODO: fix comment below... lol. is code even good? // this is bad design... but the case where isAboutToGraduate // is handled in positioning. I should move it here because it // doesn't really make sense that in this code it's assuming that // that case is handled (when it could not by another implementer) if (this.isAboutToEnterGraduationLane() && stop_at_graduation_entrance) { if (count !== 1) { throw new Error("Must roll a 1 to enter graduation") } new_piece._location = { track: GRAD_TRACK, position: 1, } return new_piece } const was_before_graduate = this._location.position <= KEY_POSITION.GRADUATE if (this._location.track === this._color && was_before_graduate) { let maybe_grad_track = this._location.track let maybe_grad_position = new_position if (maybe_grad_position > KEY_POSITION.GRADUATE) { if (stop_at_graduation_entrance) { throw new Error( "The new position would exceed the graduation lane entry" ) } maybe_grad_track = GRAD_TRACK maybe_grad_position = new_position - KEY_POSITION.GRADUATE } if (maybe_grad_track === GRAD_TRACK && maybe_grad_position > KEY_POSITION.LAST_GRAD) { throw new Error("Cannot exceed graduation") } new_piece._location = { track: maybe_grad_track, position: maybe_grad_position, } return new_piece } new_piece._location = PieceState._nextLocation( this._location.track, new_position ) return new_piece } static _nextLocation(color, position) { let new_color = color let new_position = position let was_old_color = false while (new_position > KEY_POSITION.LAST) { new_color = PieceState._nextTrackColor(new_color) new_position = new_position - (KEY_POSITION.LAST + 1) if (new_color === color) { was_old_color = true continue } if (was_old_color) { throw new Error("We looped back, this is impossible") } } return {track: new_color, position: new_position} } static _nextTrackColor(color) { switch (color) { case C.color.RED: return C.color.GREEN case C.color.GREEN: return C.color.YELLOW case C.color.YELLOW: return C.color.BLUE case C.color.BLUE: return C.color.RED default: throw new Error(`invalid color ${color}`) } } equal(other) { return this.color === other.color && this.id === other.id && this._state === other._state && this._location === other._location && this._capturer === other._capturer } sameColor(other) { return this.color === other.color } }
JavaScript
class Choice { constructor (value, index, label, selected, image) { this.CHOICE_INDEX = index this.CHOICE_VALUE = String(value) this.CHOICE_LABEL = label if (selected) { this.CHOICE_SELECTED = true } else { this.CHOICE_SELECTED = false } this.CHOICE_IMAGE = image } }
JavaScript
class PhobosClient extends Client { /** * Create a PhobosClient * @param {object} options Discord.js Client options */ constructor (options) { super(options) /** * Configs defined in src/config.js * @type {object} */ this.config = config /** * Contains categories that contain the actual commands * @type {Collection} */ this.commands = new Collection() /** * All aliases to commands (kinda like a index) * @type {Collection} */ this.aliases = new Collection() /** * Command cooldowns * @type {Collection} */ this.cooldowns = new Collection() /** * Custom logger * @type {object} */ this.log = log /** * Databases * @type {object} */ this.db = { user: db.User, guild: db.Guild } } /** * Get a command from name or alias * @param {string} name Command name or alias * @returns {object} Command */ getCmd (name) { // Loop through all categories and find commands in them for (const category of this.commands.values()) { const cmd = category.get(name) if (cmd) { return cmd } } // If not found, find in aliases return this.aliases.get(name) } }
JavaScript
class FilterSelectionInput extends React.Component { constructor( props ) { super( props ); this.state = Object.assign( {}, props, { isModalOpen: false, 'labelText': 'Filter' } ); this.onClearButtonClick = this.onClearButtonClick.bind( this ); this.setFilterSelection = this.setFilterSelection.bind( this ); this.onAction = this.onAction.bind( this ); } componentDidMount() { this.filterSelector.addEventListener( "action", this.onAction ); } componentWillUnmount() { this.filterSelector.removeEventListener( "action", this.onAction ); } componentWillReceiveProps( nextProps ) { this.setState( Object.assign( this.state, nextProps, { isModalOpen: false, 'searching': false } ) ); } onAction( evt ) { if ( evt.detail.type === "named_text_selection" ) { console.log( "FilterSelectionInput.onAction %o", evt.detail ); if ( evt.detail.lookup == null && evt.detail.id == null ) { //unset this.onClearButtonClick( {} ); return; } if ( evt.detail.lookup && evt.detail.lookup.length > 1 ) { this.setState( { searching: false, value: evt.detail.lookup, type : 'RELATIONSHIP_QUERY_LOOKUP' }) if( this.props.onChange ) { this.props.onChange( { 'value': evt.detail.lookup, 'type': 'RELATIONSHIP_QUERY_LOOKUP', 'parameter' : 'RELATIONSHIP_QUERY_LOOKUP' } ); } } else { this.setState( { searching: false, value: evt.detail.id, type : 'RELATIONSHIP_QUERY_ID' }) if( this.props.onChange ) { this.props.onChange( { 'value': evt.detail.id, 'type': 'RELATIONSHIP_QUERY_ID', 'parameter' : 'RELATIONSHIP_QUERY_ID' } ); } } } } onClearButtonClick( event ) { this.setState( { value: 'Default', 'searching': false } ); if( this.props.onReset ) { this.props.onReset(); } else if( this.props.onChange ) { this.props.onChange( { 'parameter': 'RELATIONSHIP_QUERY_ID', 'value': '' } ); this.props.onChange( { 'parameter': 'RELATIONSHIP_QUERY_LOOKUP', 'value': '' } ); } } setFilterSelection( obj ) { if( obj.lookup ) { this.setState( { 'searching': !this.state.searching, 'value': obj.lookup, 'type' : 'RELATIONSHIP_QUERY_LOOKUP' } ); } else { this.setState( { 'searching': !this.state.searching, 'value': obj.id, 'type' : 'RELATIONSHIP_QUERY_ID' } ); } if( this.props.valueChange ) { this.props.valueChange( { 'value': this.state.value, 'type' : obj.lookup ? 'RELATIONSHIP_QUERY_LOOKUP' : 'RELATIONSHIP_QUERY_ID' } ); } } render() { return ( <div className = "form-group" > <label className=" control-label" htmlFor={this.props.parameter}> {this.state.labelText}: </label> <div> <iq-named-text-selector data-type="filter" data-initial-value={this.state.value} ref={( filterSelector ) => { this.filterSelector = filterSelector; }} /> <em className="help-block" > { this.state.help } </em> </div> </div> ); } stopIt( evt ) { evt.stopPropagation(); } openModal() { this.setState( { isModalOpen: true } ); } closeModal() { this.setState( { isModalOpen: false } ); } }
JavaScript
class EtiquetasController { /** * @param $uibModal * @param toastr * @param {EtiquetasService} EtiquetasService * @param {ProcesosService} ProcesosService * @param {ActividadesService} ActividadesService * @param AppConfig * **/ constructor($uibModal, toastr, EtiquetasService, ProcesosService, ActividadesService, AppConfig) { /** @private */ this.ITEMS_SELECT = AppConfig.elementosBusquedaSelect; /** @private */ this.$uibModal = $uibModal; /** @private */ this.toastr = toastr; /** @private */ this.etiquetasService = EtiquetasService; /** @private */ this.actividadesService = ActividadesService; /** @type {boolean} */ this.busquedaVisible = true; /** @private */ this.totalProcesos = 0; /** @type {Proceso[]} */ this.procesos = []; ProcesosService.obtenerTodos(false) .then(procesos => { /** @type {Proceso[]} */ this.procesos = [].concat(...procesos); this.procesos.push({codigo: undefined, evento: ''}); }); ActividadesService.obtenerTodos(1, ['orden', 'asc'], null, 0) .then(actividades => { this.actividades = actividades; }); this.estados = [ETIQUETA_PENDIENTE, ETIQUETA_OK_DESC, ETIQUETA_NOK_DESC]; this.etiquetasService.obtenerTodos() .then(etiquetas => { let etiquetasOrdenadasPorCodigo = sortBy(etiquetas, ['codigo']); /** @type {Etiqueta[]} */ this.etiquetas = etiquetasOrdenadasPorCodigo; /** @type {Etiqueta[]} */ this.datos = etiquetasOrdenadasPorCodigo; }); this.presentacion = { entidad: 'Etiqueta', atributoPrincipal: 'descripcion', ordenInicial: ['codigo', 'asc'], columnas: [ {nombre: 'codigo', display: 'ID', ordenable: true}, {nombre: 'proceso.display', display: 'Proceso', ordenable: true}, {nombre: 'actividad.display', display: 'Actividad', ordenable: true}, {nombre: 'descripcionEstado.ordenActividad', display: 'Orden', ordenable: true}, {nombre: 'descripcionEstado.nombre', display: 'Estado', ordenable: true}, {nombre: 'descripcion', display: 'Descripción', ordenable: true}, ] }; this.columnasExcel = { titulos: ['ID', 'Proceso', 'Actividad', 'Orden', 'Estado', 'Descripción'], campos: ['codigo', 'proceso.display', 'actividad.display', 'descripcionEstado.ordenActividad', 'descripcionEstado.nombre', 'descripcion'] }; } /** * Propiedad que devuelve true si no se está mostrando la lista completa de procesos en un momento determinado. * @return {boolean} */ get mostrandoResultadosParcialesProcesos() { return this.totalProcesos > this.ITEMS_SELECT + 1; } /** * Filtra la lista de procesos según el string que haya escrito el usuario. Es case insensitive. * @param {string} busqueda * @return {Proceso[]} */ filtrarProcesos(busqueda) { const busquedaLower = busqueda.toLowerCase(); const resultado = filter(this.procesos, (elemento) => { return (busqueda && elemento.evento) ? includes(elemento.evento.toLowerCase(), busquedaLower) : true; }); this.totalProcesos = resultado.length; if (resultado.length > this.ITEMS_SELECT + 1) { return resultado.slice(0, this.ITEMS_SELECT + 1); } else { return resultado; } } /** * Abre el modal que se utiliza para crear/editar una etiqueta. Cuando se termina de trabajar con la etiqueta, * actualiza o crea una fila correspondiente en la tabla. * * @param {Etiqueta} [etiqueta] Si no se pasa una etiqueta, el modal se abre en modo de creación. */ mostrarModalEtiqueta(etiqueta) { const contenedor = angular.element(document.getElementById('modalEdicionEtiqueta')); const modal = this.$uibModal.open({ template, appendTo: contenedor, size: 'dialog-centered', // hack para que el modal salga centrado verticalmente controller: 'ModalEdicionEtiquetasController', controllerAs: '$modal', resolve: { // Los elementos que se inyectan al controlador del modal se deben pasar de esta forma: entidad: () => { return etiqueta; }, actividades: () => { return this.actividades; } } }); modal.result.then((resultado) => { this.etiquetas = this.etiquetasService.etiquetas; if (this.busquedaActiva) { this.buscar(); } else { this.datos = clone(this.etiquetas); } if (!isNil(resultado) && !isNil(resultado.codigo) && !this.filaEsVisible(resultado)) { this.toastr.warning('Aunque se guardaron los cambios, la etiqueta no está visible en la tabla en estos momentos.'); } if (this.actividadesService.actividades.length === 0) { // Es necesario volver a pedir las actividades this.actividadesService.obtenerTodos(1, ['orden', 'asc'], null, 0) .then(actividades => { this.actividades = actividades; }); } }); modal.result.catch(() => { }); } /** * Edita los datos de una etiqueta. * @param {Etiqueta} etiqueta */ editarEtiqueta(etiqueta) { let clon = cloneDeep(etiqueta); clon.proceso = etiqueta.proceso.valor; clon.actividad = etiqueta.actividad.valor; this.mostrarModalEtiqueta(clon); } /** * Elimina una etiqueta * @param {Etiqueta} etiqueta */ eliminarEtiqueta(etiqueta) { const fnActualizarEtiquetas = () => { this.etiquetas = this.etiquetasService.etiquetas; if (this.busquedaActiva) { this.buscar(); } else { this.datos = clone(this.etiquetas); } }; return this.etiquetasService.eliminar(etiqueta) .then(() => { fnActualizarEtiquetas(); }) .catch(response => { if (response && response.status === 404) { fnActualizarEtiquetas(); } throw response; }); } buscar() { if (Object.getOwnPropertyNames(this.paramsBusqueda).length === 0) { this.mostrarTodos(); } else { this.busquedaActiva = true; this.datos = reduce(this.etiquetas, (resultado, item) => { let coincidencia = isMatchWith(item, this.paramsBusqueda, (objValue, srcValue, key, object) => { if (key === 'descripcion') { return objValue && includes(objValue.toLowerCase(), srcValue.toLowerCase()); } else if (key === 'proceso') { return isNil(srcValue) || objValue.valor.id === srcValue.id; } else if (key === 'estado') { return isNil(srcValue) || object.descripcionEstado.nombre === srcValue; } }); if (coincidencia) { resultado.push(item); } return resultado; }, []); } } mostrarTodos() { this.paramsBusqueda = {}; this.busquedaActiva = false; this.datos = clone(this.etiquetas); } /** * Devuelve verdadero si la etiqueta está visible en la tabla en ese momento. * @param {Etiqueta} etiqueta * @return {boolean} */ filaEsVisible(etiqueta) { if (isNil(etiqueta)) { return false; } return !!find(this.datos, (item) => { return item.codigo === etiqueta.codigo; }); } }
JavaScript
class SeparatorHeader extends Component { view() { return <li className="Dropdown-separator TagInject--Utility-Header">{app.translator.trans('flagrow-utility-tag-inject.forum.tags.utility-header')}</li>; } }
JavaScript
class Group{ /** * Builds a new group. * @param {string} name - Required parameter. The name of the group. * @param {string} startDate - Optional parameter. The date when the group was founded. Defaults to "". * @param {string} endDate - Optional parameter. The date when the group broke apart. Defaults to "". * @constructor */ constructor(name, startDate="", endDate=""){ this._name = name; this._startDate = startDate; this._endDate = endDate; } set name(name){ this._name = name; } get name(){ return this._name; } set startDate(startDate){ this._startDate = startDate; } get startDate(){ return this._startDate; } set endDate(endDate){ this._endDate = endDate; } get endDate(){ return this._endDate; } }
JavaScript
class SelectResourcePlugin extends BasePlugin { constructor(opts) { super(opts || {}); // frequency for crawling resources if (this.opts.crawlFrequency) { this.opts.crawlFrequency = parseInt(this.opts.crawlFrequency, 10); } } // eslint-disable-next-line class-methods-use-this getPhase() { return BasePlugin.PHASE.SELECT; } // eslint-disable-next-line class-methods-use-this test() { return true; } // eslint-disable-next-line class-methods-use-this apply(site) { return site.getResourceToCrawl(this.opts.crawlFrequency); } }
JavaScript
class ChatService{ constructor(API, UserService){ 'ngInject'; this.API = API; this.UserService = UserService; } /** * getConversations gets conversations involving this user and other users * @return {promise} promise of data */ getConversations(){ return this.API.one('chat/get_conversations').get() } /** * getConversation get conversation between this user and other user * @param {object} data request data * @return {promise} promise of data */ getConversation(data){ return this.API.all('chat/get_conversation').post(data) } /** * send message * @param {object} data request data */ sendMessage(data){ return this.API.all('chat/sendmessage').post(data) } /** * getOtherUser get other user involved in conversation * @param {object} convo conversation object * @return {object} user info */ getOtherUser(convo){ if(convo.sender_id === this.UserService.user.id){ return { id: convo.recipient_id, firstname: convo.recipient.firstname, lastname: convo.recipient.lastname, avatar: convo.recipient.avatar } }else{ return { id: convo.sender_id, firstname: convo.sender.firstname, lastname: convo.sender.lastname, avatar: convo.sender.avatar } } } /** * getConvoAvatar get avatar of other user * @param {object} convo conversation object * @return {string} avatar url */ getConvoAvatar(convo){ if(convo && this.UserService.user){ //if sender is current user return recipient info else return sender info if(convo.sender_id === this.UserService.user.id){ return "/uploads/avatars/"+convo.recipient.avatar; }else{ return "/uploads/avatars/"+convo.sender.avatar; } }else{ return "/uploads/avatars/avatar-5.png"; } } }
JavaScript
class BaseFormField extends React.Component { constructor(props) { super(props); this.htmlId = `form-field-${this.props.name}`; this.state = { value: props.initial }; } validateField() { let value = this.state.value || ""; if (this.props.required && value.length <= 0) { throw `${this.props.name} is required to complete this form.`; } } getValue() { if (this.state.value !== null && this.state.value !== undefined) { return this.state.value; } else { return this.props.initial; } } render() { let label = null; if (this.props.label) { label = <label htmlFor={this.htmlId}> {this.props.label} </label> } return <div className="form-group"> {label} {this.renderField()} </div> } }
JavaScript
class ListItem extends PureComponent { static propTypes = { /** * An optional style to apply to the `li` tag. */ style: PropTypes.object, /** * An optional className to apply to the `li` tag. */ className: PropTypes.string, /** * An optional style to apply to the `.md-list-tile`. * * @see component */ tileStyle: PropTypes.object, /** * An optional className to apply to the `.md-list-tile`. * * @see component */ tileClassName: PropTypes.string, /** * Any additional children to display in the `.md-list-tile`. If you use this prop, * you will most likely need to override the `height` for the `.md-list-tile--icon`, * `.md-list-tile--avatar`, `.md-list-tile--two-lines`, and/or `.md-list-tile--three-lines` * to get it to display correctly unless the children are positioned `absolute`. */ children: PropTypes.node, /** * Boolean if the `ListItem` is disabled. */ disabled: PropTypes.bool, /** * An optional tab index for the `.md-list-tile`. If omitted, it will default to the * `AccessibleFakeButton`'s `tabIndex` default prop value. */ tabIndex: PropTypes.number, /** * The primary text to display. This will only be rendered as a single line. Any overflown * text will be converted to ellipsis. */ primaryText: PropTypes.node.isRequired, /** * An optional secondary text to display below the `primaryText`. This can be an additional * one or two lines. Like the `primaryText`, and overflown text will be converted to ellipsis. * * You must set the `threeLines` prop to `true` if you want this to be displayed as two lines. */ secondaryText: PropTypes.node, /** * An optional `FontIcon` to display to the left of the text. */ leftIcon: PropTypes.node, /** * Boolean if the list item should be inset as if there is a `leftIcon` or a `leftAvatar`. * This is used for some lists where only a parent contains the icon. */ inset: PropTypes.bool, /** * An optional `Avatar` to display to the left of the text. If you have a mixed `List` of * `FontIcon` and `Avatar`, it is recommended to set the `iconSized` prop on the `Avatar` to * `true` so that the `Avatar` will be scaled down to the `FontIcon` size. */ leftAvatar: PropTypes.node, /** * An optional `FontIcon` to display to the right of the text. */ rightIcon: PropTypes.node, /** * An optional `Avatar` to display to the right of the text. If you have a mixed `List` of * `FontIcon` and `Avatar`, it is recommended to set the `iconSized` prop on the `Avatar` to * `true` so that the `Avatar` will be scaled down to the `FontIcon` size. */ rightAvatar: PropTypes.node, /** * Boolean if the `secondaryText` should span two lines instead of one. This will include * three lines of text in total when including the `primaryText`. */ threeLines: PropTypes.bool, /** * An optional component to render the `.md-list-tile` as. This is mostly useful if you * want to use the `ListItem` for navigation and working with the `react-router`'s `Link` * component. */ component: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]).isRequired, /** * An optional list of `ListItem`, `ListItemControl`, `Divider`, or `Subheader` components * to render in a nested list. This will inject an expander icon to the right of the text * in the `.md-list-tile` that rotates 180 degrees when open. * * The nested items will be visible once the user clicks on the `ListItem`. * * @see `defaultOpen` * @see `isOpen` */ nestedItems: PropTypes.arrayOf(PropTypes.node), /** * An optional parameter determining whether `nestedItems` should be placed before or after `ListItemText` */ prependNested: PropTypes.bool, /** * Boolean if the `nestedItems` are visible by default. */ defaultOpen: PropTypes.bool, /** * Boolean if the `nestedItems` are visible. This will make the `nestedItems` controlled * and require the `onClick` function to be defined. */ isOpen: controlled(PropTypes.bool, 'onClick', 'defaultOpen'), /** * Any children used to render the expander icon. */ expanderIconChildren: PropTypes.node, /** * An icon className to use to render the expander icon. */ expanderIconClassName: PropTypes.string, /** * An optional function to call when the `.md-list-tile` is clicked. This is required if the * `isOpen` prop is defined. */ onClick: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `mouseover` event. */ onMouseOver: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `mouseleave` event. */ onMouseLeave: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `touchstart` event. */ onTouchStart: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `touchend` event. */ onTouchEnd: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `keydown` event. */ onKeyDown: PropTypes.func, /** * An optional function to call when the `.md-list-tile` triggers the `keyup` event. */ onKeyUp: PropTypes.func, /** * Boolean if the `ListItem` is currently active. This will apply the `activeClassName` prop * to the `leftIcon`, `rightIcon`, and the `primaryText`. */ active: PropTypes.bool, /** * The className to apply to the `leftIcon`, `rightIcon`, and `primaryText` when the `active` * prop is `true`. */ activeClassName: PropTypes.string, initiallyOpen: deprecated(PropTypes.bool, 'Use `defaultOpen` instead'), }; static defaultProps = { activeClassName: 'md-text--theme-primary', component: 'div', expanderIconChildren: 'keyboard_arrow_down', }; constructor(props) { super(props); this.state = { active: false }; if (typeof props.isOpen === 'undefined') { this.state.isOpen = typeof props.initiallyOpen !== 'undefined' ? props.initiallyOpen : !!props.defaultOpen; } this.focus = this.focus.bind(this); this._setTile = this._setTile.bind(this); this._setContainer = this._setContainer.bind(this); this._handleOutsideClick = this._handleOutsideClick.bind(this); this._handleClick = this._handleClick.bind(this); this._handleKeyUp = this._handleKeyUp.bind(this); this._handleKeyDown = this._handleKeyDown.bind(this); this._handleMouseOver = this._handleMouseOver.bind(this); this._handleMouseLeave = this._handleMouseLeave.bind(this); this._handleTouchStart = this._handleTouchStart.bind(this); this._handleTouchEnd = this._handleTouchEnd.bind(this); } componentWillUnmount() { if (this.state.active) { window.removeEventListener('click', this._handleOutsideClick); } if (this._touchTimeout) { clearTimeout(this._touchTimeout); } } /** * A utility function to focus the `AccessibleFakeInkedButton` in the `ListItem` and also * inject an ink to indicate focus. */ focus() { if (this._tile) { this._tile.focus(); } } /** * A utility function to blur the `AccessibleFakeInkedButton` in the `ListItem`. */ blur() { if (this._tile) { this._tile.blur(); } } _setTile(tile) { if (tile) { this._tile = tile; } } _setContainer(container) { if (container) { this._container = findDOMNode(container); } } _handleOutsideClick(e) { if (this._container && !this._container.contains(e.target)) { window.removeEventListener('click', this._handleOutsideClick); this.setState({ active: false }); } } _handleClick(e) { if (this.props.onClick) { this.props.onClick(e); } if (typeof this.state.isOpen !== 'undefined') { this.setState({ isOpen: !this.state.isOpen }); } } _handleMouseOver(e) { if (this.props.onMouseOver) { this.props.onMouseOver(e); } if (!this.props.disabled) { this.setState({ active: true }); } } _handleMouseLeave(e) { if (this.props.onMouseLeave) { this.props.onMouseLeave(e); } if (!this.props.disabled) { this.setState({ active: false }); } } _handleTouchStart(e) { if (this.props.onTouchStart) { this.props.onTouchStart(e); } this._touched = true; this.setState({ active: true, touchedAt: Date.now() }); } _handleTouchEnd(e) { if (this.props.onTouchEnd) { this.props.onTouchEnd(e); } const time = Date.now() - this.state.touchedAt; this._touchTimeout = setTimeout(() => { this._touchTimeout = null; this.setState({ active: false }); }, time > 450 ? 0 : 450 - time); } _handleKeyUp(e) { if (this.props.onKeyUp) { this.props.onKeyUp(e); } if ((e.which || e.keyCode) === TAB) { window.addEventListener('click', this._handleOutsideClick); this.setState({ active: true }); } } _handleKeyDown(e) { if (this.props.onKeyDown) { this.props.onKeyDown(e); } if ((e.which || e.keyCode) === TAB) { window.removeEventListener('click', this._handleOutsideClick); this.setState({ active: false }); } } render() { const { style, className, tileStyle, tileClassName, disabled, leftIcon, leftAvatar, inset, rightIcon, rightAvatar, primaryText, secondaryText, threeLines, children, nestedItems, prependNested, active, activeClassName, expanderIconChildren, expanderIconClassName, ...props } = this.props; delete props.isOpen; delete props.defaultOpen; delete props.initiallyOpen; const isOpen = getField(this.props, this.state, 'isOpen'); const leftNode = ( <TileAddon key="left-addon" active={active} activeClassName={activeClassName} icon={leftIcon} avatar={leftAvatar} /> ); let rightNode = ( <TileAddon key="right-addon" active={active} activeClassName={activeClassName} icon={rightIcon} avatar={rightAvatar} /> ); let nestedList; if (nestedItems) { nestedList = <Collapse collapsed={!isOpen}><List>{nestedItems}</List></Collapse>; if (!rightIcon || !rightAvatar) { rightNode = ( <TileAddon key="expander-addon" icon={( <Collapser flipped={prependNested ? !isOpen : isOpen} iconClassName={expanderIconClassName}> {expanderIconChildren} </Collapser> )} avatar={null} /> ); } } const icond = !!leftIcon || !!rightIcon; const avatard = !!leftAvatar || !!rightAvatar; return ( <li style={style} className={cn('md-list-item', { 'md-list-item--nested-container': nestedItems, }, className)} ref={this._setContainer} > {prependNested ? nestedList : null} <AccessibleFakeInkedButton {...props} __SUPER_SECRET_REF__={this._setTile} key="tile" onClick={this._handleClick} onMouseOver={this._handleMouseOver} onMouseLeave={this._handleMouseLeave} onTouchStart={this._handleTouchStart} onTouchEnd={this._handleTouchEnd} onKeyDown={this._handleKeyDown} onKeyUp={this._handleKeyUp} disabled={disabled} style={tileStyle} className={cn('md-list-tile', { 'md-text': !disabled, 'md-text--disabled': disabled, 'md-list-tile--active': this.state.active && !this._touched, 'md-list-tile--icon': !secondaryText && icond && !avatard, 'md-list-tile--avatar': !secondaryText && avatard, 'md-list-tile--two-lines': secondaryText && !threeLines, 'md-list-tile--three-lines': secondaryText && threeLines, 'md-list-item--inset': inset && !leftIcon && !leftAvatar, }, tileClassName)} aria-expanded={nestedList ? isOpen : null} > {leftNode} <ListItemText active={active} activeClassName={activeClassName} disabled={disabled} primaryText={primaryText} secondaryText={secondaryText} threeLines={threeLines} className={cn({ 'md-tile-content--left-icon': leftIcon, 'md-tile-content--left-avatar': leftAvatar, 'md-tile-content--right-padding': rightIcon || rightAvatar, })} /> {rightNode} {children} </AccessibleFakeInkedButton> {prependNested ? null : nestedList} </li> ); } }
JavaScript
class GlobalState { static initialize(root) { GlobalState.instance = new GlobalState(root) } static set(...args) { GlobalState.instance.set(...args) } constructor(root) { this.root = root this.state = clone(this.root.state) } /** * set(k1, k2, k3, v) => state[k1][k2][k3] = v */ set(...args) { const value = args.pop() const lastKey = args.pop() let obj = args.reduce((obj, k) => obj[k], this.state) obj[lastKey] = value this.root.setState(clone(this.state)) } }
JavaScript
class Tester extends EventEmitter { constructor(mod, options) { super(); this.module = extractDetail(mod); this.options = options; this.testOutput = new BufferList(); this.testError = new BufferList(); this.cleanexit = false; } async run() { this.emit('start', this.module.raw); let err = null; try { init(this); await findNode(this); const { npm, yarn } = await getPackageManagers(); this.npmPath = npm; this.yarnPath = yarn; await tempDirectory.create(this); await grabModuleData(this); await lookup(this); await grabProject(this); await unpack(this); await pkgInstall(this); await pkgTest(this); } catch (e) { err = e; } if (!this.cleanexit) { const payload = { name: this.module.name || this.module.raw, version: this.module.version, flaky: this.module.flaky, expectFail: this.module.expectFail }; if (err) { if (!payload.expectFail) { this.emit('fail', err); payload.error = err; } } else if (payload.expectFail) { this.emit('fail', 'this module should have failed'); payload.error = 'this module should have failed'; } if (this.testOutput !== '') { payload.testOutput += `${this.testOutput.toString()}\n`; } if (this.testError !== '') { payload.testOutput += `${this.testError.toString()}\n`; } try { await tempDirectory.remove(this); } catch (err) { this.emit('data', 'error', `${this.module.name} cleanup`, err); } this.emit('end', payload); this.cleanexit = true; } } async cleanup() { this.cleanexit = true; const payload = { name: this.module.name || this.module.raw, error: Error('Process Interrupted') }; this.emit('fail', payload.error); await tempDirectory.remove(this); this.emit('end', payload); } }
JavaScript
class Equation { constructor (text) { if (text !== undefined) { const formulae = text.split('==') this.formula1 = formulae[0].trim() this.formula2 = formulae[1].trim() this.formula1katex = katex.renderToString(this.formula1, { throwOnError: false }) this.formula2katex = katex.renderToString(this.formula2, { throwOnError: false }) } } /** Gets the text of the equation. @return {string} - The text of the equation. */ getText () { return this.formula1 + ' == ' + this.formula2 } /** Sets formula 1. @param {string} formulaText - The text of the formula. */ setFormula1 (formulaText) { this.formula1 = formulaText.trim() } /** Sets formula 2. @param {string} formulaText - The text of the formula. */ setFormula2 (formulaText) { this.formula2 = formulaText.trim() } getEquationIsSolved () { return this.formula1 === this.formula2 } }
JavaScript
class AlegoriaSource extends Source { /** * @constructor * @param { Object } source - Configuration object * @param { string } source.path - Url (path) to the json file. * @param { string } source.file - Json file containing related calibrations, orientations, textures and dates. */ constructor(source) { super({ url: source.path + source.file }); this.isAlegoriaSource = true; this.whenReady = AlegoriaUtils.loadJSON(source.path, source.file).then(data => ({ textures: data[0], cameras: data[1], })); } }
JavaScript
class InputValidator { static get PRODUCT_VARIANT_ID_REGEXP() { return /^([0-9a-z-]+?)-([\d]{1,3})$/; } static get CART_ENTRY_ID_REGEXP() { return /^([0-9a-z-])+$/; } constructor(args, errorType) { /** * The arguments received by OpenWhisk action. It is used to search all validated properties. * * @type {Object} */ this.args = args; /** * The first error found while validating. * * @type {BaseCcifError} */ this.error = null; /** * The error type for ErrorResponse. */ this.errorType = errorType; } /** * Ensures that the parameter is present. * * @param {String} parameterName Name of the parameter to validate. * @returns {InputValidator} Returns 'this' so methods can be chained. */ mandatoryParameter(parameterName) { if (this.error) { return this; } if (typeof this.args[parameterName] === 'undefined') { this.error = new MissingPropertyError(`Parameter '${parameterName}' is missing.`); } return this; } /** * If the parameter is set, checks if it is currency code as pe ISO 4217. * If the parameter is not set the check will pass. To enforce this parameter must have a value use 'mandatoryPrameter' or 'atLeastOneParameter'. * * @param {String} parameterName Name of the parameter to validate. * @returns {InputValidator} Returns 'this' so methods can be chained. */ isCurrencyCode(parameterName) { if (this.error) { return this; } const reg = /^([A-Za-z]){3}$/; const parameterValue = this.args[parameterName]; if (typeof parameterValue !== 'undefined' && !reg.exec(parameterValue)) { this.error = new InvalidArgumentError(`Invalid currency code '${parameterValue}'`); } return this; } /** * If the parameter is set, checks if its value represents an integer. The value can be a string as long as it * only contains an integer number. * If the parameter is not set the check will pass. To enforce this parameter must have a value use 'mandatoryPrameter' or 'atLeastOneParameter'. * * @param {String} parameterName Name of the parameter to validate. * @returns {InputValidator} Returns 'this' so methods can be chained. */ isInteger(parameterName) { if (this.error) { return this; } const parameterValue = this.args[parameterName]; if (typeof parameterValue !== 'undefined' && !Number.isInteger(parseFloat(parameterValue))) { this.error = new InvalidArgumentError(`Parameter '${parameterName}' must be an integer`); } return this; } /** * If the parameter is set, checks if its value is a number and is inside the interval determined by [left, right]. * Either one of the interval edges can be missing and it will have the default value of infinity * (i.e. in case left side is missing, the interval is considered to be (-infinity, right] ). * If the parameter is not set the check will pass. To enforce this parameter must have a value use 'mandatoryPrameter' or 'atLeastOneParameter'. * * @param {String} parameterName Name of the parameter to validate. * @param {Number} left Left edge of the closed interval. If it is missing, the interval is considered to be (-infinity, right]. * @param {Number} right Right edge of the closed interval. If it is missing, the interval is consodered to be [left, infinity). */ isInsideInterval(parameterName, left, right) { if (this.error) { return this; } const parameterValue = this.args[parameterName]; if (typeof parameterValue === 'undefined') { // Parameter is not mandatory. If it does not have a value do not throw an error. return this; } const numericalValue = parseFloat(parameterValue); if (!Number.isFinite(numericalValue)) { // If the parameter cannot be parsed to a finite number it can not be part of an interval. this.error = new InvalidArgumentError(`Parameter '${parameterName}' must have a numerical value`); return this; } if (typeof left === 'undefined' && typeof right === 'undefined') { // If both of the interval edges are missing, ignore the check. return this; } if ((typeof left !== 'undefined' && numericalValue < left) || (typeof right !== 'undefined' && numericalValue > right)) { let message; if (typeof left !== 'undefined' && typeof right !== 'undefined') { message = `in interval [${left}, ${right}]`; } else if (typeof left !== 'undefined') { message = `greater or equal to ${left}`; } else { message = `lower or equal to ${right}`; } this.error = new InvalidArgumentError(`Parameter '${parameterName}' must be ${message}`); } return this; } /** * If the parameter is set, checks if its value matches a regular expression. * If the parameter is not set the check will pass. To enforce this parameter must have a value use 'mandatoryPrameter' or 'atLeastOneParameter'. * * @param {String} parameterName Name of the parameter to validate. * @param {RegExp} regexp A regular exception which the value must match. * @returns {InputValidator} Returns 'this' so methods can be chained. */ matchRegexp(parameterName, regexp) { if (this.error) { return this; } const parameterValue = this.args[parameterName]; if (typeof parameterValue !== 'undefined' && !regexp.exec(parameterValue)) { this.error = new InvalidArgumentError( `Invalid value '${parameterValue}' for property '${parameterName}'. Must match ${regexp.toString()}`); } return this; } /** * Checks if the args received from OpenWhisk action are present. * * @returns {InputValidator} Returns 'this' so methods can be chained. */ checkArguments() { if (this.error) { return this; } if (typeof this.args === 'undefined' || !this.args) { this.error = new InvalidArgumentError('invalid arguments'); } return this; } /** * Checks if at least one of the parameters names specified is present in the input. * * @param {String[]} parameterNames A list of parameter names. * @returns {InputValidator} Returns 'this' so methods can be chained. */ atLeastOneParameter(parameterNames) { if (this.error) { return this; } let union = parameterNames.map(parameterName => this.args[parameterName]) .reduce((currentResult, parameterValue) => currentResult || parameterValue, false); if (!union) { this.error = new MissingPropertyError( `At least one parameter from [${parameterNames.join(', ')}] must be specified.`); } return this; } /** * Builds an error response which can be returned directly from the actions. * * @returns {Promise.<Object>} */ buildErrorResponse() { this.args = this.args || {}; this.args['response'] = {'error': this.error}; if (this.errorType) { this.args.response.errorType = this.errorType; } return Promise.resolve(this.args); } }
JavaScript
class GalleryController { /** * function to create Gallery * @param {object} req * @param {object} res * @returns {object} data for created Gallery */ static async createGallery(req, res) { try { const result = await cloudinary.v2.uploader.upload(req.body.images, { folder: 'avatars', }); const galleryData = { description: req.body.description, images: result.secure_url, }; const gallery = await GalleryService.createGallery(galleryData); return successResponse(res, 201, 'Gallery created successfully', gallery); } catch (error) { console.log(error); return errorResponse(res, 500, error); } } /** * function to get all Gallery * @param {object} req * @param {object} res * @returns {object} object for all user Gallery */ static async findAllGallery(req, res) { try { const allGallery = await GalleryService.findAllGallery({}); if (allGallery.length) { return successResponse( res, 200, 'Gallery are retrieved successfully', allGallery, ); } errorResponse(res, 404, 'Gallery are not found'); } catch (error) { return errorResponse(res, 500, error); } } /** * function to get one Galley * @param {object} req * @param {object} res * @returns {object} data for retrieved Document */ static async findSingleGallery(req, res) { const { galleryId } = req.params; try { const oneGallery = await GalleryService.findGallery({ id: galleryId, }); if (oneGallery) { return successResponse( res, 200, 'Gallery is retrieved successfully', oneGallery, ); } errorResponse(res, 404, 'Gallery is not found'); } catch (error) { return errorResponse(res, 500, error); } } /** * function to update Gallery * @param {object} req * @param {object} res * @returns {object} data for updated Gallery */ static async updateGallery(req, res) { const { galleryId } = req.params; try { const result = await cloudinary.v2.uploader.upload(req.body.images, { folder: 'gallery', }); const galleryData = { description: req.body.description, images: result.secure_url, }; const updatedGallery = await GalleryService.updateGallery( { id: galleryId }, galleryData, ); if (updatedGallery[0]) { return successResponse( res, 200, 'Gallery updated successfully', updatedGallery[1], ); } errorResponse(res, 404, 'Gallery is not found'); } catch (error) { return errorResponse(res, 500, error); } } /** * function to delete Gallery * @param {object} req * @param {object} res * @returns {object} data for deleted Gallery */ static async deleteSingleGallery(req, res) { const { galleryId } = req.params; try { const deletedGallery = await GalleryService.DeleteGallery({ id: galleryId, }); if (deletedGallery) { return successResponse( res, 200, 'Gallery is deleted successfully', deletedGallery, ); } errorResponse(res, 404, 'Gallery is not available'); } catch (error) { return errorResponse(res, 500, error); } } }
JavaScript
class LinkDialog extends Dialog { constructor(id) { super(id, 'Link Dialog'); this.form = new Element('form', { id: `${id}-link-form`, title: 'Link Form', }) .appendToElement(this); this.urlInput = new Element('input', { type: 'text', name: `${id}-link-url-input`, placeholder: 'http://url.com', title: 'Link Url', }) .addClass('link-url-input'); this.nameInput = new Element('input', { type: 'text', name: `${id}-link-display-input`, placeholder: 'Display text', title: 'Link Display', }) .addClass('link-display-input'); this.insertButton = new Element('button', { type: 'submit', textContent: 'Insert', title: 'Insert Link', }) .addClass('insert-link'); this.form.appendElements([ this.urlInput, this.nameInput, this.insertButton, ]); } }
JavaScript
class RootComponent extends React.Component { render() { return ( <div> Hi, Im the root Component! <button onClick={() => this.props.changeTheme('theme2')}>Change Theme</button> </div> ) } }
JavaScript
class CosmozMoment extends PolymerElement { static get is() { return 'cosmoz-moment'; } static get observers() { return [ 'localeChanged(locale)' ]; } static get properties() { return { /** * Locale abbreviation for Moment.js locale */ locale: { type: String, value: 'en' } }; } localeChanged(newLocale) { const locale = newLocale; moment.locale(locale); MOMENT_ELEMENTS.forEach(element => element._setLocale(locale)); } }
JavaScript
class ApplicationPage extends RenderableMixin(ReactiveMixin(EventTarget)) { /** * Creates a modal dialog with the error details. * @param {string} message The message to render */ reportCriticalError(message) { const dialog = document.createElement('arc-alert-dialog'); dialog.message = message; dialog.modal = true; dialog.open(); document.body.appendChild(dialog); } }
JavaScript
class WatchExpressionComponent extends _react.default.Component { constructor(props) { super(props); this._onConfirmNewExpression = () => { const text = this.refs.newExpressionEditor.getText(); this.addExpression(text); this.refs.newExpressionEditor.setText(''); }; this._onEditorCancel = () => { this._resetExpressionEditState(); }; this._onEditorBlur = () => { this._resetExpressionEditState(); }; this._resetExpressionEditState = () => { if (this.coreCancelDisposable) { this.coreCancelDisposable.dispose(); this.coreCancelDisposable = null; } this.setState({ rowBeingEdited: null }); }; this._renderExpression = (fetchChildren, watchExpression, index) => { const { expression, value } = watchExpression; if (index === this.state.rowBeingEdited) { return _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, { className: 'nuclide-debugger-watch-expression-input', key: index, onConfirm: this._onConfirmExpressionEdit.bind(this, index), onCancel: this._onEditorCancel, onBlur: this._onEditorBlur, ref: 'editExpressionEditor', size: 'sm', initialValue: expression }); } const ValueComponent = (0, (_bindObservableAsProps || _load_bindObservableAsProps()).bindObservableAsProps)(value.map(v => ({ evaluationResult: v })), (_LazyNestedValueComponent || _load_LazyNestedValueComponent()).LazyNestedValueComponent); return _react.default.createElement( 'div', { className: (0, (_classnames || _load_classnames()).default)('nuclide-debugger-expression-value-row', 'nuclide-debugger-watch-expression-row'), key: index }, _react.default.createElement( 'div', { className: (0, (_classnames || _load_classnames()).default)('nuclide-debugger-expression-value-content', 'nuclide-debugger-watch-expression-value-content'), onDoubleClick: this._setRowBeingEdited.bind(this, index) }, _react.default.createElement(ValueComponent, { expression: expression, fetchChildren: fetchChildren, simpleValueComponent: (_SimpleValueComponent || _load_SimpleValueComponent()).default, expansionStateId: this._getExpansionStateIdForExpression(expression) }) ), _react.default.createElement('i', { className: 'icon icon-x nuclide-debugger-watch-expression-xout', onClick: this.removeExpression.bind(this, index) }) ); }; this._expansionStates = new Map(); this.state = { rowBeingEdited: null }; } _getExpansionStateIdForExpression(expression) { let expansionStateId = this._expansionStates.get(expression); if (expansionStateId == null) { expansionStateId = {}; this._expansionStates.set(expression, expansionStateId); } return expansionStateId; } removeExpression(index, event) { event.stopPropagation(); this.props.onRemoveWatchExpression(index); } addExpression(expression) { this.props.onAddWatchExpression(expression); } _onConfirmExpressionEdit(index) { const text = this.refs.editExpressionEditor.getText(); this.props.onUpdateWatchExpression(index, text); this._resetExpressionEditState(); } _setRowBeingEdited(index) { this.setState({ rowBeingEdited: index }); if (this.coreCancelDisposable) { this.coreCancelDisposable.dispose(); } this.coreCancelDisposable = atom.commands.add('atom-workspace', { 'core:cancel': () => this._resetExpressionEditState() }); setTimeout(() => { if (this.refs.editExpressionEditor) { this.refs.editExpressionEditor.focus(); } }, 16); } render() { const { watchExpressions, watchExpressionStore } = this.props; const fetchChildren = watchExpressionStore.getProperties.bind(watchExpressionStore); const expressions = watchExpressions.map(this._renderExpression.bind(this, fetchChildren)); const addNewExpressionInput = _react.default.createElement((_AtomInput || _load_AtomInput()).AtomInput, { className: (0, (_classnames || _load_classnames()).default)('nuclide-debugger-watch-expression-input', 'nuclide-debugger-watch-expression-add-new-input'), onConfirm: this._onConfirmNewExpression, ref: 'newExpressionEditor', size: 'sm', placeholderText: 'add new watch expression' }); return _react.default.createElement( 'div', { className: 'nuclide-debugger-expression-value-list' }, expressions, addNewExpressionInput ); } }
JavaScript
class VmClusterNetwork extends OkitArtifact { /* ** Create */ constructor (data={}, okitjson={}) { super(okitjson); // Configure default values this.display_name = this.generateDefaultName(okitjson.vm_cluster_networks.length + 1); this.compartment_id = data.parent_id; this.read_only = true; /* ** TODO: Add Resource / Artefact specific parameters and default */ // Update with any passed data this.merge(data); this.convert(); // TODO: If the Resource is within a Subnet but the subnet_iss is not at the top level then raise it with the following functions if not required delete them. // Expose subnet_id at the top level Object.defineProperty(this, 'subnet_id', {get: function() {return this.primary_mount_target.subnet_id;}, set: function(id) {this.primary_mount_target.subnet_id = id;}, enumerable: false }); } /* ** Clone Functionality */ clone() { return new VmClusterNetwork(JSON.clone(this), this.getOkitJson()); } /* ** Name Generation */ getNamePrefix() { return super.getNamePrefix() + 'vcn'; } /* ** Static Functionality */ static getArtifactReference() { return 'Vm Cluster Network'; } }
JavaScript
class LoginSuccess extends Packet { constructor(uuid, username) { super(); this.uuid = uuid this.username = username } /** * Function called when encoding * @param {CustomBuffer} data */ encode(data) { data.writeString(this.uuid) data.writeString(this.username) } /** * Function called when decoding * @param {CustomBuffer} data */ decode(data) { this.uuid = data.readString() this.username = data.readString() } }
JavaScript
class Diamond extends GraphicalElement { constructor({id, x1, x, y1, y, x2, width, w, y2, height, h, style, preserveAspectRatio} = {}) { // The arguments validation is done inside the GraphicalElement constructor. super(...arguments); } boundaryX1For(givenY) { // Using the line equation for two points: // y - y1 = (y2 - y1)/(x2 - x1) * (x - x1) // assuming that a = (y2 - y1)/(x2 - x1) // x = x1 + (y - y1)/a; let middleY = this.y + this.height / 2; //let middleX = this.x + this.width / 2; let a = this.height / this.width; if (givenY === middleY) { // Middle. return this.x; } else if (givenY < middleY) { // Use the top "/" line. return this.x + (givenY - this.y) / a; } else { // Use the bottom "\" line. return this.x + (givenY - middleY) / a; } } boundaryX2For(givenY) { // Using the line equation for two points: // y - y1 = (y2 - y1)/(x2 - x1) * (x - x1) // assuming that a = (y2 - y1)/(x2 - x1) // x = x1 + (y - y1)/a; let middleY = this.y + this.height / 2; let middleX = this.x + this.width / 2; let a = this.height / this.width; if (givenY === middleY) { // Middle. return this.x + this.width; } else if (givenY < middleY) { // Use the top "\" line. return middleX + (givenY - this.y) / a; } else { // Use the bottom "/" line. return middleX + (givenY - middleY) / a; } } contentBox({width, w, height, h} = {}) { // For diamonds, it does not matter the current width/height of a group they may be a frame of. width = getNonNullValue(width, w, this.width); height = getNonNullValue(height, h, this.height); let deltaX = width / 4; let deltaY = height / 4; return new BoundingBox({ x1: this.x + deltaX, y1: this.y + deltaY, x2: this.x + width - deltaX, y2: this.y + height - deltaY }); } widthToFit(boundingBox) { return 2 * boundingBox.width; } heightToFit(boundingBox) { return 2 * boundingBox.height; } }
JavaScript
class Peer extends Scribe { /** * Create an instance of {@link Peer}. * @param {Object} [config] Initialization Vector for this peer. * @param {Boolean} [config.listen] Whether or not to listen for connections. * @param {Boolean} [config.upnp] Whether or not to use UPNP for automatic configuration. * @param {Number} [config.port=7777] Port to use for P2P connections. * @param {Array} [config.peers=[]] List of initial peers. */ constructor (config = {}) { super(config); this.name = 'Peer'; this.settings = merge({ address: '0.0.0.0', network: 'regtest', networking: true, listen: false, peers: [], port: 7777, upnp: true }, config); // Network Internals this.upnp = upnp.createClient(); this.server = net.createServer(this._handleConnection.bind(this)); this.stream = new stream.Transform({ transform (chunk, encoding, callback) { // TODO: parse as encrypted data callback(null, chunk); } }); this.key = new Key({ network: this.settings.network, seed: (this.settings.wallet && this.settings.wallet.seed) ? this.settings.wallet.seed : this.settings.seed }); // TODO: document wallet settings this.wallet = new Wallet({ key: { seed: (this.settings.wallet && this.settings.wallet.seed) ? this.settings.wallet.seed : this.settings.seed } }); // this.hex = this.key.public.encodeCompressed('hex'); // this.pkh = crypto.createHash('sha256').update(this.hex).digest('hex'); // TODO: add getters for these this.address = this.settings.address; this.port = this.settings.port; // Public Details this.public = { ip: null, port: this.settings.port }; // Internal properties this.chains = {}; this.connections = {}; this.peers = {}; this.memory = {}; this.handlers = {}; this.messages = new Set(); // Internal Stack Machine this.machine = new Machine(); this.meta = { messages: { inbound: 0, outbound: 0 } }; this._state = { peers: {}, chains: {}, connections: {}, status: 'sleeping' }; return this; } get id () { return this.key.pubkey; } get pubkeyhash () { return this.wallet.ring.getKeyHash('hex'); } get state () { // TODO: use Proxy return Object.assign({}, this._state); } set state (value) { this._state = value; } /** * Start the Peer. */ async start () { let address = null; if (this.settings.verbosity >= 4) console.log('[FABRIC:PEER]', 'Peer starting...'); try { await this.wallet.start(); } catch (E) { console.error('[FABRIC:PEER]', 'Could not start wallet:', E); } if (this.settings.listen) { address = await this.listen(); } if (this.settings.networking) { for (const candidate of this.settings.peers) { this._connect(candidate); } } this.emit('ready', { id: this.id, address: address, pubkey: this.key.pubkey }); return this; } /** * Stop the peer. */ async stop () { const peer = this; // Alert listeners peer.emit('log', 'Peer stopping...'); peer.upnp.close(); for (const id in peer.connections) { peer.emit('log', `Closing connection: ${id}`); const connection = peer.connections[id]; const closer = async function () { return new Promise((resolve, reject) => { // Give socket a timeout to close cleanly, destroy if failed let deadline = setTimeout(function () { console.warn('[FABRIC:PEER]', 'end() timed out for peer:', id, 'Calling destroy...'); connection.destroy(); resolve(); }, 5000); // TODO: notify remote peer of closure // Use end(SOME_CLOSE_MESSAGE, ...) return connection.end(function socketClosed (error) { if (error) return reject(error); clearTimeout(deadline); resolve(); }); }); } await closer(); } const terminator = async function () { return new Promise((resolve, reject) => { if (!peer.server.address()) return resolve(); return peer.server.close(function serverClosed (error) { if (error) return reject(error); resolve(); }); }); } await terminator(); return this; } async _setState (value) { if (!value) return new Error('You must provide a State to set the value to.'); this.state.state = value; return this.state.state; } // TODO: use in _connect async _sessionStart (socket, target) { const self = this; const address = `${target.address}:${target.port}`; self.emit('log', `Starting session with address: ${target.pubkey}@${address}`); self.connections[address].session = new Session({ recipient: target.pubkey }); await self.connections[address].session.start(); self.emit('log', `Session created: ${JSON.stringify(self.connections[address].session)}`); if (!self.public.ip) { self.public.ip = socket.localAddress; self.emit('log', `Local socket was null, changed to: ${self.public.ip}`); } // TODO: consolidate with similar _handleConnection segment // TODO: check peer ID, eject if self or known // TODO re-enable (disabled to reduce spammy messaging) // /* // TODO: re-evaluate use of IdentityRequest // const vector = ['IdentityRequest', self.id]; const vector = ['StartSession', JSON.stringify({ id: self.connections[address].session.id, identity: self.id, advertise: `${self.key.pubkey}@${self.public.ip}:${self.public.port}`, signature: self.connections[address].session.key._sign(self.id) })]; const message = Message.fromVector(vector); if (!socket.writable) { self.emit('error', `Socket is not writable.`); return false; } self.sendToSocket(address, message); // Emit notification of a newly opened connection self.emit('connections:open', { address: address, status: 'unauthenticated', initiator: true }); if (self.settings.verbosity >= 4) console.log('[FABRIC:PEER]', `Connection to ${address} established!`); } async _processCompleteDataPacket (socket, address, data) { let self = this; let message = null; // TODO: actually decrypt packet let decrypted = socket.session.decrypt(data); try { message = self._parseMessage(decrypted); } catch (exception) { console.error('[FABRIC:PEER]', 'Could not parse inbound messsage:', exception); } // disconnect from any peer sending invalid messages if (!message) return this.destroy(); let response = await self._handleMessage({ message: message, origin: address, peer: { address: address, id: 'FAKE PEER' } }); if (response) { self.meta.messages.outbound++; if (!socket.writable) { // console.trace('[FABRIC:PEER]', 'Socket is not writable.'); self.emit('error', `Socket is not writable, message was: ${JSON.stringify(response.toObject(), null, ' ')}`); return false; } self.sendToSocket(address, response); } } async _handleSocketData (socket, address, data) { let self = this; if (self.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Received data from peer:', data); if (!socket.session) { self.emit('error', `Received data on socket without a session!`); return false; } socket._reader._addData(data); } _connect (address) { let self = this; let parts = address.split(':'); let known = Object.keys(self.connections); let keyparts = parts[0].split('@'); let target = { pubkey: null, address: null, port: null }; if (keyparts.length === 2) { target.pubkey = keyparts[0]; target.address = keyparts[1]; target.port = parts[1]; } else { target.address = parts[0]; target.port = parts[1]; } if (target.pubkey === self.id) return this.emit('error', 'Cannot connect to self.'); const authority = `${target.address}:${target.port}`; if (this.settings.verbosity >= 4) console.log('[FABRIC:PEER]', 'Connecting to address:', authority); if (parts.length !== 2) return console.debug('Invalid address:', address); if (known.includes(authority)) return self.connections[authority]; // TODO: refactor to use local functions + specific unbindings try { self.connections[authority] = new net.Socket(); self.connections[authority]._reader = new Reader(); self.connections[authority]._reader.on('message', function (msg) { self._processCompleteDataPacket.apply(self, [ self.connections[authority], authority, msg ]); }); self.connections[authority].on('error', function (err) { const text = `could not connect to peer ${authority} — Reason: ${err}`; self.emit('connection:error', { message: text }); // console.debug('[PEER]', `could not connect to peer ${authority} — Reason:`, err); }); self.connections[authority].on('close', function _handleSocketClose (err) { if (err) self.debug('socket closed on error:', err); if (err) self.emit('log', `socket closed on error: ${err}`); self.emit('warning', `Connection closed: ${authority}`); self.connections[authority].removeAllListeners(); // TODO: consider using `process.nextTick` to only clean up after event? delete self.connections[authority]; self.emit('connections:close', { address: authority }); }); // TODO: unify as _dataHandler self.connections[authority].on('data', async function peerDataHandler (data) { self._handleSocketData.apply(self, [ this, authority, data ]); }); self.emit('log', `Starting connection to address: ${authority}`); // TODO: replace with handshake // NOTE: the handler is only called once per connection! self.connections[authority].connect(target.port, target.address, async function connectionAttemptComplete (error) { if (error) return new Error(`Could not establish connection: ${error}`); await self._sessionStart.apply(self, [ this, target ]); self._maintainConnection(authority); }); } catch (E) { self.log('[PEER]', 'failed to connect:', E); } return self.connections[authority]; } _disconnect (address) { if (!this.connections[address]) return false; // Halt any heartbeat if (this.connections[address].heartbeat) { clearInterval(this.connections[address].heartbeat); } // Destroy the connection this.connections[address].destroy(); // Remove connection from map delete this.connections[address]; } _parseMessage (data) { if (!data) return false; if (this.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Parsing message:', data); let self = this; let message = null; try { message = Message.fromRaw(data); } catch (E) { console.debug('[FABRIC:PEER]', 'error parsing message:', E); } if (this.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Parsed message into:', message.type, message.data); return message; } async _handleConnection (socket) { const self = this; const address = [socket.remoteAddress, socket.remotePort].join(':'); if (this.settings.verbosity >= 4) self.emit('log', `[FABRIC:PEER] [0x${self.id}] Incoming connection from address: ${address}`); self.emit('connections:open', { address: address, status: 'connected', initiator: false }); // TODO: use known key socket.session = new Session(); socket.on('close', function terminate () { self.log('connection closed:', address); self.emit('connections:close', { address: address }); self._disconnect(address); }); socket.on('data', function inboundPeerHandler (data) { try { self._handleSocketData.apply(self, [ socket, address, data ]); } catch (exception) { self.emit('error', `Could not handle socket data: ${exception}`); } }); // add this socket to the list of known connections this.connections[address] = socket; this.connections[address]._reader = new Reader(); this.connections[address]._reader.on('message', function (msg) { self._processCompleteDataPacket.apply(self, [ self.connections[address], address, msg ]); }); self._maintainConnection(address); } _maintainConnection (address) { const peer = this; if (!peer.connections[address]) return new Error(`Connection for address "${address}" does not exist.`); /* peer.connections[address]._player = setInterval(function () { peer._pingConnection.apply(peer, [ address ]); }, 60000); */ } _pingConnection (address) { const ping = Message.fromVector(['Ping', `${Date.now().toString()}`]); try { this.sendToSocket(address, ping); } catch (exception) { this.emit('error', `Couldn't deliver message to socket: ${exception}`); } } _updateLiveness (address) { // Return Error if no connection if (!this.connections[address]) { const error = `No connection for address: ${address}`; this.emit('error', error); return new Error(error); } // Set the _lastMessage property this.connections[address]._lastMessage = Date.now(); // Make chainable return this; } _registerHandler (type, method) { if (this.handlers[type]) return new Error(`Handler for method "${type}" is already registered.`); this.handlers[type] = method.bind(this); return this.handlers[type]; } _registerPeer (peer) { if (this.settings.verbosity >= 6) console.warn('[AUDIT]', 'Registering peer:', peer); let self = this; if (!peer) return false; if (!peer.id) { self.log(`Peer attribute 'id' is required.`); return false; } self.peers[peer.id] = peer; // console.log('[FABRIC:PEER]', `[@ID:$${self.id}]`, 'Peer registered:', peer); // console.log('[FABRIC:PEER]', `[@ID:$${self.id}]`, 'Peer list:', self.peers); self.emit('peer', peer); // TODO: document peer announcement // TODO: eliminate use of JSON in messaging let announcement = Message.fromVector(['PeerCandidate', JSON.stringify(peer)]); try { self.relayFrom(peer.id, announcement); } catch (exception) { self.emit('error', `Could not relay peer registration: ${exception}`); } return true; } async _requestStateFromAllPeers () { let message = Message.fromVector(['StateRequest']); this.broadcast(message); } async _handleMessage (packet) { if (!packet) return false; if (this.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Handling packet from peer:', packet.message.id); let self = this; let relay = false; let response = null; let message = packet.message; let origin = packet.origin; self._updateLiveness(packet.origin); if (!message) return console.error('Hard failure:', packet); if (self.messages.has(message.id)) { let text = `Received duplicate message [0x${message.id}] from [${origin}] in packet: ${JSON.stringify(packet)}`; if (self.settings.verbosity >= 4) console.warn('[FABRIC:PEER]', 'Received duplicate message:', message.id, message.type, message.data); /* self.emit('warning', { message: text }); */ return false; } else { self.memory[message.id] = message; self.messages.add(message.id); } // Build a response to various message types switch (message.type) { default: console.error('[PEER]', `unhandled message type "${message.type}"`); self.emit('error', `Unhandled message type "${message.type}"`); break; case 'ChatMessage': relay = true; self.emit('message', message); break; case 'Generic': relay = true; break; case 'Ping': response = Message.fromVector(['Pong', message.id]); break; case 'Pong': // self.emit('message', `Received Pong: ${message}`); break; case 'StartChain': break; case 'GenericMessage': console.warn('[FABRIC:PEER]', 'Received Generic Message:', message.data); relay = true; break; case 'IdentityRequest': console.log('[FABRIC:PEER]', 'Peer sent IdentityRequest. Responding with IdentityResponse (node id)...', self.id); response = Message.fromVector(['IdentityResponse', self.id]); break; case 'IdentityResponse': if (!self.peers[message.data]) { let peer = { id: message.data, address: packet.origin }; // TODO: remove in favor of StartSession // Why? Duplicate "peer" event is sent within _registerPeer // Try to register peer... /* try { self._registerPeer(peer); } catch (exception) { self.emit('error', `Could not register peer ${message.data} because: ${exception}`); } */ } response = Message.fromVector(['StateRoot', JSON.stringify(self.state)]); break; case 'DocumentPublish': this.emit('log', `Document published from peer: ${message.data}`); this.emit('DocumentPublish', message.data); break; case 'DocumentRequest': this.emit('DocumentRequest', message.data); break; case 'BlockCandidate': break; case 'PeerCandidate': let candidate = null; try { candidate = JSON.parse(message.data); } catch (exception) { console.error('[FABRIC:PEER]', `[@ID:$${self.id}]`, 'Could not parse PeerCandidate message:', message.data, exception); } self.emit('peer:candidate', candidate); break; case 'PeerMessage': // console.error('[FABRIC:PEER]', `[@ID:$${self.id}]`, `Received "PeerMessage" from ${packet.origin} on socket:`, message.raw); // console.error('[FABRIC:PEER]', `[@ID:$${self.id}]`, `Packet origin:`, packet.origin); // TODO: use packet's peer ID, not socket address // Likely need to track connection? self.relayFrom(packet.origin, message); break; case 'StartSession': if (self.settings.verbosity >= 6) console.warn('[AUDIT]', '[FABRIC:PEER]', `[0x${self.id}]`, 'Received "StartSession" message on socket:', message.raw); let session = null; try { session = JSON.parse(message.data.toString('utf8')); } catch (exception) { console.error('[FABRIC:PEER]', 'Session body could not be parsed:', exception); } if (self.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Proposed session:', session); // TODO: avoid using JSON in overall protocol // TODO: validate signature let valid = true; // TODO: restore session identity if (valid && session/* && session.identity */) { if (self.settings.verbosity >= 6) console.log('[AUDIT]', 'Session is valid...'); let peer = { id: session.identity, address: packet.origin, advertise: `${self.pubkeyhash}@${self.public.ip}:${self.public.port}`, status: 'unfunded' }; if (self.settings.verbosity >= 5) console.log('[FABRIC:PEER]', 'Peer to register:', peer); // TODO: document peer registration process self._registerPeer(peer); // TODO: use message type for next phase of session (i.e., NOISE) response = Message.fromVector(['StartSession', { identity: self.id }]); if (self.settings.verbosity >= 6) console.log('[AUDIT]', 'Will send response:', response); } break; case 'StateRoot': if (self.settings.verbosity >= 5) console.log('[AUDIT]', 'Message was a state root:', message.data); // TODO: test protocol flow (i.e., understand StateRoot) console.log('[AUDIT]', 'Message was a state root:', message.raw, message.data); try { const state = JSON.parse(message.data); self.emit('state', state); response = { 'type': 'Receipt', 'data': state }; } catch (E) { console.error('[FABRIC:PEER]', 'Could not parse StateRoot:', E); } break; case 'StateChange': console.log('message was a state change:', message.data); break; case P2P_BASE_MESSAGE: self._handleBasePacket(packet); break; case P2P_ROOT: response = Message.fromVector([P2P_STATE_COMMITTMENT, self.state]); self.log('type was ROOT, sending state root:', response); self.log('type was ROOT, state was:', self.state); break; case P2P_INSTRUCTION: // TODO: use Fabric.Script / Fabric.Machine let stack = message.data.split(' '); switch (stack[1]) { case 'SIGN': let signature = self.key._sign(stack[0]); let buffer = Buffer.from(signature); let script = [buffer.toString('hex'), 'CHECKSIG'].join(' '); response = Message.fromVector([P2P_INSTRUCTION, script]); break; default: console.log('[PEER]', `unhandled peer instruction "${stack[1]}"`); break; } break; } // Emit for listeners // self.emit('message', message); if (relay) { self.relayFrom(origin, message); } return response; } _handleBasePacket (packet) { let message = null; try { message = JSON.parse(packet.message.data); } catch (E) { return this.log('Error parsing message:', E); } switch (message.type) { case 'collections:post': this.emit('collections:post', message.data); break; default: console.log('unhandled base packet type:', message.type); break; } } async sendToSocket (address, message) { const self = this; if (!this.connections[address]) { this.emit('error', `Could not deliver message to unconnected address: ${address}`); return false; } if (!this.connections[address].session) { this.emit('error', `Connection does not have a Session: ${address}`); return false; } if (!this.connections[address].writable) { this.emit('error', `Connection is not writable: ${address}`); return false; } const raw = message.asRaw(); // self.emit('warning', `raw message: ${raw}`); const signature = await this.connections[address].session._appendMessage(raw); self.emit('debug', `Signature: ${signature}`); try { const result = this.connections[address].write(raw); if (!result) { self.emit('warning', 'Stream result false.'); } } catch (exception) { this.emit('error', `Exception writing to socket: ${exception}`); } } relayFrom (origin, message) { this.emit('log', `Relaying ${message.type} from ${origin}: <${typeof message.data}> ${message.data}}`); // For each known peer, send to the corresponding socket for (let id in this.peers) { this.emit('log', `Is ${id} === ${origin}?`); if (id === origin) continue; let peer = this.peers[id]; // TODO: select type byte for state updates // TODO: require `Message` type before broadcast (or, preferrably, cast as necessary) // let msg = Message.fromVector([P2P_BASE_MESSAGE, message]); let msg = Message.fromVector([message.type, message.data]); try { this.sendToSocket(peer.address, msg); } catch (exception) { this.emit('error', `Could not write message to connection "${peer.address}":`, exception); // console.error('[FABRIC:PEER]', `Could not write message to connection "${peer.address}":`, exception); } } } broadcast (message) { // Coerce to Object if (message instanceof Message) { message = message.toObject(); } if (typeof message !== 'string') message = JSON.stringify(message); let hash = crypto.createHash('sha256').update(message).digest('hex'); // Do not relay duplicate messages if (this.messages.has(hash)) { if (this.settings.verbosity >= 3) console.warn('[FABRIC:PEER]', `Attempted to broadcast duplicate message ${hash} with content:`, message); return false; } else { this.memory[hash] = message; this.messages.add(hash); } for (let id in this.peers) { let peer = this.peers[id]; // TODO: select type byte for state updates // TODO: require `Message` type before broadcast (or, preferrably, cast as necessary) // let msg = Message.fromVector([P2P_BASE_MESSAGE, message]); let msg = Message.fromVector(['PeerMessage', message]); try { this.sendToSocket(peer.address, msg); } catch (exception) { console.error('[FABRIC:PEER]', `Could not write message to connection "${peer.address}":`, exception); } } } _broadcastTypedMessage (type, message) { if (!message) message = ''; if (typeof message !== 'string') message = JSON.stringify(message); let id = crypto.createHash('sha256').update(message).digest('hex'); if (this.messages.has(id)) { this.log('attempted to broadcast duplicate message'); return false; } else { this.memory[id] = message; this.messages.add(id); } for (let id in this.peers) { let peer = this.peers[id]; // TODO: select type byte for state updates let msg = Message.fromVector([type, message]); this.sendToSocket(peer.address, msg); } } /** * Start listening for connections. * @fires Peer#ready * @return {Peer} Chainable method. */ async listen () { const self = this; const promise = new Promise((resolve, reject) => { self.server.listen(self.settings.port, self.settings.address, function listenComplete (error) { if (error) return reject(error); const details = self.server.address(); const address = `tcp://${details.address}:${details.port}`; const complete = function () { self.emit('log', `Now listening on ${address} [!!!]`); return resolve(address); } if (!self.settings.upnp) { return complete(); } // UPNP self.upnp.portMapping({ public: 7777, private: 7777, ttl: 10 }, function (err) { if (err) { self.emit('log', `error configuring upnp: ${err}`); return complete(); } self.upnp.externalIp(function (err, ip) { if (err) { self.emit('log', `Could not retrieve public IP: ${err}`); } else { self.public.ip = ip; self.emit('log', `UPNP configured! External IP: ${ip}`); } return complete(); }); }); }); }); return promise; } }
JavaScript
class Book { constructor (civilization, title, author, format) { this.civilization = civilization; this.title = title; this.author = author; this.format = format; } }
JavaScript
class Stats extends React.Component { constructor() { super(); this.state = { dreamGoal: 0, dreamDonations: 0, } } componentDidMount() { // functions goes and retreives the information pertaining to the user about dreams they have funded this.props.dreamPayFetch(this.props.userId); } render() { return( <div className="stats-main"> <div className="myDreams"> <h1>My Dreams</h1> <div className="bar"> <UserProgressCircle donationGoal={this.props.userGoal} donationsReceived={this.props.receivedDonations} /> </div> {/* idea was for button to have a pop up showing a list and total of dream donations */} {/* <button>more info</button> */} </div> <div className="support-dreams"> <h1>Total Donations</h1> <div className="bar total-donations"> {/* should also be a data viz that did not get implemented as the proper information was not saved in the DB */} ${this.props.receivedDonations} </div> {/* idea was for button to have a pop up showing a list and total of dream donations */} {/* <button>more info</button> */} </div> </div> ) } }
JavaScript
class NativeSpyService extends UIServiceCore { /** * My spy service... */ constructor(...args) { super(...args); this.setTitle("Native JavaScript Spy Service"); this.setState({ spyAgents: [] }); this._persistentSpyAgentCollection = persistentSpyAgentCollection; this.proxyOn(this._persistentSpyAgentCollection, EVT_UPDATED, () => { // TODO: Debounce (this could render a lot depending on how the spy is // set up, esp. w/ WebSocket connections) const spyAgents = this._persistentSpyAgentCollection.getChildren(); this.setState({ spyAgents }); }); } // TODO: Document getRegisteredSpies() { return nativeSpies; } // TODO: Document getSpyAgents() { return this.getState().spyAgents; } }
JavaScript
class HeatMapLayer extends VectorLayer { constructor(name, options) { super(); var _options = options ? options : {}; this.layer = new ol.layer.Heatmap({ source: _options.source, blur: _options.blur, radius: _options.radius }); this.layer.setProperties({ 'id': name }); return this.layer; } /** * @function ol.ekmap.HeatMapLayer.prototype.addTo * @description Adds the layer to the given map or layer group. * @param {ol.Map} map Adds the layer to the given map or layer group. * @returns {this} */ addTo(map) { map.addLayer(this.layer) return this.layer } }
JavaScript
class CodeMaker { constructor() { /** * The indentation level of the file. */ this.indentation = 4; this.currIndent = 0; this.files = new Array(); this.excludes = new Array(); /** * Formats an block open statement. */ this.openBlockFormatter = s => `${s} {`; /** * Formats a block close statement. */ this.closeBlockFormatter = () => '}'; } /** * Saves all the files created in this code maker. * @param rootDir The root directory for all saved files. * @returns A sorted list of all the files saved (absolute paths). */ async save(rootDir) { const paths = this.files .filter(file => !this.excludes.includes(file.filePath)) .map(file => file.save(rootDir)); return (await Promise.all(paths)).sort(); } /** * Sets the name of the current file we are working with. * Note that this doesn't really create a new file (files are only created when save() is called. * Use `closeFile` to close this file. * @param filePath The relative path of the new file. */ openFile(filePath) { if (this.currentFile) { throw new Error(`Cannot open file ${filePath} without closing the previous file ${this.currentFile.filePath}`); } this.currentFile = new filebuff_1.default(filePath); } /** * Indicates that we finished generating the current file. * @param filePath The relative file path (must be the same as one passed to openFile) */ closeFile(filePath) { if (!this.currentFile) { throw new Error(`Cannot close file ${filePath}. It was never opened`); } if (this.currentFile.filePath !== filePath) { throw new Error(`Cannot close file ${filePath}. The currently opened file is ${this.currentFile.filePath}`); } this.files.push(this.currentFile); this.currentFile = undefined; } /** * Emits a line into the currently opened file. * Line is emitted with the current level of indentation. * If no arguments are provided, an empty new line is emitted. * @param fmt String format arguments (passed to `util.format`) * @param args String arguments */ line(fmt, ...args) { if (!this.currentFile) { throw new Error('Cannot emit source lines without openning a file'); } if (fmt) { fmt = this.makeIndent() + fmt; this.currentFile.write(util.format(fmt, ...args)); } this.currentFile.write('\n'); } /** * Same as `open`. */ indent(textBefore) { this.open(textBefore); } /** * Same as `close`. */ unindent(textAfter) { this.close(textAfter); } /** * Increases the indentation level by `indentation` spaces for the next line. * @param textBefore Text to emit before the newline (i.e. block open). */ open(textBefore) { this.line(textBefore); this.currIndent++; } /** * Decreases the indentation level by `indentation` for the next line. * @param textAfter Text to emit in the line after indentation was decreased. */ close(textAfter) { this.currIndent--; this.line(textAfter); } /** * Opens a code block. The formatting of the block is determined by `openBlockFormatter`. * @param text The text to pass to the formatter. */ openBlock(text) { this.open(this.openBlockFormatter(text)); } /** * Closes a code block. The formatting of the block is determined by `closeBlockFormatter`. * @param text The text to pass to the formatter. */ closeBlock(text) { this.close(this.closeBlockFormatter(text)); } /** * Adds a file to the exclude list. This means this file will not be saved during save(). * @param filePath The relative path of the file. */ exclude(filePath) { this.excludes.push(filePath); } /** * convertsStringToCamelCase */ toCamelCase(...args) { return caseutils.toCamelCase(...args); } /** * ConvertsStringToPascalCase */ toPascalCase(...args) { return caseutils.toPascalCase(...args); } /** * convert_string_to_snake_case * @param sep Separator (defaults to '_') */ toSnakeCase(s, sep = '_') { return caseutils.toSnakeCase(s, sep); } makeIndent() { let spaces = ''; for (let i = 0; i < this.currIndent; ++i) { for (let j = 0; j < this.indentation; ++j) { spaces += ' '; } } return spaces; } }
JavaScript
class CaptionSrtGeneratorAppliance extends AbstractAppliance { /** * Create a CaptionSrtGeneratorAppliance. */ constructor(settings = { includeCounter: true, }) { super({ includeCounter: true, ...settings, }) this.setOriginPosition(0) } static getInputTypes = () => [ dataTypes.TEXT.ATOM, 'SEGMENT.START', ] static getOutputTypes = () => ['TEXT.SRT'] /** * Takes an array of TEXT.ATOM payloads to be converted into a TEXT.SRT payload. * * @param {PayloadArray} payloadArray The TEXT.ATOM payloads to be converted * @return {Payload} The resulting TEXT.SRT payload. */ generateSrtPayload = (payloadArray) => { this.counter += 1 const position = payloadArray.getPosition() const duration = payloadArray.getDuration() const counterLine = (this.settings.includeCounter ? `${this.counter}\n` : '') const srtStartTimestamp = msToSrtTimestamp(position - this.getOriginPosition()) const srtEndTimestamp = msToSrtTimestamp(position - this.getOriginPosition() + duration) const timestampLine = `${srtStartTimestamp} --> ${srtEndTimestamp}\n` const captionLine = payloadArray.toArray().map((payload) => payload.data).join('') return new Payload({ data: `${counterLine}${timestampLine}${captionLine}`, type: 'TEXT.SRT', position, duration, }) } setOriginPosition(newOriginPosition) { this.originPosition = newOriginPosition } getOriginPosition() { return this.originPosition } resetCounter = () => { this.counter = 0 } getCounter = () => this.counter /** @inheritdoc */ audit = async () => true /** @inheritdoc */ start = async () => { this.resetCounter() } /** @inheritdoc */ stop = async () => {} /** @inheritdoc */ invoke = async (payloadArray) => { const unprocessedPayloadArray = new PayloadArray() payloadArray.toArray().forEach((payload) => { switch (payload.type) { case 'SEGMENT.START': this.resetCounter() this.setOriginPosition(payload.position) break case dataTypes.TEXT.ATOM: unprocessedPayloadArray.insert(payload) if (payload.data.includes('\n')) { this.push(this.generateSrtPayload(unprocessedPayloadArray)) unprocessedPayloadArray.empty() } break default: break } }) return unprocessedPayloadArray } }
JavaScript
class Parserror { /** * Create a new instance of {@link Parserror}. * * @param {ParserrorOptions} [options] The options to customize how the class behaves. * @returns {Parserror} * @static */ static new(options) { return new Parserror(options); } /** * @param {Partial<ParserrorOptions>} [options={}] The options to customize how the * class behaves. */ constructor(options = {}) { /** * The options to customize how the class behaves. * * @type {ParserrorOptions} * @access protected * @ignore */ this._options = { CaseParserClass: CaseParser, ErrorCaseClass: ErrorCase, FormattedErrorClass: FormattedError, ScopeClass: Scope, errorContextProperties: ['context', 'response', 'data'], ...options, }; /** * The name of the global scope where the cases and parsers are added by default. * * @type {string} * @access protected * @ignore */ this._globalScopeName = 'global'; /** * A dictionary with the available scopes. * * @type {Object.<string, Scope>} * @access protected * @ignore */ this._scopes = {}; this.addScope(this._globalScopeName); } /** * Add a new error case. * * @param {ErrorCaseDefinition} definition The case definition settings. * @param {?string} [scope=null] The name of the scope where the case * should be added. * If not defined, it will be added to the * global scope. * @returns {Parserror} For chaining purposes. */ addCase(definition, scope = null) { const scopeName = definition.scope || scope || this._globalScopeName; const useScope = this.getScope(scopeName); const { ErrorCaseClass, CaseParserClass, FormattedErrorClass } = this._options; useScope.addCase( new ErrorCaseClass(definition, { CaseParserClass, FormattedErrorClass, }), ); return this; } /** * Adds a list of error cases. * * @param {ErrorCaseDefinition[]} definitions The cases' definitions. * @param {?string} [scope=null] The name of the scope where the cases * should be added. If not defined, they * will be added to the global scope. * @returns {Parserror} For chaining purposes. */ addCases(definitions, scope = null) { Utils.ensureArray(definitions).forEach((definition) => { this.addCase(definition, scope); }); return this; } /** * Adds a reusable parser. * * @param {string} name The name of the parser. * @param {Object.<string, any> | Function} parser The parser function or map. This is * the second parameter for * {@link CaseParser#constructor}. * @param {?string} scope The name of the scope where the * parser should be added. If not * defined, it will be added to the * global scope. * @returns {Parserror} For chaining purposes. */ addParser(name, parser, scope = null) { const scopeName = scope || this._globalScopeName; const useScope = this.getScope(scopeName); const { CaseParserClass } = this._options; useScope.addParser(new CaseParserClass(name, parser)); return this; } /** * Creates a new scope. * * @param {string} name * The name of the scope. * @param {ErrorCaseDefinition[]} [cases=[]] * A list of cases' defintions to add. * @param {Condition[]} [allowedOriginals=[]] * A list of conditions/definitions for cases that allow original messages to be * matched. To better understand how this work, please read the description of * {@link Parserror#allowOriginal}. * @param {boolean} [overwrite=false] * If there's a scope with the same name already, using this flag allows you to * overwrite it. * @returns {Parserror} For chaining purposes. * @throws {Error} * If `overwrite` is `false` and there's already a scope with the same name. */ addScope(name, cases = [], allowedOriginals = [], overwrite = false) { if (this._scopes[name]) { if (overwrite) { this.removeScope(name); } else { throw new Error( `The scope '${name}' already exists. You can use 'removeScope' ` + "to remove it first, or set the 'overwrite' parameter to 'true'", ); } } const { ScopeClass } = this._options; this._scopes[name] = new ScopeClass(name); if (cases.length) { this.addCases(cases, name); } if (allowedOriginals.length) { this.allowOriginals(allowedOriginals, name); } return this; } /** * Allows a specific error message to be matched. The idea is for this feature to be * used with fallback messages: If you want a message to be used as it is but at the * same time you want to use a fallback message, you would use this method; the original * message won't be discarded and you still have the fallback for messages that don't * have a match. * * @param {Condition} condition Internally, this method will generate a new * {@link ErrorCase}, so this parameter can be a string * or a regular expression to match the error message, * or an actual case definition. * By default, the created case will have a random * string as a name, but you can use a case definition * to specify the name you want. * @param {?string} [scope=null] The name of the scope where the case should be * added. If not defined, it will be added to the * global scope. * @returns {Parserror} For chaining purposes. */ allowOriginal(condition, scope = null) { let definition; if (typeof condition === 'string' || condition instanceof RegExp) { definition = {}; definition.condition = condition; } else { definition = condition; } if (!definition.name) { const nameLength = 20; definition.name = Utils.getRandomString(nameLength); } definition.useOriginal = true; return this.addCase(definition, scope); } /** * Allows for multiple error messages to be matched. This is the "bulk alias" of * {@link Parserror#allowOriginal}, so please read the documentation of that method to * better understand in which case you would want to allow original messages. * * @param {Condition[]} conditions The list of conditions/definitions for the cases * that will match the messages. * @param {?string} [scope=null] The name of the scope where the cases should be * added. If not defined, they will be added to the * global scope. * @returns {Parserror} For chaining purposes. */ allowOriginals(conditions, scope = null) { Utils.ensureArray(conditions).forEach((condition) => { this.allowOriginal(condition, scope); }); return this; } /** * Gets a scope by its name. * * @param {string} name The name of the scope. * @param {boolean} [create=true] If `true` and the scope doesn't exist, it will try to * create it. * @returns {Scope} * @throws {Error} If `create` is `false` and the scope doesn't exist. */ getScope(name, create = true) { let scope = this._scopes[name]; if (!scope) { if (create) { this.addScope(name); scope = this._scopes[name]; } else { throw new Error(`The scope '${name}' doesn't exist`); } } return scope; } /** * Parses and formats an error. * * @param {Error | string | ParserrorErrorObject} error * The error to parse. * @param {Partial<ParserrorParseOptions>} [options={}] * Options to customize how the parsing is done. * @returns {FormattedError} * @throws {TypeError} * If `error` is not an {@link Error}, a string or a {@link ParserrorErrorObject}. */ parse(error, options = {}) { const useOptions = { cases: [], scopes: [], fallback: null, ...options, }; this._validateParseOptions(useOptions); let context; let message; if (typeof error === 'string') { message = error; context = null; } else if ( error instanceof Error || (Utils.isObject(error) && typeof error.message === 'string') ) { ({ message } = error); context = this._searchForContext(error); } else { throw new TypeError( "'parse' can only handle error messages ('string'), " + "native errors ('Error') or literal objects ('object') with a " + "'message' property'", ); } const globalScope = this.getScope(this._globalScopeName); let includesGlobalScope = useOptions.scopes.includes(this._globalScopeName); let useCases; if (useOptions.cases.length) { if (includesGlobalScope) { useCases = []; } else { useCases = useOptions.cases.map((name) => globalScope.getCase(name)); } } else { if (!includesGlobalScope) { includesGlobalScope = true; useOptions.scopes.push(this._globalScopeName); } useCases = []; } const scopes = useOptions.scopes.map((scope) => this.getScope(scope)); const scopesCases = scopes .map((scope) => scope.getCases()) .reduce((newList, cases) => [...newList, ...cases], []); const cases = [...useCases, ...scopesCases]; const scopesForCases = includesGlobalScope ? scopes : [...scopes, globalScope]; let newError; cases.some((theCase) => { newError = theCase.parse(message, scopesForCases, context); return newError; }); let result; if (newError) { result = newError; } else { const { FormattedErrorClass } = this._options; result = useOptions.fallback ? new FormattedErrorClass(useOptions.fallback, {}, { fallback: true }) : new FormattedErrorClass(message, {}, { original: true }); } return result; } /** * Removes a scope. * * @param {string} name The name of the scope to remove. * @throws {Error} If you try to remove the global scope. */ removeScope(name) { if (name === this._globalScopeName) { throw new Error("You can't delete the global scope"); } delete this._scopes[name]; } /** * Creates a wrapper: a pre configured parser to format errors with specific cases * and/or scopes. * * @param {string[]} cases A list of cases' names. * @param {string[]} scopes A list of scopes' names. * @param {?string} [fallback=null] A fallback message in case the error can't be * parsed. * If not specified, the returned error will maintain * the original message. * @returns {ParserrorWrapper} */ wrap(cases = [], scopes = [], fallback = null) { return (error, fallbackMessage = null) => this.parse(error, { cases, scopes, fallback: fallbackMessage || fallback, }); } /** * Creates a wrapper for specific scopes. A wrapper is a pre configured parser to format * errors with specific cases and/or scopes. * * @param {string[]} scopes A list of scopes' names. * @param {?string} [fallback=null] A fallback message in case the error can't be * parsed. * If not specified, the returned error will maintain * the original message. * @returns {ParserrorWrapper} */ wrapForScopes(scopes, fallback = null) { return (error, fallbackMessage = null) => this.parse(error, { scopes, fallback: fallbackMessage || fallback, }); } /** * The name of the global scope. * * @type {string} */ get globalScopeName() { return this._globalScopeName; } /** * Tries to find a property inside an error to be used as context information for the * parsers. * * @param {Error | ParserrorErrorObject} error The error where the method will look for * the property. * @returns {?Object} * @access protected * @ignore */ _searchForContext(error) { const useProperty = this._options.errorContextProperties.find( (property) => typeof error[property] !== 'undefined', ); return useProperty ? error[useProperty] : null; } /** * Validates an object to ensure it can be used as {@link ParserrorParseOptions}. * * @param {ParserrorParseOptions} options The object to validate. * @throws {TypeError} If the `cases` property is not an `array`. * @throws {TypeError} If the `scopes` property is not an `array`. * @access protected * @ignore */ _validateParseOptions(options) { if (!Array.isArray(options.cases)) { throw new TypeError("The 'cases' option can only be an 'array'"); } else if (!Array.isArray(options.scopes)) { throw new TypeError("The 'scopes' option can only be an 'array'"); } } }
JavaScript
class Storage { /** * * @param connection {any} - Layer specifi connection descriptor * @param namespace {string} - Layer specific namespace(read table, bucket, index, etc) * @param options {object} - Layer specific extra magic */ constructor({connection, namespace, options}) { } /** * Fetch data by the key * * @param key {string} - The item key * @returns {Promise<object>} - Data! */ async getByKey(key) { throw new Error('Not Implemented') } /** * Fetch data by query parameters. This is not a search and is intended to return only the first matched item. * @param name {string} - The name of the property to match * @param value {string} - The value we are looking to match * @param sortBy {string} - The name of the property we are going to order by in order to determine the first item * @param order {string} - If the sortBy is going to be ascending or descending ('asc'|'desc') * @returns {Promise<object>} - Data! */ async getByProperty(name, value, sortBy, order = 'asc') { throw new Error('Not Implemented') } /** * Persist this set of data. * * @param key - The key under which we are going to persist * @param data - The data to persist * @returns {Promise<object>} - The data representation that has been persisted */ async save(key, data) { throw new Error('Not Implemented') } }
JavaScript
class PokemonForm extends React.Component { constructor(props) { super(props); this.state = { pokeName: '', }; this.handlePokeNameChange = this.handlePokeNameChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this) } handlePokeNameChange(e) { this.setState({ pokeName: e.target.value }); } handleSubmit(e){ e.preventDefault() this.props.pokemonSelect(this.state.pokeName) } render() { return ( <form onSubmit={this.handleSubmits}> <input type="text" name="Pokemon Name" placeholder="Pokemon Name" value={this.state.pokeName} onChange={this.handlePokeNameChange} /> <p> {this.state.pokeName} </p> </form> ); } }
JavaScript
class DeleteFavoriteOpt { constructor() { this.favorites = this.getAllFavorites(); this.optToDelete = d3.select('#conflateType').property('value'); } getAllFavorites() { Hoot.api.getAllUsers(); let currentFavorites = []; let allFavorites = Hoot.config.users[Hoot.user().id].members; Object.keys(allFavorites) .forEach( function(key) { currentFavorites.push( JSON.parse( allFavorites[key] ) ); } ); currentFavorites.sort(function(a, b){ const x = a.name, y = b.name; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); return currentFavorites; } sortCombobox( defaultTypes, userFavorites ) { let favorites = []; Object.keys( userFavorites ).map( fav => favorites.push( fav ) ); favorites.sort(); favorites.forEach( opt => defaultTypes.push( opt ) ); return defaultTypes; } populateCombobox( input ) { let newCombo = new FormFactory(); let element = d3.select( '#conflateType' ); element.datum().data = input; newCombo.populateCombobox( element ); } handleSubmit() { let optName = this.optToDelete; let toDelete = _find( this.favorites, o => o.name === optName ); this.processRequest = Hoot.api.deleteFavoriteOpts( toDelete ) .then( () => Hoot.getAllUsers() ) .then( async () => { d3.select('#conflateType').property('value', 'Reference'); let getOpts = AdvancedOpts.getInstance(); let advOpts = getOpts.advancedOptions; getOpts.createGroups(advOpts); let getTypes = await Hoot.api.getConflateTypes(true); let getFavorites = Hoot.config.users[Hoot.user().id].members; let allConfTypes = this.sortCombobox( getTypes, getFavorites ); this.populateCombobox( allConfTypes ); } ) .catch( err => { Hoot.message.alert( { message: err, type: 'warn' } ); } ) .finally( () => { Hoot.message.alert( { message: 'Fav. Opts Deleted Successfully', type: 'success' } ); d3.select('#updateFav').classed('hidden', true ); d3.select('#deleteFav').classed( 'hidden', true ); } ); } }
JavaScript
class Message extends React.Component { render() { return ( <div> <span className="name">Name: {this.props.user}</span> <span className="messages">Message: {this.props.message}</span> <span className="time">Time: {this.props.time}</span> </div> ); } }
JavaScript
class User { /** * @static * @description this function creates a new user * @param {object} request the request body * @param {object} response the response body * @returns response * @memberof User */ static async signUp(request, response) { const { first_name, last_name, password, } = request.body; let { email, } = request.body; email = email.toLowerCase(); const hashedPassword = userAuth.hashPassword(password); const text = `INSERT INTO users(first_name, last_name, email, password, is_admin) VALUES($1, $2, $3, $4, $5) returning *;`; const values = [first_name, last_name, email, hashedPassword, false]; try { const { rows, } = await db.query(text, values); const token = userAuth.generateToken(rows[0].id); return response.status(201).json({ status: 'success', data: { token, id: rows[0].id, first_name: rows[0].firstname, last_name: rows[0].lastname, email: rows[0].email, is_admin: rows[0].is_admin, }, }); } catch (error) { if (error.routine === '_bt_check_unique') { return response.status(400).json({ status: 'error', error: 'User with that email already exists', }); } return response.status(400).json({ status: 'error', error: error.message, }); } } /** * @static * @description this function signs in a user * @param {object} request the request body * @param {object} response the response body * @returns response * @memberof User */ static async signIn(request, response) { const { password, } = request.body; const text = 'SELECT id, first_name, last_name, email, is_admin FROM users WHERE email = $1;'; const passwordText = 'SELECT password FROM users WHERE email = $1;'; let { email, } = request.body; email = email.toLowerCase(); try { const { rows, } = await db.query(text, [email]); const hashedPasswordRow = await db.query(passwordText, [email]); const token = userAuth.generateToken(rows[0]); if (!rows[0]) { return response.status(404).json({ status: 'success', error: 'User with that email does not exist', }); } if (!userAuth.comparePassword(password, hashedPasswordRow.rows[0].password)) { return response.status(401).json({ status: 'error', error: 'Incorrect password', }); } return response.status(200).json({ status: 200, data: { token, id: rows[0].id, firstName: rows[0].first_name, lastName: rows[0].last_name, email: rows[0].email, avatar: rows[0].avatar, }, }); } catch (error) { return response.status(400).json({ status: 'error', error: error.message, }); } } }
JavaScript
class VigenereCipheringMachine { alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; sq = []; constructor(type = true) { this.type = type; } generateSquare() { for (let i = 0; i < this.alpha.length; i++) { let row = []; for (let r = i; r < this.alpha.length; r++) { row.push(this.alpha[r]); } let j = 0; while (row.length < this.alpha.length) { row.push(this.alpha[j]); j += 1; } this.sq.push(row); } return this.sq; } encrypt(msg, key) { if (msg == undefined || key == undefined) { throw new Error('Incorrect arguments!'); } this.generateSquare(); let res = []; msg = msg.toUpperCase(); key = key.toUpperCase(); let k = 0; for (let i = 0; i < msg.length; i++) { if (msg.charCodeAt(i) >= 65 && msg.charCodeAt(i) <= 90) { if (k >= key.length) { k = 0; } res.push( this.sq[this.alpha.indexOf(msg[i])][this.alpha.indexOf(key[k])] ); k += 1; } else { res.push(msg[i]); } } if (this.type) { return res.join(''); } else { return res.reverse().join(''); } } decrypt(msg, key) { if (msg == undefined || key == undefined) { throw new Error('Incorrect arguments!'); } this.generateSquare(); let res = []; msg = msg.toUpperCase(); key = key.toUpperCase(); let k = 0; for (let i = 0; i < msg.length; i++) { if (msg.charCodeAt(i) >= 65 && msg.charCodeAt(i) <= 90) { if (k >= key.length) { k = 0; } res.push( this.alpha[this.sq[this.alpha.indexOf(key[k])].indexOf(msg[i])] ); k += 1; } else { res.push(msg[i]); } } if (this.type) { return res.join(''); } else { return res.reverse().join(''); } } }
JavaScript
class FsUrlResolver extends url_resolver_1.UrlResolver { constructor(packageDir, // If provided, any URL which matches `host` will attempt to resolve // to a `file` protocol URL regardless of the protocol represented in the // URL to-be-resolved. host, // When attempting to resolve a protocol-relative URL (that is a URL which // begins `//`), the default protocol to resolve to if the resolver can // not produce a `file` URL. protocol = 'https') { super(); this.host = host; this.protocol = protocol; this.packageDir = normalizeFsPath(pathlib.resolve(packageDir || process.cwd())); this.packageUrl = this.brandAsResolved(vscode_uri_1.default.file(this.packageDir).toString()); if (!this.packageUrl.endsWith('/')) { this.packageUrl = this.brandAsResolved(this.packageUrl + '/'); } } resolve(firstHref, secondHref, _import) { const [baseUrl = this.packageUrl, unresolvedHref] = this.getBaseAndUnresolved(firstHref, secondHref); const resolvedHref = this.simpleUrlResolve(baseUrl, unresolvedHref, this.protocol); if (resolvedHref === undefined) { return undefined; } const url = utils_1.parseUrl(resolvedHref); if (this.shouldHandleAsFileUrl(url)) { return this.handleFileUrl(url, unresolvedHref); } return this.brandAsResolved(resolvedHref); } shouldHandleAsFileUrl(url) { const isLocalFileUrl = url.protocol === 'file:' && (!url.host || url.host === 'localhost'); const isOurHost = url.host === this.host; return isLocalFileUrl || isOurHost; } /** * Take the given URL which is either a file:// url or a url with the * configured hostname, and treat its pathname as though it points to a file * on the local filesystem, producing a file:/// url. * * Also corrects sibling URLs like `../foo` to point to * `./${component_dir}/foo` */ handleFileUrl(url, unresolvedHref) { let pathname; const unresolvedUrl = utils_1.parseUrl(unresolvedHref); if (unresolvedUrl.pathname && unresolvedUrl.pathname.startsWith('/') && unresolvedUrl.protocol !== 'file:') { // Absolute urls point to the package root. let unresolvedPathname; try { unresolvedPathname = path_1.posix.normalize(decodeURIComponent(unresolvedUrl.pathname)); } catch (e) { return undefined; // undecodable url } pathname = pathlib.join(this.packageDir, unresolvedPathname); } else { // Otherwise, consider the url that has already been resolved // against the baseUrl try { pathname = path_1.posix.normalize(decodeURIComponent(url.pathname || '')); } catch (e) { return undefined; // undecodable url } } const path = this.modifyFsPath(this.filesystemPathForPathname(pathname)); // TODO(rictic): investigate moving to whatwg URLs internally: // https://github.com/Polymer/polymer-analyzer/issues/804 // Re-encode URI, since it is expected we are emitting a relative URL. const resolvedUrl = utils_1.parseUrl(vscode_uri_1.default.file(path).toString()); resolvedUrl.search = url.search; resolvedUrl.hash = url.hash; return this.brandAsResolved(url_1.format(resolvedUrl)); } /** * Overridable method, for subclasses that want to redirect some filesystem * paths. * * @param fsPath An absolute path on the file system. Note that it will be * OS-specific. * @return An absolute path on the file system that we should resolve to. */ modifyFsPath(fsPath) { return fsPath; } relative(fromOrTo, maybeTo, _kind) { const [from, to] = (maybeTo !== undefined) ? [fromOrTo, maybeTo] : [this.packageUrl, fromOrTo]; return this.simpleUrlRelative(from, to); } filesystemPathForPathname(decodedPathname) { return normalizeFsPath(vscode_uri_1.default.file(decodedPathname).fsPath); } }
JavaScript
class Atlas { /** CONSTRUCTOR */ constructor(container, options) { // Debug Mode this.debug = options.map.debug; // Atlas Classes Options this.options = {}; this.options.map = options.map; this.options.leaflet = options.leaflet; this.options.tiles = options.tiles; this.options.overlayTiles = options.overlayTiles || []; this.options.point = options.point; this.options.line = options.line; this.options.legend = options.legend; this.options.topology = options.topology; this.options.tooltip = options.tooltip; this.options.controls = options.map.controls || {}; this.options.overlayTopology = options.overlayTopology || {}; this.options.minimap = options.map.minimap || false; this.options.minimapConfig = { map: options.map.minimapNetwork, data: options.map.minimapData, }; // Set default options for all classes from the passed in options this.createLineDefaults(); this.createPointDefaults(); this.createTooltipDefaults(); Legend.prototype.defaults = options.legend; // ID of Map Container this.container = container; // Collections of Class Instances this.topologies = {}; this.legends = {}; this.overlayTopologies = {}; // Map Statistics this.stats = { topologies: 0, lines: 0, points: 0, }; // Fix for Leaflet Popup bluriness due to fractional transform values in CSS window.L_DISABLE_3D = true; // Extra Leaflet Control Defaults this.options.controls.zoomMin = typeof this.options.controls.zoomMin == "undefined" ? true : this.options.controls.zoomMin; this.options.controls.allLayers = typeof this.options.controls.allLayers == "undefined" ? false : this.options.controls.allLayers; this.options.controls.editor = typeof this.options.controls.editor == "undefined" ? true : this.options.controls.editor; this.options.leaflet.atlas4 = this.options.controls; // Initialize Leaflet Map this.map = L.map(container, this.options.leaflet); // Initialize Leaflet Tileset this.tiles = {}; if (this.options.tiles) { this.createTiles(); } // Initialize Leaflet Overlay Tileset this.overlayTiles = {}; if (this.options.overlayTiles) { this.createOverlayTiles(); } // Set a Default View this.setView({ view: [0, 0], zoom: 1 }); // Add L.Control.ZoomMin Extension and flag for show/hide all layers // Remove the existing control before adding the new control // Add and extra control to the map this.layersOn = true; if (this.options.controls.zoomMin || this.options.controls.allLayers) { this.map.removeControl(this.map.zoomControl); this.map.addControl( new L.Control.Atlas({ minBounds: this.map.getBounds(), atlas: this, }) ); } // Initialize Legends Legend.createParent(this.container, this.options.legend); for (let id of Object.keys(this.options.legend.legends)) { this.legends[id] = new Legend( id, this.options.legend, this.container ); this.legends[id].hide(); } //!! DEVELOPMENT FUNCTIONALITIES !!// this.map.addEventListener("click", this.onMapClick, { passive: true }); // Returns coords of pointer when map is clicked this.map.addEventListener("zoomend", this.redraw.bind(this), { passive: true, }); // Creating Atlas Editor this.editor = new Editor(this); console.debug(`Initialized Atlas map in "#${container}"`); if (this.options.minimap) { this.showLoader(); this.drawMiniMap(); } this.map.on("zoomend", () => { this.checkForOverlaps(); }); this.events = {}; } /** GET, SET+UPDATE, & PROPERTIES */ // Get the value of the property get(property) { return this[property]; } // Set property to a new value set(property, value) { let props = property.split("."); // Single Key if (props.length === 1) { this[property] = value; this.update(property); } // Multi Key else { let ref = this; for (let i = 0; i < props.length; i++) { if (i === props.length - 1) { ref[props[i]] = value; this.update(props[i]); } else { ref = ref[props[i]]; } } } } // Recalculate any computed properties here update(property) { if (property === "tiles" || property === "options.tiles") { this.removeTiles(); this.addTiles(); } } // Get the class property names and their values properties() { return Object.entries(this); } /** CLASS METHODS */ //---- DATA /* Set the data model for Lines to a new object */ lineDataModel(model) { if (!model instanceof Object || model instanceof Array) { console.error( `The input Line data model is not an object. Type is ${typeof model}` ); } Line.prototype.dataModel = model; } /* Set the data model for Points to a new object */ pointDataModel(model) { if (!model instanceof Object || model instanceof Array) { console.error( `The input Point data model is not an object. Type is ${typeof model}` ); } Point.prototype.dataModel = model; } //---- VIEW /* Set view for the map with {view: coords, zoom: value} */ setView(options) { this.map.setView(options.view, options.zoom); } /* Focus the map view around a topology */ setFocus(topology, removeOthers = false) { if (typeof topology == "undefined") { console.error("Setting focus on an undefined topology"); } if (removeOthers) { this._showOnly(topology); } // Only the Topology's name was given if (typeof topology == "string" && this.topologies[topology]) { topology = this.topologies[topology]; } if (topology.active === false) { topology.show(); } if (topology.view) { this.map.fitBounds(topology.view); } } //---- TILES /** Create the tile URL from tile options */ createTileUrl(tileConfig) { let url = tileConfig.url; if (tileConfig.token) { url += `?access_token=${tileConfig.token}`; } return url; } /** Add the tile layer to the map using tile options*/ createTiles() { for (const tile of this.options.tiles) { this.tiles[tile.name] = L.tileLayer(this.createTileUrl(tile), tile); if (tile.default) this.tiles[tile.name].addTo(this.map); } } showTile(name) { for (const key in this.tiles) { if (key !== name) this.hideTile(key); else this.tiles[key].addTo(this.map); } this.redrawOverlayTiles(); } hideTile(name) { if (this.tiles[name]) this.tiles[name].removeFrom(this.map); } /** Remove the tiles from the map */ removeTiles() { for (const tile in this.tiles) { this.tiles[tile].removeFrom(this.map); } } // Overlay Tile Methods createOverlayTiles() { for (const tile of this.options.overlayTiles) { this.overlayTiles[tile.name] = L.tileLayer( this.createTileUrl(tile), tile ); } } showOverlayTile(name) { if (this.overlayTiles[name]) this.overlayTiles[name].addTo(this.map); } hideOverlayTile(name) { if (this.overlayTiles[name]) { this.overlayTiles[name].removeFrom(this.map); } } // Draws the overlay tiles again to bring them to the top of the map redrawOverlayTiles() { for (const tile in this.overlayTiles) { if (this.map.hasLayer(this.overlayTiles[tile])) { this.overlayTiles[tile].removeFrom(this.map); this.overlayTiles[tile].addTo(this.map); } } } // Overlay Topology Methods addOverlayTopology(data) { let ot = new OverlayTopology(data.config, this.options.overlayTopology); this.overlayTopologies[data.name] = ot; } drawOverlayTopology(name) { if (this.overlayTopologies[name]) { this.overlayTopologies[name].drawOverlayTopology(this.map); } } removeOverlayTopology(name) { if (this.overlayTopologies[name]) { this.overlayTopologies[name].hideOverlayTopology(this.map); } } //---- STATS updateStats() { this.stats = { topologies: 0, lines: 0, points: 0, }; for (let name of Object.keys(this.topologies)) { let topology = this.topologies[name]; this.stats.topologies += topology.active ? 1 : 0; this.stats.lines += topology.stats.lines; this.stats.points += topology.stats.points; } } //---- TOPOLOGY /** Set topology layer on the map */ addTopology(json, options) { if (typeof json === "string") { json = JSON.parse(json); } console.debug( `Setting the Topology for ${json.name} in "#${this.container}"` ); options = options || this.options.topology; // Pass the legends to Topologies options.legends = this.legends; //this.checkForOverlaps(json) // Create a new Topology and add it to the topologies object this.topologies[json.name] = new Topology(this, json, options); // Draw the map on creation by default this.drawTopology(this.topologies[json.name]); // Dispatch Topology Added Event this.dispatch("topology-added"); // Return the topology for application convenience return this.topologies[json.name]; } /** Render the given topology object as paths, endpoints */ drawTopology(topology) { console.debug( `Drawing topology for ${topology.name} in "#${this.container}"` ); // Add all the lines of a topology to the map for (let line of topology.lines) { // Add the first Line layer line.layer[0].addTo(this.map); // Add second Line layer if twins if (line.layer.length === 2) { line.layer[1].addTo(this.map); } } // Add all the points of the topology to the map for (let point of topology.points) { point.layer.addTo(this.map); } this.updateStats(); this.checkForOverlaps(); } hideTopology(topology) { this.topologies[topology].hide(); this.updateStats(); } showTopology(topology) { this.topologies[topology].show(); this.updateStats(); } _showOnly(topology) { let name; if (typeof topology != "string") { name = topology.name; } else { name = topology; } let bounds = []; for (let t of Object.keys(this.topologies)) { if (t == name) { if (!this.topologies[t].active) { this.topologies[t].show(); } } else { this.topologies[t].hide(); } } this.fitToView(); this.updateStats(); } showAll() { for (let t of Object.keys(this.topologies)) { if (!this.topologies[t].active) { this.topologies[t].show(); } } this.fitToView(); this.updateStats(); } fitToView() { let bounds = []; for (const topology in this.topologies) { let map = this.topologies[topology]; if (map.active) { for (const point of map.points) { bounds.push(point.layer.getLatLng()); } } } if (bounds && bounds.length > 0) this.map.fitBounds(bounds); } // Wipes the topology from existence removeTopology(name) { if (this.topologies[name]) { let topology = this.topologies[name]; for (const point of topology.points) { point.layer.removeFrom(this.map); } for (const line of topology.lines) { line.layer.forEach((element) => { element.removeFrom(this.map); }); } delete this.topologies[name]; return true; } return false; } removeAllTopologies() { let topologies = Object.keys(this.topologies); topologies.forEach((topology) => this.removeTopology(topology)); } /** Add Point or Line Object if not added to map, * If Point or Line already exists in map, then just redraw it. */ updateTopology(vectorObj) { // TODO: something.setStyle({color: 'red', weight: 10}) if (Topology.isPoint(vectorObj)) { let ep = vectorObj.get("layer"); if (!this.map.hasLayer(ep)) { ep.addTo(this.map); } } else if (Topology.isLine(vectorObj)) { if (!this.map.hasLayer(vectorObj.line)) { // Add Line To Map } } } checkForOverlaps() { if (!this.options.controls.editor) return; let zoom = this.map.getZoom(); if (Object.keys(this.topologies).length < 1) return; for (const t in this.topologies) { let topology = this.topologies[t]; for (const line of topology.lines) { if ( line.options.color == this.options.map.overlapCircuitColor ) { line.options.color = this.options.line.color; for (const layer of line.layer) { layer.setStyle({ color: this.options.line.color }); } } } let zoom_threshold = { 1: 3.5306537, 1.5: 2.0216982, 2: 1.7653677, 2.5: 1.2801464, 3: 0.8826941, 3.5: 0.6495934, 4: 0.4394531, 4.5: 0.2962163, 5: 0.2215501, 5.5: 0.172205, 6: 0.1178134, 6.5: 0.0629858, 7: 0.0553852, 7.5: 0.0408117, 8: 0.0276925, 8.5: 0.0175293, 9: 0.0137329, 9.5: 0.0116625, 10: 0.0068664, 10.5: 0.0049127, 11: 0.0034615, 11.5: 0.0025313, 12: 0.0017307, 12.5: 0.0012784, 13: 0.0008583, 13.5: 0.0006193, 14: 0.0004291, 14.5: 0.0003137, 15: 0.0001738, 15.5: 0.0001613, 16: 0.0001287, 16.5: 0.0000703, 17: 0.000054, 17.5: 0.0000403, 18: 0.000027, 18.5: 0.0000211, 19: 0.0000138, 19.5: 0.0000096, 20: 0.0000067, }; for (const i of topology.lines) { if (i.path.length > 4) continue; for (const j of topology.lines) { if (j.path.length > 4) continue; let displayingBothCircuits = true; for (const layer of i.layer) { if (!this.map.hasLayer(layer)) { displayingBothCircuits = false; } } for (const layer of j.layer) { if (!this.map.hasLayer(layer)) { displayingBothCircuits = false; } } if (j.layer.length == 0 || i.layer.length == 0) { displayingBothCircuits = false; } if (i == j || !displayingBothCircuits) continue; let AA = euclideanDistance(i.a, j.a); let BB = euclideanDistance(i.b, j.b); let AB = euclideanDistance(i.a, j.b); let BA = euclideanDistance(i.b, j.a); let thresholdDist = zoom_threshold[zoom]; if (!thresholdDist) return; if ( ((AA < thresholdDist && BB < thresholdDist) || (AB < thresholdDist && BA < thresholdDist)) && i.options.color == this.options.line.color ) { i.options.color = this.options.map.overlapCircuitColor; for (const layer of i.layer) { layer.setStyle({ color: this.options.map.overlapCircuitColor, }); } } } } } function euclideanDistance(a, b) { return Math.sqrt( Math.pow(a.lat - b.lat, 2) + Math.pow(a.lng - b.lng, 2) ); } } //---- MAP resize() { this.map.invalidateSize(); } onMapClick(e) { console.debug([e.latlng.lat, e.latlng.lng]); } redraw() { console.debug("Redraw of the map triggered"); } //---- TOOLTIPS customLineTooltip(html) { for (let topology of this.topologies) { for (let line of topology.lines) { line.set("html", html); } } } customPointTooltip(html) { for (let topology of this.topologies) { for (let point of topology.points) { point.set("html", html); } } } customTooltip(type, options) { let properties = ["html", "css", "vars"]; // Check for key errors in type and options arguments if (type != "point" && type != "line") { console.error( `Unrecognized tooltip type "${type}" given to customTooltip(). Valid types are "point" and "line"` ); } for (let key in options) { if (properties.indexOf(key) == -1) { console.error( `Unrecognized key "${key}" given in custom tooltip options. Valid keys are "css", "html", and "vars"` ); } } // Call update on all of the tooltips to refresh their contents for (let topology of Object.values(this.topologies)) { for (let property of properties) { if (!options[property]) { continue; } for (let line of topology.lines) { line.set(property, options[property]); } for (let point of topology.points) { point.set(property, options[property]); } } } } // Sets the global default options for all new Tooltip instances createTooltipDefaults() { // Get any options that were in configuration let options = this.options.tooltip; // Set the default Options for tooltips using default HTML let defaults = { point: { html: pointTooltip, css: undefined, vars: undefined, }, line: { html: lineTooltip, css: undefined, vars: undefined, }, }; // Overwrite the default Tooltip options with those given if (options) { for (let type of ["point", "line"]) { if (options[type]) { if (options[type].html) { defaults[type].html = options[type].html; } if (options[type].css) { defaults[type].css = options[type].css; } if (options[type].vars) { defaults[type].vars = options[type].vars; } } } } if (options.autoPan) defaults.autoPan = options.autoPan; // Assign to the prototype so this.templates returns the templates across Tooltip instances Tooltip.prototype.defaults = defaults; } //---- LINES createLineDefaults() { let options = this.options.line; let defaults = { weight: 1, opacity: 1, smoothFactor: 1, color: "#555555", units: "bits", dataAggregate: "first", dataTarget: "max", colorCriteria: "now", }; // TODO: Add key-checking for all possible options if (options) { for (let key in options) { defaults[key] = options[key]; } } Line.prototype.defaults = defaults; } //---- POINTS createPointDefaults() { let options = this.options.point; let defaults = { size: 4, shape: "circle", color: "black", stroke: 1, fill: "white", fillOpacity: 1, staticTooltip: false, }; if (options) { for (let key in options) { defaults[key] = options[key]; } } Point.prototype.defaults = defaults; } drawMiniMap() { console.log("Drawing map...."); fetch(this.options.minimapConfig.map) .then((data) => data.json()) .then((data) => { for (const map of data) { this.addTopology(map); this.fitToView(); if (!map.tile) this.hideLoader(); this.colorCircuits(this.get("topologies")[map.name]); } }) .catch((err) => { console.log(err); this.showError(); }); } colorCircuits(topology) { this.requestCircuitData(topology); } requestCircuitData(topology, subqueries) { let applyData = this.applyData.bind(this); let url = this.options.minimapConfig.data; fetch(url, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: topology.name, start: 'now-15m', end: 'now' }) }) .then((data) => data.json()) .then((data) => { applyData(data.results, topology.name); }) .catch((e) => { console.log(e); this.showError(); }); } showLoader() { let container = document.getElementById(this.container); let loader_elem = document.querySelector( `#${this.container} .atlas4-loader` ); if (loader_elem) loader_elem.remove(); var node = document.createElement("DIV"); node.classList.add("atlas4-loader"); node.innerHTML = loader; container.appendChild(node); } hideLoader() { let loader_elem = document.querySelector( `#${this.container} .atlas4-loader` ); if (loader_elem) loader_elem.remove(); } showError() { let container = document.getElementById(this.container); let loader_elem = document.querySelector( `#${this.container} .atlas4-loader` ); if (loader_elem) loader_elem.remove(); var node = document.createElement("DIV"); node.classList.add("atlas4-loader"); node.innerHTML = loader; node.getElementsByTagName("svg")[0].remove(); node.getElementsByTagName("p")[0].innerHTML = "Error Loading Map.<br>Please Refresh Page To Try Again."; node.getElementsByTagName("div")[0].style.width = "200px"; container.appendChild(node); } // Legend Methods: changeLegendProperty(id, property, value) { if (this.legends[id]) { this.legends[id][property] = value; this.legends[id].rerender(); this.updateTopologyData(); } } changeLegendValues(id, threshold, colors) { if (threshold.length - colors.length == 1) { let min = threshold[0]; let max = threshold[threshold.length - 1]; let correctedThreshold = threshold.slice(1, threshold.length - 1); this.legends[id].min = Number(min); this.legends[id].max = Number(max); this.legends[id].thresholds = correctedThreshold; this.legends[id].colors = colors; this.legends[id].rerender(); this.updateTopologyData(); } } // Tooltip Methods changeTooltipContent(TopologyLayer, content) { let topologies = this.topologies; for (const topology in topologies) { topologies[topology][TopologyLayer].forEach( (l) => (l.tooltip.html = content) ); } this.updateTopologyData(); } updateTopologyData() { let topologies = this.topologies; for (const topology in topologies) { topologies[topology].lines.forEach((l) => l.update("data")); topologies[topology].points.forEach((p) => p.update("data")); } } getJSON() { let topologies = []; for (const t in this.topologies) { const topology = this.topologies[t]; let json = {}; json.name = topology.name; json.legend = topology.legend; if (topology.image) json.image = topology.image; json.metadata = topology.metadata; let eps = {}; for (const point of topology.points) { let obj = {}; obj.id = point.id; obj.label = point.data.label; obj.shape = point.shape; obj.size = point.size; obj.lat = point.coord[0]; obj.lng = point.coord[1]; obj.fill = point.fill; obj.stroke = point.stroke; obj.color = point.color; obj.opacity = point.opacity; eps[point.point.name] = obj; } json.endpoints = eps; let adjs = []; for (const line of topology.lines) { let obj = {}; obj.a = line.a.name; obj.b = line.b.name; obj.anchors = line.anchors; obj.metadata = line.metadata; adjs.push(obj); } json.adjacencies = adjs; topologies.push(json); } return topologies; } on(event, callback) { if (this.events[event]) this.events[event].push(callback); else this.events[event] = [callback]; } dispatch(event) { if (this.events[event]) { for (const callback of this.events[event]) { callback(); } } } applyData(data, topology = 'all') { let topologies; if (!topology || topology === 'all') { topologies = this.get('topologies') } else { topologies = {} topologies[topology] = this.get('topologies')[topology] } if (!Object.keys(topologies).length) return for (const topologyName in topologies) { let topology = topologies[topologyName] if (!topology) { console.info(`Topology - ${topologyName} doesn't exists!`) continue } let lines = topology.lines for (const line of lines) { let lineData = { ...line.metadata, label: line.label, dataValues: { } } let lineDataTargets = line.metadata?.data_targets || [] // Will be used to prevent summing duplicate data target names let dataTargetCache = [] for (const dataPoint of data) { let aggregateGroup; let aggregateGroupName; if (lineDataTargets.includes(dataPoint.data_target)) { if (!dataPoint?.values) continue; let values = dataPoint.values.reverse() let now = values.reduce(getNow, null) let min = values.reduce(getMin, null) let max = values.reduce(getMax, null) let sum = values.reduce(getSum, 0) let count = values.reduce(getCount, 0) let avg = count === 0 ? 0 : count ? sum / count : undefined aggregateGroupName = dataPoint.aggregate_group ? dataPoint.aggregate_group : undefined; aggregateGroup = { now, min, max, avg } } if (line.dataAggregate == 'first') { if (!isAggregateGroupAlreadyDefined(aggregateGroupName, lineData) && isDataDefined(aggregateGroup)) { lineData['dataValues'][aggregateGroupName] = aggregateGroup; } } else if (line.dataAggregate == 'sum' && !dataTargetCache.includes(dataPoint.data_target)) { if (!isAggregateGroupAlreadyDefined(aggregateGroupName, lineData) && isDataDefined(aggregateGroup)) { lineData['dataValues'][aggregateGroupName] = aggregateGroup; dataTargetCache.push(dataPoint.data_target) } else if (isAggregateGroupAlreadyDefined(aggregateGroupName, lineData) && isDataDefined(aggregateGroup)) { sumData(lineData['dataValues'][aggregateGroupName], aggregateGroup) dataTargetCache.push(dataPoint.data_target) } } } line.set('data', lineData) } } function getNow(now, currentValue) { if (!now) { now = currentValue[1] } return now } function getMin(min, currentValue) { if ((!min && currentValue[1] != undefined) || (min > currentValue[1] && currentValue[1] != undefined)) { min = currentValue[1] } return min } function getMax(max, currentValue) { if ((!max && currentValue[1] != undefined) || (max < currentValue[1] && currentValue[1] != undefined)) { max = currentValue[1] } return max } function getSum(sum, currentValue) { return sum + currentValue[1] } function getCount(count, currentValue) { if (currentValue[1]) count++; return count } function isAggregateGroupAlreadyDefined(aggregateGroupName, lineData) { let aggregateGroup = lineData?.['dataValues']?.[aggregateGroupName] return isDataDefined(aggregateGroup) } function isDataDefined(aggregateGroup) { return aggregateGroup != undefined && aggregateGroup.now != undefined && aggregateGroup.min != undefined && aggregateGroup.max != undefined && aggregateGroup.avg != undefined ? true : false } function sumData(currentAggregateGroup, newAggregateGroup) { currentAggregateGroup.now += newAggregateGroup.now currentAggregateGroup.min += newAggregateGroup.min currentAggregateGroup.max += newAggregateGroup.max currentAggregateGroup.avg += newAggregateGroup.avg } } }
JavaScript
class Version extends BaseText{ /** * Implements input's validations * * @param {null|number} at - index used when input has been created as a vector that * tells which value should be used * @return {Promise<*>} value held by the input based on the current context (at) * @protected */ _validation(at){ // calling super class validations return super._validation(at).then((value) => { // minimumVersionRequired if (this.property('minimumRequired') && compareVersions(value, this.property('minimumRequired')) === -1){ throw new ValidationFail( util.format('Version is not compatible, minimum Version required: %s, current version %s', this.property('minimumRequired'), value), '524f9ed1-44e8-43d8-83b1-72dc8d33788b', ); } return value; }); } }
JavaScript
class DefaultTheme extends EmberObject { /** * Path to theme's components. It's used in the child-themes * * @property componentsPath * @default 'models-table/' * @type string */ componentsPath = 'models-table/'; /** * Default path to theme's components * * @property defaultComponentsPath * @default 'models-table/' * @type string */ defaultComponentsPath = 'models-table/'; /** * @property cellComponent * @type string * @default 'models-table/cell' */ @componentPath('cell') cellComponent; /** * @property cellContentDisplayComponent * @type string * @default 'models-table/cell-content-display' */ @componentPath('cell-content-display') cellContentDisplayComponent; /** * @property cellContentEditComponent * @type string * @default 'models-table/cell-content-edit' */ @componentPath('cell-content-edit') cellContentEditComponent; /** * @property cellContentSummaryComponent * @type string * @default 'models-table/cell-column-summary' */ @componentPath('cell-column-summary') cellContentSummaryComponent; /** * @property columnsDropdownComponent * @type string * @default 'models-table/columns-dropdown' */ @componentPath('columns-dropdown') columnsDropdownComponent; /** * @property columnsHiddenComponent * @type string * @default 'models-table/columns-hidden' */ @componentPath('columns-hidden') columnsHiddenComponent; /** * @property dataGroupBySelectComponent * @type string * @default 'models-table/data-group-by-select' */ @componentPath('data-group-by-select') dataGroupBySelectComponent; /** * @property expandAllToggleComponent * @type string * @default 'models-table/expand-all-toggle' */ @componentPath('expand-all-toggle') expandAllToggleComponent; /** * @property expandToggleComponent * @type string * @default 'models-table/expand-toggle' */ @componentPath('expand-toggle') expandToggleComponent; /** * @property footerComponent * @type string * @default 'models-table/footer' */ @componentPath('footer') footerComponent; /** * @property globalFilterComponent * @type string * @default 'models-table/global-filter' */ @componentPath('global-filter') globalFilterComponent; /** * @property groupedHeaderComponent * @type string * @default 'models-table/grouped-header' */ @componentPath('grouped-header') groupedHeaderComponent; /** * @property noDataComponent * @type string * @default 'models-table/no-data' */ @componentPath('no-data') noDataComponent; /** * @property pageSizeSelectComponent * @type string * @default 'models-table/page-size-select' */ @componentPath('page-size-select') pageSizeSelectComponent; /** * @property paginationNumericComponent * @type string * @default 'models-table/pagination-numeric' */ @componentPath('pagination-numeric') paginationNumericComponent; /** * @property paginationSimpleComponent * @type string * @default 'models-table/pagination-simple' */ @componentPath('pagination-simple') paginationSimpleComponent; /** * @property rowComponent * @type string * @default 'models-table/row' */ @componentPath('row') rowComponent; /** * @property rowExpandComponent * @type string * @default 'models-table/row-expand' */ @componentPath('row-expand') rowExpandComponent; /** * @property rowFilteringComponent * @type string * @default 'models-table/row-filtering' */ @componentPath('row-filtering') rowFilteringComponent; /** * @property rowFilteringCellComponent * @type string * @default 'models-table/row-filtering-cell' */ @componentPath('row-filtering-cell') rowFilteringCellComponent; /** * @property rowGroupingComponent * @type string * @default 'models-table/row-grouping' */ @componentPath('row-grouping') rowGroupingComponent; /** * @property rowGroupToggleComponent * @type string * @default 'models-table/row-group-toggle' */ @componentPath('row-group-toggle') rowGroupToggleComponent; /** * @property rowSelectAllCheckboxComponent * @type string * @default 'models-table/row-select-all-checkbox' */ @componentPath('row-select-all-checkbox') rowSelectAllCheckboxComponent; /** * @property rowSelectCheckboxComponent * @type string * @default 'models-table/row-select-checkbox' */ @componentPath('row-select-checkbox') rowSelectCheckboxComponent; /** * @property rowSortingComponent * @type string * @default 'models-table/row-sorting' */ @componentPath('row-sorting') rowSortingComponent; /** * @property rowSortingCellComponent * @type string * @default 'models-table/row-sorting-cell' */ @componentPath('row-sorting-cell') rowSortingCellComponent; /** * @property selectComponent * @type string * @default 'models-table/select' */ @componentPath('select') selectComponent; /** * @property summaryComponent * @type string * @default 'models-table/summary' */ @componentPath('summary') summaryComponent; /** * @property tableComponent * @type string * @default 'models-table/table' */ @componentPath('table') tableComponent; /** * @property tableBodyComponent * @type string * @default 'models-table/table-body' */ @componentPath('table-body') tableBodyComponent; /** * @property tableFooterComponent * @type string * @default 'models-table/table-footer' */ @componentPath('table-footer') tableFooterComponent; /** * @property tableHeaderComponent * @type string * @default 'models-table/table-header' */ @componentPath('table-header') tableHeaderComponent; /** * @property cellContentTagName * @type string * @default '' */ cellContentTagName = ''; /** * @property searchLabelMsg * Label for global filter * * @type string * @default 'Search:' */ searchLabelMsg = 'Search:'; /** * Placeholder for global filter * * @property searchPlaceholderMsg * @type string * @default '' */ searchPlaceholderMsg = ''; /** * Label for dropdown with columns for rows grouping * * @property groupByLabelMsg * @type string * @default 'Group by:' */ groupByLabelMsg = 'Group by:'; /** * Text on toggle for columns dropdown * * @property columnsTitleMsg * @type string * @default 'Columns' */ columnsTitleMsg = 'Columns'; /** * Label for button to show all table columns (under columns dropdown) * * @property columnsShowAllMsg * @type string * @default 'Show All' */ columnsShowAllMsg = 'Show All'; /** * Label for button to hide all table columns (under columns dropdown) * * @property columnsHideAllMsg * @type string * @default 'Hide All' */ columnsHideAllMsg = 'Hide All'; /** * Label for button to restore default visibility for table columns (under columns dropdown) * * @property columnsRestoreDefaultsMsg * @type string * @default 'Restore Defaults' */ columnsRestoreDefaultsMsg = 'Restore Defaults'; /** * Message shown in the table summary. It's used with three options: * * 1. First row's index * 2. Last row's index * 3. Overall rows count * * @property tableSummaryMsg * @type string * @default 'Show %@ - %@ of %@' */ tableSummaryMsg = 'Show %@ - %@ of %@'; /** * Message shown when all columns are hidden. It's shown inside table body * * @property allColumnsAreHiddenMsg * @type string * @default 'All columns are hidden. Use <strong>columns</strong>-dropdown to show some of them' */ allColumnsAreHiddenMsg = 'All columns are hidden. Use <strong>columns</strong>-dropdown to show some of them'; /** * Message shown when there are not data to display in the table. It's shown inside table body in cases when initial `data` is empty or when all records are filtered out * * @property noDataToShowMsg * @type string * @default 'No records to show' */ noDataToShowMsg = 'No records to show'; /** * Default label for button "Edit" inside the `cell-edit-toggle`-component * * @property editRowButtonLabelMsg * @type string * @default 'Edit' */ editRowButtonLabelMsg = 'Edit'; /** * Default label for button "Save" inside the `cell-edit-toggle`-component * * @property saveRowButtonLabelMsg * @type string * @default 'Save' */ saveRowButtonLabelMsg = 'Save'; /** * Default label for button "Cancel" inside the `cell-edit-toggle`-component * * @property cancelRowButtonLabelMsg * @type string * @default 'Cancel' */ cancelRowButtonLabelMsg = 'Cancel'; /** * Label for dropdown with page numbers. Used in both numeric and simple pagination * * @property currentPageNumberMsg * @type string * @default 'Page:' */ currentPageNumberMsg = 'Page:'; /** * Label for dropdown with rows count shown in the page * * @property rowsCountMsg * @type string * @default 'Rows:' */ rowsCountMsg = 'Rows:'; /** * Label for "First"-page in the numeric pagination. It's used for screen-readers and not "visible" by default * * @property goToFirstPageButtonTextMsg * @type string * @default 'Go to first page' */ goToFirstPageButtonTextMsg = 'Go to first page'; /** * Label for "Previous"-page in the numeric pagination. It's used for screen-readers and not "visible" by default * * @property goToPrevPageButtonTextMsg * @type string * @default 'Go to previous page' */ goToPrevPageButtonTextMsg = 'Go to previous page'; /** * Label for "Next"-page in the numeric pagination. It's used for screen-readers and not "visible" by default * * @property goToNextPageButtonTextMsg * @type string * @default 'Go to next page' */ goToNextPageButtonTextMsg = 'Go to next page'; /** * Label for "Last"-page in the numeric pagination. It's used for screen-readers and not "visible" by default * * @property goToLastPageButtonTextMsg * @type string * @default 'Go to last page' */ goToLastPageButtonTextMsg = 'Go to last page'; /** * Label for "Clear global filter"-button. It's used for screen-readers and not "visible" by default * * @property clearGlobalFilterMsg * @type string * @default 'Clear global filter input' */ clearGlobalFilterMsg = 'Clear global filter input'; /** * Label for "Clear filter"-buttons in the table header's cells. It's used for screen-readers and not "visible" by default * * @property clearFilterMsg * @type string * @default 'Clear filter input' */ clearFilterMsg = 'Clear filter input'; /** * Label for "Clear all filters"-button in the table summary section. It's used for screen-readers and not "visible" by default * * @property clearAllFiltersMsg * @type string * @default 'Clear all filters' */ clearAllFiltersMsg = 'Clear all filters'; /** * CSS-classes for `table`-tag * * @property table * @type string * @default '' */ table = ''; /** * @property buttonsGroup * @type string * @default '' */ buttonsGroup = ''; /** * CSS-classes for `div`-wrapper over components `global-filter`, `data-group-by-select` and `columns-dropdown` * * @property headerWrapper * @type string * @default '' */ headerWrapper = ''; /** * CSS-classes for wrapper used inside `global-filter` component * * @property globalFilterWrapper * @type string * @default '' */ globalFilterWrapper = ''; /** * CSS-classes for wrapper used inside `columns-dropdown` component * * @property columnsDropdownWrapper * @type string * @default '' */ columnsDropdownWrapper = ''; /** * @property columnsDropdownButtonWrapper * @type string * @default '' */ columnsDropdownButtonWrapper = ''; /** * CSS-classes for wrapper over list inside `columns-dropdown` component * * @property columnsDropdown * @type string * @default '' */ columnsDropdown = ''; /** * CSS-classes for divider for list inside `columns-dropdown` components. Divider is placed before single-column items by default * * @property columnsDropdownDivider * @type string * @default '' */ columnsDropdownDivider = ''; /** * CSS-classes for wrapper inside `data-group-by-select` component * * @property dataGroupBySelectWrapper * @type string * @default '' */ dataGroupBySelectWrapper = 'data-group-by-wrapper'; /** * CSS-classes for thead cells * * @property theadCell * @type string * @default 'table-header' */ theadCell = 'table-header'; /** * CSS-classes used for thead-cells with columns titles. This class is used only if columns is not sortable * * @property theadCellNoSorting * @type string * @default 'table-header-no-sorting' */ theadCellNoSorting = 'table-header-no-sorting'; /** * CSS-classes used for thead-cells with columns filters. This class is used only if columns is not filterable * * @property theadCellNoFiltering * @type string * @default 'table-header-no-filtering' */ theadCellNoFiltering = 'table-header-no-filtering'; /** * CSS-classes for selected rows. Used in the `row` component * * @property selectedRow * @type string * @default 'selected-row' */ selectedRow = 'selected-row'; /** * CSS-classes for expanded rows. Used in the `row` component * * @property expandedRow * @type string * @default 'expanded-row' */ expandedRow = 'expanded-row'; /** * CSS-classes for table footer * * @property tfooterWrapper * @type string * @default 'table-footer' */ tfooterWrapper = 'table-footer'; /** * CSS-classes for wrapper inside `footer` component * * @property tfooterInternalWrapper * @type string * @default '' */ tfooterInternalWrapper = ''; /** * CSS-classes for table summary block. Used in the `summary` component * * @property footerSummary * @type string * @default 'table-summary' */ footerSummary = 'table-summary'; /** * CSS-classes for table summary block. It's used when table has numeric pagination * * @property footerSummaryNumericPagination * @type string * @default '' */ footerSummaryNumericPagination = ''; /** * CSS-classes for table summary block. It's used when table has simple pagination * * @property footerSummaryDefaultPagination * @type string * @default '' */ footerSummaryDefaultPagination = ''; /** * CSS-classes for wrapper over "Page size"-block in the `footer` component * * @property pageSizeWrapper * @type string * @default '' */ pageSizeWrapper = ''; /** * @property pageSizeSelectWrapper * @type string * @default '' */ pageSizeSelectWrapper = ''; /** * Wrapper for select-tag in the current-page-number-select component * * @property currentPageSizeSelectWrapper * @type string * @default '' */ currentPageSizeSelectWrapper = ''; /** * CSS-classes for `pagination-simple` and `pagination-numeric` components * * @property paginationWrapper * @type string * @default 'table-nav' */ paginationWrapper = 'table-nav'; /** * CSS-classes for buttons-wrapper in the `pagination-simple` and `pagination-numeric` components * * @property paginationInternalWrapper * @type string * @default '' */ paginationInternalWrapper = ''; /** * CSS-classes for `pagination-numeric` component * * @property paginationWrapperNumeric * @type string * @default '' */ paginationWrapperNumeric = ''; /** * CSS-classes for `pagination-simple` component * * @property paginationWrapperDefault * @type string * @default '' */ paginationWrapperDefault = ''; /** * @property paginationBlock * @type string * @default '' */ paginationBlock = ''; /** * CSS-classes for items in the `pagination-numeric` component * * @property paginationNumericItem * @type string * @default '' */ paginationNumericItem = ''; /** * CSS-classes for active item in the `pagination-numeric` component * * @property paginationNumericItemActive * @type string * @default '' */ paginationNumericItemActive = ''; /** * CSS-classes for "default" buttons * * @property buttonDefault * @type string * @default '' */ buttonDefault = ''; /** * CSS-classes for "link"-buttons * * @property buttonLink * @type string * @default '' */ buttonLink = ''; /** * CSS-classes for `td` shown when all columns are hidden * * @property noDataCell * @type string * @default '' */ noDataCell = ''; /** * @property collapseRow * @type string * @default 'collapseRow' */ collapseRow = 'collapse-row'; /** * @property collapseAllRows * @type string * @default 'collapse-all-rows' */ collapseAllRows = 'collapse-all-rows'; /** * @property expandRow * @type string * @default 'expand-row' */ expandRow = 'expand-row'; /** * @property expandAllRows * @type string * @default 'expand-all-rows' */ expandAllRows = 'expand-all-rows'; /** * @property cellContentDisplay * @type string * @default '' */ cellContentDisplay = ''; /** * @property cellContentEdit * @type string * @default '' */ cellContentEdit = ''; /** * CSS-classes for `thead` * * @property thead * @type string * @default '' */ thead = ''; /** * CSS-classes for `form` * * @property form * @type string * @default '' */ form = ''; /** * CSS-classes for wrapper over the form elements * * @property formElementWrapper * @type string * @default '' */ formElementWrapper = ''; /** * CSS-classes for input elements * * @property input * @type string * @default '' */ input = ''; /** * CSS-classes for `select` * * @property select * @type string * @default '' */ select = ''; /** * CSS-classes for "Clear filter" button. Used for global filter and filters for each column * * @property clearFilterIcon * @type string * @default '' */ clearFilterIcon = ''; /** * CSS-classes for "Clear all filters" button inside the `summary` component * * @property clearAllFiltersIcon * @type string * @default '' */ clearAllFiltersIcon = ''; /** * @property globalFilterDropdownWrapper * @type string * @default '' */ globalFilterDropdownWrapper = ''; /** * CSS-classes for `select` inside the `data-group-by-select` component * * @property changeGroupByField * @type string * @default 'change-group-by-field' */ changeGroupByField = 'change-group-by-field'; /** * CSS-classes for "sort asc/desc" button inside the `data-group-by-select` component * * @property sortGroupedPropertyBtn * @type string * @default '' */ sortGroupedPropertyBtn = 'sort-grouped-field'; /** * CSS-class for `row-grouping` component * * @property groupingRow * @type string * @default 'grouping-row' */ groupingRow = 'grouping-row'; /** * CSS-classes for `td` inside `row-grouping` component * * @property groupingCell * @type string * @default 'grouping-cell' */ groupingCell = 'grouping-cell'; /** * CSS-classes for icons used to show that some "list" is sorted "ASC". It's used for `data-group-by-select` and `row-sorting-cell` * * @property sortAscIcon * @type string * @default '' */ sortAscIcon = ''; /** * CSS-classes for icons used to show that some "list" is sorted "DESC". It's used for `data-group-by-select` and `row-sorting-cell` * * @property sortDescIcon * @type string * @default '' */ sortDescIcon = ''; /** * CSS-classes for icons in the `columns-dropdown` related to the visible columns * * @property columnVisibleIcon * @type string * @default '' */ columnVisibleIcon = ''; /** * CSS-classes for icons in the `columns-dropdown` related to the hidden columns * * @property columnHiddenIcon * @type string * @default '' */ columnHiddenIcon = ''; /** * CSS-classes for icon used in the "First"-button (`pagination-simple`) * * @property navFirstIcon * @type string * @default '' */ navFirstIcon = ''; /** * CSS-classes for icon used in the "Prev"-button (`pagination-simple`) * * @property navPrevIcon * @type string * @default '' */ navPrevIcon = ''; /** * CSS-classes for icon used in the "Next"-button (`pagination-simple`) * * @property navNextIcon * @type string * @default '' */ navNextIcon = ''; /** * CSS-classes for icon used in the "Last"-button (`pagination-simple`) * * @property navLastIcon * @type string * @default '' */ navLastIcon = ''; /** * CSS-classes for "caret"-icon used in the `columns-dropdown` * * @property caretIcon * @type string * @default '' */ caretIcon = ''; /** * @property selectAllRowsIcon * @type string * @default '' */ selectAllRowsIcon = ''; /** * @property deselectAllRowsIcon * @type string * @default '' */ deselectAllRowsIcon = ''; /** * @property selectRowIcon * @type string * @default '' */ selectRowIcon = ''; /** * @property deselectRowIcon * @type string * @default '' */ deselectRowIcon = ''; /** * @property editRowButton * @type string * @default '' */ editRowButton = ''; /** * @property saveRowButton * @type string * @default '' */ saveRowButton = ''; /** * @property cancelRowButton * @type string * @default '' */ cancelRowButton = ''; /** * @property filteringCellInternalWrapper * @type string * @default '' */ filteringCellInternalWrapper = ''; /** * @property expandRowIcon * @type string * @default '' */ expandRowIcon = ''; /** * @property collapseRowIcon * @type string * @default '' */ collapseRowIcon = ''; /** * @property collapseAllRowsIcon * @type string * @default '' */ collapseAllRowsIcon = ''; /** * @property expandAllRowsIcon * @type string * @default '' */ expandAllRowsIcon = ''; }
JavaScript
class Node{ constructor(data){ this.data = data this.left = null this.right = null } }
JavaScript
class TreeNode { constructor() { /** * Level of tree * * @type {number} */ this.level = 0; /** * Unique id of node * * @type {string} */ this.id = "top"; /** * Header element stored in node * * @type {HTMLHeadingElement} */ this.header = undefined; /** * Subnodes list * * @type {Array<TreeNode>} */ this.childNodes = []; /** * Parent node * * @type {TreeNode} */ this.parentNode = undefined; } /** * Return last (most right) child of node * * @memberof TreeNode * @returns {TreeNode} last added subnode */ lastChild() { return lastElem(this.childNodes); } /** * Add a sub node * * @param {TreeNode} child * @memberof TreeNode */ addChild(child) { this.childNodes.push(child) } }
JavaScript
class EllipsoidConverter extends PolygonConverter { /** * @inheritDoc */ create(feature, geometry, style, context) { createEllipsoid(feature, geometry, style, context); return true; } }
JavaScript
class ContainerExecRequestTerminalSize { /** * Create a ContainerExecRequestTerminalSize. * @member {number} [rows] The row size of the terminal * @member {number} [cols] The column size of the terminal */ constructor() { } /** * Defines the metadata of ContainerExecRequestTerminalSize * * @returns {object} metadata of ContainerExecRequestTerminalSize * */ mapper() { return { required: false, serializedName: 'ContainerExecRequest_terminalSize', type: { name: 'Composite', className: 'ContainerExecRequestTerminalSize', modelProperties: { rows: { required: false, serializedName: 'rows', type: { name: 'Number' } }, cols: { required: false, serializedName: 'cols', type: { name: 'Number' } } } } }; } }
JavaScript
class LanguageModel { constructor(options) { this.enterKey = 'Enter' this.shiftKey = 'Shift' this.ok = 'OK' this.continue = 'Продолжить' this.skip = 'Пропустить' this.pressEnter = 'Нажмите :enterKey' this.multipleChoiceHelpText = 'Выберите несколько ответов' this.multipleChoiceHelpTextSingle = 'Выберите только один ответ' this.otherPrompt = 'Другое' this.placeholder = 'Напишите свой ответ здесь...' this.submitText = 'Отправить' this.longTextHelpText = 'Нажмите :shiftKey + :enterKey для переноса строки' this.prev = 'Назад' this.next = 'Вперед' this.percentCompleted = ':percent% завершено' this.invalidPrompt = 'Пожалуйста, заполните поле корректно' this.thankYouText = 'Благодарим Вас!' this.successText = 'Ваше мнение учтено!' this.ariaOk = 'Нажмите, чтобы продолжить' this.ariaRequired = 'Этот шаг обязателен' this.ariaPrev = 'Предыдущий шаг' this.ariaNext = 'Следующий шаг' this.ariaSubmitText = 'Нажмите, чтобы отправить' this.ariaMultipleChoice = 'Нажмите :letter чтобы выбрать' this.ariaTypeAnswer = 'Напишите свой ответ здесь' this.errorAllowedFileTypes = 'Некорректный тип файла. Допустимые типы файлов: :fileTypes.' this.errorMaxFileSize = 'Превышем размер файла(ов). Допустимый размер файла: :size.' this.errorMinFiles = 'Слишком мало файлов добавлено. Минимальное количество файлов: :min.' this.errorMaxFiles = 'Слишком много файлов добавлено. Максимальное количество файлов: :max.' Object.assign(this, options || {}) } /** * Inserts a new CSS class into the language model string to format the :string * Use it in a component's v-html directive: v-html="language.formatString(language.languageString)" */ formatString(string, replacements) { return string.replace(/:(\w+)/g, (match, word) => { if (this[word]) { return '<span class="f-string-em">' + this[word] + '</span>' } else if (replacements && replacements[word]) { return replacements[word] } return match }) } formatFileSize(bytes) { const units = ['B', 'kB', 'MB', 'GB', 'TB'], i = bytes > 0 ? Math.floor(Math.log(bytes) / Math.log(1024)) : 0 return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + units[i]; } }
JavaScript
class Application { constructor(server) { this.server = server; this.ignore = []; this.dom = { chat: $('#chat'), textarea: $('#message'), body: $('body') }; this.filters = [ new BBCodeFilter(), new UriFilter(), new ImageFilter(), new EmotionFilter(EmotionList), new RestrictionFilter() ]; this.init(); this.send = new SendBehavior(this); } init() { var $window = $(window) .on('connect', $.proxy(this.onConnect, this)) .on('disconnect', $.proxy(this.onDisconnect, this)) .on('message', $.proxy(this.onMessage, this)) .on('log', $.proxy(this.onLog, this)) .on('user_join', $.proxy(this.onUserJoin, this)) .on('user_leave', $.proxy(this.onUserLeave, this)) .on('error', $.proxy(this.onError, this)); $(document) .on('click.popover', '[data-popover]', $.proxy(this.onPopoverClick, this)) .on('click.profile', '[data-user-id]', $.proxy(this.onProfileClick, this)) .on('click.username', '[data-user-name]', $.proxy(this.onUsernameClick, this)) .on('click.private', '[data-private]', $.proxy(this.onPrivateClick, this)) .on('click.ignore', '[data-ignore]', $.proxy(this.onIgnoreClick, this)); $('[data-action="bbcode"]') .on('click.bbcode', $.proxy(this.onBBCodeClick, this)); // Mobile if (window.config.mobile_enable) { var snapper = new Snap({ element: document.getElementById('chat'), disable: 'right', dragger: ($window.width() < 480) ? document.getElementById('chat') : document.getElementById('do-drag') }); var open = false; $(document).on('click.show-users', '[data-action="show-users"]', () => { if (!open) { snapper.open('left'); open = true; } else { snapper.close('left'); open = false; } }); } // Correct chat size this.dom.chat.css({'bottom': $('footer').outerHeight()}); } run() { this.server.connect(); this.addRecentMessages(); } onConnect(event) { } onDisconnect(event) { } onMessage(event, message) { // Check on ignore. if (message != undefined && message.user != undefined && this.ignore.indexOf(message.user.id) != -1) { return; } this.addMessage(message); window.sound.message.play(); } onLog(event, log) { this.addLog(log.text, log.level); window.sound.message.play(); } onMessageRemove(event, message) { // Remove message from chat } addRecentMessages() { for (var message of window.recent) { this.addMessage(message); } window.scroll.instantlyDown(); } onUserJoin(event, user) { // Add user login message this.addLog(format(tr('%name% joins the chat.'), {'name': user.name})); // Play sound window.sound.join.play(); } onUserLeave(event, user) { // Add user logout message this.addLog(format(tr('%name% leaves the chat.'), {'name': user.name})); } onPopoverClick(event) { event.stopPropagation(); var button = $(event.target); var id = button.attr('data-popover'); var popover = Popover.create(id, button); popover.toggle(); } onProfileClick(event) { event.stopPropagation(); var button = $(event.target); var user = window.users.getUser(button.attr('data-user-id')); if (user) { var view = new UserProfileView(user); if (!view.exist()) { this.dom.body.append(view.render()); } var popover = Popover.create(view.id, button); popover.toggle(); } } addMessage(message) { if (message !== undefined) { this.dom.chat.append(new MessageView(message).render()); window.scroll.down(); } } addLog(log, level = 'default') { if (log !== undefined) { this.dom.chat.append(new LogView(log, level).render()); window.scroll.down(); } } onUsernameClick(event) { var name = $(event.target).attr('data-user-name'); this.dom.textarea.insertAtCaret('' + name + ', '); } onError(event, error) { } onPrivateClick(event) { var userId = $(event.target).attr('data-private'); this.send.setPrivate(userId); } onBBCodeClick(event) { var bbcode = $(event.target).attr('data-bbcode'); this.dom.textarea.insertAtCaret(bbcode); } onIgnoreClick(event) { var button = $(event.target); var ignoreId = parseInt(button.attr('data-ignore')); if (this.ignore.indexOf(ignoreId) == -1) { this.ignore.push(ignoreId); button.addClass('btn-danger'); } else { this.ignore.splice(this.ignore.indexOf(ignoreId), 1); button.removeClass('btn-danger'); } } }
JavaScript
class Mock { /** * @name getUser * @param {number} id * @returns {Object} Return an object with user datas (id, userInfos, keyData, todayScore or score) */ async getUser(id) { return USER_MAIN_DATA.find(user => user.id === parseInt(id)) }; /** * @name getPerformances * @param {number} id * @returns {Object} Return an object with user datas */ async getPerformances(id) { const userPerformance = USER_PERFORMANCE.find(user => user.userId === parseInt(id)); return userPerformance.data.map((performance, index) => { const kindName = ["cardio", "energie", "endurance", "force", "vitesse", "intensité"] return { kind: kindName[index], value: performance.value } }) }; /** * @name getDailyActivities * @param {number} id * @returns {Object} Return an object with user datas (day, kilogram, calories) */ async getDailyActivities(id) { const userDailyActivities = USER_ACTIVITY.find(user => user.userId === parseInt(id)) return userDailyActivities.sessions.map((activity, index) => { const dayNumber = ["01", "02", "03", "04", "05", "06", "07", "08", "09","10"]; return { day: dayNumber[index], kilogram: activity.kilogram, calories: activity.calories } }) }; /** * @name getAverageSessionDuration * @param {number} id * @returns {Object} Return an object with user datas (day, sessionLenght) */ async getAverageSessionDuration(id) { const userAverageSessionDuration = USER_AVERAGE_SESSIONS.find(user => user.userId === parseInt(id)) return userAverageSessionDuration.sessions.map((session, index) => { const firstDaysLetter = ["L", "M", "M", "J", "V", "S", "D"]; return { day: firstDaysLetter[index], sessionLength: session.sessionLength } }) }; }
JavaScript
class ClockReference { constructor({ sample_rate }) { check(sample_rate !== undefined, "Must provide sample_rate as a named argument"); check(Number.isInteger(sample_rate), "sample_rate must be integer"); this.sample_rate = sample_rate; this.type = this.constructor.name; } equals(other) { return this.side == other.side && this.sample_rate == other.sample_rate; } }
JavaScript
class ClockedRingBuffer { constructor(len_seconds, leadin_seconds, clock_reference, port) { if (leadin_seconds > len_seconds) { // Note that even getting close is likely to result in failure. console.error("leadin time must not exceed size"); throw new Error("leadin time must not exceed size"); } // Before the first write, all reads will be zero. After the first write, // the first leadin_samples read will be zero, then real reads will start. // (This allows a buffer to build up.) // Round both to FRAME_SIZE. this.leadin_samples = Math.round(leadin_seconds * sampleRate / FRAME_SIZE) * FRAME_SIZE; this.len = Math.round(len_seconds * sampleRate / FRAME_SIZE) * FRAME_SIZE; this.read_clock = null; this.buf = new Float32Array(this.len); this.buf.fill(NaN); if (clock_reference.sample_rate !== sampleRate) { throw new Error("clock_reference has wrong sample rate in ClockedRingBuffer constructor"); } this.clock_reference = clock_reference; this.port = port; // For debugging, mostly this.buffered_data = 0; this.last_write_clock = null; } // Note: We can get writes out of order, so having space left is // no guarantee that a given write will succeed. space_left() { return this.len - this.buffered_data; } real_offset(offset) { var len = this.len; // Hack to handle negative numbers (just in case) var real_offset = ((offset % len) + len) % len; if (!(real_offset >= 0 && real_offset < len)) { console.error("Bad offset:", offset); throw "Bad offset:" + offset; } return real_offset; } read_into(buf) { //console.debug("Reading chunk of size", buf.length); if (this.read_clock === null) { buf.fill(0); return new PlaceholderChunk({ reference: this.clock_reference, length: buf.length }); } var interval = new ClockInterval({ reference: this.clock_reference, end: this.read_clock + buf.length, length: buf.length }); var chunk = new AudioChunk({ data: buf, interval }); var errors = []; let underflowed = false; for (var i = 0; i < chunk.data.length; i++) { var sample = this.read(chunk.interval.start + i); if (typeof sample === "number") { chunk.data[i] = sample; } else if (sample === null) { chunk.data[i] = 0; underflowed = true; } else { chunk.data[i] = 0; errors.push(sample); } } if (underflowed) { this.port.postMessage({type: "underflow"}); } if (errors.length > 0) { var err_uniq = Array.from(new Set(errors)); console.error("Errors while reading chunk", interval, err_uniq); throw new Error("Failed to read audio chunk from buffer in worklet because: " + JSON.stringify(err_uniq)); } return chunk; } read() { if (LOG_ULTRA_VERBOSE) { log_every(128000, "buf_read", "leadin_samples:", this.leadin_samples, "read_clock:", this.read_clock, "buffered_data:", this.buffered_data, "space_left:", this.space_left()); } if (this.read_clock === null) { return "no read clock" ; } if (this.leadin_samples > 0) { this.read_clock++; this.leadin_samples--; return 0; } var val = this.buf[this.real_offset(this.read_clock)]; if (isNaN(val)) { // XXX TODO: Seeing an underflow should make us allocate more client slack .... but that's tricky because it will cause a noticeable glitch on the server as our window expands (but at this point it's probably too late to prevent that) // * It would also make sense to instead just try to drop some audio and recover. (Although audio trapped in the audiocontext pipeline buffers cannot be dropped without restarting the whole thing.) // XXX this used to be an error log log_every(12800, "buf_read underflow", "Buffer underflow :-( leadin_samples:", this.leadin_samples, "read_clock:", this.read_clock, "buffered_data:", this.buffered_data, "space_left:", this.space_left(), "last_write_clock:", this.last_write_clock); this.read_clock++; this.buffered_data--; return null; } this.buf[this.real_offset(this.read_clock)] = NaN; // Mostly for debugging this.read_clock++; this.buffered_data--; return val; } write_chunk(chunk) { // console.debug("SPAM", "Writing chunk of size", chunk.length); chunk.check_clock_reference(this.clock_reference); for (var i = 0; i < chunk.data.length; i++) { this.write(chunk.data[i], chunk.start + i); } } // XXX: fix performance (take an entire slice at once) write(value, write_clock) { check(write_clock == Math.round(write_clock), "write_clock not an integer?!", write_clock); if (this.last_write_clock !== null) { if (write_clock != this.last_write_clock + 1) { // Ostensibly we allow this, but I think it should never happen and is always a bug... console.error("Write clock not incrementing?! Last write clock:", this.last_write_clock, ", new write clock:", write_clock, ", difference from expected:", write_clock - (this.last_write_clock + 1)); throw new Exception("Write clock skipped or went backwards"); } } this.last_write_clock = write_clock; // XXX(slow): lib.log_every(12800, "buf_write", "write_clock:", write_clock, "read_clock:", this.read_clock, "buffered_data:", this.buffered_data, "space_left:", this.space_left()); if (this.read_clock === null) { // It should be acceptable for this to end up negative this.read_clock = write_clock - this.leadin_samples; } if (this.space_left() == 0) { // This is a "true" buffer overflow, we have actually run completely out of buffer. console.error("Buffer overflow :-( write_clock:", write_clock, "read_clock:", this.read_clock, "buffered_data:", this.buffered_data, "space_left:", this.space_left()); throw new Error("Buffer overflow"); } if (!isNaN(this.buf[this.real_offset(write_clock)])) { // This is a "false" buffer overflow -- we are overwriting some past data that the reader skipped over (presumably due to an underflow.) Just write it anyway. (XXX: this should never happen I think, and I never observe it.) // XXX this used to be a warning log log_every(12800, "sorta_overflow", "Writing over existing buffered data; write_clock:", write_clock, "read_clock:", this.read_clock, "buffered_data:", this.buffered_data, "space_left:", this.space_left()); } if (this.buffered_data >= 0) { this.buf[this.real_offset(write_clock)] = value; } else { // Don't write into the buffer if we're behind the read pointer, it will just fuck us up later when we wrap around to it log_every(12800, "compensated_underflow", "Compensating for underflow by discarding data until we reach the read pointer"); } this.buffered_data++; } }
JavaScript
class TodoActions { fetch() { return (dispatch) => { dispatch(); return API._get().then((res) => this.fetchedTodos(res.data)).catch((res) => this.fetchFailed(res.message)); }; } add(todo) { if (!todo || !todo.length) { return; } return (dispatch) => { return API._post(todo).then( (res) => this.receivedTodo(res.data)).catch((res) => console.error(res.message)); }; } remove(todoID) { return (dispatch) => { return API._delete(todoID).then(() => this.removedTodo(todoID)).catch((res) => console.error(res.message)); }; } toggleTodoState(todo) { return (dispatch) => { return API._update(todo).then( () => { if (todo.complete) { this.completeTodo(todo._id); } else { this.uncompleteTodo(todo._id); } }).catch((res) => console.error(res.message)); }; } removeCompleted(todos) { return (dispatch) => { let completedTodos = todos.filter(t => t.complete); let uncompletedTodos = todos.filter(t => !t.complete); if (!completedTodos.length) { return; } let clearRequests = []; completedTodos.forEach(t => { clearRequests.push(API._delete(t._id)); }); return API._whenAll(clearRequests).then( () => this.clearCompleted(uncompletedTodos)).catch((res) => console.error(res.message)); }; } fetchedTodos(todos) { return todos; } removedTodo(todoID) { return todoID; } receivedTodo(todo) { return todo; } completeTodo(todoID) { return todoID; } uncompleteTodo(todoID) { return todoID; } clearCompleted(uncompletedTodos) { return uncompletedTodos; } fetchFailed(errorMessage) { return errorMessage; } }
JavaScript
class Rankings { /** * Crea una instancia de Contests. * @param {service} httpService - Servicio de conexión Http (Http) * @param {service} jwtService - Servicio de manejo de Json Web Tokens (Jwt) */ constructor (httpService, jwtService) { this.jwtService = jwtService this.httpService = httpService } /** * Obtiene del backend el ranking. */ getRanking (limit, page) { return this.httpService.httpClient .fetch(API.endpoints.users + '/' + API.endpoints.ranking + '?limit=' + limit + '&page=' + page, { method: 'get', headers: { 'Authorization': 'Bearer ' + this.jwtService.token } }) .then(this.httpService.checkStatus) .then(this.httpService.parseJSON) } getSubmissions(userId, limit, page, by, sort, condition) { let strt = '' if(condition !== null) strt = '&condition=' + condition return this.httpService.httpClient .fetch(API.endpoints.users + '/' + userId + '/' + API.endpoints.submissions + '?limit=' + limit + '&page=' + page + '&by=' + by + '&sort=' + sort + strt, { method: 'get', headers: { 'Authorization': 'Bearer ' + this.jwtService.token } }) .then(this.httpService.checkStatus) .then(this.httpService.parseJSON) } loadStatsByVerdict (id) { return this.httpService.httpClient .fetch(API.endpoints.users + '/' + id + '/verdicts', { method: 'get', headers: { 'Authorization': 'Bearer ' + this.jwtService.token } }) .then(this.httpService.checkStatus) .then(this.httpService.parseJSON) } loadProfile (id) { return this.httpService.httpClient .fetch(API.endpoints.users + '/' + id, { method: 'get', headers: { 'Authorization': 'Bearer ' + this.jwtService.token } }) .then(this.httpService.checkStatus) .then(this.httpService.parseJSON) } loadStatsByLang (id) { return this.httpService.httpClient .fetch(API.endpoints.users + '/' + id + '/languages', { method: 'get', headers: { 'Authorization': 'Bearer ' + this.jwtService.token } }) .then(this.httpService.checkStatus) .then(this.httpService.parseJSON) } }
JavaScript
class ChainGateway { /** * It generates an ethereum wallet address for user * @static * @memberof ChainGateway * @returns {String} - A unique string containing the user ethereum address */ static async createEthWalletAddress(password, apikey) { const { data } = await axios.post(`${chainGatewayBaseUrl}/newAddress`, { password, apikey }); return data; } }
JavaScript
class ARCEnvironmentReadEvent extends CustomEvent { /** * @return {string} The name of the environment used to initialize this event. */ get name() { return this[nameValue]; } /** * @param {string} name The name of the environment */ constructor(name) { super(EventTypes.Model.Environment.read, { bubbles: true, composed: true, cancelable: true, detail: {}, }); this[nameValue] = name; } }
JavaScript
class ARCEnvironmentUpdateEvent extends CustomEvent { /** * @return {ARCEnvironment} An environment used to initialize this event. */ get environment() { return this[environmentValue]; } /** * @param {ARCEnvironment} environment An environment to update. */ constructor(environment) { super(EventTypes.Model.Environment.update, { bubbles: true, composed: true, cancelable: true, detail: {} }); this[environmentValue] = environment; } }
JavaScript
class ARCEnvironmentUpdatedEvent extends Event { /** * @return {ARCEntityChangeRecord} Change record */ get changeRecord() { return this[changeRecordValue]; } /** * @param {ARCEntityChangeRecord} record Entity change record. */ constructor(record) { super(EventTypes.Model.Environment.State.update, { bubbles: true, composed: true, }); this[changeRecordValue] = record; } }
JavaScript
class ARCEnvironmentDeleteEvent extends CustomEvent { /** * @return {string} The environment id used to initialize the event. */ get id() { return this[environmentIdValue]; } /** * @param {string} id The environment id */ constructor(id) { super(EventTypes.Model.Environment.delete, { bubbles: true, composed: true, cancelable: true, detail: {} }); this[environmentIdValue] = id; } }
JavaScript
class ARCEnvironmentDeletedEvent extends ARCEntityDeletedEvent { /** * @param {string} id The id of the deleted environment * @param {string} rev Updated revision */ constructor(id, rev) { super(EventTypes.Model.Environment.State.delete, id, rev); } }
JavaScript
class ARCEnvironmentListEvent extends ARCEntityListEvent { /** * @return {boolean|undefined} When set it ignores other list parameters and returns all results in a single query. * This also means that the page token is never set. */ get readall() { return this[readallValue]; } /** * @param {ARCVariablesListOptions=} opts Query options. */ constructor(opts={}) { super(EventTypes.Model.Environment.list, opts); this[readallValue] = opts.readall; } }
JavaScript
class ARCEnvironmentCurrentEvent extends CustomEvent { constructor() { super(EventTypes.Model.Environment.current, { bubbles: true, composed: true, cancelable: true, detail: {} }); } }
JavaScript
class ARCEnvironmentSelectEvent extends CustomEvent { /** * @param {string=} id The ID of the environment to select. When not set it selects the default environment. */ constructor(id) { super(EventTypes.Model.Environment.select, { bubbles: true, composed: true, cancelable: true, detail: id, }); } }
JavaScript
class ARCEnvironmentStateSelectEvent extends CustomEvent { /** * @param {EnvironmentStateDetail} detail The change record for the environment */ constructor(detail) { super(EventTypes.Model.Environment.State.select, { bubbles: true, composed: true, cancelable: true, detail, }); } }
JavaScript
class ARCVariableUpdateEvent extends CustomEvent { /** * @return {ARCVariable} A variable used to initialize this event. */ get variable() { return this[variableValue]; } /** * @param {ARCVariable} variable A variable to update. */ constructor(variable) { super(EventTypes.Model.Variable.update, { bubbles: true, composed: true, cancelable: true, detail: {} }); this[variableValue] = variable; } }
JavaScript
class ARCVariableSetEvent extends CustomEvent { /** * @return {string} The variable name used to initialize this event */ get name() { return this[nameValue]; } /** * @return {string} The variable value to set */ get value() { return this[variableValue]; } /** * @param {string} name The name of the variable. Case sensitive. * @param {string} value The value to set on the variable. */ constructor(name, value) { super(EventTypes.Model.Variable.set, { bubbles: true, composed: true, cancelable: true, detail: {} }); this[nameValue] = name; this[variableValue] = value; } }
JavaScript
class ARCVariableUpdatedEvent extends Event { /** * @return {ARCEntityChangeRecord} Change record */ get changeRecord() { return this[changeRecordValue]; } /** * @param {ARCEntityChangeRecord} record Entity change record. */ constructor(record) { super(EventTypes.Model.Variable.State.update, { bubbles: true, composed: true, }); this[changeRecordValue] = record; } }
JavaScript
class ARCVariableDeleteEvent extends CustomEvent { /** * @return {string} The variable id used to initialize the event. */ get id() { return this[variableIdValue]; } /** * @param {string} id The variable id */ constructor(id) { super(EventTypes.Model.Variable.delete, { bubbles: true, composed: true, cancelable: true, detail: {} }); this[variableIdValue] = id; } }
JavaScript
class ARCVariableDeletedEvent extends ARCEntityDeletedEvent { /** * @param {string} id The id of the deleted variable * @param {string} rev Updated revision */ constructor(id, rev) { super(EventTypes.Model.Variable.State.delete, id, rev); } }
JavaScript
class ARCVariableListEvent extends ARCEntityListEvent { /** * @return {string} The name of the environment used to initialize this event. */ get name() { return this[nameValue]; } /** * @return {boolean|undefined} When set it ignores other list parameters and returns all results in a single query. * This also means that the page token is never set. */ get readall() { return this[readallValue]; } /** * @param {string} name The name of the environment * @param {ARCVariablesListOptions=} opts Query options. */ constructor(name, opts={}) { super(EventTypes.Model.Variable.list, opts); this[nameValue] = name; this[readallValue] = opts.readall; } }
JavaScript
class LevelControl extends Control { constructor(indoorEqual, options = {}) { const element = document.createElement('div'); element.className = 'level-control ol-unselectable ol-control'; super({ element, target: options.target, }); this.indoorEqual = indoorEqual; this._renderNewLevels(); this.indoorEqual.on('change:levels', this._renderNewLevels.bind(this)); this.indoorEqual.on('change:level', this._renderNewLevels.bind(this)); } _renderNewLevels() { this.element.innerHTML = ''; const currentLevel = this.indoorEqual.get('level'); this.indoorEqual.get('levels').forEach((level) => { const button = document.createElement('button'); if (currentLevel === level) { button.classList.add('level-control-active'); } button.textContent = level; button.addEventListener('click', () => { this.indoorEqual.set('level', level); }) this.element.appendChild(button); }); } }
JavaScript
class Comments { constructor(obj) { if (!obj.comment) { throw new Error("You must include a comment"); } else if (typeof obj.comment != "string") { throw new Error("comment must be a string"); } else { this.comment = obj.comment; } } }