language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class GameObject { static deserialize(gameObjectDefinition, allComponents, allPrefabs) { //Deserialize a game object definition let toReturn = new GameObject(); //Create a new Game Object toReturn.name = gameObjectDefinition.name; //Set the name (for later reference in the game) for (let componentDefinition of gameObjectDefinition.components) { //Loop over all the defined components let componentClass = allComponents.find(i => i.name == componentDefinition.name); //Find a component definition with the appropriate name let component = new componentClass(toReturn, ...componentDefinition.args || []); //Create a new component, speading the arguments and defaulting to nothing. toReturn.components.push(component); } if (gameObjectDefinition.children) for (let childDefinition of gameObjectDefinition.children) { let child = Scene.deserializeObject(childDefinition, allComponents, allPrefabs); toReturn.children.push(child); } return toReturn; } /** * Set the default values of x and y */ constructor() { this.x = 0; this.y = 0; this.components = []; this.children = []; } /** * Update the game by iterating over every game object and calling update if available. */ update() { for (let component of this.components) { if (component.update) component.update(); } for(let child of this.children){ child.update(); } } /** * Draw the game object * @param {2D Context from a Canvas} ctx where the game object is drawn */ draw(ctx) {//How does the game object draw itself? for (let component of this.components) { if (component.draw) component.draw(ctx); } for(let child of this.children){ child.draw(ctx); } } }
JavaScript
class UiNavLink { constructor(spec) { const { id, title, order = 0, url, subUrlBase, disableSubUrlTracking, icon, euiIconType, linkToLastSubUrl = true, hidden = false, disabled = false, tooltip = '', category, } = spec; this._id = id; this._title = title; this._order = order; this._url = url; this._subUrlBase = subUrlBase || url; this._disableSubUrlTracking = disableSubUrlTracking; this._icon = icon; this._euiIconType = euiIconType; this._linkToLastSubUrl = linkToLastSubUrl; this._hidden = hidden; this._disabled = disabled; this._tooltip = tooltip; this._category = category; } getOrder() { return this._order; } toJSON() { return { id: this._id, title: this._title, order: this._order, url: this._url, subUrlBase: this._subUrlBase, icon: this._icon, euiIconType: this._euiIconType, linkToLastSubUrl: this._linkToLastSubUrl, disableSubUrlTracking: this._disableSubUrlTracking, hidden: this._hidden, disabled: this._disabled, tooltip: this._tooltip, category: this._category, }; } }
JavaScript
class PgLiteral { static create(str) { return new PgLiteral(str); } constructor(str) { this._str = str; } toString() { return this._str; } }
JavaScript
class App extends React.Component { // componentDidMount() { // this.props.fetchHouses({type: 'FETCH_HOUSES', payload: {address:'testaddress' }}) // fetch('http://localhost:3000/api/v1/houses', { // method: 'GET' // }) // .then(response => response.json()) // .then(data => console.log(data)) // } render() { return ( <div className="App"> <header className="App-header"> <HousesContainer/> </header> <br></br> <Photo /> </div> ); } }
JavaScript
class Month { /** * Creates an instance of Month. * * The class `Month` requires an optional parameter `options`, must be an * `Object` with the properties `current`, `weekend` and `datebook`. * * The `options.current` value must be type `date`, it is used as a base to identify * the days that have `elapsed`, the `remaining` days of the month and `current` day, * the `default` value is `new Date()`. * * The `options.weekend` value must be a `string` or integer `number` between `0` to `15`. * If a `string` is passed, the string must match to regex `/^[0-1]{7}$/`, the * `default` value is `0`. * * The `options.datebook` value must be an object `array`, that represents a * collection of scheduled activities from a Datebook, the `default` value is `[]`. * * @memberof Month * @param {object} [options] - Month class options. * @param {Date} [options.current] - Current date of month. * @param {WeekendOption} [options.weekend] - Option to specify weekends. * @param {Datebook} [options.datebook] - Scheduled activities of the month. * @throws {MonthError} If `options.current` is not instance Date. * @throws {MonthError} If `options.weekend` is not a valid weekend option. * @throws {MonthError} If `options.datebook` is not an array. * @throws {MonthError} If any `options.datebook` elements is not a valid object. * @example const month = new Month(); * * @example const month = new Month({ * current: new Date(2021, 0, 15), * weekend: 0, * datebook: [ * { * date: '2021-01-20', * title: "Mom's birthday", * description: "Don't forget to buy a gift", * type: 'event', * holiday: true, * }, * { * date: '2021-01-10', * title: 'Send final sales report', * description: "Don't forget to attach graphics", * type: 'task', * holiday: true, * }, * ], * }); * */ constructor({ current = new Date(), weekend = 0, datebook = [] } = {}) { if (!utils.isDate(current)) { throw new MonthError(ERRORS.TYPE_CURRENT_OPTION); } if (!isValid.weekend(weekend)) { throw new MonthError(ERRORS.INVALID_WEEKEND_OPTION); } if (!utils.isArray(datebook)) { throw new MonthError(ERRORS.TYPE_DATEBOOK_OPTION); } if (!utils.isEmptyArray(datebook) && !isValid.datebook(datebook)) { throw new MonthError(ERRORS.INVALID_DATEBOOK_SCHEMA); } // » DEFINE READ-ONLY PROPERTIES /** * Its a number `array` with three elements. * * The array elements represent the year number, month number and day * number `[YY, MM, DD]`. * * @type {Array.<number>} * @member YYMMDD * @memberof Month * @instance * @readonly */ Object.defineProperty(this, 'YYMMDD', { value: readonly.createYYMMDD(current) }); /** * Its a number `array`. * * The array elements represent days of the week that are not working days * and takes as weekend, its value is like like as `Date.prototype.getDay()`. * * @type {Array.<number>} * @member WEEKEND * @memberof Month * @instance * @readonly */ Object.defineProperty(this, 'WEEKEND', { value: readonly.createWeekend(weekend) }); /** * Its a number `array`, with three elements. * * The array elements represent one day of the month, the day month start, * the day month current and the day month end, its value is like * `Date.prototype.getDate()`. * * @type {Array.<number>} * @member SCE * @memberof Month * @instance * @readonly */ Object.defineProperty(this, 'SCE', { value: readonly.createSCE(this.YYMMDD) }); /** * The year of the month. * * Its value is like `Date.prototype.getFullYear()`. * * @type {number} */ this.year = this.YYMMDD[0]; // eslint-disable-line prefer-destructuring /** * The month number. * * Its value is like `Date.prototype.getDate()`. * * @type {number} */ this.number = this.YYMMDD[1]; // eslint-disable-line prefer-destructuring /** * Collection of activities of the month, organized by type. * * An `Object` with the properties `tasks`, `events`, `appointments` and * `meetings`, every property of the object is an `array`. * * @type {Planner} */ this.planner = createPlanner({ datebook, YYMMDD: this.YYMMDD, SCE: this.SCE, }); /** * The month days that are weekends. * * A number `array` that value of elements is like `Date.prototype.getDate()`. * * @type {Array.<number>} */ this.weekends = createWeekends({ YYMMDD: this.YYMMDD, WEEKEND: this.WEEKEND, SCE: this.SCE, }); /** * The month days that are holidays. * * A number `array` that value of elements is like a `Date.prototype.getDate()`. * * @type {Array.<number>} */ this.holidays = createHolidays(this.planner); /** * The month days that are non workdays. * * A number `array` that value of elements is like a `Date.prototype.getDate()`. * * @type {Array.<number>} */ this.nonworkdays = createNonWorkdays({ weekends: this.weekends, holidays: this.holidays, }); /** * The details of the days of the month, a collection of information about * all the days of the month. * * An object `array`, every `array` element contains information about a day * of the month, If it is a weekend or a work day, if it has already elapsed, * it is the current day, week number. * * @type {Days} */ this.days = createDays({ YYMMDD: this.YYMMDD, SCE: this.SCE, weekends: this.weekends, nonworkdays: this.nonworkdays, planner: this.planner, }); /** * Summary of the month with information on weeks, working days and dates. * * An `Object` with the properties `dates`, `days`, `weeks`, and `workdays`. * * @type {Summary} */ this.summary = createSummary({ YYMMDD: this.YYMMDD, nonworkdays: this.nonworkdays, }); } /** * The `addDatebook()` method adds scheduled activities. * * `datebook` value must be an object `array`, . * * @memberof Month * @param {Datebook} datebook - Plans of the month. * @returns {this} To chain methods. * @throws {MonthError} If `datebook` is not an array. * @throws {MonthError} If any `datebook` elements is not a valid object. * @example const month = new Month(); * * month.addDatebook([ * { * date: '2021-01-10', * title: 'Send final sales report', * description: "Don't forget to attach graphics", * type: 'task', * holiday: true, * }, * ]); * */ addDatebook(datebook) { if (!utils.isArray(datebook)) { throw new MonthError(ERRORS.TYPE_DATEBOOK_OPTION); } if (!utils.isEmptyArray(datebook) && !isValid.datebook(datebook)) { throw new MonthError(ERRORS.INVALID_DATEBOOK_SCHEMA); } const { tasks, events, appointments, meetings } = createPlanner({ datebook, YYMMDD: this.YYMMDD, SCE: this.SCE, }); const { tasks: Tasks, events: Events, appointments: Appointments, meetings: Meetings, } = this.planner; // » JOIND OLD AND NEW DATEBOOK ITEMS const addedTasks = [...Tasks, ...tasks]; const addedEvents = [...Events, ...events]; const addedAppointments = [...Appointments, ...appointments]; const addedMeetings = [...Meetings, ...meetings]; // » UPDATE DATEBOOK PROPERTIES this.planner = { tasks: addedTasks, events: addedEvents, appointments: addedAppointments, meetings: addedMeetings, }; // » UPDATE DAYS PROPERTIES this.holidays = createHolidays(this.planner); this.nonworkdays = createNonWorkdays({ weekends: this.weekends, holidays: this.holidays, }); this.days = createDays({ YYMMDD: this.YYMMDD, SCE: this.SCE, weekends: this.weekends, nonworkdays: this.nonworkdays, planner: this.planner, }); // » UPDATE SUMMARY PROPERTIES this.summary = createSummary({ YYMMDD: this.YYMMDD, nonworkdays: this.nonworkdays, }); return this; } }
JavaScript
class AppStore { constructor() { this.usersRef = undefined; this.usersProfile = undefined; this.matchedPropertysRef = undefined; this.agentsRef = undefined; this.agentsProfile = undefined; this.agentsFilterRef = undefined; this.agentSaleRef = undefined; this.agentBuyRef = undefined; this.agentLeaseRef = undefined; this.agentRentRef = undefined; } // Catch user login before assign any database reference updateUid = () => { console.log( 'updateUid') const uid = MobxStore.app.uid; // Testing only const user = firebase.auth().currentUser; console.log( 'updateUid user.uid ', user.uid); console.log( 'updateUid MobxStore.app.uid ', uid) console.log( 'updateUid usersRef ', `users/${uid}/propertys`); // users database this.usersRef = firebase.database().ref(`users/${uid}/propertys`); this.usersProfile = firebase.database().ref(`users/${uid}/profile`); this.matchedPropertysRef = firebase.database().ref(`users/${uid}/matchedPropertys`); // agents database this.agentsRef = firebase.database().ref(`agents/${uid}/propertys`); this.agentsProfile = firebase.database().ref(`agents/${uid}/profile`); // Use in agent match panel for filtering! this.agentsFilterRef = firebase.database().ref(`agents/${uid}/filters`); this.agentSaleRef = firebase.database().ref(`agents/${uid}/sale`); this.agentBuyRef = firebase.database().ref(`agents/${uid}/buy`); this.agentRentRef = firebase.database().ref(`agents/${uid}/rent`); this.agentLeaseRef = firebase.database().ref(`agents/${uid}/lease`); // init userModelView, for mobx, // can't be used inside constructor // when app start will call an empty constructor propertys.init(); // Agent only agentModel.init(); console.log( 'end of updateUid') } }
JavaScript
class Dashboard extends Component { nonBallComment = []; // wicket_detail = [ // { // bowler: "", // wkt_det: "" // } // ]; constructor(props) { super(props); this.ScoreCard = this.ScoreCard.bind(this); this.convertCSV = this.convertCSV.bind(this); this.closeModal = this.closeModal.bind(this); this.toggle = this.toggle.bind(this); this.toggleCollapse_bat = this.toggleCollapse_bat.bind(this); this.toggleCollapse_bowl = this.toggleCollapse_bowl.bind(this); this.toggleCollapse_comment = this.toggleCollapse_comment.bind(this); this.state = { visible: false, activeTab: 0, collapse_bat: false, collapse_bowl: false, commentary: false, matchType: "", status: "" }; } app = CommonService.getAppContext(); UNSAFE_componentWillMount() { this.props.liveScore(); } UNSAFE_componentWillReceiveProps(nextProps) { } ScoreCard(Mid, Sid) { this.props.getScoreCard(Mid, Sid); this.props.getMatchDetails(Mid, Sid); this.props.getPlayers(Mid, Sid); this.props.getComments(Mid, Sid); this.props.getCurrentScore(Mid, Sid); this.setState({ visible: true }); this.props.resetPrediction(); } convertCSV() { if (this.props.matchDetail.match !== undefined && this.props.comments.commentary !== undefined && this.props.currentScore.matchDetail !== undefined) { let runsScored_last_5 = 0; let wicketsTaken_last_5 = 0; let strikeRate = 0; let non_strikeRate = 0; let overs_done; for (var i = 0; i < this.props.comments.commentary.innings[0].overs.length; i++) { if (i < 5) { if (this.props.comments.commentary.innings[0].overs[i].id !== -1) { runsScored_last_5 += Number(this.props.comments.commentary.innings[0].overs[i].overSummary.runsConcededinOver); } } } for (var j = 0; j < this.props.comments.commentary.innings[0].overs.length; j++) { if (j < 5) { if (this.props.comments.commentary.innings[0].overs[j].id !== -1) { wicketsTaken_last_5 += Number(this.props.comments.commentary.innings[0].overs[j].overSummary.wicketsTakeninOver); } } } for (i = 0; i < this.props.currentScore.matchDetail.currentBatters.length; i++) { if (this.props.currentScore.matchDetail.currentBatters[i].isFacing) { strikeRate = Number(this.props.currentScore.matchDetail.currentBatters[i].strikeRate); } else { non_strikeRate = Number(this.props.currentScore.matchDetail.currentBatters[i].strikeRate); } } if (this.props.comments.commentary.innings[0].overs[0].balls.length === 6) { overs_done = this.props.comments.commentary.innings[0].overs[0].number } else { overs_done = this.props.comments.commentary.innings[0].overs[0].id + "." + this.props.comments.commentary.innings[0].overs[0].balls.length } let csvData = { mid: this.props.matchDetail.match.id, date: this.props.matchDetail.match.localStartDate, venue: this.props.matchDetail.match.venue.name, bat_team: this.props.matchDetail.match.homeTeam.name, bowl_team: this.props.matchDetail.match.awayTeam.name, batsman: this.props.comments.commentary.innings[0].overs[0].balls[0].comments[0].batsmanName, bowler: this.props.comments.commentary.innings[0].overs[0].balls[0].comments[0].bowlerName, runs: this.props.comments.commentary.innings[0].overs[0].balls[0].comments[0].battingTeamScore, wickets: this.props.comments.commentary.innings[0].overs[0].balls[0].comments[0].wickets, overs: Number(overs_done), runs_last_5: runsScored_last_5, wickets_last_5: wicketsTaken_last_5, striker: strikeRate, non_striker: non_strikeRate, total: this.props.comments.commentary.innings[0].overs[0].balls[0].comments[0].battingTeamScore } console.log(csvData, "CSV_DATA"); this.props.convertToCsv(csvData); } } componentDidUpdate(prevProps) { if (this.props != prevProps) { if (this.props.matchDetail !== undefined && this.props.matchDetail.match !== undefined) { this.setState({ matchType: this.props.matchDetail.match.cmsMatchType.toLowerCase(), status: this.props.matchDetail.match.status }); } } } loading = () => <div className="animated fadeIn pt-1 text-center">Loading...</div> closeModal() { this.props.resetMatchDetails(); this.setState({ visible: false, activeTab: 0, collapse_bat: false, collapse_bowl: false, commentary: false }); } toggle(id) { this.setState({ activeTab: id }) } toggleCollapse_bat() { this.setState({ collapse_bat: !this.state.collapse_bat }); } toggleCollapse_bowl() { this.setState({ collapse_bowl: !this.state.collapse_bowl }); } toggleCollapse_comment() { this.setState({ commentary: !this.state.commentary }); } render() { return ( <div className="animated fadeIn"> {this.props.score.meta !== undefined ? this.props.score.meta.inProgressMatchCount === 0 ? null : <Card> <CardHeader> <h3>LIVE</h3> </CardHeader> <CardBody> <div> <div className="wrapper"> <div className="scrolls"> <Row className="card-score"> {this.props.score.matchList !== undefined ? this.props.score.matchList.matches.map((live) => ( <div key={live.id}> {live.status === "LIVE" && ( <Fragment> <Col xs="12" sm="6" lg="3"> <Card className="bg-info text-white fade-in" tag="a" onClick={() => this.ScoreCard(live.id, live.series.id)} style={{ cursor: "pointer" }}> {/* <CardImg top width="100%" src={`data:image/png;base64,${this.props.image}`} alt="Card image cap" /> */} <CardBody className="pb-0"> <span className="avatar mb-2 seriesImage"> <img src={live.series.shieldImageUrl !== undefined ? live.series.shieldImageUrl : ""} className="img-avatar" alt="Team Image" /> </span> <span className="mb-2 text-white seriesName"> {live.name !== "" && (<>{live.name},{' '}</>)} {live.series.shortName} </span> <Row className="mb-1"> <span className="avatar ml-3"> <img src={live.homeTeam.logoUrl !== undefined ? live.homeTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.homeTeam.shortName} </Col> <Col className="text-white"> {live.scores.homeScore} </Col> </Row> <Row> <span className="avatar ml-3"> <img src={live.awayTeam.logoUrl !== undefined ? live.awayTeam.logoUrl : ""} className="img-avatar avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.awayTeam.shortName} </Col> <Col className="text-white"> {live.scores.awayScore} </Col> </Row> <div className="mt-2 text-white"> {live.matchSummaryText} </div> </CardBody> </Card> </Col> </Fragment> ) } {live.status === "INPROGRESS" && ( <Fragment> <Col xs="12" sm="6" lg="3"> <Card className="bg-info text-white fade-in" tag="a" onClick={() => this.ScoreCard(live.id, live.series.id)} style={{ cursor: "pointer" }}> {/* <CardImg top width="100%" src={`data:image/png;base64,${this.props.image}`} alt="Card image cap" /> */} <CardBody className="pb-0"> <span className="avatar mb-2 seriesImage"> <img src={live.series.shieldImageUrl !== undefined ? live.series.shieldImageUrl : ""} className="img-avatar" alt="Team Image" /> </span> <span className="mb-2 seriesName"> {live.name !== "" && (<>{live.name},{' '}</>)} {live.series.shortName} </span> <Row className="mb-1"> <span className="avatar ml-3"> <img src={live.homeTeam.logoUrl !== undefined ? live.homeTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.homeTeam.shortName} </Col> <Col> {live.scores.homeScore} </Col> </Row> <Row> <span className="avatar ml-3"> <img src={live.awayTeam.logoUrl !== undefined ? live.awayTeam.logoUrl : ""} className="img-avatar avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.awayTeam.shortName} </Col> <Col> {live.scores.awayScore} </Col> </Row> <div className="mt-2"> {live.matchSummaryText} </div> </CardBody> </Card> </Col> </Fragment> ) } </div> )) : ""} </Row> </div> </div> </div> </CardBody> </Card> : null} {this.props.score.meta !== undefined ? this.props.score.meta.completedMatchCount === 0 ? null : <Card> <CardHeader><h3>COMPLETED</h3></CardHeader> <CardBody> <div> <div className="wrapper"> <div className="scrolls"> <Row className="card-score"> {this.props.score.matchList !== undefined ? this.props.score.matchList.matches.map((live) => ( <div key={live.id}> {live.status === "COMPLETED" && ( <Fragment> <Col xs="12" sm="6" lg="3"> <Card className="bg-info fade-in" tag="a" onClick={() => this.ScoreCard(live.id, live.series.id, live.matchSummaryText, live.scores, live.homeTeam, live.awayTeam)} style={{ cursor: "pointer" }}> {/* <CardImg top width="100%" src={`data:image/png;base64,${this.props.image}`} alt="Card image cap" /> */} <CardBody className="pb-0"> <span className="avatar mb-2 seriesImage"> <img src={live.series.shieldImageUrl !== undefined ? live.series.shieldImageUrl : ""} className="img-avatar" alt="Team Image" /> </span> <span className="mb-2 text-white seriesName"> {live.name !== "" && (<>{live.name},{' '}</>)} {live.series.shortName} </span> <Row className="mb-1"> <span className="avatar ml-3"> <img src={live.homeTeam.logoUrl !== undefined ? live.homeTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.homeTeam.shortName} </Col> <Col className="text-white"> {live.scores.homeScore} </Col> </Row> <Row> <span className="avatar ml-3"> <img src={live.awayTeam.logoUrl !== undefined ? live.awayTeam.logoUrl : ""} className="img-avatar avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.awayTeam.shortName} </Col> <Col className="text-white"> {live.scores.awayScore} </Col> </Row> <div className="mt-2 text-white"> {live.matchSummaryText} </div> </CardBody> </Card> </Col> </Fragment> ) } </div> )) : ""} </Row> </div> </div> </div> </CardBody> </Card> : null} {this.props.score.meta !== undefined ? this.props.score.meta.upcomingMatchCount === 0 ? null : <Card> <CardHeader><h3>UPCOMING</h3></CardHeader> <CardBody> <div> <div className="wrapper"> <div className="scrolls"> <Row className="card-score"> {/* <div className="vl"></div> */} {this.props.score.matchList !== undefined ? this.props.score.matchList.matches.map((live) => ( <div key={live.id}> {live.status === "UPCOMING" && ( <div> <Col xs="12" sm="6" lg="3"> <Card className="bg-info text-white fade-in"> {/* <CardImg top width="100%" src={`data:image/png;base64,${this.props.image}`} alt="Card image cap" /> */} <CardBody className="pb-0"> <span className="avatar mb-2 seriesImage"> <img src={live.series.shieldImageUrl !== undefined ? live.series.shieldImageUrl : ""} className="img-avatar" alt="Team Image" /> </span> <span className="mb-2 seriesName"> {live.name !== "" && <span>{live.name},{' '}</span>} {live.series.shortName} </span> <Row className="mb-1"> <span className="avatar ml-3"> <img src={live.homeTeam.logoUrl !== undefined ? live.homeTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.homeTeam.shortName} </Col> </Row> <Row> <span className="avatar ml-3"> <img src={live.awayTeam.logoUrl !== undefined ? live.awayTeam.logoUrl : ""} className="img-avatar avatar" alt="Team Image" /> </span> <Col className="text-white"> {live.awayTeam.shortName} </Col> </Row> <Row className="mt-2"> <Col> {dateFormat(live.startDateTime, "isoDate")},{' '} {dateFormat(live.startDateTime, "shortTime")} </Col> </Row> </CardBody> </Card> </Col> </div> )} </div> )) : ""} </Row> </div> </div> </div> </CardBody> </Card> : null} {!this.app.state.loader && <Modal isOpen={this.state.visible} toggle={this.closeModal} fallback={this.loading()}> <ModalHeader toggle={this.closeModal}> {this.props.scoreCard.meta !== undefined ? <Fragment> <> {this.props.matchDetail.match !== undefined && <span className="avatar m-2"> <img src={this.props.matchDetail.match.series.shieldImageUrl !== undefined ? this.props.matchDetail.match.series.shieldImageUrl : ""} className="img-avatar" alt="Series Image" /> </span> } </> <strong className="series-name">{this.props.scoreCard.meta.series.name}</strong> </Fragment> : ""} </ModalHeader> <ModalBody> <Row> <Col xs="8"> <Fragment> <h3> <Row className="mb-1"> <Col className="col-lg-10"> <span className="avatar m-2"> <img src={this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.homeTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> {this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.homeTeam.shortName : ""} <span className="ml-4">{this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.scores.homeScore !== "" ? this.props.matchDetail.match.scores.homeScore : '0-0' : ""}{' '} {'('}{this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.scores.homeOvers !== "" ? this.props.matchDetail.match.scores.homeOvers : "0.0" : ""}{')'}</span> </Col> </Row> <Row> <Col> <span className="avatar m-2"> <img src={this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.awayTeam.logoUrl : ""} className="img-avatar" alt="Team Image" /> </span> {this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.awayTeam.shortName : ""} <span className="ml-4">{this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.scores.awayScore !== "" ? this.props.matchDetail.match.scores.awayScore : '0-0' : ""}{' '} {'('}{this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.scores.awayOvers !== "" ? this.props.matchDetail.match.scores.awayOvers : "0.0" : ""}{')'}</span> </Col> </Row> </h3> <div className="large text-muted ml-3">{this.props.matchDetail.match !== undefined && <> <strong>VENUE: </strong> <span> {/* <span className="avatar m-2" style={{ position: "relative", top: "5px" }}> <img src={this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.venue.image : ""} className="img-avatar" alt="Venue Image" /> </span> */} {this.props.matchDetail.match.venue.name} </span> </> } </div> </Fragment> <div className="m-2 text-info" style={{ fontSize: "20px" }}> <strong>{this.props.matchDetail.match !== undefined ? this.props.matchDetail.match.matchSummaryText : ""}<br /></strong> </div> <Table hover responsive className="table-outline m-2 d-none d-sm-table cur_table"> <thead className="thead-light"> <tr> <th className="text-center">Batsman</th> <th className="text-center">R</th> <th className="text-center">B</th> <th className="text-center">SR</th> </tr> </thead> <tbody> {this.props.currentScore.matchDetail !== undefined ? this.props.currentScore.matchDetail.currentBatters.map((cur_bat) => ( <> <tr> <td className="text-center"> <strong>{cur_bat.name !== undefined ? cur_bat.name : "-"} {cur_bat.name && cur_bat.isFacing && <sup className="bat-avatar"> {/* <i className="fa fa-star fa-sm" aria-hidden="true"></i> */} <span className="bat-avatar-status badge-success"></span> </sup>} </strong> </td> <td className="text-center"> {/* <i className="flag-icon flag-icon-us h4 mb-0" title="us" id="us"></i> */} <span>{cur_bat.runs !== undefined ? cur_bat.runs : <strong>-</strong>}</span> </td> <td> <div className="text-center"> {/* <div className="float-left"> */} <span>{cur_bat.ballsFaced !== undefined ? cur_bat.ballsFaced : <strong>-</strong>}</span> {/* </div> */} {/* <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> */} </div> {/* <Progress className="progress-xs" color="success" value="50" /> */} </td> <td> {cur_bat.name && <div className="text-center"> <strong>{cur_bat.strikeRate !== undefined ? cur_bat.strikeRate : <strong>-</strong>}</strong> </div> } </td> </tr> </> )) : ""} </tbody> </Table> <Table hover responsive className="table-outline m-2 mb-3 d-none d-sm-table cur_table"> <thead className="thead-light"> <tr> <th className="text-center">Bowler</th> <th className="text-center">O</th> <th className="text-center">R</th> <th className="text-center">W</th> <th className="text-center">ER</th> </tr> </thead> <tbody> {this.props.currentScore.matchDetail !== undefined && this.props.currentScore.matchDetail.bowler !== undefined && <> <tr> <td className="text-center"> <strong>{this.props.currentScore.matchDetail.bowler.name !== undefined ? this.props.currentScore.matchDetail.bowler.name : "-"}</strong> </td> <td className="text-center"> {/* <i className="flag-icon flag-icon-us h4 mb-0" title="us" id="us"></i> */} <span>{this.props.currentScore.matchDetail.bowler.bowlerOver !== undefined ? this.props.currentScore.matchDetail.bowler.bowlerOver : <strong>-</strong>}</span> </td> <td className="text-center"> <span>{this.props.currentScore.matchDetail.bowler.runsAgainst !== undefined ? this.props.currentScore.matchDetail.bowler.runsAgainst : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td className="text-center"> <span>{this.props.currentScore.matchDetail.bowler.wickets !== undefined ? this.props.currentScore.matchDetail.bowler.wickets : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td> <div className="text-center"> <strong>{this.props.currentScore.matchDetail.bowler.economy !== undefined ? this.props.currentScore.matchDetail.bowler.economy : <strong>-</strong>}</strong> </div> </td> </tr> </> } </tbody> </Table> </Col> <Col xs="4"> {this.props.matchDetail.match !== undefined && this.props.comments.commentary !== undefined && <> {this.props.matchDetail.match.status === "COMPLETED" ? "" : ( <> <div style={{ marginLeft: "90px" }}> <a onClick={() => this.ScoreCard(this.props.matchDetail.match.id, this.props.matchDetail.match.series.id)} style={{ color: "#20a8d8", cursor: "pointer", fontSize: "20px", position: "relative", top: "2px" }} className="refresh "><i className="icon-refresh icons font-3xl mr-1"></i>Refresh</a> <button className="btn btn-ghost-success btn-md" type="button" style={{ marginLeft: "7px" }} onClick={() => this.convertCSV()}>Export to CSV</button> </div> <ScorePredictor /> </> )} </> } </Col> </Row> {this.props.score.matchList !== undefined ? this.props.score.matchList.matches.map((live) => ( <> {this.props.matchDetail.match !== undefined && <> {live.id === this.props.matchDetail.match.id && ( <> {live.status === "COMPLETED" && ( <> {/* {this.props.scoreCard.fullScorecard !== undefined ? this.props.scoreCard.fullScorecard.innings.map((ings) => ( <> {ings.batsmen.map((bat) => ( <> */} {this.props.playersByMatch.playersInMatch !== undefined && <> {this.props.scoreCard.fullScorecardAwards !== undefined && <> {this.props.playersByMatch.playersInMatch.homeTeam.players.map((player) => ( <> {this.props.scoreCard.fullScorecardAwards.manOfTheMatchId === player.playerId && ( <span style={{ position: "relative", bottom: "15px" }}> <mark className="mr-4" style={{ fontSize: "15px", fontWeight: "bold" }}>PLAYER OF THE MATCH: </mark> <span className="avatar"> <img src={player.imageURL !== undefined ? player.imageURL : playerImage} className="img-avatar" alt="Player Image" style={{ position: "relative", top: "10px", right: "10px" }} /> </span> <span style={{ fontSize: "20px", fontWeight: "bold" }}>{this.props.scoreCard.fullScorecardAwards.manOfTheMatchName}</span> </span> ) } </> ))} {this.props.playersByMatch.playersInMatch.awayTeam.players.map((player) => ( <> {this.props.scoreCard.fullScorecardAwards.manOfTheMatchId === player.playerId && ( <span style={{ position: "relative", bottom: "15px" }}> <mark className="m-4" style={{ fontSize: "15px", fontWeight: "bold" }}>PLAYER OF THE MATCH: </mark> <span className="avatar"> <img src={player.imageURL !== undefined ? player.imageURL : playerImage} className="img-avatar" alt="Player Image" style={{ position: "relative", top: "10px", right: "10px" }} /> </span> <span style={{ fontSize: "20px", fontWeight: "bold" }}>{this.props.scoreCard.fullScorecardAwards.manOfTheMatchName}</span> </span> ) } </> ))} </> } </> } {/* </> ))} </> )) : "MOM"} */} </> )} </> )} </>} </> )) : ""} <hr /> <div> <Nav tabs> {this.props.scoreCard.fullScorecard !== undefined ? this.props.scoreCard.fullScorecard.innings.map((ings) => ( <NavItem className="team"> <NavLink active={this.state.activeTab === ings.id} onClick={() => this.toggle(ings.id)} className="teamName" > {ings.shortName} </NavLink> </NavItem> )) : ""} </Nav> {this.props.scoreCard.fullScorecard !== undefined ? this.props.scoreCard.fullScorecard.innings.map((ing) => ( <> {ing.id === this.state.activeTab && <> <ListGroupItem> <Button block color="link" className="text-left m-0 p-0" onClick={this.toggleCollapse_bat} style={{ color: "black" }}> <h4 className="mt-2 p-0 float-left">BATTING<span className="ml-5">{this.props.scoreCard.fullScorecard !== undefined && <> {ing.wicket}-{ing.run}{' '}{'('}{ing.over}{')'} <span className="ml-4">RR {' '} {ing.runRate}</span> <span style={{ marginLeft: "500px" }}>EXTRAS{' '}<strong className="mr-2">{ing.extra}</strong><span className="extra-color">b</span>{ing.bye},{''}<span className="extra-color">lb</span>{ing.legBye},{''}<span className="extra-color">w</span>{ing.wide},{''}<span className="extra-color">nb</span>{ing.noBall}</span> </> }</span></h4> <i className="icon-arrow-down icons font-2xl d-block mt-4 float-right"></i> </Button> <Collapse isOpen={this.state.collapse_bat}> <TabContent activeTab={this.state.activeTab}> <Table hover responsive className="table-outline mb-0 d-none d-sm-table"> <thead className="thead-light"> <tr> <th className="text-center"><i className="icon-people"></i></th> <th className="text-center">Batsman</th> <th className="text-center">R</th> <th className="text-center">B</th> <th className="text-center">4s</th> <th className="text-center">6s</th> <th className="text-center">SR</th> </tr> </thead> <tbody> {this.props.scoreCard.fullScorecard !== undefined ? this.props.scoreCard.fullScorecard.innings.map((ings) => ( <> {this.state.activeTab === ings.id && ( <> {ings.batsmen.map((bat) => ( <> <tr> <td className="text-center"> <div className="avatar"> <img src={bat.imageURL !== undefined ? bat.imageURL : playerImage} className="img-avatar" alt="Player Image" /> {bat.howOut === "not out" && <span className="avatar-status badge-success"></span>} </div> </td> <td className="text-center"> <strong>{bat.name} {/* {bat.howOut === "not out" ? <sup><i className="fa fa-star fa-sm mt-4" aria-hidden="true"></i> </sup> : ""} */} </strong> <div className="small text-muted"> <span>{bat.howOut}</span> </div> </td> <td className="text-center"> {/* <i className="flag-icon flag-icon-us h4 mb-0" title="us" id="us"></i> */} <span>{bat.runs !== "" ? bat.runs : <strong>-</strong>}</span> </td> <td> <div className="text-center"> {/* <div className="float-left"> */} <span>{bat.balls !== "" ? bat.balls : <strong>-</strong>}</span> {/* </div> */} {/* <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> */} </div> {/* <Progress className="progress-xs" color="success" value="50" /> */} </td> <td className="text-center"> <span>{bat.fours !== "" ? bat.fours : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td className="text-center"> <span>{bat.sixes !== "" ? bat.sixes : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td> <div className="text-center"> <strong>{bat.strikeRate}</strong> </div> </td> </tr> </> ))} </> )} </> )) : ""} </tbody> </Table> </TabContent> </Collapse> </ListGroupItem> <ListGroupItem> <Button block color="link" className="text-left m-0 p-0" onClick={this.toggleCollapse_bowl} style={{ color: "black" }}> <h4 className="mt-2 p-0 float-left">BOWLING</h4> <i className="icon-arrow-down icons font-2xl d-block mt-4 float-right" style={{ position: "relative", bottom: "10px" }}></i> </Button> <Collapse isOpen={this.state.collapse_bowl}> <TabContent activeTab={this.state.activeTab}> <Table hover responsive className="table-outline mb-0 d-none d-sm-table"> <thead className="thead-light"> <tr> <th className="text-center"><i className="icon-people"></i></th> <th className="text-center">Bowler</th> <th className="text-center">O</th> <th className="text-center">M</th> <th className="text-center">R</th> <th className="text-center">W</th> <th className="text-center">ER</th> </tr> </thead> <tbody> {this.props.scoreCard.fullScorecard !== undefined ? this.props.scoreCard.fullScorecard.innings.map((ings) => ( <> {this.state.activeTab === ings.id && ( <> {ings.bowlers.map((bowl) => ( <> <tr> <td className="text-center"> {this.props.currentScore.matchDetail.bowler.name !== undefined ? this.props.currentScore.matchDetail.bowler.id === bowl.id ? <div className="avatar"> <img src={bowl.imageURL !== undefined ? bowl.imageURL : playerImage} className="img-avatar" alt="Player Image" /> <span className="avatar-status badge-success"></span> </div> : <div className="avatar"> <img src={bowl.imageURL !== undefined ? bowl.imageURL : playerImage} className="img-avatar" alt="Player Image" /> </div> : "" } </td> <td className="text-center"> <strong>{bowl.name}</strong> </td> <td className="text-center"> {/* <i className="flag-icon flag-icon-us h4 mb-0" title="us" id="us"></i> */} <span>{bowl.overs !== "" ? bowl.overs : <strong>-</strong>}</span> </td> <td> <div className="text-center"> {/* <div className="float-left"> */} <span>{bowl.maidens !== "" ? bowl.maidens : <strong>-</strong>}</span> {/* </div> */} {/* <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> */} </div> {/* <Progress className="progress-xs" color="success" value="50" /> */} </td> <td className="text-center"> <span>{bowl.runsConceded !== "" ? bowl.runsConceded : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td className="text-center"> <span>{bowl.wickets !== "" ? bowl.wickets : <strong>-</strong>}</span> {/* <i className="fa fa-cc-mastercard" style={{ fontSize: 24 + 'px' }}></i> */} </td> <td> <div className="text-center"> <strong>{bowl.economy}</strong> </div> </td> </tr> </> ))} </> )} </> )) : ""} </tbody> </Table> </TabContent> </Collapse> </ListGroupItem> <ListGroupItem> <Button block color="link" className="text-left m-0 p-0" onClick={this.toggleCollapse_comment} style={{ color: "black" }}> <h4 className="mt-2 p-0 float-left">COMMENTARY</h4> <i className="icon-arrow-down icons font-2xl d-block mt-4 float-right" style={{ position: "relative", bottom: "10px" }}></i> </Button> <Collapse isOpen={this.state.commentary}> <TabContent activeTab={this.state.activeTab}> {this.props.comments.commentary !== undefined && <> {this.props.comments.commentary.innings.map((ings) => ( <> {ings.id === this.state.activeTab && <Fragment> <h3 className="m-3" style={{ color: "crimson" }}>{ings.name}</h3> {ings.overs.map((over) => ( <Fragment> <div className="col-lg-12 text-black" style={{ backgroundColor: "lightgray", fontSize: "18px" }}> {over.overSummary !== undefined && <> <span className="avatar" style={{ top: "10px" }}> <img src={over.overSummary.bowlersImage !== undefined ? over.overSummary.bowlersImage : playerImage} className="img-avatar" alt="Player Image" /> <span className="avatar-status badge-success"></span> </span> <span className="mt-2" style={{ position: "relative", bottom: "0px" }}> <span className="ml-3 mr-4 mb-1"><strong>{over.overSummary.bowlersName}{' '}</strong></span> <span>Total{' '}{over.overSummary.bowlersBowlingFigures}</span></span> <div className="mt-3 mb-2 pb-2"> <span className="mt-2 mr-2"><strong>{over.number}<sup>th</sup>OVER,{' '}</strong></span> <span className="mt-2 mr-2">Runs Conceded:{' '}{over.overSummary.runsConcededinOver}</span> <span className="mt-2 mr-2">Wickets:{' '}{over.overSummary.wicketsTakeninOver}</span> <span className="mt-2 mr-2">{over.overSummary.extrasConcededinOver}</span> </div> </> } </div> {over.balls.map((ball) => ( <Fragment> <> <Row className="mb-3"> {ball.comments.map((cmt) => ( <> {cmt.ballType !== "NonBallComment" ? <Fragment> <Col className="col-lg-2 ml-3 text-center" style={{ fontSize: "25px" }}> <strong> {over.number - 1}. {ball.ballNumber} </strong> <div> {/* {cmt.isFallOfWicket && (this.wicket_detail.push({ "wkt_det": cmt.wicketSummary, "bowler": cmt.bowlerId }))} */} {cmt.isFallOfWicket ? <Badge pill color="danger">OUT</Badge> : <> {cmt.runs === "4" ? <Badge pill color="success">4</Badge> : <> {cmt.runs === "6" && <Badge pill color="primary">6</Badge>} </> } </> } </div> </Col> <Col className="ml-3 mr-3" style={{ fontSize: "20px" }}> {cmt.text} {cmt.isFallOfWicket && <> {cmt.wicketSummary !== undefined && <div style={{ position: "relative", bottom: "10px" }}> <span className="avatar" style={{ top: "10px" }}> <img src={cmt.wicketSummary.batsmanImage !== undefined ? cmt.wicketSummary.batsmanImage : playerImage} className="img-avatar" alt="Player Image" /> <span className="avatar-status badge-success"></span> </span> <span style={{ position: "absolute", bottom: "0px" }}> <span className="ml-2" style={{ color: "red" }}>{cmt.wicketSummary.batsmanName}</span> <span className="ml-2"><strong>Runs:{' '}</strong>{cmt.wicketSummary.batsmanRuns}</span> <span className="ml-2"><strong>Balls:{' '}</strong>{cmt.wicketSummary.ballsFaced}</span> <span className="ml-2"><strong>4s:{' '}</strong>{cmt.wicketSummary.batsman4sinInnings}</span> <span className="ml-2"><strong>6s:{' '}</strong>{cmt.wicketSummary.batsman6sinInnings}</span> <span className="ml-2"><strong>SR:{' '}</strong>{cmt.wicketSummary.strikeRate}</span> </span> </div> } </> } </Col> </Fragment> : ""} </> ))} </Row> </> </Fragment> ))} </Fragment> ))} </Fragment> } </> ))} </> } </TabContent> </Collapse> </ListGroupItem> </> } </> )) : ""} </div> </ModalBody> </Modal> } </div > ); } }
JavaScript
@provideTranslations @provideContext class FullTable extends Component { /** * constructor */ constructor(props) { // parent constructor super(props); // set translation this.t = this.props.t; // prepare cols this.cols = Object.keys(this.props.cols); // set initial state this.state = { list: [], activePage: 1, pageSize: this.props.pageSize }; } /** * componentWillMount() * executed directly before component will be mounted to DOM */ componentWillMount() { // load rows this.props.reloadRows(); } /** * updates given parts of the state * * @param state the state name to be updated * @param value the value for state */ updateState(state, value) { var currentState = this.state; // check if state exists currentState[state] = value; this.setState(currentState); } /** * getTableHead() * gets the head row of the table */ getTableHead() { // prepare head rows var headRows = []; // add col for row number headRows.push(<th key={0}>#</th>); // walk through cols for(var i = 0; i < this.cols.length; i++) { // add row headRows.push( <th key={i + 1} style={this.props.cols[this.cols[i]].width != undefined ? {minWidth: this.props.cols[this.cols[i]].width} : undefined} > {this.props.cols[this.cols[i]].title} </th> ); } // add info, view and action col if(typeof this.props.infoContent == 'function') { headRows.push(<th key={this.cols.length + 1}><FontAwesome name="info-circle" title={this.t('FullTable.info')} /></th>); } if(typeof this.props.viewContent == 'function') { headRows.push(<th key={this.cols.length + 2}><FontAwesome name="eye" title={this.t('FullTable.views')} /></th>); } if(typeof this.props.actionContent == 'function') { headRows.push(<th key={this.cols.length + 3}><FontAwesome name="tasks" title={this.t('FullTable.tasks')} /></th>); } // return head return ( <thead> <tr> {headRows} </tr> </thead> ); } /** * getTableBody(rows) * gets and formats the body rows of the table * * @param array rows the list of rows to display in body */ getTableBody(rows) { // prepare body rows var bodyRows = []; // walk through data for(var i = 0; i < rows.length; i++) { // prepare cols var cols = []; // calculate row numbers var rowNumber = 0; if(this.state.activePage == 1) { rowNumber = i + 1; } else if(this.state.activePage == 2){ rowNumber = i + 1 + this.state.pageSize; } else { rowNumber = i + 1 + ((this.state.activePage -1) * this.state.pageSize); } // add number col cols.push( <td key={0}>{rowNumber}</td> ); // walk through cols for(var j = 0; j < this.cols.length; j++) { // format if function "content" is set var content = rows[i][this.cols[j]]; if(this.props.cols[this.cols[j]].content != undefined) { content = this.props.cols[this.cols[j]].content(rows[i][this.cols[j]]); } // prepare on click handler var onClick = undefined; var style = undefined; var title = undefined; if(this.props.cols[this.cols[j]].onClick != undefined && this.props.cols[this.cols[j]].isClickable(rows[i]) === true) { onClick = this.props.cols[this.cols[j]].onClick.bind(this, rows[i]); style = {cursor: "pointer"}; title = this.props.cols[this.cols[j]].onClickTitle; } cols.push( <td key={j + 1} onClick={onClick} style={style} title={title} > {content} </td> ); } // add view and settings cols if(typeof this.props.infoContent == 'function') { cols.push(<td key={this.cols.length + 1} style={{cursor: "default"}}>{this.props.infoContent(rows[i])}</td>); } if(typeof this.props.viewContent == 'function') { cols.push(<td key={this.cols.length + 2}>{this.props.viewContent(rows[i])}</td>); } if(typeof this.props.actionContent == 'function') { cols.push(<td key={this.cols.length + 3}>{this.props.actionContent(rows[i])}</td>); } // add row bodyRows.push( <tr key={i}> {cols} </tr> ); } // return body return ( <tbody> {bodyRows} </tbody> ); } /** * handlePagination(page, pageSize) * eventhandler to handle the state change from pagination * * @param int page the new/current page number * @param int pageSize the new/current count of items per page */ handlePagination(page, pageSize) { // update states this.updateState('activePage', parseInt(page, 10)); this.updateState('pageSize', parseInt(pageSize, 10)); // reload rows this.props.reloadRows(); } /** * method to render the component */ /* cols: { id: { title: string, content: func(value), width: number, onClick: func(value, completeRow) }, title: { } } */ render() { var allRows = this.props.rows; var page = this.state.activePage; var pageSize = this.state.pageSize; // calculate start/end var start = 0; if(page != 1) { start = pageSize * (page - 1); } var end = (start + pageSize > allRows.length ? allRows.length : start + pageSize); // get rows var rows = []; for(var i = start; i < end; i++) { rows.push(allRows[i]); } // get page count var pageCount = (allRows.length % pageSize != 0 ? Math.floor(allRows.length / pageSize) + 1 : Math.floor(allRows.length / pageSize)); return ( <div> <Toolbar config={this.props.toolbarConfig} /> <p></p> <Table striped bordered condensed hover responsive > {this.getTableHead()} {this.getTableBody(rows)} </Table> <PaginationPagesize activePage={this.state.activePage} pageSize={this.state.pageSize} pageCount={pageCount} onSelect={this.handlePagination.bind(this)} /> </div> ); } }
JavaScript
class SchedulerProBase extends SchedulerBase { //region Config static get $name() { return 'SchedulerProBase'; } static get type() { return 'schedulerprobase'; } static get configurable() { return { projectModelClass : ProjectModel }; } static get isSchedulerPro() { return true; } //endregion //region Internal // Overrides grid to take project loading into account toggleEmptyText() { const me = this; if (me.bodyContainer) { DomHelper.toggleClasses(me.bodyContainer, 'b-grid-empty', !(me.rowManager.rowCount || me.project.isLoadingOrSyncing)); } } // Needed to work with Gantt features get taskStore() { return this.project.eventStore; } //endregion internalAddEvent(startDate, resourceRecord, row) { // If task editor is active dblclick will trigger number of async actions: // store add which would schedule project commit // editor cancel on next animation frame // editor hide // rejecting previous transaction // and there is also dependency feature listening to transitionend on scheduler to draw lines after // It can happen that user dblclicks too fast, then event will be added, then dependency will schedule itself // to render, and then event will be removed as part of transaction rejection from editor. So we cannot add // event before active transaction is done. if (this.taskEdit && this.taskEdit.isEditing) { this.on({ aftertaskedit : () => super.internalAddEvent(startDate, resourceRecord, row), once : true }); } else { return super.internalAddEvent(startDate, resourceRecord, row); } } }
JavaScript
class Polytype { constructor(dimensions, delimiter = '&') { this.delimiter = delimiter; this.globalStr = '_GLOBAL_'; if (!Array.isArray(dimensions)) { throw new XError(XError.INVALID_ARGUMENT, 'dimensions must be an array'); } for (let dimension of dimensions) { if (!(dimension instanceof Dimension)) { throw new XError(XError.INVALID_ARGUMENT, `${dimension} is not an instance of Dimension`); } } this.dimensions = dimensions; } /** * Generate and return a set of tokens that contain the given range tuple as accurately as possible. * * @method getRangeTokens * @param {Mixed[]} rangeTuple * @return {String[]} tokens - Set of tokens which comprise this range. */ getRangeTokens(rangeTuple) { return this._getPolyTypeTokens('range', rangeTuple); } /** * Return the set of tokens to which a point can potentially belong. Any tokenized range that contains at least * one of these tokens also contains this point. * * @method getTokensForPoint * @param {Mixed[]} pointTuple * @return {String[]} token - Set of tokens which contain this point. */ getTokensForPoint(pointTuple) { return this._getPolyTypeTokens('point', pointTuple); } /** * Generate polyType tokens given either an array of ranges or an array of points * * @method _getPolyTypeTokens * @private * @param {String} type - can either be 'range' or 'point' * @param {Mixed[]} tuple - an array of ranges or points, Should be consistant with `type` * @throws {XError} - throws an xerror instance with code `invalid_argument` * @return {String[]} - return generated tokens */ _getPolyTypeTokens(type, tuple) { if (!tuple) return []; if (!Array.isArray(tuple)) { throw new XError(XError.INVALID_ARGUMENT, `${type} tuple must be an array`); } if (tuple.length !== this.dimensions.length) { throw new XError(XError.INVALID_ARGUMENT, `${type} tuple length must equal to number of dimensions`); } let dimensionTokens = []; for (let i = 0; i < tuple.length; i++) { let element = tuple[i]; let dimension = this.dimensions[i]; let curDimensionTokens = []; if (type === 'point') { // Generate point tokens curDimensionTokens = dimension.getTokensForPoint(element); if (dimension.globalToken) { curDimensionTokens.push(this.globalStr); } } else { // Generate range tokens if (dimension.globalToken && element === this.globalStr) { curDimensionTokens = [ this.globalStr ]; } else { curDimensionTokens = dimension.getRangeTokens(element); } } dimensionTokens.push(curDimensionTokens); } let tokens = []; this._getTokens(dimensionTokens, 0, '', tokens); return tokens; } /** * Recursively "multiply" the given dimension tokens and generate tokens for this polytype. * * @method _getTokens * @private * @param {String[][]} dimensionTokens - array of tokens generated by each dimension * @param {Number} index - index of current dimension in the array * @param {String} token - the polytype token generated b so far iterated dimensions * @param {string[]} tokens - generated tokens so far */ _getTokens(dimensionTokens, index, token = '', tokens) { if (index === this.dimensions.length) { tokens.push(token); return; } let dimension = this.dimensions[index]; for (let dimensionToken of dimensionTokens[index]) { if (dimensionToken.indexOf(this.delimiter) >= 0) { throw new XError(`${dimension.getName()} token contains polytype token delimiter ${this.delimiter}`); } let curToken = `${token}${dimensionToken}`; if (index < this.dimensions.length - 1) curToken += this.delimiter; this._getTokens(dimensionTokens, index + 1, curToken, tokens); } } /** * Perform a definitive test on whether the given range includes the given point. This is used * because the tokenization done by this libray is an approximation. If an accurate result is desired, this * can be called after a database query on the tokens returns, in order to filter out the 'accidental' matches. * * @method checkRangeInclusion * @param {Mixed} rangeTuple * @param {Mixed} pointTuple * @return {Boolean} - True if the point is inside the range, false otherwise. */ checkRangeInclusion(rangeTuple, pointTuple) { if (rangeTuple.length !== this.dimensions.length || pointTuple.length !== this.dimensions.length) { throw new XError(XError.INVALID_ARGUMENT, 'Tuple length must be equal to number of dimensions'); } for (let i = 0; i < this.dimensions.length; i++) { let dimension = this.dimensions[i]; if (dimension.globalToken && rangeTuple[i] === this.globalStr) { continue; // Always match a global range } if (!dimension.checkRangeInclusion(rangeTuple[i], pointTuple[i])) return false; } return true; } }
JavaScript
class InputBase { get polling() { let dt = performance.now() - this._lastPollingTime; return dt < 1_000; } /** @abstract */ get value() { return 0; } /** @protected */ get size() { return this._size; } /** * @abstract * @param {number} size The initial binding state size. */ constructor(size) { /** @private */ this._size = size; /** @private */ this._lastPollingTime = Number.MIN_SAFE_INTEGER; } /** * Called to internally resize to accomodate more/less * binding states. * * @protected * @param {number} newSize */ resize(newSize) { this._size = newSize; } /** * @abstract * @param {BindingIndex} code * @returns {number} */ // eslint-disable-next-line no-unused-vars getState(code) { throw new Error('Missing implementation.'); } /** * @abstract * @param {BindingIndex} code * @param {number} value * @param {number} delta */ // eslint-disable-next-line no-unused-vars onUpdate(code, value, delta) { throw new Error('Missing implementation.'); } /** * @abstract * @param {BindingIndex} code * @param {number} value */ // eslint-disable-next-line no-unused-vars onStatus(code, value) { throw new Error('Missing implementation.'); } /** * Called to poll all bound states. * * @param {number} now */ onPoll(now) { this._lastPollingTime = now; } /** * Called to bind a state to the given binding code. * * @param {BindingIndex} code * @param {BindingOptions} [opts] */ // eslint-disable-next-line no-unused-vars onBind(code, opts = {}) { if (code >= this._size) { this.resize(code + 1); } } /** * Called to unbind all states. */ onUnbind() { this.resize(0); } }
JavaScript
class Axis extends InputBase { /** @returns {AxisBindingState} */ static createAxisBindingState() { return { value: 0, delta: 0, inverted: false, }; } /** @returns {number} */ get delta() { return this._delta; } /** * @override * @returns {number} */ get value() { return this._value; } /** * @param {number} [size] */ constructor(size = 0) { super(size); let state = new Array(); for(let i = 0; i < size; ++i) { state.push(this.constructor.createAxisBindingState()); } /** * @private * @type {Array<AxisBindingState>} */ this._state = state; /** @private */ this._value = 0; /** @private */ this._delta = 0; } /** * @override * @protected */ resize(newSize) { let oldState = this._state; let oldSize = oldState.length; let newState; if (newSize <= oldSize) { newState = oldState.slice(0, newSize); } else { newState = oldState; // Fill with new states for(let i = oldSize; i < newSize; ++i) { newState.push(this.constructor.createAxisBindingState()); } } this._state = newState; super.resize(newSize); } /** * @override * @param {BindingIndex} code * @returns {number} */ getState(code) { return this._state[code].value; } /** * @override * @param {number} now */ onPoll(now) { let state = this._state; let accumulatedValue = 0; let accumulatedDelta = 0; const len = state.length; for(let i = 0; i < len; ++i) { let value = state[i]; accumulatedValue += value.value * (value.inverted ? -1 : 1); accumulatedDelta += value.delta; state[i].delta = 0; } this._value = accumulatedValue; this._delta = accumulatedDelta; super.onPoll(now); } /** * @override * @param {BindingIndex} code * @param {number} value * @param {number} delta */ onUpdate(code, value, delta) { if (typeof value === 'undefined') { this.onAxisChange(code, delta); } else { this.onAxisMove(code, value, delta); } } /** * @override * @param {BindingIndex} code * @param {number} value */ onStatus(code, value) { this.onAxisStatus(code, value); } /** * @override * @param {BindingIndex} code * @param {BindingOptions} [opts] */ onBind(code, opts = {}) { super.onBind(code, opts); const { inverted = false } = opts; let state = this._state; state[code].inverted = inverted; } /** * @protected * @param {BindingIndex} code * @param {number} x * @param {number} dx */ onAxisMove(code, x, dx) { let state = this._state[code]; state.value = x; state.delta += dx; } /** * @protected * @param {BindingIndex} code * @param {number} dx */ onAxisChange(code, dx) { let state = this._state[code]; state.value += dx; state.delta += dx; } /** * @protected * @param {BindingIndex} code * @param {number} x */ onAxisStatus(code, x) { let state = this._state[code]; let prev = state.value; state.value = x; state.delta = x - prev; } }
JavaScript
class InputDevice { /** @abstract */ // eslint-disable-next-line no-unused-vars static isAxis(code) { return false; } /** @abstract */ // eslint-disable-next-line no-unused-vars static isButton(code) { return false; } /** * @param {string} deviceName * @param {EventTarget} eventTarget */ constructor(deviceName, eventTarget) { if (!eventTarget) { throw new Error(`Missing event target for device ${deviceName}.`); } this.name = deviceName; this.eventTarget = eventTarget; /** * @private * @type {Record<string, Array<InputDeviceEventListener>>} */ this.listeners = { input: [] }; } /** * @param {EventTarget} eventTarget */ setEventTarget(eventTarget) { if (!eventTarget) { throw new Error(`Missing event target for device ${this.name}.`); } this.eventTarget = eventTarget; } destroy() { let listeners = this.listeners; for(let event in listeners) { listeners[event].length = 0; } } /** * @param {string} event * @param {InputDeviceEventListener} listener */ addEventListener(event, listener) { let listeners = this.listeners; if (event in listeners) { listeners[event].push(listener); } else { listeners[event] = [listener]; } } /** * @param {string} event * @param {InputDeviceEventListener} listener */ removeEventListener(event, listener) { let listeners = this.listeners; if (event in listeners) { let list = listeners[event]; let i = list.indexOf(listener); if (i >= 0) { list.splice(i, 1); } } } /** * @param {InputDeviceEvent} e * @returns {boolean} Whether the input event should be consumed. */ dispatchInputEvent(e) { let flag = 0; for(let listener of this.listeners.input) { flag |= listener(e); } return Boolean(flag); } }
JavaScript
class KeyboardDevice extends InputDevice { /** @override */ // eslint-disable-next-line no-unused-vars static isAxis(keyCode) { return false; } /** @override */ // eslint-disable-next-line no-unused-vars static isButton(keyCode) { return true; } /** * Constructs a listening keyboard with no listeners (yet). * * @param {string} deviceName * @param {EventTarget} eventTarget * @param {object} [opts] Any additional options. * @param {boolean} [opts.ignoreRepeat] Whether to * accept repeated key events. */ constructor(deviceName, eventTarget, opts = {}) { super(deviceName, eventTarget); const { ignoreRepeat = true } = opts; this.ignoreRepeat = ignoreRepeat; /** * @private * @type {InputDeviceEvent} */ this._eventObject = { target: eventTarget, device: deviceName, code: '', event: '', // Key values value: 0, control: false, shift: false, alt: false, }; /** @private */ this.onKeyDown = this.onKeyDown.bind(this); /** @private */ this.onKeyUp = this.onKeyUp.bind(this); eventTarget.addEventListener('keydown', this.onKeyDown); eventTarget.addEventListener('keyup', this.onKeyUp); } /** @override */ setEventTarget(eventTarget) { if (this.eventTarget) this.destroy(); super.setEventTarget(eventTarget); eventTarget.addEventListener('keydown', this.onKeyDown); eventTarget.addEventListener('keyup', this.onKeyUp); } /** @override */ destroy() { let eventTarget = this.eventTarget; eventTarget.removeEventListener('keydown', this.onKeyDown); eventTarget.removeEventListener('keyup', this.onKeyUp); super.destroy(); } /** * @private * @param {KeyboardEvent} e */ onKeyDown(e) { if (e.repeat && this.ignoreRepeat) { e.preventDefault(); e.stopPropagation(); return false; } let event = this._eventObject; // We care more about location (code) than print char (key). event.code = e.code; event.event = 'pressed'; event.value = 1; event.control = e.ctrlKey; event.shift = e.shiftKey; event.alt = e.altKey; let result = this.dispatchInputEvent(event); if (result) { e.preventDefault(); e.stopPropagation(); return false; } } /** * @private * @param {KeyboardEvent} e */ onKeyUp(e) { /** @type {InputDeviceEvent} */ let event = this._eventObject; // We care more about location (code) than print char (key). event.code = e.code; event.event = 'released'; event.value = 1; event.control = e.ctrlKey; event.shift = e.shiftKey; event.alt = e.altKey; let result = this.dispatchInputEvent(event); if (result) { e.preventDefault(); e.stopPropagation(); return false; } } }
JavaScript
class MouseDevice extends InputDevice { /** @override */ static isAxis(keyCode) { return keyCode === 'PosX' || keyCode === 'PosY' || keyCode === 'WheelX' || keyCode === 'WheelY' || keyCode === 'WheelZ'; } /** @override */ static isButton(keyCode) { return !this.isAxis(keyCode); } /** * Constructs a listening mouse with no listeners (yet). * * @param {string} deviceName * @param {EventTarget} eventTarget * @param {Object} [opts] Any additional options. * @param {Boolean} [opts.eventsOnFocus=true] Whether to capture events only when it has focus. */ constructor(deviceName, eventTarget, opts = {}) { super(deviceName, eventTarget); const { eventsOnFocus = true } = opts; this.eventsOnFocus = eventsOnFocus; this.canvasTarget = this.getCanvasFromEventTarget(eventTarget); /** @private */ this._downHasFocus = false; /** * @private * @type {InputDeviceEvent} */ this._eventObject = { target: eventTarget, device: deviceName, code: '', event: '', // Button values value: 0, control: false, shift: false, alt: false, }; /** * @private * @type {InputDeviceEvent} */ this._positionObject = { target: eventTarget, device: deviceName, code: '', event: 'move', // Pos values value: 0, movement: 0, }; /** * @private * @type {InputDeviceEvent} */ this._wheelObject = { target: eventTarget, device: deviceName, code: '', event: 'wheel', // Wheel values movement: 0, }; /** @private */ this.onMouseDown = this.onMouseDown.bind(this); /** @private */ this.onMouseUp = this.onMouseUp.bind(this); /** @private */ this.onMouseMove = this.onMouseMove.bind(this); /** @private */ this.onContextMenu = this.onContextMenu.bind(this); /** @private */ this.onWheel = this.onWheel.bind(this); eventTarget.addEventListener('mousedown', this.onMouseDown); eventTarget.addEventListener('contextmenu', this.onContextMenu); eventTarget.addEventListener('wheel', this.onWheel); document.addEventListener('mousemove', this.onMouseMove); document.addEventListener('mouseup', this.onMouseUp); } /** @override */ setEventTarget(eventTarget) { if (this.eventTarget) this.destroy(); super.setEventTarget(eventTarget); this.canvasTarget = this.getCanvasFromEventTarget(eventTarget); eventTarget.addEventListener('mousedown', this.onMouseDown); eventTarget.addEventListener('contextmenu', this.onContextMenu); eventTarget.addEventListener('wheel', this.onWheel); document.addEventListener('mousemove', this.onMouseMove); document.addEventListener('mouseup', this.onMouseUp); } /** @override */ destroy() { let eventTarget = this.eventTarget; eventTarget.removeEventListener('mousedown', this.onMouseDown); eventTarget.removeEventListener('contextmenu', this.onContextMenu); eventTarget.removeEventListener('wheel', this.onWheel); document.removeEventListener('mousemove', this.onMouseMove); document.removeEventListener('mouseup', this.onMouseUp); super.destroy(); } setPointerLock(force = true) { if (force) { this.eventTarget.requestPointerLock(); } else { this.eventTarget.exitPointerLock(); } } hasPointerLock() { return document.pointerLockElement === this.eventTarget; } /** * @private * @param {MouseEvent} e */ onMouseDown(e) { this._downHasFocus = true; let event = this._eventObject; // We care more about location (code) than print char (key). event.code = 'Button' + e.button; event.event = 'pressed'; event.value = 1; event.control = e.ctrlKey; event.shift = e.shiftKey; event.alt = e.altKey; let result = this.dispatchInputEvent(event); if (result) { // Make sure it has focus first. if (document.activeElement === this.eventTarget) { e.preventDefault(); e.stopPropagation(); return false; } } } /** * @private * @param {MouseEvent} e */ onContextMenu(e) { e.preventDefault(); e.stopPropagation(); return false; } /** * @private * @param {WheelEvent} e */ onWheel(e) { let dx, dy, dz; switch(e.deltaMode) { case WheelEvent.DOM_DELTA_LINE: dx = e.deltaX * DEFAULT_LINE_PIXELS; dy = e.deltaY * DEFAULT_LINE_PIXELS; dz = e.deltaZ * DEFAULT_LINE_PIXELS; break; case WheelEvent.DOM_DELTA_PAGE: dx = e.deltaX * DEFAULT_PAGE_PIXELS; dy = e.deltaY * DEFAULT_PAGE_PIXELS; dz = e.deltaZ * DEFAULT_PAGE_PIXELS; break; case WheelEvent.DOM_DELTA_PIXEL: default: dx = e.deltaX; dy = e.deltaY; dz = e.deltaZ; break; } let result = 0; let event = this._wheelObject; event.code = 'WheelX'; event.movement = dx; result |= this.dispatchInputEvent(event); event.code = 'WheelY'; event.movement = dy; result |= this.dispatchInputEvent(event); event.code = 'WheelZ'; event.movement = dz; result |= this.dispatchInputEvent(event); if (result) { e.preventDefault(); e.stopPropagation(); return false; } } /** * @private * @param {MouseEvent} e */ onMouseUp(e) { // Make sure mouse down was pressed before this (with focus). if (!this._downHasFocus) return; this._downHasFocus = false; let event = this._eventObject; // We care more about location (code) than print char (key). event.code = 'Button' + e.button; event.event = 'released'; event.value = 1; event.control = e.ctrlKey; event.shift = e.shiftKey; event.alt = e.altKey; let result = this.dispatchInputEvent(event); if (result) { e.preventDefault(); e.stopPropagation(); return false; } } /** * @private * @param {MouseEvent} e */ onMouseMove(e) { if (this.eventsOnFocus && document.activeElement !== this.eventTarget) return; const element = this.canvasTarget; const { clientWidth, clientHeight } = element; const rect = element.getBoundingClientRect(); let dx = e.movementX / clientWidth; let dy = e.movementY / clientHeight; let x = (e.clientX - rect.left) / clientWidth; let y = (e.clientY - rect.top) / clientHeight; let event = this._positionObject; event.code = 'PosX'; event.value = x; event.movement = dx; this.dispatchInputEvent(event); event.code = 'PosY'; event.value = y; event.movement = dy; this.dispatchInputEvent(event); } /** @private */ getCanvasFromEventTarget(eventTarget) { if (eventTarget instanceof HTMLCanvasElement) { return eventTarget; } else { return eventTarget.canvas || eventTarget.querySelector('canvas') || (eventTarget.shadowRoot && eventTarget.shadowRoot.querySelector('canvas')) || eventTarget; } } }
JavaScript
class AutoPoller { /** * @param {Pollable} pollable */ constructor(pollable) { /** @private */ this.onAnimationFrame = this.onAnimationFrame.bind(this); /** @private */ this.animationFrameHandle = null; /** @private */ this.pollable = pollable; } get running() { return this.animationFrameHandle !== null; } start() { let handle = this.animationFrameHandle; if (handle) cancelAnimationFrame(handle); this.animationFrameHandle = requestAnimationFrame(this.onAnimationFrame); } stop() { let handle = this.animationFrameHandle; if (handle) cancelAnimationFrame(handle); this.animationFrameHandle = null; } /** @private */ onAnimationFrame(now) { this.animationFrameHandle = requestAnimationFrame(this.onAnimationFrame); this.pollable.onPoll(now); } }
JavaScript
class DeviceInputAdapter { /** * @param {InputBindings} bindings */ constructor(bindings) { /** @private */ this.onInput = this.onInput.bind(this); this.onPoll = this.onPoll.bind(this); this.bindings = bindings; } onPoll(now) { for(let input of this.bindings.getInputs()) { input.onPoll(now); } } onInput(e) { const { device, code, event, value, movement, // eslint-disable-next-line no-unused-vars control, shift, alt, } = e; let bindings = this.bindings.getBindings(device, code); switch(event) { case 'pressed': for(let { input, index } of bindings) { input.onUpdate(index, 1, 1); } break; case 'released': for(let { input, index } of bindings) { input.onUpdate(index, 0, -1); } break; case 'move': for(let { input, index } of bindings) { input.onUpdate(index, value, movement); } break; case 'wheel': for(let { input, index } of bindings) { input.onUpdate(index, undefined, movement); } break; } return bindings.length > 0; } }
JavaScript
class InputBindings { constructor() { /** * @private * @type {Record<DeviceName, Record<KeyCode, Array<Binding>>} */ this.bindingMap = {}; /** * @private * @type {Map<InputBase, Array<Binding>>} */ this.inputMap = new Map(); } clear() { for(let input of this.inputMap.keys()) { input.onUnbind(); } this.inputMap.clear(); this.bindingMap = {}; } /** * @param {InputBase} input * @param {DeviceName} device * @param {KeyCode} code * @param {BindingOptions} [opts] */ bind(input, device, code, opts = {}) { let binding; let inputMap = this.inputMap; if (inputMap.has(input)) { let bindings = inputMap.get(input); let index = input.size; input.onBind(index, opts); binding = new Binding(device, code, input, index); bindings.push(binding); } else { let bindings = []; inputMap.set(input, bindings); let index = 0; input.onBind(index, opts); binding = new Binding(device, code, input, index); bindings.push(binding); } let bindingMap = this.bindingMap; if (device in bindingMap) { if (code in bindingMap[device]) { bindingMap[device][code].push(binding); } else { bindingMap[device][code] = [binding]; } } else { bindingMap[device] = { [code]: [binding] }; } } /** * @param {InputBase} input */ unbind(input) { let inputMap = this.inputMap; if (inputMap.has(input)) { let bindingMap = this.bindingMap; let bindings = inputMap.get(input); for(let binding of bindings) { let { device, code } = binding; let boundList = bindingMap[device][code]; let i = boundList.indexOf(binding); boundList.splice(i, 1); } bindings.length = 0; input.onUnbind(); inputMap.delete(input); } } /** * @param {InputBase} input * @returns {boolean} */ isBound(input) { return this.inputMap.has(input); } /** @returns {IterableIterator<InputBase>} */ getInputs() { return this.inputMap.keys(); } /** @returns {IterableIterator<Binding>} */ getBindingsByInput(input) { return this.inputMap.get(input); } /** * @param {DeviceName} device * @param {KeyCode} code * @returns {IterableIterator<Binding>} */ getBindings(device, code) { let deviceCodeBindings = this.bindingMap; if (device in deviceCodeBindings) { let codeBindings = deviceCodeBindings[device]; if (code in codeBindings) { return codeBindings[code]; } } return []; } }
JavaScript
class WindowRootNode extends BasicRootNode { /** @override */ onFocus() { super.onFocus(); let focusNode = this.automationNode; while (focusNode.className !== 'BrowserFrame' && focusNode.parent.role === chrome.automation.RoleType.WINDOW) { focusNode = focusNode.parent; } focusNode.focus(); } /** * Creates the tree structure for a window node. * @param {!AutomationNode} windowNode * @return {!WindowRootNode} */ static buildTree(windowNode) { const root = new WindowRootNode(windowNode); const childConstructor = (node) => BasicNode.create(node, root); BasicRootNode.findAndSetChildren(root, childConstructor); return root; } }
JavaScript
class ContractService { constructor(rootStore) { this._contract = {}; this.rootStore = rootStore; this.sysQuestions = JSON.parse(fs.readFileSync(path.join(PATH_TO_CONTRACTS, './sysQuestions.json'), 'utf8')); this.ercAbi = JSON.parse(fs.readFileSync(path.join(PATH_TO_CONTRACTS, './ERC20.abi'))); } /** * sets instance of contract to this._contract * @param {object} instance instance of contract created by Web3Service */ // eslint-disable-next-line consistent-return setContract(instance) { const { Web3Service: { web3 } } = this.rootStore; if (!(instance instanceof web3.eth.Contract)) return new Error('this is not contract'); this._contract = instance; } /** * compiles contracts and returning type of compiled contract, bytecode & abi * @param {string} type - ERC20 - if compiling ERC20 token contract, project - if project contract * @returns {object} contains type of compiled contract, his bytecode and abi for deploying */ compileContract(type) { return new Promise((resolve, reject) => { window.BrowserSolc.getVersions((sources, releases) => { const version = releases['0.4.24']; const contract = this.combineContract(type); const contractName = type === 'ERC20' ? ':ERC20' : ':Voter'; window.BrowserSolc.loadVersion(version, (compiler) => { const compiledContract = compiler.compile(contract); const contractData = compiledContract.contracts[contractName]; if (contractData.interface !== '') { const { bytecode, metadata } = contractData; const { output: { abi } } = JSON.parse(metadata); resolve({ type, bytecode, abi }); } else reject(new Error('Something went wrong on contract compiling')); }); }); }); } /** * reading all imports in main contract file and importing all files in one output file * @param {string} type type of project - ERC20 for ERC-20 tokens, Project for project contract * @returns {string} combined contracts */ // eslint-disable-next-line class-methods-use-this combineContract(type) { const dir = type === 'ERC20' ? './' : './Voter/'; const compiler = 'pragma solidity ^0.4.24;'; const pathToMainFile = type === 'ERC20' ? path.join(PATH_TO_CONTRACTS, `${dir}ERC20.sol`) : path.join(PATH_TO_CONTRACTS, `${dir}Voter.sol`); const importedFiles = {}; let output = readSolFile(pathToMainFile, importedFiles); output = output.replace(SOL_VERSION_REGEXP, compiler); output = output.replace(/(calldata)/g, ''); return output; } /** * Sendind transaction with contract to blockchain * @param {object} params parameters for deploying * @param {array} params.deployArgs ERC20 - [Name, Symbol, Count], Project - [tokenAddress] * @param {string} params.bytecode bytecode of contract * @param {JSON} params.abi JSON interface of contract * @param {string} params.password password of user wallet * @returns {Promise} Promise of web3.sendSignedTransaction which resolves on txHash */ deployContract({ deployArgs, bytecode, abi, password, }) { const { rootStore: { Web3Service, userStore } } = this; const { address } = userStore; const maxGasPrice = 30000000000; const contract = Web3Service.createContractInstance(abi); const txData = contract.deploy({ data: `0x${bytecode}`, arguments: deployArgs, }).encodeABI(); const tx = { data: txData, gasLimit: 8000000, gasPrice: maxGasPrice, }; return new Promise((resolve) => { Web3Service.createTxData(address, tx, maxGasPrice) .then((formedTx) => userStore.singTransaction(formedTx, password)) .then((signedTx) => Web3Service.sendSignedTransaction(`0x${signedTx}`)) .then((txHash) => resolve(txHash)); }); } /** * checks erc20 tokens contract on totalSupply and symbol * @param {string} address address of erc20 contract * @return {object} {totalSypply, symbol} */ async checkTokens(address) { const { rootStore: { Web3Service }, ercAbi } = this; const contract = Web3Service.createContractInstance(ercAbi); contract.options.address = address; const totalSupply = await contract.methods.totalSupply().call(); const symbol = await contract.methods.symbol().call(); return { totalSupply, symbol }; } /** * checks is the address of contract * @param {string} address address of contract * @return {Promise} Promise with function which resolves, if address is contract */ // eslint-disable-next-line class-methods-use-this checkProject(address) { const { rootStore: { Web3Service } } = this; return new Promise((resolve, reject) => { Web3Service.web3.eth.getCode(address).then((bytecode) => { if (bytecode === '0x') reject(); resolve(bytecode); }); }); } /** * calling contract method * @param {string} method method, which will be called * @param {string} from address of caller * @param params parameters for method */ async callMethod(method, ...params) { const data = await this._contract.methods[method](...params).call(); return data; } /** * checks count of uploaded to contract questions and total count of system questions * @function * @returns {object} {countOfUploaded, totalCount} */ async checkQuestions() { const countOfUploaded = await this._contract.methods.getCount().call(); const totalCount = Object.keys(this.sysQuestions).length; return ({ countOfUploaded, totalCount }); } /** * send question to created contract * @param {number} idx id of question; * @return {Promise} Promise, which resolves on transaction hash */ async sendQuestion(idx) { const { Web3Service, userStore, } = this.rootStore; const sysQuestion = this.sysQuestions[idx]; await this.fetchQuestion(idx).then((result) => { if (result.caption === '') { const { address, password } = userStore; const question = new Question(sysQuestion); const contractAddr = this._contract.options.address; const params = question.getUploadingParams(contractAddr); const dataTx = this._contract.methods.saveNewQuestion(...params).encodeABI(); const maxGasPrice = 30000000000; const rawTx = { to: contractAddr, data: dataTx, gasLimit: 8000000, value: '0x0', }; return new Promise((resolve) => { Web3Service.createTxData(address, rawTx, maxGasPrice) .then((formedTx) => userStore.singTransaction(formedTx, password)) .then((signedTx) => Web3Service.sendSignedTransaction(`0x${signedTx}`)) .then((txHash) => resolve(txHash)); }); } return Promise.reject(); }); } /** * Fetching one question from contract * @param {number} id id of question * @returns {Object} Question data from contract */ fetchQuestion(id) { return this.callMethod('question', [id]); } /** * getting one voting * @param {number} id id of voting * @param {string} from address who calls method */ async fetchVoting(id) { return this.callMethod('getVoting', [id]); } /** * getting votes weights for voting * @param {number} id id of voting * @param {string} from address, who calls */ async fetchVotingStats(id) { return this.callMethod('getVotingStats', [id]); } /** * Starting the voting * @param {id} id id of question * @param {string} from address, who starts * @param params parameters of voting */ async sendVotingStart(id, from, params) { return (this, id, from, params); } /** * Finishes the voting */ async sendVotingFinish() { return this; } }
JavaScript
class ToFastaBGZFEntry extends Transform { constructor (options) { if (! options) options = {}; options.objectMode = true; super(options); this._buffer = new FastaBuffer(); this._curr = new FastaBGZFEntry(); } _transform (indata,encoding,callback) { this._buffer.push(indata); var fdata = this._buffer.read(); for (let i = 0; i < fdata.length; i++) { if (fdata[i].head) { if (this._curr.header) { // we have a header defined this.push(this._curr); this._curr = new FastaBGZFEntry(); } this._curr.header = fdata[i].head; } if (fdata[i].seq) { this._curr.add_seq(fdata[i].seq); } } callback(); } _flush (callback) { let fdata = this._buffer.drain(); for (let i = 0; i < fdata.length; i++) { if (fdata[i].head) { if (this._curr.header) { // we have a header defined this.push(this._curr); this._curr = new FastaEntry(); } this._curr.header = fdata[i].head; } if (fdata[i].seq) { this._curr.add_seq(fdata[i].seq); } } if (this._curr.header) this.push(this._curr); callback(); } }
JavaScript
class Recorder { constructor (url, interval, size) { this._writer = new Writer(url, size) this._scheduler = new Scheduler(() => this._writer.flush(), interval) } init () { this._scheduler.start() } record (span) { this._writer.append(span) } }
JavaScript
class DevopsPropertyManager extends Devops { constructor(devopsSettings, dependencies) { super(devopsSettings, dependencies); this.promoteEmailString = "emails for activation: "; } async createPipeline() { //Overwrite the super class to do nothing } /** * Creates a whole new Property. Async since a bunch of REST calls are being made * * @param createPropertyInfo * @returns {Promise.<*>} */ async createProperty(createPropertyInfo) { logger.info("creating new property with info:", helpers.jsonStringify(createPropertyInfo)); let ruleTree; let project = this.getProject(createPropertyInfo.projectName, false); if (project.exists()) { if (createPropertyInfo.isInRetryMode) { logger.info(`Property folder '${project.projectFolder}' already exists, ignore`); } else { throw new errors.ArgumentError(`Property folder '${project.projectFolder}' already exists`, "property_folder_already_exists", project.projectFolder); } } project.validateEnvironmentNames(createPropertyInfo.environments); if (_.isString(createPropertyInfo.propertyName) && !_.isNumber(createPropertyInfo.propertyId)) { let results = await this.getPAPI().findProperty(createPropertyInfo.propertyName); if (results.versions.items.length === 0) { throw new errors.ArgumentError(`Can't find any versions for property '${createPropertyInfo.propertyName}'`); } createPropertyInfo.propertyId = helpers.parsePropertyId(results.versions.items[0].propertyId); } if (_.isNumber(createPropertyInfo.propertyId)) { logger.info(`Attempting to load rule tree for property id: ${createPropertyInfo.propertyId} and version: ${createPropertyInfo.propertyVersion}`); let propertyInfo = await project.getPropertyInfo(createPropertyInfo.propertyId, createPropertyInfo.propertyVersion); ruleTree = await project.getPropertyRuleTree(createPropertyInfo.propertyId, propertyInfo.propertyVersion); if (!createPropertyInfo.groupId) { let defaultGroupId = helpers.parseGroupId(propertyInfo.groupId); createPropertyInfo.groupId = defaultGroupId; } if (!createPropertyInfo.contractId) { createPropertyInfo.contractId = propertyInfo.contractId; } if (!createPropertyInfo.productId) { createPropertyInfo.productId = propertyInfo.productId; } if (!_.isBoolean(createPropertyInfo.secureOption)) { createPropertyInfo.secureOption = ruleTree.rules.options.is_secure; } if (!createPropertyInfo.propertyVersion) { createPropertyInfo.propertyVersion = propertyInfo.propertyVersion; } } else { createPropertyInfo.secureOption = createPropertyInfo.secureOption || false; } logger.info('Creating new PM CLI property with data: ', helpers.jsonStringify(createPropertyInfo)); if (createPropertyInfo.noLocalFolders) { logger.info('Creating new PM CLI property without local folders'); let results = await this.getPAPI().createProperty(project.projectName, createPropertyInfo.productId, createPropertyInfo.contractId, createPropertyInfo.groupId, null, createPropertyInfo.propertyId, createPropertyInfo.propertyVersion); return results; } if (!project.exists()) { project.createProjectFolders(createPropertyInfo); } //Creating "environment" let env = project.getEnvironment(project.getName()); await env.create(createPropertyInfo); await project.setupPropertyTemplate(ruleTree, createPropertyInfo.variableMode); return project; } /** * Imports Property from Property Manager. Async since a bunch of REST calls are being made * * @param createPropertyInfo * @returns {Promise.<*>} */ async importProperty(createPropertyInfo) { //validate property name if (!_.isString(createPropertyInfo.propertyName)) { throw new errors.ArgumentError(`Property name '${createPropertyInfo.propertyName}' is not a string`, "property_name_not_string", createPropertyInfo.propertyName); } //check if property already exists locally let project = this.getProject(createPropertyInfo.propertyName, false); if (project.exists()) { throw new errors.ArgumentError(`Property folder '${createPropertyInfo.propertyName}' already exists locally`, "property_folder_already_exists", createPropertyInfo.propertyName); } //check if property exists on server let results = await this.getPAPI().findProperty(createPropertyInfo.propertyName); if (results.versions.items.length === 0) { throw new errors.ArgumentError(`Can't find any version of property '${createPropertyInfo.propertyName}'`, "property_does_not_exist_on_server", createPropertyInfo.propertyName); } createPropertyInfo.propertyId = helpers.parsePropertyId(results.versions.items[0].propertyId); let propertyInfo = await project.getPropertyInfo(createPropertyInfo.propertyId); createPropertyInfo.propertyVersion = propertyInfo.propertyVersion; logger.info(`Attempting to load rule tree for property id: ${createPropertyInfo.propertyId} and version: ${createPropertyInfo.propertyVersion}`); let ruleTree = await project.getPropertyRuleTree(createPropertyInfo.propertyId, createPropertyInfo.propertyVersion); createPropertyInfo.groupId = helpers.parseGroupId(propertyInfo.groupId); createPropertyInfo.contractId = helpers.prefixeableString('ctr_')(propertyInfo.contractId); createPropertyInfo.productId = helpers.prefixeableString('prd_')(propertyInfo.productId); createPropertyInfo.secureOption = ruleTree.rules.options.is_secure; createPropertyInfo.variableMode = createPropertyInfo.variableMode || helpers.allowedModes[1]; logger.info('Importing existing property with data: ', helpers.jsonStringify(createPropertyInfo)); //Creating project folder if (!project.exists()) { project.createProjectFolders(createPropertyInfo); } //Creating "environment" let env = project.getEnvironment(project.getName()); await env.importProperty(createPropertyInfo); await project.setupPropertyTemplate(ruleTree, createPropertyInfo.variableMode, true); return project; } async updateProperty(createPropertyInfo) { logger.info("Updating property with info:", helpers.jsonStringify(createPropertyInfo)); let ruleTree; let project = this.getProject(createPropertyInfo.projectName, false); if (!project.exists()) { throw new errors.ArgumentError(`Property folder '${createPropertyInfo.projectName}' does not exist`, "property_folder_does_not_exist", createPropertyInfo.projectName); } let envInfo = project.loadEnvironmentInfo(); if (_.isString(envInfo.propertyName) && !_.isNumber(envInfo.propertyId)) { let results = await this.getPAPI().findProperty(envInfo.propertyName); if (results.versions.items.length === 0) { throw new errors.ArgumentError(`Can't find any versions for property '${envInfo.propertyName}'`); } envInfo.propertyId = helpers.parsePropertyId(results.versions.items[0].propertyId); } let propertyInfo = await project.getPropertyInfo(envInfo.propertyId); ruleTree = await project.getPropertyRuleTree(envInfo.propertyId, propertyInfo.propertyVersion); let projectInfo = project.getProjectInfo(); let isSecure = ruleTree.rules.options.is_secure; projectInfo.secureOption = isSecure; project.createProjectSettings(projectInfo); logger.info('Updating PM CLI property with data: ', helpers.jsonStringify(createPropertyInfo)); let env = project.getEnvironment(project.getName()); //Creating "environment" await env.update(isSecure); await project.setupPropertyTemplate(ruleTree, createPropertyInfo.variableMode, true); return project; } async checkActivations(propertyId, activationId) { let result = await this.getPAPI().activationStatus(propertyId, activationId); return result.activations.items[0]; } /** * Extract the desired project name either from devopsSettings.json file or * from the -p [project name] command line option * @param options * @param useDefault * @returns {null} */ extractProjectName(options) { let projectName = options ? options.property : null; if (!_.isString(projectName)) { projectName = this.getDefaultProjectName(); } return projectName; } /** * retrieve default property name from file. * @returns {*} */ getDefaultProjectName() { let projectName = this.devopsSettings.defaultProject; if (!projectName) { throw new errors.DependencyError("Can't read default property name from snippetsSettings.json " + "and no property name provided per -p <property name> option", "missing_default_property_file"); } return projectName; } /** * Merge config snippets into a merged rule tree for passed project name * @param projectName {string} * @param validate {boolean} send ruletree to validation endpoint? */ merge(projectName, validate = true) { return this.getEnvironment(projectName).merge(validate) } /** * Create Environment instance. Manages low level calls. Only 1 "environment" per property * @param projectName * @param environmentName */ getEnvironment(projectName) { const project = this.getProject(projectName); return project.getEnvironment(projectName); } /** * Sets the default property in snippetsSettings.json * @param propertyName {String} */ setDefaultProject(propertyName) { let project = this.getProject(propertyName); if (!project.exists()) { throw new errors.ArgumentError(`PM CLI property with name '${this.projectName}' doesn't exist.`, "pm_cli_does_not_exist", this.projectName); } logger.info(`Setting default property to '${propertyName}`); this.devopsSettings.defaultProject = propertyName; this.updateDevopsSettings({ defaultProject: propertyName }); } /** * Writes update to snippetsSettings.json * @param update {object} updated settings */ updateDevopsSettings(update) { logger.info("updating PM CLI settings"); let snippetsConfig = path.join(this.devopsHome, "snippetsSettings.json"); let settings = {}; if (this.utils.fileExists(snippetsConfig)) { settings = this.utils.readJsonFile(snippetsConfig); } settings = Object.assign(settings, update); this.utils.writeJsonFile(snippetsConfig, settings); if (this.devopsSettings.__savedSettings === undefined || this.devopsSettings.__savedSettings === null) { this.devopsSettings.__savedSettings = {}; } this.devopsSettings.__savedSettings = Object.assign(this.devopsSettings.__savedSettings, settings); } /** * Deactivate property on a newtwork * @param propertyName {String} * @param environmentName {String} * @param network {String} "STAGING" or "PRODUCTION" * @param emails {Array<String>} */ deactivate(propertyName, network, emails, message) { const project = this.getProject(propertyName); let emailSet = this.createEmailSet(emails); return project.deactivate(propertyName, network, emailSet, message); } }
JavaScript
class TestResource extends R.Resource { /** * Open resource * @returns {Promise} promise **/ open() { console.log('resource: opening in %d', process.pid); this.opened(); this.openedTime = Date.now(); return Promise.resolve(); } /** * Close resource * @returns {Promise} promise **/ close() { console.log('resource: closing in %d', process.pid); this.closed(); return Promise.resolve(); } /** * Kill resource * @returns {Promise} promise **/ kill() { console.log('resource: killed in %d', process.pid); return Promise.resolve(); } /** * Check if resource is used * @returns {Promise} promise **/ checkActive() { console.log('resource: checkActive in %d', process.pid); return Promise.resolve(Date.now() - this.openedTime < 20000); } /** Start using resource **/ start() { this.openedTime = Date.now(); super.start.apply(this, arguments); } }
JavaScript
class IPCTestJob extends J.IPCJob { /** * Prepare the job * @param {object} manager - resource manager * @param {Db} db - db connection */ async prepare(manager, db) { console.log('preparing in %d', process.pid); await new Promise((res, rej) => db.collection('jobs').updateOne({_id: this._id}, {$set: {'data.prepared': 1}}, err => err ? rej(err) : res())); } /** * Get resource name * @returns {string} resource name **/ resourceName() { return 'resource:test'; } /** * Create resource * @param {string} _id - resource _id * @param {string} name - resource name * @param {Db} db - db connection * @returns {Resource} resource */ createResource(_id, name, db) { return new TestResource(_id, name, db); } /** * Get retry policy * @returns {RetryPolicy} retry policy **/ retryPolicy() { return new RET.NoRetryPolicy(); } /** * Get concurrency * @returns {number} concurency **/ getConcurrency() { return this.data && this.data.concurrency || 0; } /** * Run the job * @param {Db} db connection */ async run(db) { console.log('running in %d', process.pid); should.exist(this.resource); (this.resource instanceof TestResource).should.be.true(); await new Promise((res, rej) => db.collection('jobs').updateOne({_id: this._id}, {$set: {'data.run': 1}}, err => err ? rej(err) : res())); if (this.data && this.data.fail) { throw new Error(this.data.fail); } if (this.data && this.data.concurrency) { await new Promise(res => setTimeout(res, 3000)); } console.log('done running in %d', process.pid); } }
JavaScript
class BootstrapStack { constructor(sdkProvider, sdk, resolvedEnvironment, toolkitStackName, currentToolkitInfo) { this.sdkProvider = sdkProvider; this.sdk = sdk; this.resolvedEnvironment = resolvedEnvironment; this.toolkitStackName = toolkitStackName; this.currentToolkitInfo = currentToolkitInfo; } static async lookup(sdkProvider, environment, toolkitStackName) { toolkitStackName = toolkitStackName !== null && toolkitStackName !== void 0 ? toolkitStackName : toolkit_info_1.DEFAULT_TOOLKIT_STACK_NAME; const resolvedEnvironment = await sdkProvider.resolveEnvironment(environment); const sdk = (await sdkProvider.forEnvironment(resolvedEnvironment, aws_auth_1.Mode.ForWriting)).sdk; const currentToolkitInfo = await toolkit_info_1.ToolkitInfo.lookup(resolvedEnvironment, sdk, toolkitStackName); return new BootstrapStack(sdkProvider, sdk, resolvedEnvironment, toolkitStackName, currentToolkitInfo); } get parameters() { return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.parameters : {}; } get terminationProtection() { return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.terminationProtection : undefined; } async partition() { return (await this.sdk.currentAccount()).partition; } /** * Perform the actual deployment of a bootstrap stack, given a template and some parameters */ async update(template, parameters, options) { var _a; const newVersion = bootstrapVersionFromTemplate(template); if (this.currentToolkitInfo.found && newVersion < this.currentToolkitInfo.version && !options.force) { logging.warning(`Bootstrap stack already at version '${this.currentToolkitInfo.version}'. Not downgrading it to version '${newVersion}' (use --force if you intend to downgrade)`); if (newVersion === 0) { // A downgrade with 0 as target version means we probably have a new-style bootstrap in the account, // and an old-style bootstrap as current target, which means the user probably forgot to put this flag in. logging.warning('(Did you set the \'@aws-cdk/core:newStyleStackSynthesis\' feature flag in cdk.json?)'); } return { noOp: true, outputs: {}, stackArn: this.currentToolkitInfo.bootstrapStack.stackId, }; } const outdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-bootstrap')); const builder = new cxapi.CloudAssemblyBuilder(outdir); const templateFile = `${this.toolkitStackName}.template.json`; await fs.writeJson(path.join(builder.outdir, templateFile), template, { spaces: 2 }); builder.addArtifact(this.toolkitStackName, { type: cxschema.ArtifactType.AWS_CLOUDFORMATION_STACK, environment: cxapi.EnvironmentUtils.format(this.resolvedEnvironment.account, this.resolvedEnvironment.region), properties: { templateFile, terminationProtection: (_a = options.terminationProtection) !== null && _a !== void 0 ? _a : false, }, }); const assembly = builder.buildAssembly(); return deploy_stack_1.deployStack({ stack: assembly.getStackByName(this.toolkitStackName), resolvedEnvironment: this.resolvedEnvironment, sdk: this.sdk, sdkProvider: this.sdkProvider, force: options.force, roleArn: options.roleArn, tags: options.tags, execute: options.execute, parameters, usePreviousParameters: true, // Obviously we can't need a bootstrap stack to deploy a bootstrap stack toolkitInfo: toolkit_info_1.ToolkitInfo.bootstraplessDeploymentsOnly(this.sdk), }); } }
JavaScript
class Main extends Client { constructor(options) { super(options); this.commands = new Collection(); this.aliases = new Collection(); this.database = new Collection(); } login(token) { token = process.env.TOKEN; return super.login(token).then(async () => [await this.initLoaders()]); } load(commandPath, commandName) { const props = new (require(`${commandPath}/${commandName}`))(this); props.location = commandPath; if (props.init) { props.init(this); } this.commands.set(props.name, props); props.aliases.forEach((aliases) => { this.aliases.set(aliases, props.name); }); return false; } async initLoaders() { return Files.requireDirectory("./src/loaders", (Loader) => { Loader.load(this).then( console.log(c.green("[Loaders] - Pasta Loaders carregada com sucesso.")) ); }); } async getLanguage(firstGuild) { if (!firstGuild) return; const guild = await Guild.findOne({ idS: !isNaN(firstGuild) ? firstGuild : firstGuild.id, }); if (guild) { let lang = guild.lang; if (lang === undefined) { guild.lang = "pt-BR"; guild.save(); return "pt-BR"; } else { return lang; } } else { await Guild.create({ idS: firstGuild.id }); return "pt-BR"; } } async getActualLocale() { return this.t; } async setActualLocale(locale) { this.t = locale; } async getTranslate(guild) { const language = await this.getLanguage(guild); const translate = new Locale("src/languages"); const t = await translate.init({ returnUndefined: false, }); translate.setLang(language); return t; } }
JavaScript
class AbstractImportUI { /** * Constructor. */ constructor() { /** * If local storage is required by the import process. * @type {boolean} */ this.requiresStorage = false; } /** * @inheritDoc */ getTitle() { return ''; } /** * @inheritDoc */ mergeConfig(from, to) { to['color'] = from['color']; to['icon'] = from['icon']; to['shapeName'] = from['shapeName']; to['description'] = from['description']; to['mappings'] = from['mappings']; to['tags'] = from['tags']; to['title'] = from['title']; } /** * @inheritDoc */ getDefaultConfig(file, config) { // implement a good default config for the individual import types return config; } /** * @inheritDoc */ handleDefaultImport(file, config) { // implemented by extending classes to support importing files with a known structure } }
JavaScript
class Convert { static toProjectResponse(json) { return JSON.parse(json); } static projectResponseToJson(value) { return JSON.stringify(value); } }
JavaScript
class FlowChart extends Component { constructor(props) { super(props); this.state = { tooltipVisible: false, tooltipIsRight: false, tooltipText: null, tooltipX: 0, tooltipY: 0 }; this.containerRef = React.createRef(); this.svgRef = React.createRef(); this.wrapperRef = React.createRef(); this.edgesRef = React.createRef(); this.nodesRef = React.createRef(); this.handleWindowResize = this.handleWindowResize.bind(this); this.handleNodeMouseOver = this.handleNodeMouseOver.bind(this); this.handleNodeMouseOut = this.handleNodeMouseOut.bind(this); } componentDidMount() { // Create D3 element selectors this.el = { svg: select(this.svgRef.current), wrapper: select(this.wrapperRef.current), edgeGroup: select(this.edgesRef.current), nodeGroup: select(this.nodesRef.current) }; this.updateChartSize(); this.initZoomBehaviour(); this.drawChart(); this.zoomChart(); window.addEventListener('resize', this.handleWindowResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowResize); } componentDidUpdate(prevProps) { if (prevProps.visibleNav !== this.props.visibleNav) { this.updateChartSize(); } if (prevProps.zoom !== this.props.zoom) { this.zoomChart(); } this.drawChart(); } /** * Configure globals for the container dimensions, * and apply them to the chart SVG */ updateChartSize() { const { left, top, width, height } = this.containerRef.current.getBoundingClientRect(); const navOffset = this.getNavOffset(width); this.props.onUpdateChartSize({ x: left, y: top, outerWidth: width, outerHeight: height, width: width - navOffset, height, navOffset }); } getNavOffset(width) { const navWidth = 300; // from _variables.scss const breakpointSmall = 480; // from _variables.scss if (this.props.visibleNav && width > breakpointSmall) { return navWidth; } return 0; } /** * Handle window resize */ handleWindowResize() { this.updateChartSize(); } /** * Setup D3 zoom behaviour on component mount */ initZoomBehaviour() { this.zoomBehaviour = zoom().on('zoom', () => { this.el.wrapper.attr('transform', event.transform); this.hideTooltip(); }); this.el.svg.call(this.zoomBehaviour); } /** * Zoom and scale to fit */ zoomChart() { const { chartSize, zoom } = this.props; const { scale, translateX, translateY } = zoom; const navOffset = this.getNavOffset(chartSize.outerWidth); this.el.svg .transition() .duration(DURATION) .call( this.zoomBehaviour.transform, zoomIdentity.translate(translateX + navOffset, translateY).scale(scale) ); } /** * Render chart to the DOM with D3 */ drawChart() { const { layout, textLabels } = this.props; const { nodes, edges } = layout; // Create selections this.el.edges = this.el.edgeGroup .selectAll('.edge') .data(edges, edge => edge.id); this.el.nodes = this.el.nodeGroup .selectAll('.node') .data(nodes, node => node.id); // Set up line shape function const lineShape = line() .x(d => d.x) .y(d => d.y) .curve(curveBasis); // Create edges const enterEdges = this.el.edges .enter() .append('g') .attr('class', 'edge') .attr('opacity', 0); enterEdges.append('path').attr('marker-end', d => `url(#arrowhead)`); this.el.edges .exit() .transition('exit-edges') .duration(DURATION) .attr('opacity', 0) .remove(); this.el.edges = this.el.edges.merge(enterEdges); this.el.edges .transition('show-edges') .duration(DURATION) .attr('opacity', 1); this.el.edges .select('path') .transition('update-edges') .duration(DURATION) .attrTween('d', function(edge) { const current = edge.points && lineShape(edge.points); const previous = select(this).attr('d') || current; return interpolatePath(previous, current); }); // Create nodes const enterNodes = this.el.nodes .enter() .append('g') .attr('class', 'node'); enterNodes .attr('transform', node => `translate(${node.x}, ${node.y})`) .attr('opacity', 0); enterNodes.append('circle').attr('r', 25); enterNodes.append('rect'); enterNodes.append(icon); enterNodes .append('text') .text(node => node.name) .attr('text-anchor', 'middle') .attr('dy', 4); this.el.nodes .exit() .transition('exit-nodes') .duration(DURATION) .attr('opacity', 0) .remove(); this.el.nodes = this.el.nodes .merge(enterNodes) .classed('node--data', node => node.type === 'data') .classed('node--task', node => node.type === 'task') .classed('node--icon', !textLabels) .classed('node--text', textLabels) .classed('node--active', node => node.active) .on('mouseover', this.handleNodeMouseOver) .on('mouseout', this.handleNodeMouseOut); this.el.nodes .transition('update-nodes') .duration(DURATION) .attr('opacity', 1) .attr('transform', node => `translate(${node.x}, ${node.y})`); this.el.nodes .select('rect') .attr('width', node => node.width - 5) .attr('height', node => node.height - 5) .attr('x', node => (node.width - 5) / -2) .attr('y', node => (node.height - 5) / -2) .attr('rx', node => (node.type === 'data' ? node.height / 2 : 0)); } /** * Event handler for toggling a node's active state, * showing tooltip, and highlighting linked nodes * @param {Object} node Datum for a single node */ handleNodeMouseOver(node) { const { layout, onToggleNodeActive } = this.props; onToggleNodeActive(node, true); this.showTooltip(node); linkedNodes.show({ el: this.el, nodeID: node.id, ...layout }); } /** * Event handler for toggling a node's active state, * hiding tooltip, and dimming linked nodes * @param {Object} node Datum for a single node */ handleNodeMouseOut(node) { this.props.onToggleNodeActive(node, false); linkedNodes.hide(this.el); this.hideTooltip(); } /** * Show, fill and and position the tooltip * @param {Object} node A node datum */ showTooltip(node) { const { chartSize } = this.props; const eventOffset = event.target.getBoundingClientRect(); const navOffset = this.getNavOffset(chartSize.outerWidth); const isRight = eventOffset.left - navOffset > chartSize.width / 2; const xOffset = isRight ? eventOffset.left - (chartSize.width + navOffset) : eventOffset.left; this.setState({ tooltipVisible: true, tooltipIsRight: isRight, tooltipText: node.name, tooltipX: xOffset - chartSize.x + eventOffset.width / 2, tooltipY: eventOffset.top - chartSize.y }); } /** * Hide the tooltip */ hideTooltip() { if (this.state.tooltipVisible) { this.setState({ tooltipVisible: false }); } } /** * Render React elements */ render() { const { outerWidth, outerHeight } = this.props.chartSize; const { tooltipVisible, tooltipIsRight, tooltipText, tooltipX, tooltipY } = this.state; return ( <div className="pipeline-flowchart kedro" ref={this.containerRef}> <svg className="pipeline-flowchart__graph" width={outerWidth} height={outerHeight} ref={this.svgRef}> <defs> <marker id="arrowhead" className="pipeline-flowchart__arrowhead" viewBox="0 0 10 10" refX="7" refY="5" markerUnits="strokeWidth" markerWidth="8" markerHeight="6" orient="auto"> <path d="M 0 0 L 10 5 L 0 10 L 4 5 z" /> </marker> </defs> <g ref={this.wrapperRef}> <g className="pipeline-flowchart__edges" ref={this.edgesRef} /> <g id="nodes" className="pipeline-flowchart__nodes" ref={this.nodesRef} /> </g> </svg> <div className={classnames('pipeline-flowchart__tooltip kedro', { 'tooltip--visible': tooltipVisible, 'tooltip--right': tooltipIsRight })} style={{ transform: `translate(${tooltipX}px, ${tooltipY}px)` }}> <span>{tooltipText}</span> </div> </div> ); } }
JavaScript
class FaqpageShortcode extends NunjucksShortcode { /** * Render. * * @param {object} context URL. * @param {Array} args Other arguments. * * @return {string} */ renderPaired(context, body, args) { //let ctxData = context.ctx; //let kwargs = args[0] || {}; if (!this.config.schema[context.ctx.permalink]) { this.config.schema[context.ctx.permalink] = new Schema(this.config); } this.config.schema[context.ctx.permalink].addRaw('faqpage', {name: args[0]}); let [html, text] = this.config.templateHandlers.markdown.handler.parseMarkdown(body); let ret = ''; ret += `<div class="faq">`; ret += html; ret += '</div>'; return ret; } }
JavaScript
class lite3 { /** * Create DB Connection with SQLite3 File * @param {string} file - Name of SQLite3 file to connect */ constructor(file) { this.db = new sqlite3.cached.Database(file); this.queryType = null; this.tableName = null; this.queryStmt = null; this.stmt = null; } /** * Sets lite3.tableName property to perform operations. * @param {string} tbl - Name of table to perform operations. * @returns {lite3} - The Class with lite3.tableName property now set. */ table(tbl) { this.tableName = tbl; return this; } /** * Prepares UPDATE statement to run with lite3.values() * @param {string} query - Sets lite3.stmt and UPDATE query syntax. * @returns {lite3} - Class with lite3.stmt & lite3.queryType property set. */ update(query) { this.stmt = this.db.prepare(`UPDATE ${this.tableName} SET ${query} WHERE id=?`); this.queryStmt = query; this.queryType = 'UPDATE'; return this; } /** * Prepares INSERT statement to run with lite3.values() * @param {string} query - Question marks equal to the amount of values inserting * @returns {lite3} - Class with lite3.stmt, lite3.queryStmt, lite3.queryType property set */ insert(query) { this.stmt = this.db.prepare(`INSERT INTO ${this.tableName} VALUES (${query})`); this.queryStmt = query; this.queryType = 'INSERT'; return this; } /** * Prepares DELETE statement to run with lite3.values() * @returns {lite3} - Class with lite3.queryType set. */ del() { this.stmt = this.db.prepare(`DELETE FROM ${this.tableName} WHERE id=?`); this.queryType = 'DELETE'; return this; } /** * Reassigns lite3.stmt with the new clause to perform query. * @param {string} clause - Clause to perform query. * @returns {lite3} - Class with clause set. */ clause(clause) { switch (this.queryType !== null) { case this.queryType == 'UPDATE': this.stmt = this.db.prepare(`UPDATE ${this.tableName} SET ${this.queryStmt} WHERE ${clause}`); break; case this.queryType == 'DELETE': this.stmt = this.db.prepare(`DELETE FROM ${this.tableName} WHERE ${clause}`); break; } return this; } /** * Sugar method which read like english. * @param {string} clause - Clause to include into new lite3.stmt. * @returns {lite3} - Class with clause set. */ where(clause) { return this.clause(clause); } /** * Runs values using lite3.stmt query created from lite3.update(), lite3.prepare() methods * @param {string} vals - Values to update or insert, must be in order with lite3.stmt to succeed * @param {boolean} [returnChange] - True to return promise of changed lastID and changes */ values(vals, returnChange) { if (returnChange !== true) { this.stmt.run(vals); this.stmt.finalize(); return; } return new Promise((resolve, reject) => { this.stmt.run(vals, [], (err, res) => { if (err) { reject(err); } else { resolve(this); } }) }) } /** * Returns a promise of SELECT * SQL query on the lite3.tableName property */ selectAll() { return new Promise((resolve, reject) => { this.db.all(`SELECT * FROM ${this.tableName}`, [], (err, res) => { if (err) { reject(Error(`Error finding rows associated with ${this.tableName} table`)) } resolve(res); }) }) } /** * Find a speicifc row in lite3.tableName with constraint * @param {string} clause - constraint on which row to find */ selectWhere(clause) { return new Promise((resolve, reject) => { this.db.get(`SELECT * FROM ${this.tableName} WHERE ${clause}`, (err, row) => { if (err) { reject(Error(`Unable to find row in the ${this.tableName} table WHERE ${clause}`)); return; } resolve(row); }) }) } /** * Returns a promise of schema on lite.tableName if lite.tableName == * return lite3.allTables() */ schema() { if (this.tableName !== '*') { return new Promise((resolve, reject) => { this.db.all(`PRAGMA TABLE_INFO(${this.tableName})`, (err, res) => { if (err) { reject(err) } resolve(res); }) }); } return this.allTables(); } /** * Returns a promise of all table names in the DB */ allTables() { return new Promise((resolve, reject) => { this.db.all('SELECT name FROM sqlite_master WHERE type="table"', (err, res) => { if (err) { reject(Error('Either invalid database on new lite3 instance or no existing tables in DB')); } resolve(res); }) }) } }
JavaScript
class CSSLibrary extends Library { /** * @constructor * @param {string} [fileName] Name of library file * @param {HTMLLinkElement|HTMLStyleElement} [element] Style or Link element of library * if empty then it will be style with content inside * otherwise it will be link with href=<lib-root>/filename */ constructor(fileName, element) { super(fileName, element); } /** * Creates HTML Element for library with basic attributes * @param {string} currentPath current file basepath * @returns {HTMLStyleElement|HTMLLinkElement} Element for library */ createHTMLElement(currentPath) { if (this.fileName) { this.element = document.createElement('link'); this.setAttribute('rel', 'stylesheet'); this.setAttribute('href', this.getRelativePath(currentPath)); } else { this.element = document.createElement('style'); } return this.element; } /** * get css selector of library element * @returns {string} css selector of particular library */ getSelector() { const minifiedName = `${basename(this.fileName, 'css')}min.css`; return `link[href$="${this.fileName}"], link[href$="${minifiedName}"]`; } }
JavaScript
class SubjectController { /** * Add a Subject test * @param {Request} req - Response object. * @param {Response} res - The payload. * @memberof SubjectController * @returns {JSON} - A JSON success response. * */ static async addSubject(req, res) { try { const subject = await Subject.create({ ...req.body }); return res.status(200).json({ status: 'success', data: { subject, }, }); } catch (error) { return res.status(500).json({ status: '500 Internal server error', error: 'Error Saving Subject', }); } } /** * get Subjects * @param {Request} req - Response object. * @param {Response} res - The payload. * @memberof SubjectController * @returns {JSON} - A JSON success response. * */ static async getSubjects(req, res) { try { const subjects = await Subject.find({}).populate( 'mainSubjectId courseId', ); return res.status(200).json({ status: 'success', data: { subjects, }, }); } catch (error) { return res.status(500).json({ status: '500 Internal server error', error: 'Error Saving Subject', }); } } }
JavaScript
class User { constructor(obj) { Object.assign(this, obj); this.meta = User.parseName(obj.username); } save(cb) { if(this.meta.save === 'success') { cb(null, this); } else { cb('error', null); } } }
JavaScript
class DIDUpdater { constructor(didBuilder) { this.didBuilder = didBuilder; this.originalManagementKeys = [...this.didBuilder._managementKeys]; this.originalDIDKeys = [...this.didBuilder._didKeys]; this.originalServices = [...this.didBuilder._services]; this.didKeyPurposesToRevoke = {}; } /** * @returns {ManagementKey[]} The current state of management keys. */ get managementKeys() { return this.didBuilder._managementKeys; } /** * @returns {DIDKey[]} The current state of DID keys. */ get didKeys() { /** Apply revocation of DID key purposes */ let didKeys = []; this.didBuilder._didKeys.forEach(key => { let revoked = false; Object.keys(this.didKeyPurposesToRevoke).forEach(alias => { if (alias === key.alias) { const revokedPurpose = this.didKeyPurposesToRevoke[alias]; const remainingPurpose = revokedPurpose === DIDKeyPurpose.PublicKey ? DIDKeyPurpose.AuthenticationKey : DIDKeyPurpose.PublicKey; didKeys.push( new DIDKey( key.alias, remainingPurpose, key.keyType, key.controller, key.priorityRequirement, key.publicKey, key.privateKey ) ); revoked = true; return; } }); if (!revoked) { didKeys.push(key); } }); return didKeys; } /** * @returns {Services[]} The current state of services. */ get services() { return this.didBuilder._services; } /** * Adds a management key to the DIDBuilder object. * @param {string} alias * @param {number} priority * @param {KeyType} [keyType] * @param {string} [controller] * @param {number} [priorityRequirement] * @returns {DIDUpdater} - DIDUpdater instance. */ addManagementKey(alias, priority, keyType = KeyType.EdDSA, controller, priorityRequirement) { this.didBuilder.managementKey(alias, priority, keyType, controller, priorityRequirement); return this; } /** * Adds a DID key to the DIDBuilder object. * @param {string} alias * @param {DIDKeyPurpose | DIDKeyPurpose[]} purpose * @param {KeyType} [keyType] * @param {string} [controller] * @param {number} [priorityRequirement] * @returns {DIDUpdater} - DIDUpdater instance. */ addDIDKey(alias, purpose, keyType = KeyType.EdDSA, controller, priorityRequirement) { this.didBuilder.didKey(alias, purpose, keyType, controller, priorityRequirement); return this; } /** * Adds a new service to the DIDBuilder object. * @param {string} alias * @param {string} serviceType * @param {string} endpoint * @param {number} [priorityRequirement] * @param {Object} [customFields] * @returns {DIDUpdater} */ addService(alias, serviceType, endpoint, priorityRequirement, customFields) { this.didBuilder.service(alias, serviceType, endpoint, priorityRequirement, customFields); return this; } /** * Revokes a management key from the DIDBuilder object. * @param {string} alias - The alias of the key to be revoked * @returns {DIDUpdater} */ revokeManagementKey(alias) { this.didBuilder._managementKeys = this.didBuilder._managementKeys.filter( k => k.alias !== alias ); return this; } /** * Revokes a DID key from the DIDBuilder object. * @param {string} alias - The alias of the key to be revoked * @returns {DIDUpdater} */ revokeDIDKey(alias) { this.didBuilder._didKeys = this.didBuilder._didKeys.filter(k => k.alias !== alias); return this; } /** * Revokes a single purpose of a DID key from the DIDBuilder object. * @param {string} alias - The alias of the key to be revoked * @param {DIDKeyPurpose} purpose - The purpose to revoke * @returns {DIDUpdater} */ revokeDIDKeyPurpose(alias, purpose) { if (![DIDKeyPurpose.AuthenticationKey, DIDKeyPurpose.PublicKey].includes(purpose)) { return this; } const didKey = this.didBuilder._didKeys.find(k => k.alias === alias); if (!didKey) { return this; } if (!didKey.purpose.includes(purpose)) { return this; } if (didKey.purpose.length === 1) { return this.revokeDIDKey(alias); } else { this.didKeyPurposesToRevoke[alias] = purpose; return this; } } /** * Revokes a service from the DIDBuilder object. * @param {string} alias - The alias of the service to be revoked * @returns {DIDUpdater} */ revokeService(alias) { this.didBuilder._services = this.didBuilder._services.filter(k => k.alias !== alias); return this; } /** * Rotates a management key. * @param {string} alias - The alias of the management key to be rotated * @returns {DIDUpdater} */ rotateManagementKey(alias) { const managementKey = this.didBuilder._managementKeys.find(k => k.alias === alias); if (managementKey) { this.didBuilder._managementKeys = this.didBuilder._managementKeys.filter( k => k.alias !== alias ); const managementKeyClone = Object.assign({}, managementKey); Object.setPrototypeOf(managementKeyClone, ManagementKey.prototype); managementKeyClone.rotate(); this.didBuilder._managementKeys.push(managementKeyClone); } return this; } /** * Rotates a DID key. * @param {string} alias - The alias of the DID key to be rotated * @returns {DIDUpdater} */ rotateDIDKey(alias) { const didKey = this.didBuilder._didKeys.find(k => k.alias === alias); if (didKey) { this.didBuilder._didKeys = this.didBuilder._didKeys.filter(k => k.alias !== alias); const didKeyClone = Object.assign({}, didKey); Object.setPrototypeOf(didKeyClone, DIDKey.prototype); didKeyClone.rotate(); this.didBuilder._didKeys.push(didKeyClone); } return this; } exportEntryData() { if (!this.didBuilder._managementKeys.some(k => k.priority === 0)) { throw new Error('DIDUpdate entry would leave no management keys of priority zero.'); } const newMgmtKeysResult = this._getNew( this.originalManagementKeys, this.didBuilder._managementKeys ); const newDIDKeysResult = this._getNew(this.originalDIDKeys, this.didBuilder._didKeys); const newServicesResult = this._getNew(this.originalServices, this.didBuilder._services); const revokedMgmtKeysResult = this._getRevoked( this.originalManagementKeys, this.didBuilder._managementKeys ); const revokedDIDKeysResult = this._getRevoked( this.originalDIDKeys, this.didBuilder._didKeys ); const revokedServicesResult = this._getRevoked( this.originalServices, this.didBuilder._services ); const addObject = this._constructAddObject( newMgmtKeysResult.new, newDIDKeysResult.new, newServicesResult.new ); const revokeObject = this._constructRevokeObject( revokedMgmtKeysResult.revoked, revokedDIDKeysResult.revoked, revokedServicesResult.revoked ); Object.keys(this.didKeyPurposesToRevoke).forEach(alias => { try { revokeObject['didKey'].push({ id: `${this.didBuilder._id}#${alias}`, purpose: [this.didKeyPurposesToRevoke[alias]] }); } catch (e) { revokeObject['didKey'] = [ { id: `${this.didBuilder._id}#${alias}`, purpose: [this.didKeyPurposesToRevoke[alias]] } ]; } }); const updateEntryContent = {}; if (Object.keys(addObject).length > 0) { updateEntryContent['add'] = addObject; } if (Object.keys(revokeObject).length > 0) { updateEntryContent['revoke'] = revokeObject; } if (Object.keys(updateEntryContent).length === 0) { throw new Error('The are no changes made to the DID.'); } const signingKey = this.originalManagementKeys.sort((a, b) => a.priority - b.priority)[0]; /** Currently unreachable code! const updateKeyRequiredPriority = Math.min( newMgmtKeysResult.requiredPriorityForUpdate, revokedMgmtKeysResult.requiredPriorityForUpdate, revokedDIDKeysResult.requiredPriorityForUpdate, revokedServicesResult.requiredPriorityForUpdate ); if (signingKey.priority > updateKeyRequiredPriority) { throw new Error( `The update requires a key with priority <= ${updateKeyRequiredPriority}, but the highest priority key available is with priority ${signingKey.priority}` ); } */ const signingKeyId = signingKey.fullId(this.didBuilder._id); const entryContent = JSON.stringify(updateEntryContent); const dataToSign = ''.concat( EntryType.Update, ENTRY_SCHEMA_V100, signingKeyId, entryContent ); const sha256Hash = createHash('sha256'); sha256Hash.update(Buffer.from(dataToSign)); const signature = signingKey.sign(sha256Hash.digest()); const extIds = [ Buffer.from(EntryType.Update), Buffer.from(ENTRY_SCHEMA_V100), Buffer.from(signingKeyId), Buffer.from(signature) ]; const entrySize = calculateEntrySize(extIds, Buffer.from(entryContent)); if (entrySize > ENTRY_SIZE_LIMIT) { throw new Error('You have exceeded the entry size limit!'); } return { extIds, content: Buffer.from(entryContent) }; } _getNew(original, current) { let _new = []; let requiredPriorityForUpdate = Number.POSITIVE_INFINITY; const originalStrArray = original.map(e => JSON.stringify(e)); current.forEach(obj => { if (!originalStrArray.includes(JSON.stringify(obj))) { _new.push(obj.toEntryObj(this.didBuilder._id)); if (obj.priority && obj.priority < requiredPriorityForUpdate) { requiredPriorityForUpdate = obj.priority; } } }); return { new: _new, requiredPriorityForUpdate }; } _getRevoked(original, current) { let revoked = []; let requiredPriorityForUpdate = Number.POSITIVE_INFINITY; const currentStrArray = current.map(e => JSON.stringify(e)); original.forEach(obj => { if (!currentStrArray.includes(JSON.stringify(obj))) { revoked.push({ id: `${this.didBuilder._id}#${obj.alias}` }); if ( obj.priorityRequirement && obj.priorityRequirement < requiredPriorityForUpdate ) { requiredPriorityForUpdate = obj.priorityRequirement; } if ( obj.priority && !obj.priorityRequirement && obj.priority < requiredPriorityForUpdate ) { requiredPriorityForUpdate = obj.priority; } } }); return { revoked, requiredPriorityForUpdate }; } _constructAddObject(newManagementKeys, newDidKeys, newServices) { const add = {}; if (newManagementKeys.length > 0) { add['managementKey'] = newManagementKeys; } if (newDidKeys.length > 0) { add['didKey'] = newDidKeys; } if (newServices.length > 0) { add['service'] = newServices; } return add; } _constructRevokeObject(revokedManagementKeys, revokedDidKeys, revokedServices) { const revoke = {}; if (revokedManagementKeys.length > 0) { revoke['managementKey'] = revokedManagementKeys; } if (revokedDidKeys.length > 0) { revoke['didKey'] = revokedDidKeys; } if (revokedServices.length > 0) { revoke['service'] = revokedServices; } return revoke; } }
JavaScript
class CommandData { constructor(name, reference, parameter) { this.name = name; this.reference = reference; if (parameter) { this.parameter = parameter; } } execute(data) { return __awaiter(this, void 0, void 0, function* () { let parameterValues = this.parameter.map((current) => data[current]); return yield this.reference(...parameterValues); }); } }
JavaScript
class ComparisonConfigService { /** * @param {?} _http * @param {?} _config */ constructor(_http, _config) { this._http = _http; this._config = _config; this._comparisonConfig = new BehaviorSubject(new ComparisonConfig()); this._updatedConfig = this._comparisonConfig.asObservable(); } /** * @return {?} */ get updatedConfig() { return this._updatedConfig; } /** * @return {?} */ load() { return new Promise((/** * @param {?} resolve * @param {?} reject * @return {?} */ (resolve, reject) => { /** @type {?} */ const configEndpoint = this._config.getConfigEndpoint(Api.COMPARISON_APP); this._http.get(configEndpoint, Api.httpOptionsJson).toPromise().then((/** * @param {?} response * @return {?} */ (response) => { /** @type {?} */ const comparisonConfig = (/** @type {?} */ (response)); this._comparisonConfig.next(comparisonConfig); resolve(); })).catch((/** * @param {?} response * @return {?} */ (response) => { reject(`Could not load comparison config: ${JSON.stringify(response)}`); })); })); } }
JavaScript
class ComparisonService { /** * @param {?} _http * @param {?} _config */ constructor(_http, _config) { this._http = _http; this._config = _config; } /** * @param {?} path * @return {?} */ loadFiles(path) { return this._http.post(this._config.getComparisonApiEndpoint() + Api.LOAD_FILE_TREE, { 'path': path }, Api.httpOptionsJson); } /** * @return {?} */ getFormats() { return this._http.get(this._config.getComparisonApiEndpoint() + Api.LOAD_FORMATS, Api.httpOptionsJson); } /** * @param {?} credentials * @return {?} */ loadFile(credentials) { return this._http.post(this._config.getComparisonApiEndpoint() + Api.LOAD_DOCUMENT_DESCRIPTION, credentials, Api.httpOptionsJson); } /** * @param {?} file * @param {?} url * @param {?} rewrite * @return {?} */ upload(file, url, rewrite) { /** @type {?} */ const formData = new FormData(); formData.append("file", file); formData.append('rewrite', String(rewrite)); if (url) { formData.append("url", url); } return this._http.post(this._config.getComparisonApiEndpoint() + Api.UPLOAD_DOCUMENTS, formData); } /** * @param {?} file * @return {?} */ save(file) { return this._http.post(this._config.getComparisonApiEndpoint() + Api.SAVE_FILE, file, Api.httpOptionsJson); } /** * @param {?} credentials * @return {?} */ getDownloadUrl(credentials) { return this._config.getComparisonApiEndpoint() + Api.DOWNLOAD_DOCUMENTS + '/?guid=' + credentials.guid; } /** * @param {?} credentials * @param {?} page * @return {?} */ loadPage(credentials, page) { return this._http.post(this._config.getComparisonApiEndpoint() + Api.LOAD_DOCUMENT_PAGE, { 'guid': credentials.guid, 'password': credentials.password, 'page': page }, Api.httpOptionsJson); } /** * @param {?} arr * @return {?} */ compare(arr) { return this._http.post(this._config.getComparisonApiEndpoint() + Api.COMPARE_FILES, { 'guids': arr }, Api.httpOptionsJson); } }
JavaScript
class UploadFilePanelComponent { /** * @param {?} _uploadService * @param {?} _modalService */ constructor(_uploadService, _modalService) { this._uploadService = _uploadService; this._modalService = _modalService; this.active = new EventEmitter(); this.showUploadFile = false; } /** * @return {?} */ ngOnInit() { } /** * @return {?} */ openModal() { this.active.emit(this.panel); this._modalService.open(CommonModals.BrowseFiles); } /** * @param {?} $event * @return {?} */ dropped($event) { if ($event) { this.active.emit(this.panel); this.showUploadFile = false; } } }
JavaScript
class DifferencesService { constructor() { this._activeChange = new BehaviorSubject(null); this.activeChange = this._activeChange.asObservable(); } /** * @param {?} id * @return {?} */ setActiveChange(id) { this._activeChange.next(id); } }
JavaScript
class DifferenceComponent { /** * @param {?} changeService */ constructor(changeService) { this.changesService = changeService; } /** * @return {?} */ ngOnInit() { this.changesService.activeChange.subscribe((/** * @param {?} activeID * @return {?} */ activeID => this.active = this.change.id === activeID)); } /** * @param {?} value * @return {?} */ getRgbaColor(value) { return `rgba(${value.red},${value.green},${value.blue},${value.alpha})`; } }
JavaScript
class DifferencesComponent { /** * @param {?} changeService * @param {?} navigateService */ constructor(changeService, navigateService) { this.changes = []; this.changesService = changeService; this.navigateService = navigateService; } /** * @return {?} */ ngOnInit() { } /** * @param {?} id * @param {?} page * @param {?} event * @return {?} */ highlightDifference(id, page, event) { event.stopPropagation(); this.changesService.setActiveChange(id); this.navigateService.navigateTo(page + 1); } }
JavaScript
class BackupModel { constructor(data = {}) { this.BACKUPID = data.BACKUPID; this.date_created = data.date_created; this.description = data.description; this.size = data.size; this.status = data.status; } }
JavaScript
class ProjectedVector extends AVector { constructor(m, f, thisArgument = m, valuetype = m.valuetype, _idtype = m.rowtype) { super(null); this.m = m; this.f = f; this.thisArgument = thisArgument; this.valuetype = valuetype; this._idtype = _idtype; this.desc = { name: m.desc.name + '-p', fqname: m.desc.fqname + '-p', type: 'vector', id: m.desc.id + '-p', size: this.dim[0], idtype: m.rowtype, value: this.valuetype, description: m.desc.description, creator: m.desc.creator, ts: m.desc.ts }; this.root = this; } persist() { return { root: this.m.persist(), f: this.f.toString(), valuetype: this.valuetype === this.m.valuetype ? undefined : this.valuetype, idtype: this.idtype === this.m.rowtype ? undefined : this.idtype.name }; } restore(persisted) { let r = this; if (persisted && persisted.range) { //some view onto it r = r.view(ParseRangeUtils.parseRangeLike(persisted.range)); } return r; } get idtype() { return this._idtype; } get idtypes() { return [this._idtype]; } size() { return this.m.nrow; } /** * return the associated ids of this vector */ names(range) { return this.m.rows(range); } ids(range) { return this.m.rowIds(range); } /** * returns a promise for getting one cell * @param i */ async at(i) { const d = await this.m.data(Range.list(i)); return this.f.call(this.thisArgument, d[0]); } /** * returns a promise for getting the data as two dimensional array * @param range */ async data(range) { return (await this.m.data(range)).map(this.f, this.thisArgument); } async sort(compareFn, thisArg) { const d = await this.data(); const indices = ArrayUtils.argSort(d, compareFn, thisArg); return this.view(Range.list(indices)); } async filter(callbackfn, thisArg) { const d = await this.data(); const indices = ArrayUtils.argFilter(d, callbackfn, thisArg); return this.view(Range.list(indices)); } }
JavaScript
class HybridTabs { constructor ($container) { this.$tabButtons = $container.find('.js-tabs-button'); this.$tabContents = $container.find('.js-tabs-content'); this.tabsMode = null; } init (initialTabsMode) { this.tabsMode = initialTabsMode; const _this = this; this.$tabButtons.click((event) => HybridTabs.onClickTabButton(event, _this)); this.fixTabsState(); } setTabsMode (newTabsMode) { this.tabsMode = newTabsMode; this.fixTabsState(); } fixTabsState () { if (this.tabsMode === HybridTabs.TABS_MODE_SINGLE) { const $activeButtons = this.$tabButtons.filter('.active'); if ($activeButtons.length > 0) { this.activateOneTabAndDeactivateOther($activeButtons.last().data('tab-id')); } else { this.activateOneTabAndDeactivateOther(this.$tabButtons.first().data('tab-id')); } } else if (this.tabsMode === HybridTabs.TABS_MODE_MULTIPLE) { const _this = this; this.$tabContents.each(function () { const tabId = $(this).data('tab-id'); const $tabButton = _this.$tabButtons.filter('[data-tab-id="' + tabId + '"]'); const isTabActive = $tabButton.hasClass('active'); _this.toggleTab(tabId, isTabActive); }); } } static onClickTabButton (event, hybridTabs) { const tabId = $(event.currentTarget).data('tab-id'); if (hybridTabs.tabsMode === HybridTabs.TABS_MODE_SINGLE) { hybridTabs.activateOneTabAndDeactivateOther(tabId); } else if (hybridTabs.tabsMode === HybridTabs.TABS_MODE_MULTIPLE) { const isTabActive = $(event.currentTarget).hasClass('active'); hybridTabs.toggleTab(tabId, !isTabActive); } return false; } // activates exactly one tab (in "single" mode) activateOneTabAndDeactivateOther (tabId) { const _this = this; this.$tabButtons.each(function () { const currentTabId = $(this).data('tab-id'); const isCurrentTab = currentTabId === tabId; _this.toggleTab(currentTabId, isCurrentTab); }); } // use true to show the tab or false to hide it without checking single/multiple mode toggleTab (tabId, display) { const $tabButton = this.$tabButtons.filter('[data-tab-id="' + tabId + '"]'); const $tabContent = this.$tabContents.filter('[data-tab-id="' + tabId + '"]'); $tabButton.toggleClass('active', display); $tabContent.toggleClass('active', display); } }
JavaScript
class VConsolePlugin { constructor(id, name = 'newPlugin') { this.id = id; this.name = name; this.eventList = {}; } get id() { return this._id; } set id(value) { if (!value) { throw 'Plugin ID cannot be empty'; } this._id = value.toLowerCase(); } get name() { return this._name; } set name(value) { if (!value) { throw 'Plugin name cannot be empty'; } this._name = value; } get vConsole() { return this._vConsole || undefined; } set vConsole(value) { if (!value) { throw 'vConsole cannot be empty'; } this._vConsole = value; } /** * register an event * @public * @param string * @param function */ on(eventName, callback) { this.eventList[eventName] = callback; return this; } /** * trigger an event * @public * @param string * @param mixed */ trigger(eventName, data) { if (typeof this.eventList[eventName] === 'function') { // registered by `.on()` method this.eventList[eventName].call(this, data); } else { // registered by `.onXxx()` method let method = 'on' + eventName.charAt(0).toUpperCase() + eventName.slice(1); if (typeof this[method] === 'function') { this[method].call(this, data); } } return this; } } // END class
JavaScript
class Rank { constructor(name, abbr, low, high, colorClass) { this.name = name; this.abbr = abbr; this.low = low; this.high = high; this.colorClass = colorClass; } static forRating(rating) { if (rating == null) { return Rank.UNRATED; } for (const rank of Rank.RATED) { if (rating < rank.high) { return rank; } } return Rank.RATED[Rank.RATED.length - 1]; } }
JavaScript
class M_AbstractLight extends M_Element { constructor(glBoostContext) { super(glBoostContext); if (this.constructor === M_AbstractLight) { throw new TypeError('Cannot construct AbstractLight instances directly.'); } this._gl = this._glContext.gl; this._isCastingShadow = true; this._isLightType = ''; this._camera = null; } prepareToRender() { if (this._camera) { if (this._camera.customFunction) { this._camera.customFunction(this); } } } set isCastingShadow(flg) { this._isCastingShadow = flg; } get isCastingShadow() { return this._isCastingShadow; } get lightType() { return this._isLightType; } isTypeAmbient() { return this._isLightType === 'ambient'; } isTypeDirectional() { return this._isLightType === 'directional'; } isTypePoint() { return this._isLightType === 'point'; } isTypeSpot() { return this._isLightType === 'spot'; } set camera(camera) { this._camera = camera; } get camera() { return this._camera; } }
JavaScript
class PreformatFilter extends Filter { /** * @inheritDoc */ filter(element) { if (element instanceof HTMLElement && element.localName === TagName.FIGURE && element.classList.contains(Preformat.name) && element.querySelector(':scope > ' + TagName.PRE) && !element.querySelector(':scope > ' + TagName.FIGCAPTION) ) { element.insertAdjacentElement(Position.BEFOREBEGIN, element.querySelector(':scope > ' + TagName.PRE)); element.parentElement.removeChild(element); } } }
JavaScript
class StaticParticles { /** * * @param {String} id Unique ID for this object * @param {Array.Array.<Number>} points an array of X,Y,Z cartesian points, one for each particle * @param {Object} options container * @param {Color} options.defaultColor color to use for all particles can be a THREE string color name or hex value * @param {Number} options.size the size of each particle * @param {Object} contextOrSimulation Simulation context or simulation object */ constructor(id, points, options, contextOrSimulation) { this._options = options; this._id = id; // TODO(ian): Add to ctx if (true) { // User passed in Simulation this._simulation = contextOrSimulation; this._context = contextOrSimulation.getContext(); } else { // User just passed in options this._simulation = null; this._context = contextOrSimulation; } // Number of particles in the scene. this._particleCount = points.length; this._points = points; this._geometry = undefined; this.init(); this._simulation.addObject(this, true); } init() { const positions = new Float32Array(this._points.length * 3); const colors = new Float32Array(this._points.length * 3); const sizes = new Float32Array(this._points.length); let color = new THREE.Color(DEFAULT_COLOR); if (this._options.defaultColor) { color = new THREE.Color(this._options.defaultColor); } let size = DEFAULT_PARTICLE_SIZE; if (this._options.size) { size = this._options.size; } for (let i = 0, l = this._points.length; i < l; i++) { const vertex = this._points[i]; positions.set(vertex, i * 3); color.toArray(colors, i * 3); sizes[i] = size; } const geometry = new THREE.BufferGeometry(); geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3)); geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); geometry.addAttribute('size', new THREE.BufferAttribute(sizes, 1)); const material = new THREE.ShaderMaterial({ vertexColors: THREE.VertexColors, vertexShader: STAR_SHADER_VERTEX, fragmentShader: STAR_SHADER_FRAGMENT, transparent: true, }); this._geometry = new THREE.Points(geometry, material); } /** * A list of THREE.js objects that are used to compose the skybox. * @return {THREE.Object} Skybox mesh */ get3jsObjects() { return [this._geometry]; } /** * Get the unique ID of this object. * @return {String} id */ getId() { return this._id; } }
JavaScript
class IndexPage extends React.Component { constructor(props) { super(props) this.state = { code:"NA", } } componentDidMount(){ let code = window.location.hash.substr(1); this.setState({code: code}) var dataRef = JSON.parse(localStorage.getItem('paymentObj')); alert(dataRef); console.log(dataRef.type); const db = firebase.firestore(); db.settings({}); var docRef = db.collection(dataRef.type).doc(dataRef._id); docRef.update({ paid: 1 }) .then(() => { console.log("Document successfully updated!"); }) .catch((error) => { // The document probably doesn't exist. console.error("Error updating document: ", error); }); } render(){ return( <Layout> <div className="welcome-area" id="welcome"> <div className="header-text"> <div className="container"> <div className="row"> <div className="left-text col-lg-6 col-md-12 col-sm-12 col-xs-12" data-scroll-reveal="enter left move 30px over 0.6s after 0.4s"> <h1>Registered Successfully</h1> <p className="text-danger">We have made an confirmation email to the registered email address.</p> <a href="/" className="main-button-slider">Return Home</a> </div> <div className="hero-pic col-lg-6 col-md-12 col-sm-12 col-xs-12"> <img className="success-img" src={require(".././images/check.png")} alt="Nadanaloga Natyalaya"/> </div> </div> </div> </div> </div> </Layout> ) } }
JavaScript
class Keyboard { constructor() { autoBind(this); this.keysPressed = []; this.onNextKeyPress = function () {}; // custom mapping from key pressed to hex // does not follow the technical reference mapping this.keyMapping = { 0x0: 'X', 0x1: '1', 0x2: '2', 0x3: '3', 0x4: 'Q', 0x5: 'W', 0x6: 'E', 0x7: 'A', 0x8: 'S', 0x9: 'D', 0xA: 'Z', 0xB: 'C', 0xC: '4', 0xD: 'R', 0xE: 'F', 0xF: 'V', }; } /** * Event handler for keyDown event * simulates key being pressed * @param {KeyboardEvent} event args passed from event */ keyDown(event) { // decode from code to string const key = String.fromCharCode(event.which); // insert to know which key from the mapping was pressed this.keysPressed[key] = true; Object.entries(this.keyMapping).forEach(([oKey, oVal]) => { const keyCode = this.keyMapping[oVal]; // if key pressed exists if (keyCode === key) { try { this.onNextKeyPress(parseInt(oKey, 10)); } finally { this.onNextKeyPress = function () {}; } } }); } /** * Event handler for keyUp event * simulates key being unpressed * @param {KeyboardEvent} event args passed from event */ keyUp(event) { const key = String.fromCharCode(event.which); this.keysPressed[key] = false; } isKeyPressed(keyCode) { const keyPressed = this.keyMapping[keyCode]; // return the values truthy value return !!this.keysPressed[keyPressed]; } /** * Clear pressed keys */ clear() { this.keysPressed = []; } }
JavaScript
class DiscoverWpApi extends Component { constructor(props) { super(); let queryCreds = {}; const query = location.search; if (query.length) { // holds an array of paired params name and value const pairs = query.substr(1).split('&'); for (var i = pairs.length - 1; i >= 0; i--) { const _pair = pairs[i].split('='); queryCreds[_pair[0]] = _pair[1]; } // location.search = ''; } this.state = { view: '', creds: PTT.get('creds') || queryCreds, message: props.message || 'Let\'s find your site and get you authenticated.', processing: false, onDiscovered: props.onDiscovered || null, onUserFound: props.onUserFound || null, }; this._handleSubmit = this._handleSubmit.bind(this); this._selectUser = this._selectUser.bind(this); this._saveUserOnSelect = this._saveUserOnSelect.bind(this); } // called before the component is rendered to the page. componentWillMount() { this._checkCredentials(); } _checkCredentials() { if ( ! this.state.creds || ! this.state.creds.url || ! this.state.creds.key || ! this.state.creds.secret ) { PTT._reset(); } else { const message = 'Authenticating you..'; this.setState({ message: message, processing: true, }); // Discover the site. this._discoverSite( this.state.creds ); } } render() { const _view = (this.state.processing) ? <LoadingIcon message={this.state.message} /> : this._theForm(); return ( <div className="discover-wp-api"> {_view} </div> ); } // Returns the form. _theForm() { let callback = window.location.href; // Remove "index.html". callback = callback.replace( 'index.html', '' ) .replace( /\?.*/, '').replace( /#.*/, ''); callback += 'land.html'; const message = this.state.message; return ( <div className="discovery-form"> <form id="discover_form" onSubmit={this._handleSubmit}> <div className="message"> <p>{message}</p> </div> <div> <span>Use this as your callback:</span> <pre className="land-url"> <code>{callback}</code> </pre> </div> <div> <label>Site URL <input type="url" name="site_url" /> </label> </div> <div> <label>Client Key <input name="client_key" /> </label> </div> <div> <label>Client Secret <input name="client_secret" /> </label> </div> <button type="submit">Submit</button> </form> </div> ); } _handleSubmit(e) { e.preventDefault(); // Loading icon. this.setState({ message: 'Looking for your site..', processing: true }); // Get the data from the form. // const data = new FormData( e.target ); // holds an array of objects - each object // corresponds to one of the form fields. const _data = $('#discover_form').serializeArray(); let _creds = {}; for (var i = _data.length - 1; i >= 0; i--) { if (0 < _data[i].value.length) { _creds[_data[i].name] = _data[i].value; } else { this.setState( { message: <span className="error"> None of the fields can be empty. </span>, processing: false, }); return false; } } // Build our credentials object from our form // and normalize it for use later. const creds = { url: _creds.site_url, key: _creds.client_key, secret: _creds.client_secret, } // Discover the site. this._discoverSite( creds ); } /** * Finds the site and authenticates the user * * @param {Object} creds the credentials to authenticate user */ _discoverSite( creds ) { creds = creds || null; if ( ! creds ) { console.error( 'No credentials supplied to discover site.' ); return false; } // get the site fetch( creds.url + '/wp-json/' ) .then( resp => { resp.json() .then( site => { this.setState({ message: 'We found your site!' }); // we got the site, // let's authenticate the user const auth = window.wpApiAuth( { oauth_consumer_key: creds.key, oauth_secret: creds.secret, url: creds.api_url, urls: site.authentication.oauth1, singlepage: false, }); // save the endpoint for use later const endpoint = site.url + '/wp-json/wp/v2/premise_time_tracker'; // save the ptt object const newPtt = { creds, site, auth, endpoint, }; PTT.set( newPtt ); // save Cookies PTT.setCookies(); // authenticate! auth.authenticate( this._maybeAuthenticated.bind(this) ); }); }); } _maybeAuthenticated( error ) { if ( error ) { // console.log(error); const message = <span className="error"> {error.responseText} </span>; this.setState({ message }); } // if no errors else { this.setState({ message: 'You\'re authenticated!', }); // get user info if ( ! PTT.get('user') ) { this._getCurrentUser(); } else { this.state.onDiscovered(); } } } _getCurrentUser() { this.setState({ message: 'Getting your user info..', }); if ( PTT.get( 'auth' ) && PTT.get( 'auth' ).authenticated() ) { // User is authenticated, we can proceed // reference 'this', we'll need it later let _this = this; $.ajax({ method: 'GET', beforeSend: PTT.get( 'auth' ).ajaxBeforeSend, url: PTT.get( 'site' ).url + '/wp-json/wp/v2/users/me', // there was an issue getting the user // but we are authenticated. // This is not right! // We do not update the cookie // so the app knows something is up. error: function( err ) { // console.log(err); _this.setState({ message: 'Sorry for the wait. We should be done soon.', }); _this._forceUserDownload(); return false; }, }) .done( function( user ) { PTT.set( user, 'user' ); PTT.setCookies(); _this.state.onDiscovered(); }); } else { this.setState({ message: 'Your user info could not be retreived. It looks like you are not authenticated.', }); } } _forceUserDownload() { let _this = this; $.ajax({ method: 'GET', beforeSend: PTT.get( 'auth' ).ajaxBeforeSend, url: PTT.get( 'site' ).url + '/wp-json/premise_time_tracker/v2/currentuser/', error: function( err ) { _this.setState({ message: 'Sorry, we could not find you user. Let\'s load it manually.', }); _this._selectUser(); return false; }, }) .done( function( user ) { PTT.set( user, 'user' ); PTT.setCookies(); _this.state.onDiscovered(); }); } _selectUser() { let _this = this; $.ajax({ method: 'GET', beforeSend: PTT.get( 'auth' ).ajaxBeforeSend, url: PTT.get( 'site' ).url + '/wp-json/wp/v2/users/', error: function( err ) { _this.setState({ message: err.responseText, }); }, }) .done( function( user ) { console.log(user); let _list = [ <option key={0} className="user-option"> Please slect YOUR user.. </option> ]; for (var i = user.length - 1; i >= 0; i--) { const _listItem = <option key={user[i].id} className="user-option" value={user[i].id}> {user[i].name} </option>; _list.push( _listItem ); } const _select = <select onInput={_this._saveUserOnSelect}> {_list} </select>; _this.setState({ message: 'Select a user.', view: _select, }); }); } _saveUserOnSelect(e) { e.preventDefault(); const _uid = e.target.value; let _this = this; $.ajax({ method: 'GET', beforeSend: PTT.get( 'auth' ).ajaxBeforeSend, url: PTT.get( 'site' ).url + '/wp-json/wp/v2/users/' + _uid, error: function( err ) { _this.setState({ message: err.responseText, }); }, }) .done( function ( user ) { PTT.set( user, 'user' ); PTT.setCookies(); _this.state.onDiscovered(); }); } }
JavaScript
class Server { constructor(customSettingsObj) { if (ServerLib.hrtime) { // Does the server support the "Process.hrtime" object? if (!uduInstance) { uduInstance = this; this.instanceReset = () => { uduInstance = null; }; Common.setCustomSettings(customSettingsObj); Common.loadColorScheme(); ServerLib.executeColoring(); this.appConfig = Common.config.serviceApp; this.executionAllowed = Common.config.runtime.run; Common.console.info(ServerLib.appDescription + this.appConfig.consoleEOL + ServerLib.appVersion); if (!this.executionAllowed) { Common.console.info(ServerLib.appStopped); } } } else { this.executionAllowed = false; Common.console.warn(`${Common.config.serviceApp.appName}: "${Common.getErrorMessage('constructorServer')}"`); } return uduInstance; } //-------------------------------------------------- /** * The method stops execution of the utility. * This method returns nothing. */ stopExec() { this.executionAllowed = false; ServerLib.testPointTime = []; Common.testLevelsPack = []; } /** * The method resumes execution of the utility. * This method returns nothing. */ resumeExec() { if (Common.config.runtime.run) { this.executionAllowed = true; } } //-------------------------------------------------- /** * Outputs debugging information to the console. * This method returns nothing. * @param {*} value - A value of any type. * @param {string} [comment] - Additional explanatory comment to the displayed value. */ log(value, comment = '') { if (this.executionAllowed) { Common.console.log(this.appConfig.consoleEOL + ServerLib.appName + ServerLib.getDebugMessage(value, comment)); } } //-------------------------------------------------- /** * Run-time testing (RTT). * Sets the control point in the code. * Calculates the code execution time between two control points (in milliseconds). * Displays the calculated value in the console. * @param {string} [name] - An optional explanatory name for the control point. * @returns {number} - Returns the computed value. */ rttPoint(name = '') { let performanceResult = 0; if (this.executionAllowed) { const processTimeNow = ServerLib.getProcessTime(); try { Common.checkValueType(name, 'String', 'rttPoint1'); const pointTime = ServerLib.testPointTime; Common.checkValueType(pointTime, 'Array', 'rttPoint2'); ServerLib.testPointTime = processTimeNow; let result; if (pointTime.length === 0) { result = this.appConfig.consoleEOL + ServerLib.appName + ServerLib.wrapString('Point RTT | 0 ms | ', 'slave'); if (name) { result += ServerLib.wrapString(name, 'master'); } else { result += ServerLib.wrapString('Starting point.', 'master'); } } else { performanceResult = ServerLib.getMilliseconds(ServerLib.getProcessTime(pointTime)); result = ServerLib.appName + ServerLib.wrapString('Point RTT | ', 'slave') + ServerLib.wrapString(`+${Common.correctDecimals(performanceResult)} ms`, 'master'); if (name) { result += ServerLib.wrapString(' | ', 'slave') + ServerLib.wrapString(name, 'master'); } } Common.console.info(result); } catch (e) { Common.errorHandler(e); } } return performanceResult; } //-------------------------------------------------- /** * Run-time testing (RTT). * The starting point for computing the execution time of some code. * This method returns nothing. * @param {string} [name] - An optional explanatory name for Run-time testing. * @param {int} [levelIndex] - An optional index for the level of nesting (for nested tests). */ rttStart(name = '', levelIndex = 0) { if (this.executionAllowed) { try { Common.checkValueType(name, 'String', 'rttStart1'); Common.checkValueType(levelIndex, 'Number', 'rttStart2'); const level = Common.setRTTLevel(levelIndex); Common.checkValueType(level, 'Object', 'rttStart3'); level.name = name; level.time = ServerLib.getMilliseconds(process.hrtime()); } catch (e) { Common.errorHandler(e); } } } //-------------------------------------------------- /** * Run-time testing (RTT). * The end point for the "rttStart()" method. * Calculates the code execution time between the start and current points (in milliseconds). * Displays the calculated value in the console. * @param {int} [levelIndex] - An optional index for the level of nesting (for nested tests). * @returns {number} - Returns the computed value. */ rttFinish(levelIndex = 0) { let performanceResult = 0; if (this.executionAllowed) { const processTimeNow = process.hrtime(); try { Common.checkValueType(levelIndex, 'Number', 'rttFinish1'); const level = Common.getRTTLevel(levelIndex); Common.checkValueType(level, 'Object', 'rttFinish2'); performanceResult = ServerLib.getMilliseconds(processTimeNow) - level.time; if (level.name) { Common.console.info(this.appConfig.consoleEOL + ServerLib.appName + ServerLib.wrapString('Single RTT | ', 'slave') + ServerLib.wrapString(`${Common.correctDecimals(performanceResult)} ms`, 'master') + ServerLib.wrapString(' | ', 'slave') + ServerLib.wrapString(level.name, 'master')); } } catch (e) { Common.errorHandler(e); } } return performanceResult; } //-------------------------------------------------- /** * Run-time testing (RTT). * Calculates the average execution time of some code (in milliseconds). * Displays the calculated value in the console. * @param {function} codeContainer - Container for the code under test. * @param {int} cycles - Number of cycles to repeat the test (maximum 1000 cycles). * @param {string} [name] - An optional explanatory name for Run-time testing. * @param {boolean} [timeEachIteration] - Display the execution time of each iteration? * Optional argument, disabled by default. * @returns {number} - Returns the computed value. */ rttAverage(codeContainer, cycles, name = '', timeEachIteration = false) { let performanceResult = 0; if (this.executionAllowed) { try { Common.checkValueType(codeContainer, 'Function', 'rttAverage1'); Common.checkValueType(cycles, 'Number', 'rttAverage2'); Common.checkValueType(name, 'String', 'rttAverage3'); Common.checkValueType(timeEachIteration, 'Boolean', 'rttAverage4'); let countCycles = (cycles > 1000) ? 1000 : cycles; // Max 1000 cycles. const cycleSkipped = Math.round(countCycles * 0.1); // 10%. let cyclePosition = 0; let oneIterationTime; let totalTestTime = 0; const timeEachIterationArr = []; countCycles += cycleSkipped; while (cyclePosition < countCycles) { cyclePosition += 1; this.rttStart(); codeContainer(); oneIterationTime = this.rttFinish(); if (cyclePosition > cycleSkipped) { totalTestTime += oneIterationTime; timeEachIterationArr.push(oneIterationTime); } } performanceResult = totalTestTime / (countCycles - cycleSkipped); // Average time. let result = this.appConfig.consoleEOL; result += ServerLib.appName + ServerLib.wrapString('Average RTT | ', 'slave') + ServerLib.wrapString(`${Common.correctDecimals(performanceResult)} ms`, 'master'); if (name) { result += ServerLib.wrapString(' | ', 'slave') + ServerLib.wrapString(name, 'master'); } if (timeEachIteration === true) { timeEachIterationArr.forEach((item, index) => { result += this.appConfig.consoleEOL + ServerLib.wrapString(` iteration ${index + 1}: ${Common.correctDecimals(item)} ms`, 'slave'); }); } Common.console.info(result); } catch (e) { Common.errorHandler(e); } } return performanceResult; } }
JavaScript
class Block$1 { decodeTransactionLength (buf, offset, bridge) { return 1; } encodeTx (tx, bridge) { return '0xff'; } decodeTx (rawStringOrArray, bridge) { return { from: ADDRESS_ZERO$1, to: ADDRESS_ZERO$1, hash: ZERO_HASH$3, nonce: BIG_ZERO$7 }; } async executeTx (tx, bridge, dry) { return { errno: 0, returnValue: '0x', logs: [] }; } toRaw (bridge) { if (this._raw) { return this._raw; } let ret = '0x' + packString([this.number, this.blockType, this.timestamp], [32, 32, 32]); for (const tx of this.transactions) { ret += this.encodeTx(tx, bridge).replace('0x', ''); } return ret; } async fromBeacon (data, rootBlock, bridge) { this.blockType = 2; this._raw = '0x' + packString([this.number, this.blockType, Number(rootBlock.timestamp), data], [32, 32, 32, 0]); this.hash = keccak256HexPrefix(this._raw); this.timestamp = Number(rootBlock.timestamp); this.log(`new Block ${this.number}/${this.hash}`); const buf = arrayify(this._raw); const bufLength = buf.length; // skip block header let offset = 96; while (offset < bufLength) { try { const txLen = this.decodeTransactionLength(buf, offset, bridge); const txOffset = offset; const rawTx = buf.slice(offset, offset += txLen); try { this.txOffsets[txOffset] = await this.addTransaction(rawTx, bridge, true); } catch (e) { this.log('informative', e); } } catch (e) { this.log('TODO - proper tx parsing', e); } } this.log('Done'); } async fromCustomBeacon (data, rootBlock, bridge) { this.blockType = 3; this._raw = '0x' + packString([this.number, this.blockType, Number(rootBlock.timestamp), data], [32, 32, 32, 0]); this.hash = keccak256HexPrefix(this._raw); this.timestamp = Number(rootBlock.timestamp); this.log(`new Custom-Block ${this.number}/${this.hash}`); try { // block header const txOffset = 96; this.txOffsets[txOffset] = await this.addCustomMessage('0x' + data, bridge); } catch (e) { this.log('fromCustomBeacon', e); } } async onDeposit (data, rootBlock, bridge) { this.blockType = 1; this.timestamp = Number(rootBlock.timestamp); this.isDepositBlock = true; this._raw = '0x' + packString([this.number, this.blockType, this.timestamp, data], [32, 32, 32, 0]); this.hash = keccak256HexPrefix(this._raw); this.log(`new Deposit-Block ${this.number}/${this.hash}`); const buf = arrayify(this._raw); const bufLength = buf.length; // skip block header let offset = 96; while (offset < bufLength) { try { const txOffset = offset; const owner = toHexPrefix(slicePadEnd(buf, offset, offset += 20)); const token = toHexPrefix(slicePadEnd(buf, offset, offset += 20)); const value = toHexPrefix(slicePadEnd(buf, offset, offset += 32)); const tokenType = toHexPrefix(slicePadEnd(buf, offset, offset += 32)); this.txOffsets[txOffset] = await this.addDeposit({ owner, token, value, tokenType }, bridge); } catch (e) { this.log('onDeposit', e); } } this.log('Done'); } constructor (prevBlock) { // previous block - if applicable this.prevBlock = prevBlock; // the blockHash - non-zero if this block was submitted to the Bridge. this.hash = ZERO_HASH$3; // the blockNumber this.number = prevBlock ? prevBlock.number + BIG_ONE$5 : BIG_ONE$5; // the timestamp (from the L1 block) this.timestamp = prevBlock ? prevBlock.timestamp : 0; // address > nonce mapping this.nonces = {}; // ordered list of transactions in this Block this.transactions = []; this.isDepositBlock = false; this.submissionDeadline = 0; this.txOffsets = {}; this.blockType = 0; this._barrier = null; if (prevBlock) { // copy nonces since `prevBlock` this.nonces = Object.assign({}, prevBlock.nonces); } } calculateSize () { let ret = 0; for (const tx of this.transactions) { const size = tx.size || ((this.encodeTx(tx).length - 2) / 2); ret += size; } return ret; } async addDeposit (obj, bridge) { // borrow the transactions field for a deposit (we only have one deposit per block atm) // transactionHash = blockHash this.log('addDeposit', obj); const tx = { hash: this.hash, from: obj.owner, to: obj.token, data: obj.value, nonce: BIG_ZERO$7, status: '0x1', errno: 0, logs: [], returnData: '0x', size: 104, }; this.transactions.push(tx); return tx; } async addCustomMessage (data, bridge) { const tx = { hash: this.hash, from: ADDRESS_ZERO$1, to: ADDRESS_ZERO$1, data: data, nonce: BIG_ZERO$7, status: '0x1', errno: 0, logs: [], returnData: '0x', // 0x... size: (data.length / 2) - 1, }; this.transactions.push(tx); return tx; } log (...args) { timeLog(`${this.isDepositBlock ? 'DepositBlock' : 'Block'}(${this.number})`, ...args); } freeze () { } prune () { this._raw = null; this.nonces = {}; } async rebase (block, bridge) { this.log(`Rebase:Started ${block.transactions.length} transactions`); for (const tx of block.transactions) { if (this.prevBlock) { let duplicate = false; for (const _tx of this.prevBlock.transactions) { if (_tx.hash === tx.hash) { duplicate = true; break; } } if (duplicate) { this.log('Rebase:Dropping tx', tx.hash); continue; } } this.log('Rebase:Adding tx', tx.hash); try { await this.addDecodedTransaction(tx, bridge); } catch (e) { this.log(e); } } this.log(`Rebase:Complete ${this.transactions.length} transactions left`); } async addTransaction (rawStringOrArray, bridge, fromBeacon) { if (this._barrier) { try { this.log('active barrier'); await this._barrier; } catch (e) { // ignore } } try { this._barrier = new Promise( async (resolve, reject) => { try { const tx = this.decodeTx(rawStringOrArray, bridge); resolve(await this.addDecodedTransaction(tx, bridge, fromBeacon)); } catch (e) { reject(e); } } ); const ret = await this._barrier; this._barrier = null; return ret; } catch (e) { this._barrier = null; throw e; } } async addDecodedTransaction (tx, bridge, fromBeacon) { if (this.validateTransaction(tx)) { const { errno, returnValue, logs } = await this.executeTx(tx, bridge); this.log(`${tx.from}:${tx.nonce}:${tx.hash}`); // TODO // check modified storage keys, take MAX_SOLUTION_SIZE into account if (errno !== 0) { this.log(`invalid tx errno:${errno}`); if (!fromBeacon) { // if this transaction is not already included in a block, then throw const errMsg = maybeDecodeError(returnValue); if (errMsg) { throw new Error(errMsg); } else { throw new Error(`transaction evm errno: ${errno}`); } } } tx.logs = logs || []; tx.status = errno === 0 ? '0x1' : '0x0'; tx.errno = errno; tx.returnData = returnValue; this.nonces[tx.from] = tx.nonce + BIG_ONE$5; if (bridge.alwaysKeepRevertedTransactions || errno === 0 || fromBeacon) { // 'save' the transaction this.transactions.push(tx); } return tx; } this.log('invalid or duplicate tx', tx.hash); return null; } validateTransaction (tx) { return true; } async dryExecuteTx (tx, bridge) { const { errno, returnValue } = await this.executeTx(tx, bridge, true); if (errno !== 0) { const errMsg = maybeDecodeError(returnValue); if (errMsg) { throw new Error(errMsg); } else { throw new Error(`evm errno: ${errno}`); } } return returnValue || '0x'; } async submitBlock (bridge) { const transactions = []; const tmp = []; // TODO // this also has to take MAX_SOLUTION_SIZE into account let payloadLength = 0; for (const tx of this.transactions) { if (tx.submitted) { this.log(`Already marked as submitted: ${tx.from}:${tx.nonce}`); continue; } if (tx.errno !== 0) { this.log(`Skipping due to transaction errno:${tx.errno} from:${tx.from} nonce:${tx.nonce}`); continue; } this.log('Preparing ' + tx.from + ':' + tx.nonce + ':' + tx.hash); const encoded = this.encodeTx(tx, bridge).replace('0x', ''); const byteLength = encoded.length / 2; if (payloadLength + byteLength > bridge.MAX_BLOCK_SIZE) { this.log('reached MAX_BLOCK_SIZE'); break; } payloadLength += byteLength; transactions.push(encoded); // mark it as submitted // if we get any errors in submitBlock, we unmark all again tmp.push(tx); tx.submitted = true; } if (transactions.length === 0) { this.log('Nothing to submit'); return; } const rawData = transactions.join(''); const txData = bridge.rootBridge.encodeSubmit(rawData); const n = this.number; let tx; try { // post data tx = await bridge.wrapSendTransaction(txData); } catch (e) { this.log(e); // TODO: check if we really failed to submit the block // unmark all transactions for (const v of tmp) { v.submitted = false; } } this.log('Block.submitBlock.postData', Number(tx.gasUsed)); this.log( { total: this.transactions.length, submitted: transactions.length, } ); // TODO: blockHash/number might not be the same if additional blocks are submitted in the meantime return n; } /// @dev Computes the solution for this Block. async computeSolution (bridge) { // first 32 bytes are the (unused) stateRoot const payload = ''.padStart(64, '0'); if ((payload.length / 2) > bridge.MAX_SOLUTION_SIZE) { throw new Error(`Reached MAX_SOLUTION_SIZE: ${payload.length / 2} bytes`); } const solution = { payload, hash: keccak256HexPrefix(payload), }; return solution; } async computeChallenge (challengeOffset, bridge) { const blockData = this.toRaw(bridge); return { blockData, witnesses: [], rounds: 1 }; } }
JavaScript
class ReportFactory { /** * Retrieve the instance of the given type. * * @param {ReportType} type - type of instance to get * @returns {ReportBase} instance of the given type, if such an instance has * been registered * @throws {InvalidReportTypeError} if no such instance has been registered */ static getInstance(type) { if (!this.instances.has(type)) { throw new InvalidReportTypeError(type); } return this.instances.get(type); } /** * Registers the given instance, using `ReportBase#type` to determine what key to * register it under. * * @param {ReportBase} instance - instance of {@link ReportBase} to be registered */ static registerInstance(instance) { const type = instance.type(); this.instances.set(type, instance); } }
JavaScript
class mxSelectionChange { constructor(selectionModel, added, removed) { this.selectionModel = selectionModel this.added = (added != null) ? added.slice() : null this.removed = (removed != null) ? removed.slice() : null } /** * Function: execute * * Changes the current root of the view. */ execute() { var t0 = mxLog.enter('mxSelectionChange.execute') window.status = mxResources.get( this.selectionModel.updatingSelectionResource) || this.selectionModel.updatingSelectionResource if (this.removed != null) { for (var i = 0; i < this.removed.length; i++) { this.selectionModel.cellRemoved(this.removed[i]) } } if (this.added != null) { for (var i = 0; i < this.added.length; i++) { this.selectionModel.cellAdded(this.added[i]) } } var tmp = this.added this.added = this.removed this.removed = tmp window.status = mxResources.get(this.selectionModel.doneResource) || this.selectionModel.doneResource mxLog.leave('mxSelectionChange.execute', t0) this.selectionModel.fireEvent(new mxEventObject(mxEvent.CHANGE, 'added', this.added, 'removed', this.removed)) } }
JavaScript
class VolumeGenerator { /** * verts - array of THREE.Vector3 */ static renderTriangle(xDim, yDim, zDim, pixels, verts) { const xyDim = xDim * yDim; // outer loop: // [0] -> [1] // [0] -> [2] const v01 = new THREE.Vector3(); const v02 = new THREE.Vector3(); const v12 = new THREE.Vector3(); v01.x = verts[1].x - verts[0].x; v01.y = verts[1].y - verts[0].y; v01.z = verts[1].z - verts[0].z; v02.x = verts[2].x - verts[0].x; v02.y = verts[2].y - verts[0].y; v02.z = verts[2].z - verts[0].z; v12.x = verts[2].x - verts[1].x; v12.y = verts[2].y - verts[1].y; v12.z = verts[2].z - verts[1].z; const dist01 = Math.sqrt(v01.x * v01.x + v01.y * v01.y + v01.z * v01.z); const dist02 = Math.sqrt(v02.x * v02.x + v02.y * v02.y + v02.z * v02.z); const dist12 = Math.sqrt(v12.x * v12.x + v12.y * v12.y + v12.z * v12.z); let distMax = (dist01 > dist02) ? dist01 : dist02; distMax = (dist12 > distMax) ? dist12 : distMax; const ITERS_ESTIMATE = 1.2; const numIters = Math.floor(distMax * ITERS_ESTIMATE); const vLScale = new THREE.Vector3(); const vRScale = new THREE.Vector3(); vLScale.x = v01.x / numIters; vLScale.y = v01.y / numIters; vLScale.z = v01.z / numIters; vRScale.x = v02.x / numIters; vRScale.y = v02.y / numIters; vRScale.z = v02.z / numIters; const vL = new THREE.Vector3(verts[0].x, verts[0].y, verts[0].z); const vR = new THREE.Vector3(verts[0].x, verts[0].y, verts[0].z); const vLR = new THREE.Vector3(); const vScale = new THREE.Vector3(); const v = new THREE.Vector3(); for (let iterSide = 0; iterSide <= numIters; iterSide++) { vLR.x = vR.x - vL.x; vLR.y = vR.y - vL.y; vLR.z = vR.z - vL.z; vScale.x = vLR.x / numIters; vScale.y = vLR.y / numIters; vScale.z = vLR.z / numIters; v.x = vL.x; v.y = vL.y; v.z = vL.z; const VIS = 255; // interpolate between vL <-> vR for (let i = 0; i <= numIters; i++) { let x = Math.floor(v.x); let y = Math.floor(v.y); let z = Math.floor(v.z); if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } // try to fill neighb x = Math.floor(v.x) + 1; y = Math.floor(v.y) + 0; z = Math.floor(v.z) + 0; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } x = Math.floor(v.x) + 0; y = Math.floor(v.y) + 1; z = Math.floor(v.z) + 0; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } x = Math.floor(v.x) + 0; y = Math.floor(v.y) + 0; z = Math.floor(v.z) + 1; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } x = Math.floor(v.x) - 1; y = Math.floor(v.y) + 0; z = Math.floor(v.z) + 0; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } x = Math.floor(v.x) + 0; y = Math.floor(v.y) - 1; z = Math.floor(v.z) + 0; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } x = Math.floor(v.x) + 0; y = Math.floor(v.y) + 0; z = Math.floor(v.z) - 1; if ((x >= 0) && (y >= 0) && (z >= 0) && (x < xDim) && (y < yDim) && (z < zDim)) { const off = x + (y * xDim) + (z * xyDim); pixels[off] = VIS; } // next v v.x += vScale.x; v.y += vScale.y; v.z += vScale.z; } // next L, R vL.x += vLScale.x; vL.y += vLScale.y; vL.z += vLScale.z; vR.x += vRScale.x; vR.y += vRScale.y; vR.z += vRScale.z; } } /** * * return true, if success */ static generateFromFaces(xDim, yDim, zDim, pixelsDst, geo, withFillInside) { const numTriangles = geo.getNumTriangles(); const indices = geo.getIndices(); // Uint32 array const vertices = geo.getVertices(); // floar array let i, i3; const NUM_VERT_TRI = 3; const NUM_COMP_VERTEX = 4; const OFF_0 = 0; const OFF_1 = 1; const OFF_2 = 2; console.log('VolumeGeberator. render triangles'); // clear dst buffer const numPixels = xDim * yDim * zDim; for (i = 0; i < numPixels; i++) { pixelsDst[i] = 0; } const vs = []; vs.push(new THREE.Vector3()); vs.push(new THREE.Vector3()); vs.push(new THREE.Vector3()); for (i = 0, i3 = 0; i < numTriangles; i++, i3 += NUM_VERT_TRI) { const ia = indices[i3 + OFF_0]; const ib = indices[i3 + OFF_1]; const ic = indices[i3 + OFF_2]; vs[OFF_0].x = vertices[(ia * NUM_COMP_VERTEX) + OFF_0]; vs[OFF_0].y = vertices[(ia * NUM_COMP_VERTEX) + OFF_1]; vs[OFF_0].z = vertices[(ia * NUM_COMP_VERTEX) + OFF_2]; vs[OFF_1].x = vertices[(ib * NUM_COMP_VERTEX) + OFF_0]; vs[OFF_1].y = vertices[(ib * NUM_COMP_VERTEX) + OFF_1]; vs[OFF_1].z = vertices[(ib * NUM_COMP_VERTEX) + OFF_2]; vs[OFF_2].x = vertices[(ic * NUM_COMP_VERTEX) + OFF_0]; vs[OFF_2].y = vertices[(ic * NUM_COMP_VERTEX) + OFF_1]; vs[OFF_2].z = vertices[(ic * NUM_COMP_VERTEX) + OFF_2]; VolumeGenerator.renderTriangle(xDim, yDim, zDim, pixelsDst, vs); } // for (i) all triangles console.log('VolumeGeberator. fill internal'); if (withFillInside) { const fillTool = new FloodFillTool(); const xyzDim = xDim * yDim * zDim; const pixelsFill = new Uint8Array(xyzDim); const MAX_SEED_POINTS = 16; const vaSeeds = []; for (i = 0; i < MAX_SEED_POINTS; i++) { vaSeeds.push(new THREE.Vector3()); } const numSeedPoints = fillTool.detectSeedPoint3d(xDim, yDim, zDim, pixelsDst, vaSeeds, MAX_SEED_POINTS); console.log(`VolGen. Detected ${numSeedPoints} seed points`); let foundGoodFill = false; for (let s = 0; s < numSeedPoints; s++) { // fill using seed point const vSeed = vaSeeds[s]; // memcpy(pixelsFill, pixels, xyzDim); for (i = 0; i < xyzDim; i++) { pixelsFill[i] = pixelsDst[i]; } console.log(`VolGen. Try to flood fill from ${vSeed.x}, ${vSeed.y}, ${vSeed.z} `); console.log(`VolGen. inside volume ${xDim}, ${yDim}, ${zDim} `); const okFill = fillTool.floodFill3d(xDim, yDim, zDim, pixelsFill, vSeed); console.log(`VolGen. Result fill = ${okFill}. numDraws = ${fillTool.m_numFilled3d}`); const VIS = 255; const OFF_CORNER = 1 + (1 * xDim) + (1 * xDim * yDim); if ((okFill === 1) && (pixelsFill[OFF_CORNER] !== VIS)) { foundGoodFill = true; break; } } // for (s) all seed points // copy back if (foundGoodFill) { // memcpy(pixels, pixelsFill, xyzDim); for (i = 0; i < xyzDim; i++) { pixelsDst[i] = pixelsFill[i]; } } if (!foundGoodFill) { return false; } } // if need fill return true; } }
JavaScript
class TaxonomicUnitWrapper { /* Types of taxonomic units we support (see documentation above). */ /** A taxon or taxon concept. */ static get TYPE_TAXON_CONCEPT() { return TaxonConceptWrapper.TYPE_TAXON_CONCEPT; } /** A specimen. */ static get TYPE_SPECIMEN() { return SpecimenWrapper.TYPE_SPECIMEN; } /** Wrap a taxonomic unit. */ constructor(tunit, defaultNomenCode = owlterms.NAME_IN_UNKNOWN_CODE) { this.tunit = tunit; this.defaultNomenCode = defaultNomenCode; } /** * What type of specifier is this? This is an array that could contain multiple * classes, but should contain one of: * - {@link TYPE_TAXON_CONCEPT} * - {@link TYPE_SPECIMEN} */ get types() { if (!has(this.tunit, '@type')) return []; if (isArray(this.tunit['@type'])) return this.tunit['@type']; return [this.tunit['@type']]; } /** * Return this taxonomic unit if it is a taxon concept. */ get taxonConcept() { if (this.types.includes(TaxonomicUnitWrapper.TYPE_TAXON_CONCEPT)) return this.tunit; return undefined; } /** * Return this taxonomic unit if it is a specimen. */ get specimen() { // Only specimens have scientific names. if (this.types.includes(TaxonomicUnitWrapper.TYPE_SPECIMEN)) return this.tunit; return undefined; } /** * Return the list of external references for this taxonomic unit. * This is just all the '@ids' of this object. */ get externalReferences() { if (!has(this.tunit, '@id')) return []; if (isArray(this.tunit['@id'])) return this.tunit['@id']; return [this.tunit['@id']]; } /** * Return the label of this taxonomic unit. */ get label() { // A label or description for this TU? if (has(this.tunit, 'label')) return this.tunit.label; if (has(this.tunit, 'description')) return this.tunit.description; // Is this a specimen? if (this.specimen) { return new SpecimenWrapper(this.specimen).label; } // Is this a taxon concept? if (this.taxonConcept) { return new TaxonConceptWrapper(this.taxonConcept).label; } // If its neither a specimen nor a taxon concept, just list the // external references. const externalReferences = this.externalReferences; if (externalReferences.length > 0) { return externalReferences .map(externalRef => `<${externalRef}>`) .join(' and '); } // If we don't have any properties of a taxonomic unit, return undefined. return undefined; } /** * Given a label, attempt to parse it into a taxonomic unit, whether a scientific * name or a specimen identifier. The provided nomenclatural code is used. * * @return A taxonomic unit that this label could be parsed as. */ static fromLabel(nodeLabel, nomenCode = owlterms.NAME_IN_UNKNOWN_CODE) { if (nodeLabel === undefined || nodeLabel === null || nodeLabel.trim() === '') return undefined; // Rather than figuring out with this label, check to see if we've parsed // this before. if (PhyxCacheManager.has(`TaxonomicUnitWrapper.taxonomicUnitsFromNodeLabelCache.${nomenCode}`, nodeLabel)) { return PhyxCacheManager.get(`TaxonomicUnitWrapper.taxonomicUnitsFromNodeLabelCache.${nomenCode}`, nodeLabel); } // Look for taxon concept. const taxonConcept = TaxonConceptWrapper.fromLabel(nodeLabel, nomenCode); // Look for specimen information. let specimen; if (nodeLabel.toLowerCase().startsWith('specimen ')) { // Eliminate a 'Specimen ' prefix if it exists. specimen = SpecimenWrapper.fromOccurrenceID(nodeLabel.substr(9)); } let tunit; if (taxonConcept && specimen) { // If we have both, then treat it as a specimen that has been identified // to a particular taxonomic name. tunit = assign({}, taxonConcept, specimen); tunit['@type'] = TaxonomicUnitWrapper.TYPE_SPECIMEN; } else if (taxonConcept) { tunit = taxonConcept; } else if (specimen) { tunit = specimen; } // Look for external references. For now, we only check to see if the entire // nodeLabel starts with URL/URNs, but we should eventually just look for // them inside the label. const URL_URN_PREFIXES = [ 'http://', 'https://', 'ftp://', 'sftp://', 'file://', 'urn:', ]; if (URL_URN_PREFIXES.filter(prefix => nodeLabel.startsWith(prefix)).length > 0) { // The node label starts with something that looks like a URL! // Treat it as an external reference. if (tunit === undefined) tunit = {}; tunit['@id'] = nodeLabel; } // Finally, let's record the label we parsed to get to this tunit! if (tunit) { tunit.label = nodeLabel; } // Record in the cache PhyxCacheManager.put(`TaxonomicUnitWrapper.taxonomicUnitsFromNodeLabelCache.${nomenCode}`, nodeLabel, tunit); return tunit; } /** * Return the JSON representation of this taxonomic unit, i.e. the object we're wrapping. */ get asJSON() { return this.tunit; } /** * Return this taxonomic unit as an OWL/JSON-LD object. */ get asJSONLD() { const jsonld = cloneDeep(this.tunit); // Add CDAO_TU as a type to the existing types. if (has(this.tunit, '@type')) { if (isArray(this.tunit['@type'])) this.tunit['@type'].push(owlterms.CDAO_TU); } const equivClass = this.asOWLEquivClass; if (equivClass) { jsonld.equivalentClass = equivClass; } return jsonld; } /** * Return the equivalent class expression for this taxonomic unit. */ get asOWLEquivClass() { if (this.types.includes(TaxonomicUnitWrapper.TYPE_TAXON_CONCEPT)) { return new TaxonConceptWrapper(this.tunit, this.defaultNomenCode).asOWLEquivClass; } if (this.types.includes(TaxonomicUnitWrapper.TYPE_SPECIMEN)) { return new SpecimenWrapper(this.specimen).asOWLEquivClass; } // Nothing we can do, so just ignore it. return undefined; } }
JavaScript
class AudioManager{ static audioContext = null; static volume = null; /** Get audio context of the window @returns {AudioContext} @static */ static getAudioContext(){ if(this.audioContext == null) this.initManager(); return this.audioContext; } /** Audio Manager initialisation @static */ static initManager(){ this.audioContext = new (window.AudioContext || window.webkitAudioContext)(); this.volume = this.audioContext.createGain(); this.volume.gain.setValueAtTime(0, this.audioContext.currentTime); this.volume.connect(this.audioContext.destination); } /** Connect two nodes @returns {bool} @static */ static connect(input, output, i, j){ input.connect(output); return true; } /** Set output volume @param {number} volume [0,1] @param {number} volume [0,1] @static */ static setDestinationVolume(f, time = 0.1){ const audioContext = this.getAudioContext(); this.volume.gain.linearRampToValueAtTime(f, audioContext.currentTime + time); } /** Get Destination node @returns {AudioNode} @static */ static getDestination(){ return this.volume; } }
JavaScript
class PasteUpSaver { constructor() { this.map = {}; this.id = 0; } newId() { return (++this.id).toString().padStart(4, '0'); } varName(key) { let id = this.map[key]; if (!id) { id = "e_" + this.newId(); this.map[key] = id; } return id; } save(model, optFrames, asTemplate) { let [resultArray, resultDict, otherDict] = this.collectFrames(model, optFrames, asTemplate); return this.json(resultArray, resultDict, otherDict); } collectFrames(parent, optFrames, asTemplate) { // okay, we only collect frames let resultArray = []; let resultDict = []; let otherDict = {}; let children = parent.childNodes.slice(); children = children.filter(e => e.hasHandler("FrameModel")); if (optFrames) { children = children.filter(e => optFrames.find(f => f === e)); } children = children.sort((a, b) => { let z = (e) => e.style.getPropertyValue("z-index") || 0; return z(a) - z(b); }); children.forEach((child) => { let target = child.getElement(child._get("target")); let value = this.frameInfo(child, target, otherDict, asTemplate); let key = child.asElementRef().asKey(); resultDict[key] = value; resultArray.push(key); }); return [resultArray, resultDict, otherDict]; } frameInfo(frame, target, otherDict, asTemplate) { let result = {}; result["target"] = this.storeTarget(target, null, otherDict, asTemplate ? target : null); result["scriptingInfo"] = frame.getScriptingInfo(); result["transform"] = JSON.stringify(frame.getTransform()); return result; } json(resultArray, resultDict, otherDict) { let frameSaveOrder = [ "target", "scriptingInfo", "transform" ]; let frames = []; for (let i = 0; i < resultArray.length; i++) { let key = resultArray[i]; let inDict = resultDict[key]; let outDict = {}; frameSaveOrder.forEach((k) => { let entry = inDict[k]; if (entry === undefined || entry.trim().length === 0) {return;} outDict[k] = entry; }); frames[i] = outDict; } let otherSaveOrder = [ "elementClass", "scriptingInfo", "children", "style", "innerHTML", "listeners", "code", "viewCode", "text" ]; let other = {}; for (let key in otherDict) { let inDict = otherDict[key]; let outDict = {}; otherSaveOrder.forEach((k) => { let entry = inDict[k]; if (entry === undefined || entry.trim().length === 0) {return;} outDict[k] = entry; }); other[inDict.key] = outDict; } return [frames, other]; } allNodesCollect(parent, elem, func, resultArray, resultDict) { if (resultArray === undefined) { resultArray = []; resultDict = []; } let value = func(parent, elem); resultDict[elem.elementId] = value; resultArray.push(elem.elementId); let children = elem.childNodes; for (let i = 0; i < children.length; i++) { let child = elem.getElement(children[i].elementId); this.allNodesCollect(elem, child, func, resultArray, resultDict); } return [resultArray, resultDict]; } localUrl(url) { // @@ temporary: copied from VideoChatView, and patched if (url.startsWith("http")) { return url; } let path = window.location.origin + window.location.pathname; let hostname = window.location.hostname; if (hostname === "localhost" || hostname.endsWith(".ngrok.io")) { // many bets are off if (!url.startsWith("./apps/")) { return new URL(url, "https://croquet.io/dev/greenlight/").toString(); } } // until we changes the situation here if (path.indexOf("files/v1/pitch") >= 0) { return new URL(url, "https://croquet.io/dev/greenlight/").toString(); } // And we have another case where the system is installed somewhere else if (path.indexOf("croquet.io/events/") >= 0) { return new URL(url, "https://croquet.io/greenlight/").toString(); } if (url.startsWith(".")) { return new URL(url, path).toString(); } throw new Error("unrecognized URL fragment"); } urlFromTemplate(urlTemplate) { let randomSessionId = Math.floor(Math.random() * 36 ** 10).toString(36); /* eslint-disable no-template-curly-in-string */ let relativeUrl = urlTemplate.replace("${q}", randomSessionId); return this.localUrl(relativeUrl); } storeTarget(elem, parent, otherDict, owner) { let result = {}; result["key"] = elem.asElementRef().asKey(); result["elementClass"] = elem.constructor.name || "Element"; let scriptingInfo = elem.getScriptingInfo(); if (owner) { let appInfo = owner._get("appInfo"); if (elem.constructor.name === "IFrameElement" && appInfo && appInfo.urlTemplate) { let url = this.urlFromTemplate(appInfo.urlTemplate); scriptingInfo = scriptingInfo.replace(/^src: .*$/m, `src: "${url}"`); } } result["scriptingInfo"] = scriptingInfo; result["style"] = elem.getStyleString(); result["innerHTML"] = elem.innerHTML; result["listeners"] = elem.getListenersInfo(); result["code"] = JSON.stringify(elem.getCode()); result["viewCode"] = JSON.stringify(elem.getViewCode()); if (elem._get("_useCustomSaver")) { let custom = elem.call(...elem._get("_useCustomSaver"), this); result = {...result, ...{children: "[]"}, ...custom}; } else { let children = elem.childNodes; let childResult = []; children.forEach((child) => { let childKey = this.storeTarget(child, this, otherDict, owner); childResult.push(childKey); }); result["children"] = JSON.stringify(childResult); } otherDict[result.key] = result; if (elem.constructor.name === "TextElement") { // somewhat redundant in the presence of the custom saver mechanism... result["text"] = JSON.stringify({ runs: elem.doc.runs, defaultFont: elem.doc.defaultFont, defaultSize: elem.doc.defaultSize }); } return result.key; } loadTarget(key, otherDict, parent) { let root = otherDict[key]; let elem = parent.createElement(root["elementClass"]); elem.setScriptingInfo(root["scriptingInfo"]); elem.setStyleString(root["style"]); elem.innerHTML = root["innerHTML"]; elem.setListenersInfo(root["listeners"]); JSON.parse(root["children"]).forEach((childKey) => { elem.appendChild(this.loadTarget(childKey, otherDict, parent)); }); elem.setCode(JSON.parse(root["code"])); elem.setViewCode(JSON.parse(root["viewCode"])); if (elem._get("_useCustomLoader")) { elem.call(...elem._get("_useCustomLoader"), this, root); } if (root["elementClass"] === "TextElement" && root["text"]) { let json = JSON.parse(root["text"]); elem.setDefault(json.defaultFont, json.defaultSize); elem.load(json.runs); } return elem; } load(data, parent) { let [frames, otherDict] = data; return frames.map((dict) => { let frame = parent.createElement(); let target = this.loadTarget(dict["target"], otherDict, parent); let transform = JSON.parse(dict["transform"]); frame.setTransform(transform); frame.setScriptingInfo(dict["scriptingInfo"]); frame.setCode("boards.FrameModel"); frame.setViewCode("boards.FrameView"); frame.call("FrameModel", "setObject", target, {x: transform[4], y: transform[5]}); frame.call("FrameModel", "beSolidBackground"); return frame; }); } }
JavaScript
class NATSManager extends EventEmitter { constructor(url, options = {}) { super(); if (typeof url === 'string') { options = Object.assign({ url }, options); } else if (typeof url === 'object') { options = url; } this.nats = NATS.connect(options); this.connected = false; this.reconnecting = false; this.nats.on('connect', (...args) => { this.connected = true; this.emit('connect', ...args); }); this.nats.on('disconnect', (...args) => { this.connected = false; this.emit('disconnect', ...args); }); this.nats.on('reconnecting', (...args) => { this.reconnecting = true; this.emit('reconnecting', ...args); }); this.nats.on('reconnect', (...args) => { this.connected = true; this.reconnecting = false; this.emit('reconnect', ...args); }); this.on('close', (...args) => { this.connected = false; this.reconnecting = false; this.emit('close', ...args); }); } /** * @return {Promise<void>} */ async waitForConnection() { if (this.connected) return; await new Promise((resolve, reject) => { this.nats.once('connect', resolve); this.nats.once('error', reject); }); } /** * @return {Promise<void>} */ async disconnect() { if (!this.connected && !this.reconnecting) return; await new Promise((resolve, reject) => { this.nats.close(); this.nats.once('close', resolve); this.nats.once('error', reject); }); } /** * @param subject * @param msg * @param optReply * @return {Promise<any>} */ publish(subject, msg, optReply) { return new Promise((resolve, reject) => { this.nats.publish(subject, msg, optReply, (result) => { if (result instanceof NATS.NatsError) return reject(result); resolve(); }); }); } /** * @param subject * @param opts * @param callback * @return {Number} */ subscribe(subject, opts, callback) { return this.nats.subscribe(subject, opts, callback); } /** * @param sid * @param optMax */ unsubscribe(sid, optMax) { return this.nats.unsubscribe(sid, optMax); } /** * @param subject * @param optMsg * @param optOptions * @return {Promise<any>} */ request(subject, optMsg, optOptions) { return new Promise((resolve, reject) => { this.nats.request(subject, optMsg, optOptions, (response) => { if (response instanceof NATS.NatsError) { return reject(response); } resolve(response); }); }); } /** * @param subject * @param optMsg * @param optOptions * @param timeout * @return {Promise<any>} */ requestOne(subject, optMsg, optOptions, timeout) { return new Promise((resolve, reject) => { this.nats.request(subject, optMsg, optOptions, timeout, (response) => { if (response instanceof NATS.NatsError) { return reject(response); } resolve(response); }); }); } /** * @return {Promise<void>} */ flush() { return new Promise((resolve) => { this.nats.flush(resolve); }); } timeout(sid, timeout, expected) { return new Promise((resolve) => { this.nats.timeout(sid, timeout, expected, resolve); }); } }
JavaScript
class AddChart extends Component { constructor(props) { super(props); this.state = { step: 0, newChart: { name: "Untitled", query: "connection.collection('users').find()", displayLegend: false, connection_id: null, Datasets: [{ xAxis: "root", legend: "Dataset #1", }], offset: "offset", draft: true, includeZeros: true, timeInterval: "day", }, ddConnections: [], updatedEdit: false, // eslint-disable-line viewDatasetOptions: false, activeDataset: 0, timeToSave: true, autosave: true, }; } componentDidMount() { const { cleanErrors } = this.props; cleanErrors(); this._populateConnections(); } componentDidUpdate(prevProps, prevState) { const { newChart, timeToSave, autosave } = this.state; if (prevProps.charts) { if (prevProps.match.params.chartId && prevProps.charts.length > 0 && !prevState.updatedEdit) { this._prepopulateState(); } } if (prevProps.connections.length > 0 && prevState.ddConnections.length === 0) { this._populateConnections(); } // update the draft if it's already created and only if it's a draft if (!_.isEqual(prevState.newChart, newChart) && timeToSave && newChart.id && autosave) { this._updateDraft(); } } _prepopulateState = () => { const { connections, charts, match } = this.props; charts.forEach((chart) => { if (chart.id === parseInt(match.params.chartId, 10)) { const foundChart = chart; // objectify the date range if it exists if (chart.startDate) { foundChart.startDate = moment(chart.startDate); } if (chart.endDate) { foundChart.endDate = moment(chart.endDate); } // check if the chart has a connection and populate that one as well let selectedConnection = null; if (foundChart.connection_id) { for (let i = 0; i < connections.length; i++) { if (connections[i].id === foundChart.connection_id) { selectedConnection = connections[i]; break; } } } this.setState({ newChart: foundChart, updatedEdit: true, selectedConnection, autosave: foundChart.draft, }, () => { this._onPreview(); }); } }); } _populateConnections = () => { const { connections } = this.props; const { ddConnections } = this.state; if (connections.length < 1) return; if (ddConnections.length > 0) return; const tempState = ddConnections; connections.map((connection) => { return tempState.push({ key: connection.id, value: connection.id, text: connection.name, }); }); this.setState({ ddConnections: tempState }); } _onChangeStep = (step) => { const { createChart, match } = this.props; const { newChart } = this.state; this.setState({ step }); if (!newChart.id && step > 0) { createChart(match.params.projectId, newChart) .then((chart) => { if (chart && chart.id) { this.setState({ newChart: { ...newChart, id: chart.id, Datasets: chart.Datasets, } }); } }); } } _onChangeConnection = (value) => { const { connections } = this.props; const { newChart } = this.state; let { query } = newChart; let selectedConnection; for (let i = 0; i < connections.length; i++) { if (connections[i].id === value) { selectedConnection = connections[i]; } } if (!newChart.id) { if (selectedConnection.type === "mongodb") { query = "connection.collection('users').find()"; } else if (selectedConnection.type === "postgres") { query = "SELECT * FROM table1;"; } } this.setState({ newChart: { ...newChart, connection_id: value, query }, selectedConnection, noSource: true, }); } _onChangeType = ({ type, subType }) => { const { newChart } = this.state; this.setState({ newChart: { ...newChart, type, subType: subType || "" } }); } _onChangeAxis = ({ xAxis, yAxis }) => { const { activeDataset, newChart } = this.state; const tempChart = { ...newChart }; if (xAxis) { tempChart.Datasets[activeDataset].xAxis = xAxis; } if (yAxis) { tempChart.yAxis = yAxis; } this.setState({ newChart: tempChart }); } _onChangeChart = ({ datasetColor, fillColor, fill, xAxis, patterns, legend, }) => { const { activeDataset, newChart, previewChart } = this.state; const tempChart = newChart; const realTimeData = previewChart; if (datasetColor) { tempChart.Datasets[activeDataset].datasetColor = datasetColor; if (previewChart) { if (realTimeData.data.datasets[activeDataset]) { realTimeData.data.datasets[activeDataset].borderColor = datasetColor; } } } if (fillColor) { tempChart.Datasets[activeDataset].fillColor = fillColor; if (previewChart && realTimeData.data.datasets[activeDataset]) { realTimeData.data.datasets[activeDataset].backgroundColor = fillColor; } } if (fill || fill === false) { tempChart.Datasets[activeDataset].fill = fill; if (previewChart && realTimeData.data.datasets[activeDataset]) { realTimeData.data.datasets[activeDataset].fill = fill; } } if (xAxis) { tempChart.Datasets[activeDataset].xAxis = xAxis; } if (patterns) { tempChart.Datasets[activeDataset].patterns = JSON.parse(JSON.stringify(patterns)); } if (legend) { tempChart.Datasets[activeDataset].legend = legend; if (previewChart) { if (realTimeData.data.datasets[activeDataset]) { if (legend) { realTimeData.data.datasets[activeDataset].label = legend; } else { realTimeData.data.datasets[activeDataset].label = ""; } } } } if (previewChart) { this.setState({ newChart: tempChart, previewChart: realTimeData, }); } else { this.setState({ newChart: tempChart, }); } } _onChangeGlobalSettings = ({ pointRadius, displayLegend, dateRange, includeZeros, timeInterval, currentEndDate, }) => { const { newChart, previewChart } = this.state; let realTimeData; if (previewChart) { realTimeData = { ...previewChart }; // point realTimeData.options.elements.point.radius = pointRadius; realTimeData.data.datasets[0].pointRadius = pointRadius; // legend realTimeData.options.legend.display = displayLegend; } this.setState({ previewChart: realTimeData || previewChart, newChart: { ...newChart, pointRadius: typeof pointRadius !== "undefined" ? pointRadius : newChart.pointRadius, displayLegend: typeof displayLegend !== "undefined" ? displayLegend : newChart.displayLegend, startDate: (dateRange && dateRange.startDate) || newChart.startDate, endDate: (dateRange && dateRange.endDate) || newChart.endDate, timeInterval: timeInterval || newChart.timeInterval, includeZeros: typeof includeZeros !== "undefined" ? includeZeros : newChart.includeZeros, currentEndDate: typeof currentEndDate !== "undefined" ? currentEndDate : newChart.currentEndDate, }, }, () => { if (includeZeros || includeZeros === false || currentEndDate || currentEndDate === false || timeInterval ) { this._onPreview(); } }); } /* API Stuff */ _formatApiRequest = () => { const { apiRequest } = this.state; if (!apiRequest) return {}; const { formattedHeaders } = apiRequest; let newHeaders = {}; for (let i = 0; i < formattedHeaders.length; i++) { if (formattedHeaders[i].key && formattedHeaders[i].value) { newHeaders = { [formattedHeaders[i].key]: formattedHeaders[i].value, ...newHeaders }; } } const newRequest = apiRequest; newRequest.headers = newHeaders; this.setState({ noSource: false }); return newRequest; } _onPaginationChanged = (type, value) => { const { newChart } = this.state; let newValue = value; if (type === "itemsLimit" && value && value !== "0") { newValue = Math.abs(parseInt(value, 10)); } this.setState({ newChart: { ...newChart, [type]: newValue, }, }); } /* End of API Stuff */ _onPreview = (e, refresh) => { const { getPreviewData, match } = this.props; const { newChart, selectedConnection, noSource } = this.state; const previewData = newChart; let tempNoSource = noSource; if (refresh === true) { tempNoSource = false; } if (selectedConnection && selectedConnection.type === "api") { previewData.apiRequest = this._formatApiRequest(); } this.setState({ previewLoading: true, previewError: false }); getPreviewData(match.params.projectId, previewData, tempNoSource) .then((chartData) => { this.setState({ previewChart: chartData, previewLoading: false, noSource: true }); }) .catch(() => { this.setState({ previewLoading: false, previewError: true }); }); } _testQuery = () => { const { testQuery, match } = this.props; const { newChart } = this.state; this.setState({ testError: false, testingQuery: true, testSuccess: false, testFailed: false, }); return testQuery(match.params.projectId, newChart) .then((data) => { this.setState({ testingQuery: false, testSuccess: true, queryData: data, }); }) .catch((error) => { if (error === 413) { this.setState({ testingQuery: false, testError: true }); } else { this.setState({ testingQuery: false, testFailed: true, testError: true }); } }); } _apiTest = (data) => { this.setState({ testSuccess: true, queryData: data }); } _validate = () => { const { newChart } = this.state; // Line chart with timeseries if ((newChart.type === "line" || newChart.type === "bar") && (newChart.subType === "lcTimeseries" || newChart.subType === "lcAddTimeseries" || newChart.subType === "bcTimeseries" || newChart.subType === "bcAddTimeseries")) { // check if the xAxis is properly formatted (the date is inside an array) if (newChart.xAxis.indexOf("[]") === -1 || (newChart.xAxis.match(/[]/g) || []).length > 1) { // eslint-disable-line this.setState({ lcArrayError: true }); return false; } } return true; } _onAddNewDataset = () => { const { newChart } = this.state; const tempChart = { ...newChart }; tempChart.Datasets.push({ xAxis: "root", legend: `Dataset #${tempChart.Datasets.length + 1}`, }); this.setState({ newChart: tempChart, activeDataset: tempChart.Datasets.length - 1, viewDatasetOptions: true }); } _onRemoveDataset = (remove) => { const { newChart, activeDataset } = this.state; const tempChart = { ...newChart }; tempChart.Datasets[activeDataset].deleted = remove; this.setState({ newChart: tempChart }); this._onPreview(); } _onUpdateConfirmation = () => { const { newChart } = this.state; let showModal = false; for (const dataset of newChart.Datasets) { // eslint-disable-line if (dataset.deleted) { showModal = true; break; } } if (showModal) { this.setState({ removeModal: true }); } else { this._onCreateChart(); } } _updateDraft = () => { this.setState({ timeToSave: false }); this._onCreateChart(); setTimeout(() => { this.setState({ timeToSave: true }); }, 10000); } _onSetAutosave = () => { const { autosave } = this.state; this.setState({ autosave: !autosave }); } _onCreateChart = (create) => { const { createChart, match, runQuery, history, updateChart } = this.props; const { newChart, selectedConnection } = this.state; const updatedChart = newChart; if (selectedConnection && selectedConnection.type === "api") { updatedChart.apiRequest = this._formatApiRequest(); } this.setState({ createLoading: true, removeModal: false }); if (!newChart.id) { createChart(match.params.projectId, updatedChart) .then((chart) => { return runQuery(match.params.projectId, chart.id); }) .then(() => { this.setState({ createLoading: false }); history.push(`/${match.params.teamId}/${match.params.projectId}/dashboard`); }) .catch(() => { this.setState({ createLoading: false, createError: true }); }); } else { if (create) updatedChart.draft = false; updateChart( match.params.projectId, newChart.id, updatedChart ) .then((chart) => { this.setState({ createLoading: false }); toast.success("Chart updated 👌", { position: "bottom-right", autoClose: 1500, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, transition: Flip, }); runQuery(match.params.projectId, chart.id); if (create) { history.push(`/${match.params.teamId}/${match.params.projectId}/dashboard`); } this.setState({ newChart: { ...newChart, Datasets: chart.Datasets, }, }); return Promise.resolve(true); }) .catch(() => { this.setState({ createLoading: false, createError: true }); }); } } render() { const { activeDataset, newChart, previewChart, selectedConnection, testSuccess, viewDatasetOptions, queryData, step, ddConnections, testError, testFailed, testingQuery, apiRequest, previewLoading, previewError, lcArrayError, createError, autosave, removeModal, createLoading, removeLoading, } = this.state; const { connections, match } = this.props; return ( <div style={styles.container}> <Sidebar.Pushable as={Segment}> <Sidebar as={Segment} color="teal" animation="overlay" visible={viewDatasetOptions} width="very wide" direction="right" style={{ width: "50%" }} > <Container textAlign="center"> <Button.Group widths="3"> <Button icon labelPosition="left" onClick={this._onPreview} > <Icon name="refresh" /> Preview </Button> <Button secondary onClick={() => { this.setState({ viewDatasetOptions: false }); this._onPreview(); }} > Done </Button> {!newChart.Datasets[activeDataset].deleted && ( <Button basic negative icon labelPosition="right" onClick={() => this._onRemoveDataset(true)} > <Icon name="x" /> Remove </Button> )} {newChart.Datasets[activeDataset].deleted && ( <Button basic icon labelPosition="right" onClick={() => this._onRemoveDataset(false)} > <Icon name="plus" /> Re-enable </Button> )} </Button.Group> </Container> <Divider /> <Container text> <Popup trigger={( <Button icon labelPosition="left"> <Icon name="info" /> How to select fields </Button> )} > <Container text> <Header>Selecting fields</Header> <p>{"You can use the object visualizer below. Just click on it to expand your data tree."}</p> <p>{"You can manually select a field just as you would access an attribute within an object in Javascript:"}</p> <pre>root.someOtherObject.value</pre> <p>{"Array fields are identified by appending '[]' at the end like so"}</p> <pre>root.someArrayField[].value</pre> </Container> </Popup> </Container> <br /> {queryData && ( <ObjectExplorer objectData={queryData} type={newChart.type} subType={newChart.subType} onChange={this._onChangeAxis} xAxisField={newChart.Datasets[activeDataset].xAxis} /> )} <br /> {activeDataset !== false && ( <ChartBuilder type={newChart.type} subType={newChart.subType} editChart={!!newChart.id} xAxis={newChart.Datasets[activeDataset].xAxis || ""} datasetColor={newChart.Datasets[activeDataset].datasetColor} fillColor={newChart.Datasets[activeDataset].fillColor} fill={newChart.Datasets[activeDataset].fill} legend={newChart.Datasets[activeDataset].legend} patterns={newChart.Datasets[activeDataset].patterns} dataArray={previewChart && previewChart.data.datasets[activeDataset] ? previewChart.data.datasets[activeDataset].data : newChart.chartData && newChart.chartData.data.datasets[activeDataset] ? newChart.chartData.data.datasets[activeDataset].data : []} dataLabels={previewChart ? previewChart.data.labels : newChart.chartData ? newChart.chartData.data.labels : []} onChange={this._onChangeChart} /> )} </Sidebar> <Sidebar.Pusher> <Container fluid style={{ paddingLeft: 20, paddingRight: viewDatasetOptions ? 0 : 10, }} onClick={() => { if (viewDatasetOptions) { this.setState({ viewDatasetOptions: false }); } }} > <Segment attached style={styles.mainSegment}> <Step.Group fluid widths={4}> <Step active={step === 0} onClick={() => this._onChangeStep(0)} > <Icon name="th large" /> <Step.Content> <Step.Title>Chart type</Step.Title> <Step.Description>Choose your chart type</Step.Description> </Step.Content> </Step> <Step active={step === 1} disabled={!newChart.subType} onClick={() => this._onChangeStep(1)} > <Icon name="plug" /> <Step.Content> <Step.Title>Connect</Step.Title> <Step.Description>Your database connection</Step.Description> </Step.Content> </Step> <Step active={step === 2} disabled={ !newChart.connection_id || !newChart.name || !newChart.subType } onClick={() => this._onChangeStep(2)} > <Icon name="database" /> <Step.Content> <Step.Title>Query</Step.Title> <Step.Description>Get some data</Step.Description> </Step.Content> </Step> <Step active={step === 3} disabled={ !newChart.connection_id || !newChart.name || !testSuccess || !newChart.subType } onClick={() => this._onChangeStep(3)} > <Icon name="chart area" /> <Step.Content> <Step.Title>Build</Step.Title> <Step.Description>Build your chart</Step.Description> </Step.Content> </Step> </Step.Group> {step === 0 && ( <ChartTypesSelector type={newChart.type} subType={newChart.subType} onChange={this._onChangeType} /> )} {step === 1 && ( <Form> <Form.Field> <label>What will your chart show?</label> <Input placeholder="Give your chart a short description" value={newChart.name || ""} onChange={(e, data) => { this.setState({ newChart: { ...newChart, name: data.value } }); }} /> </Form.Field> <Form.Field> <label>Select a connection</label> <Dropdown placeholder="Select an available connection from the list" selection value={newChart.connection_id} options={ddConnections} disabled={connections.length < 1} onChange={(e, data) => this._onChangeConnection(data.value)} /> </Form.Field> {connections.length < 1 && ( <Form.Field> <Link to={`/${match.params.teamId}/${match.params.projectId}/connections`}> <Button primary icon labelPosition="right"> <Icon name="plug" /> Go to connections </Button> </Link> </Form.Field> )} </Form> )} {step === 2 && selectedConnection.type === "mongodb" && ( <MongoQueryBuilder currentQuery={newChart.query} onChangeQuery={(value) => { this.setState({ newChart: { ...newChart, query: value } }); }} testQuery={this._testQuery} testSuccess={testSuccess} testError={testError} testFailed={testFailed} testingQuery={testingQuery} /> )} {step === 2 && selectedConnection.type === "api" && ( <ApiBuilder connection={selectedConnection} onComplete={(data) => this._apiTest(data)} apiRequest={apiRequest || ""} onChangeRequest={(apiRequest) => { this.setState({ apiRequest }); }} chartId={newChart.id} itemsLimit={newChart.itemsLimit} items={newChart.items} offset={newChart.offset} pagination={newChart.pagination} onPaginationChanged={this._onPaginationChanged} /> )} {step === 2 && selectedConnection.type === "postgres" && ( <PostgresQueryBuilder currentQuery={newChart.query} onChangeQuery={(value) => { this.setState({ newChart: { ...newChart, query: value } }); }} testQuery={this._testQuery} testSuccess={testSuccess} testError={testError} testFailed={testFailed} testingQuery={testingQuery} /> )} {step === 2 && selectedConnection.type === "mysql" && ( <MysqlQueryBuilder currentQuery={newChart.query} onChangeQuery={(value) => { this.setState({ newChart: { ...newChart, query: value } }); }} testQuery={this._testQuery} testSuccess={testSuccess} testError={testError} testFailed={testFailed} testingQuery={testingQuery} /> )} {step === 3 && ( <Grid columns={2} centered divided> <Grid.Column width={8}> <Dimmer inverted active={previewLoading}> <Loader inverted /> </Dimmer> <Container textAlign="center"> <Header textAlign="left" as="h3" dividing> Build your chart </Header> <Button.Group widths={10}> <Button icon labelPosition="left" onClick={this._onPreview} style={{ marginBottom: 20 }} > <Icon name="refresh" /> Refresh preview </Button> <Button icon labelPosition="right" onClick={() => this._onPreview(null, true)} style={{ marginBottom: 20 }} basic > <Icon name="angle double down" /> Get latest data </Button> </Button.Group> </Container> {previewChart && ( <div style={{ maxHeight: "30em" }}> {newChart.type === "line" && ( <Line data={previewChart.data} options={previewChart.options} height={300} /> )} {newChart.type === "bar" && ( <Bar data={previewChart.data} options={previewChart.options} height={300} /> )} {newChart.type === "pie" && ( <Pie data={previewChart.data} options={previewChart.options} height={300} /> )} {newChart.type === "doughnut" && ( <Doughnut data={previewChart.data} options={previewChart.options} height={300} /> )} {newChart.type === "radar" && ( <Radar data={previewChart.data} options={previewChart.options} height={300} /> )} {newChart.type === "polar" && ( <Polar data={previewChart.data} options={previewChart.options} height={300} /> )} </div> )} {!previewChart && <p>{"No data to preview. Configure your datasets and press the refresh button."}</p>} {previewError && ( <div> <br /> <Message negative onDismiss={() => this.setState({ previewError: false })} > <Message.Header> {"Oh snap! We could't render the chart for you"} </Message.Header> <p>{"Make sure your configuration, like the query and selected fields are valid."}</p> </Message> </div> )} </Grid.Column> <Grid.Column width={8}> <Header as="h3" dividing> Configure your datasets </Header> <Header size="small">Datasets</Header> {newChart.Datasets.map((dataset, index) => { if (dataset.deleted) { return ( <Button key={dataset.legend} basic primary icon labelPosition="right" onClick={() => { this.setState({ viewDatasetOptions: true, activeDataset: index }); }} > <Icon name="x" /> {dataset.legend || "Dataset"} </Button> ); } return ( <Button key={dataset.legend} primary icon labelPosition="right" onClick={() => { this.setState({ viewDatasetOptions: true, activeDataset: index }); }} > <Icon name="options" /> {dataset.legend || "Dataset"} </Button> ); })} <br /> {newChart.type !== "polar" && ( <List animated verticalAlign="middle"> <List.Item as="a" onClick={this._onAddNewDataset}> <Icon name="plus" /> <List.Content> <List.Header> Add a new dataset </List.Header> </List.Content> </List.Item> </List> )} <Divider /> <Header size="small"> Global settings </Header> <TimeseriesGlobalSettings type={newChart.type} subType={newChart.subType} pointRadius={newChart.pointRadius} startDate={newChart.startDate} endDate={newChart.endDate} displayLegend={newChart.displayLegend} includeZeros={newChart.includeZeros} currentEndDate={newChart.currentEndDate} timeInterval={newChart.timeInterval} onChange={this._onChangeGlobalSettings} onComplete={() => this._onPreview()} /> </Grid.Column> </Grid> )} {createError && ( <Message negative onDismiss={() => this.setState({ createError: false })} header="There was a problem with your request" content="This is on us, we couldn't process your request. Please try again." /> )} {lcArrayError && ( <Message negative onDismiss={() => this.setState({ lcArrayError: false })} header="The data you selected is not correct" content="In order to create a valid time series chart, you must select a date field that is within an array. Make sure there is only one array in your selector '[]'." /> )} <ToastContainer position="bottom-right" autoClose={1500} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnVisibilityChange draggable pauseOnHover transition={Flip} /> </Segment> <Button.Group attached="bottom"> <Button secondary icon labelPosition="left" disabled={step === 0} onClick={() => this._onChangeStep(step - 1)} > <Icon name="chevron left" /> Back </Button> {newChart.id && ( <Button color={autosave ? "teal" : "gray"} onClick={this._onSetAutosave} icon labelPosition="left" > <Icon name={autosave ? "toggle on" : "toggle off"} /> Autosave { autosave ? " on" : " off" } </Button> )} {newChart.id && ( <Button primary loading={createLoading} onClick={this._onUpdateConfirmation} icon labelPosition="right" > <Icon name="edit" /> Update the chart </Button> )} {step < 3 && ( <Button secondary icon labelPosition="right" onClick={() => { if (step === 2 && !testSuccess && selectedConnection.type !== "api") { this._testQuery(); } else { this._onChangeStep(step + 1); } }} loading={testingQuery} disabled={ (step === 0 && !newChart.subType) || (step === 1 && (!newChart.connection_id || !newChart.name)) } > <Icon name="chevron right" /> {(step === 2 && !testSuccess && selectedConnection.type !== "api") ? "Run test" : "Next"} </Button> )} {step > 2 && newChart.draft && ( <Button secondary icon labelPosition="right" disabled={!testSuccess} loading={createLoading} onClick={() => this._onCreateChart(true)} > <Icon name="checkmark" /> Create the chart </Button> )} </Button.Group> </Container> </Sidebar.Pusher> </Sidebar.Pushable> <Modal open={removeModal} basic size="small" onClose={() => this.setState({ removeModal: false })} > <Header icon="exclamation triangle" content="All the datasets that were market as deleted will be forever removed upon updating" /> <Modal.Content> <p> {"You can always re-enable datasets while editing the chart, but once you save the changes all the datasets marked as deleted will be gone forever."} </p> </Modal.Content> <Modal.Actions> <Button basic inverted onClick={() => this.setState({ removeModal: false })} > Go back </Button> <Button color="teal" inverted loading={!!removeLoading} onClick={() => this._onCreateChart()} > <Icon name="checkmark" /> Update & Remove datasets </Button> </Modal.Actions> </Modal> </div> ); } }
JavaScript
class Codegen extends Visitor { /** * Creates new instance of codegen with empty symbol table. */ constructor() { super(); this._symbolTable = {}; this._code = []; } /** * Get symbol table. * * @returns {Object} */ getSymbolTable() { return this._symbolTable; } /** * Get generated assembly code. * * @returns {Array<String>} */ getCode() { return this._code; } /** * Emits one instruction (push it into the sequence of assembly op codes). * * @param {String} instruction Assembly instruction * @returns {Codegen} */ emit(instruction) { this._code.push(instruction); return this; } /** * Triggers when ArgumentsList node is met. * * @param {ArgumentsList} node */ onArgumentsList(node) { const symbolTable = this.getSymbolTable(); const variables = node.getNodes(); for (let i = 0; i < variables.length; i++) { symbolTable[variables[i].getIdentifier()] = i; } } /** * Triggers when BinaryOperator node is met. * * @param {BinaryOperator} node */ onBinaryOperator(node) { const lhs = node.getLHS(); const operator = node.getOperator(); const rhs = node.getRHS(); this.visit(lhs); this.emit(Codegen.SW()); this.visit(rhs); switch (operator) { case '-': this.emit(Codegen.SU()); break; case '+': this.emit(Codegen.AD()); break; case '*': this.emit(Codegen.MU()); break; case '/': this.emit(Codegen.DI()); break; } } /** * Triggers when FunctionDeclaration node is met. * * @param {FunctionDeclaration} node * @returns {Array<String>} */ onFunctionDeclaration(node) { this.visit(node.getArgumentsList()); this.visit(node.getExpression()); } /** * Triggers when NumberLiteral node is met. * * @param {NumberLiteral} node * @returns {String} */ onNumberLiteral(node) { this.emit(Codegen.IM(node.getValue())); } /** * Triggers when VariableIdentifier node is met. * * @param {VariableIdentifier} node */ onVariableIdentifier(node) { const symbolTable = this.getSymbolTable(); const identifier = node.getIdentifier(); if (typeof symbolTable[identifier] === 'undefined') { throw new Error(`Unknown variable: ${identifier}`); } this.emit(Codegen.AR(symbolTable[identifier])); } /** * Converts current codegen phase to string representation. * * @returns {String} */ toString() { return this.getCode().join('\n'); } /** * Load the constant value n into R0. * * @static * @param {Number} n Constant value (number literal) * @returns {String} */ static IM(n) { return `IM ${n}`; } /** * Load the n-th input argument into R0. * * @static * @param {Number} n Arguments index * @returns {String} */ static AR(n) { return `AR ${n}`; } /** * Swap R0 and R1. * * @static * @returns {String} */ static SW() { return 'SW'; } /** * Push R0 onto the stack. * * @static * @returns {String} */ static PU() { return 'PU'; } /** * Pop the top value off of the stack into R0. * * @static * @returns {String} */ static PO() { return 'PO'; } /** * Add R1 to R0 and put the result in R0. * * @static * @returns {String} */ static AD() { return 'AD'; } /** * Subtract R1 from R0 and put the result in R0. * * @static * @returns {String} */ static SU() { return 'SU'; } /** * Multiply R0 by R1 and put the result in R0. * * @static * @returns {String} */ static MU() { return 'MU'; } /** * Divide R0 by R1 and put the result in R0. * * @static * @returns {String} */ static DI() { return 'DI'; } }
JavaScript
class MapPopupInfo extends Component { state = { center: { lat: 47.646935, lng: -122.303763, }, // array of objects of markers markers: [ { position: new google.maps.LatLng(47.646145, -122.303763), showInfo: false, infoContent: ( <div className="d-flex"> <div> <svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" > <path d="M3.5 0c-1.7 0-3 1.6-3 3.5 0 1.7 1 3 2.3 3.4l-.5 8c0 .6.4 1 1 1h.5c.5 0 1-.4 1-1L4 7C5.5 6.4 6.5 5 6.5 3.4c0-2-1.3-3.5-3-3.5zm10 0l-.8 5h-.6l-.3-5h-.4L11 5H10l-.8-5H9v6.5c0 .3.2.5.5.5h1.3l-.5 8c0 .6.4 1 1 1h.4c.6 0 1-.4 1-1l-.5-8h1.3c.3 0 .5-.2.5-.5V0h-.4z" /> </svg> </div> <div className="ml-1"> <p>UW Medical Center</p> <p>1959 NE Pacific St</p> <p>Seattle, WA 98195</p> </div> </div> ), }, { position: new google.maps.LatLng(47.647935, -122.303763), showInfo: false, infoContent: ( <div className="d-flex"> <div> <svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" > <path d="M6 14.5c0 .828-.672 1.5-1.5 1.5S3 15.328 3 14.5 3.672 13 4.5 13s1.5.672 1.5 1.5zM16 14.5c0 .828-.672 1.5-1.5 1.5s-1.5-.672-1.5-1.5.672-1.5 1.5-1.5 1.5.672 1.5 1.5zM16 8V2H4c0-.552-.448-1-1-1H0v1h2l.75 6.438C2.294 8.805 2 9.368 2 10c0 1.105.895 2 2 2h12v-1H4c-.552 0-1-.448-1-1v-.01L16 8z" /> </svg> </div> <div className="ml-1"> <p>University of Washington Intramural Activities (IMA) Building</p> <p>3924 Montlake Blvd NE</p> <p>Seattle, WA 98195</p> </div> </div> ), }, ], }; handleMarkerClick = this.handleMarkerClick.bind(this); handleMarkerClose = this.handleMarkerClose.bind(this); // Toggle to 'true' to show InfoWindow and re-renders simple handleMarkerClick(targetMarker) { this.setState({ markers: this.state.markers.map(marker => { if (marker === targetMarker) { return { ...marker, showInfo: true, }; } return marker; }), }); } handleMarkerClose(targetMarker) { this.setState({ markers: this.state.markers.map(marker => { if (marker === targetMarker) { return { ...marker, showInfo: false, }; } return marker; }), }); } render() { return ( <PopUpInfoWindowExampleGoogleMap loadingElement={<div style={{height: `100%`}}/>} containerElement={<div style={{height: `550px`}}/>} mapElement={<div style={{height: `100%`}}/>} center={this.state.center} markers={this.state.markers} onMarkerClick={this.handleMarkerClick} onMarkerClose={this.handleMarkerClose} /> ); } }
JavaScript
class ParamSeekHandler { constructor(paramStart, paramEnd) { this._startName = paramStart; this._endName = paramEnd; } getConfig(baseUrl, range) { let url = baseUrl; if (range.from !== 0 || range.to !== -1) { let needAnd = true; if (url.indexOf('?') === -1) { url += '?'; needAnd = false; } if (needAnd) { url += '&'; } url += `${this._startName}=${range.from.toString()}`; if (range.to !== -1) { url += `&${this._endName}=${range.to.toString()}`; } } return { url: url, headers: {} }; } }
JavaScript
class Nav extends Component { // M.AutoInit(); componentDidMount() { var elem = document.querySelector(".sidenav"); var instance = M.Sidenav.init(elem, { edge: "left", inDuration: 250 }); } render() { // console.log(this.props) return ( <div> <ul id="slide-out" className="sidenav"> <li /> {(this.props.loggedInUser.isLoggedIn) ? <li> <a>Welcome back, {this.props.loggedInUser.username}!</a> </li> : <li> <a>Welcome! Login or Signup Below!</a> </li> } <li> <div className="divider" /> </li> <li> <a href="/search">Search the ACNH Database!</a> </li> <li> <a href="/newuser"> {/* <i className="material-icons">cloud</i> */} Sign Up! </a> </li> {(!this.props.loggedInUser.isLoggedIn) ? <li> <a href="/login">Login</a> </li> : <li> <a className="waves-effect" href="/login" onClick={this.props.logoutHandle}> Logout </a> </li> } <li> <a className="waves-effect" href={"/users/" + this.props.loggedInUser.id}> My Dashboard </a> </li> </ul> <a href="#" data-target="slide-out" className="sidenav-trigger"> <Button className="green accent-5 nav-button" floating icon={<Icon>menu</Icon>} large node="button" waves="light" /> </a> </div> ) } }
JavaScript
class CacheManager { constructor() { this.cache = new Map(); } /** * Add to cache */ set(key, value) { this.cache.set(key, value); } /** * Read from cache */ get(key) { return this.cache.get(key); } }
JavaScript
class SimpleDockerode extends Dockerode { /** * Wrapper for Dockerode's native function, to swap exec for {@link processArgs} * @param {Array} args A spread parameter, passed through to Dockerode's getContainer */ getContainer(...args) { const container = super.getContainer(...args) container.execRaw = container.exec container.exec = processArgs return container } }
JavaScript
class View { constructor(width, height, options) { this.width = width this.height = height this.reset(options) } reset(options = {}) { this.zoomLevel = options.initialZoom || 1 this.zoomBy(0) // set this.size. // In tile coordinates. this.scrollX = options.initialX || 0 this.scrollY = options.initialY || 0 draw() } fit(w, h, offx, offy) { // Put a 1 tile border in. //offx -= 1; offy -= 1 //w += 2; h += 2 this.scrollX = offx this.scrollY = offy const sizeW = this.width / w, sizeH = this.height / h let tileSize //debugger; if (sizeW > sizeH) { tileSize = clamp(sizeH, 1, 100) this.scrollX -= (this.width/tileSize - w)/2 } else { tileSize = clamp(sizeW, 1, 100) this.scrollY -= (this.height/tileSize - h)/2 } this.zoomLevel = tileSize this.zoomBy(0) } zoomBy(diff, center) { // Center is {x, y} //console.log(diff, center) const oldsize = this.size this.zoomLevel += diff this.zoomLevel = clamp(this.zoomLevel, 1, 100) this.size = this.zoomLevel // Recenter if (center != null) { this.scrollX += center.x / oldsize - center.x / this.size this.scrollY += center.y / oldsize - center.y / this.size } this.clampFrame() //console.log(scrollX, scrollY, this.size) draw() } snap(center) { const fl = Math.floor(this.size) // const AMT = 0.05 if (this.size != fl) { const oldsize = this.size this.size = fl//(oldsize - fl < AMT) ? fl : oldsize - AMT if (center != null) { this.scrollX += center.x / oldsize - center.x / this.size this.scrollY += center.y / oldsize - center.y / this.size } return true } else return false } scrollBy(dx, dy) { if (isNaN(dx)) throw Error('dx NaN') this.scrollX += dx / this.size this.scrollY += dy / this.size this.clampFrame() draw() } clampFrame() { // Clamp the visible area so the middle of the screen always has content. const imgwidth = 1000 * this.size const visX = this.width / this.size const visY = this.height / this.size if (imgwidth > this.width) this.scrollX = clamp(this.scrollX, -visX/2, 1000 - visX/2) else this.scrollX = clamp(this.scrollX, 500 - visX, 500) if (imgwidth > this.height) this.scrollY = clamp(this.scrollY, -visX/2, 1000 - visY/2) else this.scrollY = clamp(this.scrollY, 500 - visY, 500) } resizeTo(width, height) { this.width = width this.height = height canvas.width = width * devicePixelRatio canvas.height = height * devicePixelRatio ctx = canvas.getContext('2d') ctx.scale(window.devicePixelRatio, window.devicePixelRatio) // TODO: Scale based on devicePixelRatio. draw() } // **** Utility methods // given pixel x,y returns tile x,y screenToWorld(px, py) { if (px == null) return {tx:null, ty:null} // first, the top-left pixel of the screen is at |_ scroll * size _| px from origin px += Math.floor(this.scrollX * this.size) py += Math.floor(this.scrollY * this.size) // now we can simply divide and floor to find the tile const tx = Math.floor(px / this.size) const ty = Math.floor(py / this.size) return {tx, ty} } worldToScreen(tx, ty) { return { px: tx * this.size - Math.floor(this.scrollX * this.size), py: ty * this.size - Math.floor(this.scrollY * this.size) } } }
JavaScript
class Scratch3SpeakBlocks { constructor (runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; // Clear sound effects on green flag and stop button events. // this._clearEffectsForAllTargets = this._clearEffectsForAllTargets.bind(this); if (this.runtime) { // @todo // this.runtime.on('PROJECT_STOP_ALL', this._clearEffectsForAllTargets); } /** * Locale code of the viewer * @type {string} * @private */ this._language = this.getViewerLanguageCode(); } /** * The key to load & store a target's synthesis state. * @return {string} The key. */ static get STATE_KEY () { return 'Scratch.text2speech'; } /** * @returns {object} metadata for this extension and its blocks. */ getInfo () { return { id: 'text2speech', name: 'Text-to-Speech', menuIconURI: '', // @todo Add the final icons. blockIconURI: '', blocks: [ { opcode: 'speakAndWait', text: formatMessage({ id: 'speak.speakAndWaitBlock', default: 'speak [WORDS]', description: 'speak some words' }), blockType: BlockType.COMMAND, arguments: { WORDS: { type: ArgumentType.STRING, defaultValue: formatMessage({ id: 'speak.defaultTextToSpeak', default: 'hello', description: 'hello: the default text to speak' }) } } } ], menus: { voices: this.supportedVoices } }; } /** * Get the viewer's language code. * @return {string} the language code. */ getViewerLanguageCode () { // @todo This should be the language code of the project *creator* // rather than the project viewer. return navigator.language || navigator.userLanguage || 'en-US'; } /** * Return the supported voices for the extension. * @return {Array} Supported voices */ supportedVoices () { return [ 'Quinn', 'Max', 'Squeak', 'Monster', 'Puppy' ]; } /** * Convert the provided text into a sound file and then play the file. * @param {object} args Block arguments * @return {Promise} A promise that resolves after playing the sound */ speakAndWait (args) { // Cast input to string args.WORDS = Cast.toString(args.WORDS); // Build up URL let path = `${SERVER_HOST}/synth`; path += `?locale=${this._language}`; path += `&gender=male`; // @todo path += `&text=${encodeURI(args.WORDS)}`; // Perform HTTP request to get audio file return new Promise(resolve => { nets({ url: path, timeout: SERVER_TIMEOUT }, (err, res, body) => { if (err) { log.warn(err); return resolve(); } if (res.statusCode !== 200) { log.warn(res.statusCode); return resolve(); } // Play the sound const sound = { // md5: 'test', // name: 'test', // format: 'audio/mpg', data: { buffer: body.buffer } }; this.runtime.audioEngine.decodeSoundPlayer(sound).then(soundPlayer => { soundPlayer.connect(this.runtime.audioEngine); soundPlayer.play(); soundPlayer.on('stop', resolve); }); }); }); } }
JavaScript
class FontsArePreloaded extends rule_1.Rule { run({ $ }) { const css = $("style[amp-custom]").html(); if (!css || !FONT_FACE_URL_PATTERN.test(css)) { return this.pass(); } const preloadedFonts = $("link[rel='preload'],[as='font']").length; if (preloadedFonts === 0) { return this.info("Web fonts are used without preloading. Preload them if they are used in the first viewport."); } return this.pass(); } meta() { return { url: "https://web.dev/codelab-preload-web-fonts/", title: "Web fonts are preloaded", info: "", }; } }
JavaScript
class WT_MapViewTrackVectorLayer extends WT_MapViewMultiLayer { constructor(airspeedSensorIndex, className = WT_MapViewTrackVectorLayer.CLASS_DEFAULT, configName = WT_MapViewTrackVectorLayer.CONFIG_NAME_DEFAULT) { super(className, configName); this._airspeedSensorIndex = airspeedSensorIndex; this._dynamicLookaheadMax = new WT_NumberUnit(0, WT_Unit.SECOND); this._optsManager = new WT_OptionsManager(this, WT_MapViewTrackVectorLayer.OPTIONS_DEF); this._vectorLayer = new WT_MapViewCanvas(false, true); this.addSubLayer(this._vectorLayer); this._lastTime = 0; this._lastTurnSpeed = 0; this._lastDrawnBounds = {left: 0, top: 0, width: 0, height: 0}; this._tempNM = WT_Unit.NMILE.createNumber(0); this._tempKnot = WT_Unit.KNOT.createNumber(0); this._tempTrueBearing = new WT_NavAngleUnit(false).createNumber(0); this._tempGeoPoint1 = new WT_GeoPoint(0, 0); this._tempGeoPoint2 = new WT_GeoPoint(0, 0); } _setPropertyFromConfig(name) { if (name === "dynamicLookaheadMax") { this._dynamicLookaheadMax.refNumber = this.config[name]; } else { super._setPropertyFromConfig(name); } } /** * @property {WT_NumberUnit} dynamicLookaheadMax - the maximum lookahead time to use when calculating dynamic track vectors. * @type {WT_NumberUnit} */ get dynamicLookaheadMax() { return this._dynamicLookaheadMax.readonly(); } set dynamicLookaheadMax(value) { this._dynamicLookaheadMax.set(value); } /** * @param {WT_MapViewState} state */ isVisible(state) { return state.model.trackVector.show; } /** * @param {WT_MapViewState} state */ onConfigLoaded(state) { for (let property of WT_MapViewTrackVectorLayer.CONFIG_PROPERTIES) { this._setPropertyFromConfig(property); } } _initTurnSpeedSmoother() { this._turnSpeedSmoother = new WT_ExponentialSmoother(this.smoothingConstant, 0, WT_MapViewTrackVectorLayer.SMOOTHING_MAX_TIME_DELTA); } onAttached(state) { super.onAttached(state); this._initTurnSpeedSmoother(state); } _setLastDrawnBounds(left, top, width, height) { this._lastDrawnBounds.left = left; this._lastDrawnBounds.top = top; this._lastDrawnBounds.width = width; this._lastDrawnBounds.height = height; } /** * Determines the time step to use when calculating a dynamic track vector in order to achieve this layer's desired spatial * resolution. * @param {WT_MapViewState} state - the current map view state. */ _calculateDynamicTimeStep(state) { let tas = state.model.airplane.sensors.getAirspeedSensor(this._airspeedSensorIndex).tas(this._tempKnot); let resolution = state.projection.viewResolution; let targetResolutionDistance = this.dynamicTargetResolution * resolution.asUnit(WT_Unit.METER); return targetResolutionDistance / tas.asUnit(WT_Unit.MPS); } /** * Calculates the path for a dynamic track vector using current aircraft parameters to build the predicted path. * @param {WT_MapViewState} state - the current map view state. */ _calculateDynamicVector(state) { let airplane = state.model.airplane; let timeStep = this._calculateDynamicTimeStep(state); let dt = state.currentTime / 1000 - this._lastTime; let resolution = state.projection.viewResolution.asUnit(WT_Unit.METER); let trackRad = (airplane.navigation.trackTrue() + state.projection.rotation) * Avionics.Utils.DEG2RAD; let tasPx = airplane.sensors.getAirspeedSensor(this._airspeedSensorIndex).tas(this._tempKnot).asUnit(WT_Unit.MPS) / resolution; let headingRad = (airplane.navigation.headingTrue() + state.projection.rotation) * Avionics.Utils.DEG2RAD; let turnSpeedRad = airplane.navigation.turnSpeed() * Avionics.Utils.DEG2RAD; let windSpeedPx = airplane.environment.windSpeed(this._tempKnot).asUnit(WT_Unit.MPS) / resolution; let windDirectionRad = (airplane.environment.windDirection(this._tempTrueBearing).number + state.projection.rotation + 180) * Avionics.Utils.DEG2RAD; let dynamicHeadingDeltaMaxRad = this.dynamicHeadingDeltaMax * Avionics.Utils.DEG2RAD; turnSpeedRad = this._turnSpeedSmoother.next(turnSpeedRad, dt); let lookahead = state.model.trackVector.lookahead.asUnit(WT_Unit.SECOND); let planeVelocityPx = new WT_GVector2(0, 0); let windVelocityPx = new WT_GVector2(0, 0); let points = [state.viewPlane]; let i = 0; for (let t = 0; t < lookahead; t += timeStep) { let angleDelta = Math.abs((headingRad - trackRad) % (2 * Math.PI)); if (Math.min(angleDelta, 2 * Math.PI - angleDelta) > dynamicHeadingDeltaMaxRad) { break; } planeVelocityPx.setFromPolar(tasPx, headingRad); windVelocityPx.setFromPolar(windSpeedPx, windDirectionRad); let currentPoint = points[i++]; let nextPoint = planeVelocityPx.plus(windVelocityPx).scale(timeStep, true).add(currentPoint); points.push(nextPoint); if (!state.projection.isInView(nextPoint, 0.05)) { break; } headingRad += turnSpeedRad * timeStep; } return points; } /** * Loads a path definition into this layer's canvas rendering context. * @param {{x:Number, y:Number}[]} points - a list of points, in pixel coordinates, comprising the path. */ _composeVectorPath(points) { this._vectorLayer.display.context.beginPath(); let i = 0; let currentPoint = points[i++]; this._vectorLayer.display.context.moveTo(currentPoint.x, currentPoint.y); while (i < points.length) { this._vectorLayer.display.context.lineTo(currentPoint.x, currentPoint.y); currentPoint = points[i++]; } } /** * Applies a stroke to this layer's canvas rendering context using the specified styles. * @param {Number} lineWidth - the width of the stroke, in pixels. * @param {String|CanvasGradient|CanvasPattern} strokeStyle - the style of the stroke. */ _applyStroke(lineWidth, strokeStyle) { this._vectorLayer.display.context.lineWidth = lineWidth; this._vectorLayer.display.context.strokeStyle = strokeStyle; this._vectorLayer.display.context.stroke(); } /** * Draws a dynamic track vector. * @param {WT_MapViewState} state - the current map view state. */ _drawDynamicVector(state) { let points = this._calculateDynamicVector(state); this._vectorLayer.display.context.clearRect(this._lastDrawnBounds.left, this._lastDrawnBounds.top, this._lastDrawnBounds.width, this._lastDrawnBounds.height); this._composeVectorPath(points); if (this.outlineWidth > 0) { this._applyStroke((this.outlineWidth * 2 + this.strokeWidth) * state.dpiScale, this.outlineColor); } this._applyStroke(this.strokeWidth * state.dpiScale, this.strokeColor); let thick = (this.outlineWidth + this.strokeWidth / 2) * state.dpiScale; let toDrawLeft = Math.max(0, Math.min(...points.map(point => point.x)) - thick - 5); let toDrawTop = Math.max(0, Math.min(...points.map(point => point.y)) - thick - 5); let toDrawWidth = Math.min(state.projection.viewWidth, Math.max(...points.map(point => point.x)) + thick + 5) - toDrawLeft; let toDrawHeight = Math.min(state.projection.viewHeight, Math.max(...points.map(point => point.y)) + thick + 5) - toDrawTop; this._setLastDrawnBounds(toDrawLeft, toDrawTop, toDrawWidth, toDrawHeight); } /** * Builds a GeoJSON LineString Feature object from a list of lat/long coordinates. * @param {{lat:Number, long:Number}[]} points - a list of lat/long coordinates. */ _buildGeoJSON(points) { return { type: "LineString", coordinates: points.map(latLong => [latLong.long, latLong.lat]) }; } /** * Draws a non-dynamic track vector. * @param {WT_MapViewState} state - the current map view state. */ _drawSimpleVector(state) { let airplane = state.model.airplane; let planePos = airplane.navigation.position(this._tempGeoPoint1); let gs = airplane.navigation.groundSpeed(this._tempKnot).number; let lookahead = state.model.trackVector.lookahead.asUnit(WT_Unit.HOUR); let points = [ planePos, state.projection.offsetByBearing(planePos, this._tempNM.set(gs * lookahead), airplane.navigation.trackTrue(), this._tempGeoPoint2) ]; let geoJSON = this._buildGeoJSON(points); this._vectorLayer.display.context.clearRect(this._lastDrawnBounds.left, this._lastDrawnBounds.top, this._lastDrawnBounds.width, this._lastDrawnBounds.height); this._vectorLayer.display.context.beginPath(); state.projection.renderer.renderCanvas(geoJSON, this._vectorLayer.display.context); if (this.outlineWidth > 0) { this._applyStroke((this.outlineWidth * 2 + this.strokeWidth) * state.dpiScale, this.outlineColor); } this._applyStroke(this.strokeWidth * state.dpiScale, this.strokeColor); let bounds = state.projection.renderer.calculateBounds(geoJSON); let thick = (this.outlineWidth + this.strokeWidth / 2) * state.dpiScale; let toDrawLeft = Math.max(0, bounds[0].x - thick - 5); let toDrawTop = Math.max(0, bounds[0].y - thick - 5); let toDrawWidth = Math.min(state.projection.viewWidth, bounds[1].x + thick + 5) - toDrawLeft; let toDrawHeight = Math.min(state.projection.viewHeight, bounds[1].y + thick + 5) - toDrawTop; this._setLastDrawnBounds(toDrawLeft, toDrawTop, toDrawWidth, toDrawHeight); } /** * @param {WT_MapViewState} state */ onUpdate(state) { super.onUpdate(state); if (state.model.airplane.sensors.isOnGround()) { return; } let lookahead = state.model.trackVector.lookahead; if (lookahead.compare(this.dynamicLookaheadMax) <= 0) { this._drawDynamicVector(state); } else { this._drawSimpleVector(state); } this._lastTime = state.currentTime / 1000; } }
JavaScript
class ReactiveComponent extends Component { constructor(pureRender, ref) { super(); // A pure function this.pureRender = pureRender; this.hooksIndex = 0; this.hooks = {}; this.didMountHandlers = []; this.didUpdateHandlers = []; this.willUnmountHandlers = []; if (pureRender.forwardRef) { this.prevForwardRef = this.forwardRef = ref; } const compares = pureRender.compares; if (compares) { this.shouldComponentUpdate = (nextProps) => { // Process composed compare let arePropsEqual = true; // Compare push in and pop out for (let i = compares.length - 1; i > -1; i--) { if (arePropsEqual = compares[i](this.props, nextProps)) { break; }; } return !arePropsEqual || this.prevForwardRef !== this.forwardRef; }; } } getCurrentHookId() { return ++this.hooksIndex; } readContext(context) { const Provider = context.Provider; const unmaskContext = this._internal._context; const contextProp = Provider.contextProp; const contextEmitter = unmaskContext[contextProp]; if (contextEmitter) { const mountId = this._internal._mountID; if (!contextEmitter[mountId]) { // One context one updater bind contextEmitter[mountId] = {}; const contextUpdater = (newContext) => { if (newContext !== contextEmitter[mountId].renderedContext) { this.update(); } }; contextEmitter.on(contextUpdater); this.willUnmountHandlers.push(() => { delete contextEmitter[mountId]; contextEmitter.off(contextUpdater); }); } return contextEmitter[mountId].renderedContext = contextEmitter.value; } return Provider.defaultValue; } isComponentRendered() { return Boolean(this._internal._renderedComponent); } componentDidMount() { this.didMountHandlers.forEach(handler => handler()); } componentDidUpdate() { this.didUpdateHandlers.forEach(handler => handler()); } componentWillUnmount() { this.willUnmountHandlers.forEach(handler => handler()); } // Async update update() { scheduleImmediateCallback(() => this.forceUpdate()); } render() { if (process.env.NODE_ENV !== 'production') { Host.measurer && Host.measurer.beforeRender(); } this.hooksIndex = 0; return this.pureRender(this.props, this.forwardRef ? this.forwardRef : this.context); } }
JavaScript
class StackArray { /** * Creates a STACK data-structure * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); */ constructor() { this._stack = []; } /** * Adds a element to the top of the STACK * @param {* | Array} element Element or Array passed to insert * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.push(5); //inserts 5 to the top of the stack * stack.push([8,63,2]); //inserts 8,63 and 2 to the top of the stack, in this order */ push(element) { this._stack.push(element); } /** * Removes a element from the top of the STACK * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.push(3); * stack.push(9); * * stack.pop(); //removes element 9 */ pop() { if (this._stack.length === 0) return undefined; this._stack.pop(); } /** * Returns the element on the top of the STACK * @returns {*|undefined} Returns the element or undefined if stack is empty * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.top();// returns undefined * * stack.push(23); * stack.push(89); * * stack.top(); //return 89 */ top() { if (this._stack.length === 0) return undefined; return this._stack[this._stack.length - 1]; } /** * Returns the size of the STACK data-structure * @returns {Number} The number of elements in the STACK * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.size(); //returns 0; * * stack.push(8); * * stack.size(); //returns 1; */ size() { return this._stack.length; } /** * Resets the STACK data-structure * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.push(15); * * stack.clear(); // now stack is empty */ clear() { this._stack = []; } /** * Returns if the STACK data-structure is empty * @returns {Boolean} * @example * const { StackArray } = require('data-structures-algorithms-js'); * const stack = new StackArray(); * * stack.isEmpty(); // returns true; * * stack.push(23); * * stack.isEmpty(); //returns false; */ isEmpty() { return this._stack.length === 0; } }
JavaScript
class AesService { /** * Encrypts data using AES. * * @constructs AesService * @param {string} pathToAesStore path to the AES parameters JSON file. * @param {number} byteSize The number of bytes to use when generating the key and IV. * 32 bytes used by default. Exception with GCM mode; IV will use 12 bytes. Key size * determines AES size: * - 16 => AES-128 * - 24 => AES-192 * - 32 => AES-256 * @param {string} mode The AES mode to use for encrypting. Default is 'AES-GCM'. * Accepted values: * - 'AES-GCM' * - 'AES-ECB' * - 'AES-CBC' * - 'AES-CFB' * - 'AES-OFB' * - 'AES-CTR' */ constructor(pathToAesStore, byteSize = 32, mode = 'AES-GCM') { this.pathToAesStore = pathToAesStore; this.byteSize = byteSize; switch (mode.toUpperCase()) { case 'AES-GCM': this.mode = 'AES-GCM'; break; case 'AES-ECB': this.mode = 'AES-ECB'; break; case 'AES-CBC': this.mode = 'AES-CBC'; break; case 'AES-CFB': this.mode = 'AES-CFB'; break; case 'AES-OFB': this.mode = 'AES-OFB'; break; case 'AES-CTR': this.mode = 'AES-CTR'; break; default: throw `The mode ${mode} is not a valid AES mode.`; } this.key = ''; this.iv = ''; this.gcmTag = ''; } /** * Gets the AES parameter file. If the file does not exist, it will * be created and populated with new AES parameters. */ getAesStore() { try { if (fs.existsSync(this.pathToAesStore)) { const aesStore = fs.readFileSync(this.pathToAesStore); const params = JSON.parse(aesStore); this.key = params.key; this.iv = params.iv; } else { // Create file with new AES parameters. this.generateAesParameters(this.byteSize); fs.writeFileSync(this.pathToAesStore, `{ "key": "${this.key}", "iv": "${this.iv}" }`); } } catch (e) { throw e; } } /** * Writes new AES parameters to the file store. */ writeToAesStore() { try { if (fs.existsSync(this.pathToAesStore)) { fs.writeFileSync(this.pathToAesStore, `{ "key": "${this.key}", "iv": "${this.iv}" }`); } else { throw `File path: ${this.pathToAesStore} does not exist.`; } } catch (e) { throw e; } } /** * Generates and sets new AES parameters. * * @param {number} byteSize The number of bytes to use for generating * the key and IV. */ generateAesParameters(byteSize) { try { this.key = forge.util.bytesToHex(forge.random.getBytesSync(byteSize)); if (this.mode === 'AES-GCM') { this.iv = forge.util.bytesToHex(forge.random.getBytesSync(12)); // Forge recommends 12 byte IV. } else { this.iv = forge.util.bytesToHex(forge.random.getBytesSync(byteSize)); } } catch (e) { throw e; } } /** * Encrypts the given text using AES. * * @param {string} text The text to be encrypted. * @returns Hexadecimal string representation of the encrypted data. */ encrypt(text) { try { if (this.mode === 'AES-GCM') { const cipher = forge.cipher.createCipher('AES-GCM', forge.util.hexToBytes(this.key)); cipher.start({iv: forge.util.hexToBytes(this.iv)}); cipher.update(forge.util.createBuffer(someBytes)); cipher.finish(); const encrypted = cipher.output; this.gcmTag = cipher.mode.tag; return encrypted.toHex() } else { const cipher = forge.cipher.createCipher(this.mode, forge.util.hexToBytes(this.key)); cipher.start({iv: forge.util.hexToBytes(this.iv)}); cipher.update(forge.util.createBuffer(text)); cipher.finish(); return cipher.output.toHex(); } } catch (e) { throw e; } } /** * Decrypts the given encrypted data. * * @param {string} encryptedData The hexadecimal string representation of the * encrypted data. * @returns UTF-8 string output of the plain text. */ decrypt(encryptedData) { try { if (this.mode === 'AES-GCM') { const encryptedBytes = forge.util.hexToBytes(encryptedData); const decipher = forge.cipher.createDecipher(this.mode, forge.util.hexToBytes(this.key)); decipher.start({ iv: forge.util.hexToBytes(this.iv), tag: this.gcmTag }); decipher.update(encryptedBytes); const result = decipher.finish(); if(result) { return decipher.output.toString(); } else { throw 'Could not decrypt the given data with the key.' } } else { const encryptedBytes = forge.util.hexToBytes(encryptedData); const decipher = forge.cipher.createDecipher(this.mode, forge.util.hexToBytes(this.key)); decipher.start({iv: forge.util.hexToBytes(this.iv)}); decipher.update(encryptedBytes); const result = decipher.finish(); if (result) { return decipher.output.toString('utf8'); } else { throw 'Could not decrypt the given data with the key.' } } } catch (e) { throw e; } } }
JavaScript
class DataActionResult { Success = true; Error = null; /** * Creates an instance of the DataActionResult class * @param {Error} error */ constructor(error = null) { this.Success = !error; this.Error = error || DataActionError.None; } /** * Gets the error message * @returns {string} */ get ErrorMessage() { if (Error === DataActionError.NotFound) { return "Item not found"; } if (Error === DataActionError.NotFound) { return "Duplicated item"; } return ""; } }
JavaScript
@inject('template') class Template extends PureComponent { componentDidMount() { const { getDetail } = this.props.templateActions; const { id } = this.props.location.query; getDetail({id}); } onSubmit = err => { if(!!err) return; const { update } = this.props.templateActions; const { form } = this.props.templateStore; // const { // fields1, // fields2, // fields3, // fields4, // } = form; // const params = { // fields1, // fields2, // fields3, // fields4, // }; // update(params).then(() => history.go(-1)) }; // 表单联动 // relateField1 = field1Value => { // const { form } = this.state; // this.dynamicForm.setFieldsValue({ // field1: field1Value, // }); // this.setState({form}); // }; onChange = ({name, value}) => { const { updateForm } = this.props.templateActions; const { form } = this.props.templateStore; form[name] = value; updateForm(form); }; render() { const { form } = this.props.templateStore; return ( <div id="template"> <DynamicForm wrappedComponentRef={dynamicForm => this.dynamicForm = dynamicForm} formFields={form} fieldsConfig={fieldsConfig} onSubmit={this.onSubmit} onChange={this.onChange}> <Button type='primary' htmlType='submit'>保存</Button> </DynamicForm> </div> ); } }
JavaScript
class RadSliderInteractionLayer extends Component { constructor(props) { super(props); this.scrollHappened = this.scrollHappened.bind(this); this.onUpScroll = this.onUpScroll.bind(this); this.onDownScroll = this.onDownScroll.bind(this); } /* * Scrolling capability */ // Handles the onScroll event on the interaction layer and determines the scroll direction // and dispatching a CustomEvent representing the direction scrolled. scrollHappened(e){ e.preventDefault(); let element = document.getElementsByClassName("RadSliderInteractionLayer")[0] let scrollUpEvent = new CustomEvent("scrollUp"), scrollDownEvent = new CustomEvent("scrollDown"); if(e.deltaY < 0){ element.dispatchEvent(scrollUpEvent); } else { element.dispatchEvent(scrollDownEvent); } } // UI handler for scroll up - callback to main container. onUpScroll(e) { this.props.handleChangeSetTemp(this.props.setTemp + 0.5); } // UI handler for scroll down - callback to main container. onDownScroll(e) { this.props.handleChangeSetTemp(this.props.setTemp - 0.5); } // Add scroll listeners on mount. componentDidMount() { let element = document.getElementsByClassName("RadSliderInteractionLayer")[0] element.addEventListener("scrollUp", this.onUpScroll); element.addEventListener("scrollDown", this.onDownScroll); } // Remove scroll listeners on dismount to avoid memory leaks. componentWillUnmount() { let element = document.getElementsByClassName("RadSliderInteractionLayer")[0] element.removeEventListener("scrollUp", this.onUpScroll); element.removeEventListener("scrollDown", this.onDownScroll); } render() { return ( <div className="RadSliderInteractionLayer" onWheel={this.scrollHappened}> <Thumb className="Thumb" handleChangeSetTemp={this.props.handleChangeSetTemp} setTemp={this.props.setTemp} /> </div> ) } }
JavaScript
class Players extends React.Component { static propTypes = { t: PropTypes.func.isRequired, nextTimeStamp: PropTypes.number, endRoom: PropTypes.func.isRequired, roomId: PropTypes.string.isRequired, players: PropTypes.shape().isRequired, member: PropTypes.shape(), uid: PropTypes.string, offset: PropTypes.number, currentTurn: PropTypes.string, gameResultModalShown: PropTypes.bool, gameSettings: PropTypes.shape(), currentType: PropTypes.string, // user: PropTypes.string, quitRound: PropTypes.bool, quitRoundFunction: PropTypes.func.isRequired, gifts: PropTypes.shape(), toggleGiftsModal: PropTypes.func.isRequired, roomGifts: PropTypes.shape(), ignoredUsers: PropTypes.shape(), unBlockUser: PropTypes.func.isRequired, toggleBlockUser: PropTypes.func.isRequired, emotions: PropTypes.shape(), closeResultModal: PropTypes.func.isRequired, toggleLastRound: PropTypes.func.isRequired, refetchRoomData: PropTypes.func.isRequired, myPos: PropTypes.string, largePlayer: PropTypes.string, gameState: PropTypes.string, talking: PropTypes.string, currentHand: PropTypes.number, lowBalPlayers: PropTypes.shape(), lastRound: PropTypes.bool, disableTimer: PropTypes.bool, gameResult: PropTypes.shape(), roomClosed: PropTypes.bool, fastGame: PropTypes.bool, userSettings: PropTypes.shape().isRequired }; static defaultProps = { nextTimeStamp: null, member: {}, currentType: null, gameResultModalShown: true, gameSettings: {}, // user: null, quitRound: false, gifts: {}, roomGifts: {}, ignoredUsers: {}, emotions: {}, myPos: null, largePlayer: null, gameState: null, talking: null, currentHand: null, lowBalPlayers: null, lastRound: false, disableTimer: null, gameResult: null, roomClosed: false, fastGame: null, }; constructor(props) { super(props); this.state = { playersArranged: [], }; this.myTurnAudio = new Audio(myTurnSound); } componentDidMount() {} componentWillReceiveProps(nextProps) { const { players, myPos } = nextProps; const playersArranged = []; if (players && players.playerList) { if (myPos === 'player1') { playersArranged[0] = { ...players.player2, position: 'player2' }; playersArranged[1] = { ...players.player3, position: 'player3' }; playersArranged[2] = { ...players.player1, position: 'player1' }; } if (myPos === 'player2') { playersArranged[0] = { ...players.player3, position: 'player3' }; playersArranged[1] = { ...players.player1, position: 'player1' }; playersArranged[2] = { ...players.player2, position: 'player2' }; } if (myPos === 'player3') { playersArranged[0] = { ...players.player1, position: 'player1' }; playersArranged[1] = { ...players.player2, position: 'player2' }; playersArranged[2] = { ...players.player3, position: 'player3' }; } } this.setState({ playersArranged }) } shouldComponentUpdate(nextProps) { if (!isEqual(nextProps, this.props)) { return true; } return false; } componentDidUpdate(prevProps) { const { gameState, talking, member, currentTurn, roomId, userSettings } = this.props; const { gameState: prevGameState, currentTurn: prevCurrentTurn, talking: prevTalking } = prevProps; if(userSettings && userSettings.soundOn){ let turnChanged = prevCurrentTurn !== currentTurn; let position = undefined; if(member && member.joinedRooms && member.joinedRooms[roomId]){ position = member.joinedRooms[roomId].position; } if((prevGameState !== 'choose' || !prevTalking) && gameState === 'choose' && member.uid && talking && talking.toString() === member.uid.toString()){ this.myTurnAudio.play(); }else if(gameState === 'burry' && (position && position === currentTurn) && turnChanged){ this.myTurnAudio.play(); }else if(gameState === 'play' && (position && position === currentTurn) && turnChanged){ // this.myTurnAudio.play(); } } } render() { const { players, myPos, t, // member, uid, offset, nextTimeStamp, currentTurn, largePlayer, // currentTable, currentType, gameState, talking, lowBalPlayers, lastRound, disableTimer, gameResult, roomClosed, currentHand, fastGame, endRoom, // globalParams, gameResultModalShown, gameSettings, // user, quitRound, quitRoundFunction, gifts, toggleGiftsModal, roomGifts, ignoredUsers, unBlockUser, toggleBlockUser, // emotions, closeResultModal, toggleLastRound, cardPlayed, refetchRoomData, } = this.props; const { playersArranged } = this.state; /* const playersArranged = []; if (players && players.playerList && playersArranged.length === 0) { if (myPos === 'player1') { playersArranged[0] = { ...players.player2, position: 'player2' }; playersArranged[1] = { ...players.player3, position: 'player3' }; playersArranged[2] = { ...players.player1, position: 'player1' }; } if (myPos === 'player2') { playersArranged[0] = { ...players.player3, position: 'player3' }; playersArranged[1] = { ...players.player1, position: 'player1' }; playersArranged[2] = { ...players.player2, position: 'player2' }; } if (myPos === 'player3') { playersArranged[0] = { ...players.player1, position: 'player1' }; playersArranged[1] = { ...players.player2, position: 'player2' }; playersArranged[2] = { ...players.player3, position: 'player3' }; } } */ return ( <Fragment> {playersArranged && playersArranged.map((player, index) => ( <Fragment key={player.position}> {player && player.uid && ( <div id={`player-${player.position}`} key={player.position} className={`player ${(gameState === 'play' && player.position === currentTurn) && ' is-player-turn'} ${index === 0 && ' player-left'} ${index === 1 && ' player-right'} ${index === 2 && ' player-firstperson'}`}> <div className="player-status-wrapper"> {(gameState === 'choose' && talking.toString() === player.uid.toString()) && ( <div className="player-status">{t('actionChoose')}</div> )} {(gameState === 'burry' && player.position === currentTurn) && ( <div className="player-status">{t('actionBurry')}</div> )} {(gameState === 'play' && player.position === currentTurn) && ( <div className="player-status">{t('actionMove')}</div> )} </div> <div className="player-image-timer-wrapper"> <PlayerImage photo={player.photo || ''} currentType={currentType} gameState={gameState} largePlayer={!!(largePlayer && player.position === largePlayer)} /> {(talking && player.uid && uid && ((gameState === 'choose' && talking.toString() === player.uid.toString()) || (gameState === 'play' && player.position === currentTurn) || (gameState === 'burry' && player.position === currentTurn) || (gameState === 'results' && player.uid.toString() === uid.toString()) || (gameState === 'lowBal' && lowBalPlayers))) && ( <TurnTimer endRoom={endRoom} nextTimeStamp={nextTimeStamp} // players={players} offset={offset} gameResult={gameResult} gameState={gameState} lowBalPlayers={lowBalPlayers} disableTimer={disableTimer || null} fastGame={fastGame} roomClosed={roomClosed} closeResultModal={closeResultModal} gameResultModalShown={gameResultModalShown} gameSettings={gameSettings} cardPlayed={cardPlayed} refetchRoomData={refetchRoomData} currentTurn={currentTurn} myPos={myPos} /> )} <PlayerGift index={index} gifts={gifts} roomGifts={roomGifts} uid={player.uid} toggleGiftsModal={toggleGiftsModal} /> {(index === 0 || index === 1) && ( <> {ignoredUsers && player.uid && ignoredUsers[player.uid.toString()] ? ( <> <Button color="link" className="block-button" onClick={() => unBlockUser(player.uid.toString())} > <Media className="block-button-image" src={unblockImg} alt="" /> </Button> </> ) : ( <> <Button color="link" className="block-button" onClick={() => toggleBlockUser(player.uid.toString(), player.name)} > <Media className="block-button-image" src={blockImg} alt="" /> </Button> </> )} </> )} </div> {largePlayer && ( <PlayerType t={t} currentType={currentType} gameState={gameState} largePlayer={!!(largePlayer && player.position === largePlayer)} /> )} <PlayerHand gameState={gameState} currentHand={currentHand} playerPosition={player.position} currentTurn={currentTurn} /> <PlayerInfo lvl={player.lvl} name={player.name} bal={player.bal} /> <PlayerEmotion index={index} emotion={players[player.position].emotion} /> </div> )} </Fragment> ))} <Fragment> {/* Last round button */} <div className="last-round"> <Button disabled={lastRound} className={`last-round-button ${lastRound && 'active'}`} onClick={toggleLastRound} > {t('lastRound')} </Button> </div> {/* Quit round button */} {!!(largePlayer && myPos === largePlayer) && ( <div className="quit-round"> <Button className={`quit-round-button ${quitRound && 'active'}`} onClick={quitRoundFunction} > {t('quitRound')} </Button> </div> )} </Fragment> </Fragment> ); } }
JavaScript
class ProgramStore { programCategories = []; interactionStore = new InteractionStore(); constructor() { const reactToStuff = autorun(() => { console.log("New Value: ", this.programCategories); this.programCategories.forEach((category, i) => { category.blocks.forEach((block, i) => { console.log(block.sliderValue) }); }); }); }; setProgramCategories(val) { this.programCategories = []; val.forEach((category, i) => { const categoryStore = new CategoryStore(category.title, 'c_' + i); this.programCategories.push(categoryStore); category.blocks.forEach((block, i) => { const blockStore = new BlockStore(block.title, 'b_' + i); categoryStore.addBlock(blockStore); blockStore.updateSlider(block.sliderValue); block.details.forEach((detail, i) => { blockStore.addDetail(new DetailStore(detail.title, 'd_' + i)); }); }); }); } }
JavaScript
class Test { constructor() { //this.slerpV3(); // setTimeout(()=>{ // // let x = new THREE.Object3D(); // x.position.set(-20, -50, 80); // window._scene.add(x); // // console.time('a'); // window._scene.updateMatrixWorld(); // for (var i = 0; i < 100; i++) { // Utils.getWorldPos(x); // } // console.timeEnd('a') // // }, 100) this.worldRotation(); } quaToRot() { let a = Utils.rotToQua(new Vector3(45, 30, 0)); let b = Utils.quaToRot(a); console.log(b); } clampVectorLength() { const a = new Vector3(35, 12, 16); const b = a.clone().clampLength(-Infinity, 10); console.log( a.length(), b.length()) } worldRotation() { setTimeout(()=>{ let x = new THREE.Object3D(); x.position.set(-20, -50, 80); window._scene.add(x); let a = new THREE.Object3D(); a.position.set(10, 20, 0); a.rotation.set(10/radToDeg, 10/radToDeg, 0); x.add(a); let b = new THREE.Object3D(); b.position.set(-30, -90, 10); b.rotation.set(22/radToDeg,32/radToDeg,42/radToDeg); a.add(b); //window._scene.updateMatrixWorld(); console.time('a'); //b.parent.updateMatrixWorld(); console.timeEnd('a'); //b.setWorldPosition(new Vector3(10, 20, 30)) b.setWorldQuaternion( new THREE.Quaternion(0.4, 0.2, 0.3, 0.9) ) console.log(b.position, b.quaternion) console.log(b.getWorldPosition()) console.log(b.getWorldQuaternion()) //console.log( b.setWorldPosition() ) //let rotate = new THREE.Euler().setFromRotationMatrix(b.matrixWorld); // // // console.log( Utils.getWorldPos(b) ) // // Utils.setWorldPos(b, new Vector3(39, -30, -54)); // 0, 10, 5 // // console.log(b.position, Utils.getWorldPos(b) ) // // // //b.rotation.order = 'YXZ' // // let euler = new THREE.Euler().setFromQuaternion(b.quaternion).reorder('YXZ') // let c = new Vector3(euler.x, euler.y, euler.z)//.multiplyScalar(radToDeg); // // // //object.updateMatrixWorld(); // let rotate = new THREE.Euler().setFromRotationMatrix(b.matrixWorld); // //b.rotation.set(rotate) // // console.log(b.quaternion, rotate) // // // // (0.3, 0.2, 0.3, 0.9) // let euler = new THREE.Euler().setFromQuaternion(target)//.reorder('YXZ') // // const degToRad = (Math.PI / 180.0); // let c = new Vector3(euler.x, euler.y, euler.z)/.divideScalar(degToRad); // // console.log( b.quaternion, b.rotation, c, b.rotation.clone(), new THREE.Quaternion().setFromEuler( new THREE.Euler(b.rotation.x, b.rotation.y, b.rotation.z, 'YXZ'), false ) ) // //object.position.copy(position); }, 100); } worldPosition() { setTimeout(()=>{ let x = new THREE.Object3D(); x.position.set(-20, -50, 80); window._scene.add(x); let a = new THREE.Object3D(); a.position.set(10, 20, 0); x.add(a); let b = new THREE.Object3D(); b.position.set(-30, -90, 10); a.add(b); console.log( Utils.getWorldPos(b) ) Utils.setWorldPos(b, new Vector3(39, -30, -54)); // 0, 10, 5 console.log(b.position, Utils.getWorldPos(b) ) }, 100); } worldPositionRotation() { setTimeout(()=>{ let a = new THREE.Object3D(); //a.position.set(100, 200, 300); a.rotation.set(10, 20, 30); window._scene.add(a); let b = new THREE.Object3D(); //b.position.set(12, 20, 30); //b.rotation.set(30, 60, 20); a.add(b); window._scene.updateMatrixWorld(); let v = new Vector3(); //b.getWorldPosition(v); // // var v1 = new THREE.Vector3(); // var worldQuaternion = new THREE.Quaternion(); // a.getWorldQuaternion( worldQuaternion ); // v1.copy( a.up ).applyQuaternion( worldQuaternion ); var target = new THREE.Euler(); var quaternion = new THREE.Quaternion(); b.getWorldQuaternion(quaternion) target.setFromQuaternion( quaternion, b.rotation.order, false ); let t = new Vector3(); a.getWorldDirection(t) //worldRot.reorder("ZYX"); //var bRot = new THREE.Euler().setFromQuaternion(b.getWorldQuaternion()) console.log(t, target, b.rotation ) }, 100) } // THREEJS test convertRotation() { let a = new THREE.Object3D(); a.rotation.set(10, 20, 30); // Convert THREEJS rotation to Unity quaternion let qua = Quaternion.euler(a.rotation.x, a.rotation.y, a.rotation.z); // Get transform.forward //qua.clone().multiplyVector3( Vector3.forward ) // Convert back to euler rotation :) console.log( Quaternion.toEulerRad(qua) ); } // Animation test // OK createAnimationCurve() { let a = new AnimationCurve([ new Keyframe(0, 0, 0, 0), new Keyframe(1, 0.2, 0, 0) ]); console.log(a.evaluate(0.5)); } // Math tests // Test OK // Output both: => 90 deltaAngle() { console.log( Math.deltaAngle(1080,90) ); } // OK // Output unity: 89.96136 // Output web: 89.96136638173678 smoothDamp() { console.log( Math.smoothDamp( 10, 90, 0, 0.3, Infinity, 14) ); } // OK // Output unity: 10.15 // Output web: 10.15 moveTowards() { console.log( Math.moveTowards(10, 18, 0.15) ); } // Vector3 tests // OK orthoNormalize() { const a = new Vector3(35, 12, 16); const b = new Vector3(22, 32, 42); a.orthoNormalize(b) console.log( a, b ); } // Test: OK // Output unity: => (29.5, 20.4, 26.9) // Output web: => {x: 29.54, y: 20.4, z: 26.92} // The parameter t is clamped to the range [0, 1]. // When t = 0 returns a. When t = 1 returns b. // When t = 0.5 returns the point midway between a and b. lerpV3() { const a = new Vector3(35, 12, 16); const b = new Vector3(22, 32, 42); console.log( a.lerp(b, 0.42) ); } // Test: OK // Output unity: (33.2, 20.4, 27.0) // Output web: {x: 33.19615173398555, y: 20.42314226418747, z: 26.98439516966527} // The parameter t is clamped to the range [0, 1]. slerpV3() { const a = new Vector3(35, 12, 16); const b = new Vector3(22, 32, 42); console.log( a.slerp(b, 0.42) ); } // Test: OK // Output unity: (12.3, 17.9, 23.4) // Output web: {x: 12.277506112469437, y: 17.858190709046454, z: 23.43887530562347} projectOnVector() { const a = new Vector3(35, 12, 16); const b = new Vector3(22, 32, 42); console.log( a.projectOnVector(b) ); } // Quaternion tests // Test OK // Outpur unity: (29.8, 10.9, 29.9) // Ouput web: {x: 29.830000000000002, y: 10.939999999999998, z: 29.94} multiplyQuaWithVector3() { const a = new Quaternion(.5, .10, .15, .20); const b = new Vector3(22, 32, 42); console.log( a.multiplyVector3(b) ); } // Test OK // Ouput unity: => // angle: 138.8288 // axis: (0.8, 0.4, 0.4) // Output web: => // angle: 138.82880534572357 // axis: {x: 0.8164965809277259, y: 0.40824829046386296, z: 0.40824829046386296} toAngleAxis() { const a = new Quaternion(.2, .10, .1, .092); console.log(a.toAngleAxis()) } // Test OK // Ouput unity: (-0.1, 0.5, 0.1, 0.8) // Output web: =>  {x: -0.12667275591175206, y: 0.5343205382230671, z: 0.0813737199537705, w: 0.8317655276841057} setLookRotation() { const a = new Vector3(35, 12, 16); console.log( new Quaternion().setLookRotation(a) ); } // Test OK // Ouput unity: (0.0, -0.3, 0.2, 0.9) // Output web: => {x: -0.0018326748290413432, y: -0.2561163073585285, z: 0.19609620670742434, w: 0.9465449572645569} setFromToRotation() { const a = new Vector3(35, 12, 16); const b = new Vector3(22, 32, 42); console.log( new Quaternion().setFromToRotation(a, b) ); } // Test OK // Output web: => 0.5678908345800273 length() { const a = new Quaternion(.5, .10, .15, .20); console.log(a.length()); } // Test OK // Output unity: => 0.309 // Output web: => 0.30900000000000005 dot() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log(a.dot(b)); } // Test OK (small inaccuracy on the web.. ) // Output unity: => (0.4, 0.2, 0.1, 0.9) // {x: 0.42503652679580517, y: 0.15109311037061723, z: 0.13969134227676283, w: 0.8814766881664016} euler() { console.log( Quaternion.euler(45, 33, 32) ); } // Test OK // Output unity: => (-0.3, 0.2, 0.0, 0.9) // Ouput web: => {x: -0.2746567483172059, y: 0.15385645171776968, z: 0.04457065446637163, w: 0.9481061752931873} lookRotation() { let a = new Vector3(5, 10, 15); console.log( Quaternion.lookRotation(a) ); } // Test OK // Output unity: => (0.5, 0.0, -0.2, 0.9) // Output web: =>  {x: 0.4529010706053633, y: 0, z: -0.1607068315051289, w: 0.8769572022351478} fromToRotation() { let a = new Vector3(11, 21, 31); console.log( Quaternion.fromToRotation(Vector3.up, a) ); } // Test OK // Ouput unity: => (0.5, 0.1, 0.2, 0.2) // Output web: => {x: 0.500525479928413, y: 0.10238431285989641, z: 0.1530809873606677, w: 0.203777661861439} rotateTowards() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log( Quaternion.rotateTowards(a, b, 0.9) ); } // Test OK // Ouput unity: => (0.3, 0.3, 0.4, 0.5) // Output web: =>  {x: 0.27519862078728924, y: 0.3176242311246034, z: 0.41935275821578644, w: 0.5210812853069696} slerp() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log( a.slerp(b, 0.9) ); } // Test OK // Ouput unity: => (0.3, 0.4, 0.5, 0.7) // Output web: => {x: 0.34838007294638385, y: 0.4020875994660481, z: 0.5308680111823826, w: 0.6596484228987174} lerp() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log( a.lerp(b, 0.9) ); } // Test OK // Output unity: => (0.2, 0.0, 0.1, 1.0) // Output web: => {x: 0.24347647686305673, y: 0.04869529537261135, z: 0.07304294305891701, w: 0.9659258262890683} angleAxis() { const a = new Vector3(.5, .10, .15); console.log( Quaternion.angleAxis(30, a) ); } // Test OK // Output unity: => 144.0021 // Output web: => 144.0020476241247 angle() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log(Quaternion.angle(a, b)); } // Test OK // Output web: => {x: 0.8804509063256238, y: 0.17609018126512477, z: 0.26413527189768715, w: 0.35218036253024954} normalize() { const a = new Quaternion(.5, .10, .15, .20); console.log(a.normalize()); } // Test OK inverse() { const a = new Quaternion(.5, .410, .15, .20); console.log(a.inverse()); } // Test OK // Output web: => {x: 0.28, y: -0.22, z: -0.27, w: -0.32} sub() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log(a.sub(b)); } // Test OK // Output unity: => (0.3, -0.1, 0.3, -0.1) // Output web: => {x: 0.298, y: -0.060999999999999985, z: 0.30000000000000004, w: -0.101} multiply() { const a = new Quaternion(.5, .10, .15, .20); const b = new Quaternion(.22, .32, .42, .52); console.log(a.multiply(b)); } }
JavaScript
class CollectionComponent { /** * Creates a new CollectionComponent instance * @param {Collection} [collection] Optional collection object * @param {Component} component Component * @param {CollectionComponent~updateCallback} update Callback function called on collection events and when component is rendered * @param {object} [opt] Optional parameters * @param {string} [opt.postrenderUpdate] Flag setting if call to update should be done after render. Defaults to false. */ constructor(collection, component, update, opt) { if (typeof component === 'function') { update = component; component = collection; collection = null; } this.postrender = !!(opt && opt.postrenderUpdate); this.ml = new CollectionListener(collection, component, update); } /** * Set collection * If component is rendered, update will be triggered. * @param {?Collection} collection Collection * @returns {this} */ setCollection(collection) { this.ml.setCollection(collection); return this; } /** * Returns the wrapped component * @returns {Component} Wrapped component */ getComponent() { return this.ml.component; } render(el) { if (!this.postrender) this.ml.onRender(); let rel = this.ml.component.render(el); if (this.postrender) this.ml.onRender(); return rel; } unrender() { this.ml.component.unrender(); this.ml.onUnrender(); } }
JavaScript
class FileThumbnail extends IsWorkingMixin(Control) { constructor(settings = {}) { settings.type = settings.type || controlTypes.FILE_THUMBNAIL; super(settings); const self = this; self.addClass(THUMBNAIL_CLASS + PREVIEW_SIZES.SMALL) .on(MOUSE_ENTER_EVENT, () => { if (self.onDelete()) { if (!self[DELETE_BUTTON]) { self[DELETE_BUTTON] = new Button({ container: self.element, stopPropagation: true, icon: CLEAR_ALT_ICON, classes: BUTTON_CLASS, onClick() { if (self.onDelete()) { self.onDelete()(self); } }, fade: true }); } } }) .on(MOUSE_LEAVE_EVENT, () => { self[hideDeleteButton](); }); self[IMAGE_WRAPPER] = new Div({ container: self, classes: IMAGE_WRAPPER_CLASS }); self[ICON] = new Icon({ container: self[IMAGE_WRAPPER] }); self[IMAGE] = new Image({ container: self[IMAGE_WRAPPER] }); self[IMAGE].css(OPACITY, 0); self.isWorking(true); applySettings(self, settings); } [hideDeleteButton]() { const self = this; if (self[DELETE_BUTTON]) { self[DELETE_BUTTON].remove(); self[DELETE_BUTTON] = null; } } }
JavaScript
class RequestManager { /** * Creates a new request manager. * @param {Object} options The options. * @param {string} options.processingMode The processing mode for this instance. * @param {string} options.propagationMode The propagation mode for queued requests. * @param {number|false} options.timeout Requests timeout duration. */ constructor({ processingMode = PROCESS_ANY, propagationMode = PROPAGATE_SINGLE, timeout = false, } = {}) { this.processingMode = processingMode; this.propagationMode = propagationMode; this.requestQueue = []; this.lastReceivedTime = 0; this.pendingRequests = 0; this.timeout = timeout; this.timers = []; } /** * Pushes a new request to the queue. * @param {Request} request The request. * @param {function} resolve The resolve() callback of the request promise. * @param {function} reject The reject() callback of the request promise. */ enqueueRequest(request, resolve, reject) { // Get the current timestamp. const timestamp = this.currentTime; // Find the queue index position at the given timestamp. const index = this.requestQueue.findIndex(item => item.timestamp > timestamp); const item = { request, resolve, reject, timestamp, response: null, }; if (index === -1) { // Not found, append to queue. this.requestQueue.push(item); } else { // Insert at the correct timestamp index. this.requestQueue.splice(index, 0, item); } } /** * Handles a new dispatch. * @param {Request} request The request. * @param {function} resolve The resolve() callback of the request promise. * @param {function} reject The reject() callback of the request promise. */ handleDispatch(request, resolve, reject) { if (this.processingMode !== PROCESS_ANY) { // Enqueue this request if it requires special handling. this.enqueueRequest(request, resolve, reject); } if (this.processingMode === PROCESS_SEQUENTIALLY && this.pendingRequests > 0) { // Never dispatch more than a single request when running sequentially. return; } this.pendingRequests += 1; request.onDispatch(resolve, reject); if (this.timeout > 0) { this.timers[request.serial] = setTimeout( () => request.onTimeout(resolve, reject), this.timeout ); } } /** * Handles an error that occurred during the request. * @param {Request} request The request this response belongs to. * @param {function} reject The reject() callback of the request promise. * @param {Object} [message] The error object. */ handleError(request, reject, message) { clearTimeout(this.timers[request.serial]); delete this.timers[request.serial]; if (this.processingMode === PROCESS_ANY) { reject(message); return; } const index = this.requestQueue.findIndex(item => item.request.serial === request.serial); if (index >= 0) { this.pendingRequests -= 1; this.requestQueue.splice(index, 1); reject(message); } } /** * Handles a received response. * @param {Request} request The request this response belongs to. * @param {function} resolve The resolve() callback of the request promise. * @param {Object} response The response. */ handleResponse(request, resolve, response) { clearTimeout(this.timers[request.serial]); delete this.timers[request.serial]; this.pendingRequests -= 1; switch (this.processingMode) { case PROCESS_LAST_REQUEST: processLastRequest(this, request, response, resolve); break; case PROCESS_FIRST_RESPONSE: processFirstResponse(this, request, response, resolve); break; case PROCESS_ORDERED_REQUEST: processOrderedRequest(this, request, response); break; case PROCESS_SEQUENTIALLY: processSequentially(this, response, resolve); break; default: // No special handling, just resolve the promise. resolve(response); } } /** * @return {number} The current unix timestamp. */ get currentTime() { // eslint-disable-line class-methods-use-this return Date.now(); } }
JavaScript
class KMZ extends Duplex { constructor(disk) { super({ objectMode: true, highWaterMark: config().rowBufferSize }); this._zName = '/tmp/kmz_' + uuid.v4() + '.zip'; this._zBuffer = disk.allocate(this._zName, { defaultEncoding: 'binary' }); this.on('finish', this._onFinished.bind(this)); this._zBuffer.on('finish', this._onBuffered.bind(this)); } static canDecode() { return ['application/vnd.google-earth.kmz']; } static canDecodeExtensions() { return ['.kmz']; } _write(chunk, encoding, done) { return this._zBuffer.write(chunk, null, done); } _onFinished() { logger.debug('Finished reading stream, closing underlying kmz buffer'); this._zBuffer.end(); } _onBuffered() { this.emit('readable'); } _onOpenKmlStream(kmlStream) { return kmlStream .pipe(new KML()) .on('error', (err) => this.emit('error', err)) .on('data', (data) => { if (this._readableState.ended) return; if (!this.push(data)) { //our reader has gone away, this kills the stream. //so end the stream with a null and flush anything //that's buffered into oblivion if (!this._readableState.pipes) { this.push(null); return this.pipe(new DevNull()); } if (!kmlStream.isPaused()) { this._readableState.pipes.once('drain', () => { kmlStream.resume(); }); kmlStream.pause(); } } }); } _startPushing() { this._isPushing = true; var hasOpened = false; yauzl.open(this._zName, { lazyEntries: true }, (err, zipFile) => { if (err) return this.emit('error', new ArchiveError(err.toString())); zipFile .on('error', (err) => { this.emit('error', new ArchiveError(err.toString())); }) .on('entry', (entry) => { logger.info(`Checking KMZ entry ${entry.fileName}`); if (path.extname(entry.fileName) !== '.kml') return zipFile.readEntry(); zipFile.openReadStream(entry, (err, kmlStream) => { if (err) return this.emit('error', err); logger.info(`Extracting kml ${entry.fileName} from kmz archive`); this._onOpenKmlStream(kmlStream) .on('end', () => zipFile.readEntry()); }); }) .once('end', () => { this.push(null); logger.info('Done reading KMZ archive'); }); zipFile.readEntry(); }); } //just cuz _read() { if (!this._readableState.emittedReadable && !this._isPushing) { this.once('readable', this._startPushing.bind(this)); } else if (!this._isPushing) { this._startPushing(); } } summarize(cb) { return (new KML()).summarize(cb); } canSummarizeQuickly() { return false; } }
JavaScript
@withContext @withStyles(styles) class App { componentDidMount() { window.addEventListener('popstate', this.handlePopState); } componentWillUnmount() { window.removeEventListener('popstate', this.handlePopState); } // shouldComponentUpdate(nextProps) { // return this.props.path !== nextprops.path; // } handlePopState(event) { AppActions.navigateTo(window.location.pathname, {replace: !!event.state}); } render() { return <LandingPage />; } }
JavaScript
class ApiClient extends HttpRequest { /** * Perform a RQLite data API get request * @param {String} path The path for the request i.e. /db/query * @param {String} sql The SQL query * @param {HttpRequestOptions} [options={}] RQLite API options */ async get (path, sql, options = {}) { const { useLeader } = options if (!path) { throw new Error('The path argument is required') } return super.get({ useLeader, uri: path, httpMethod: HTTP_METHOD_GET, query: { ...createQuery(options), q: sql }, }) } /** * Perform a RQLite data API post request * @param {String} path The path for the request i.e. /db/query * @param {String} sql The SQL query * @param {HttpRequestOptions} [options={}] RQLite API options */ async post (path, sql, options = {}) { const { useLeader } = options if (!path) { throw new Error('The path argument is required') } return super.post({ useLeader, uri: path, httpMethod: HTTP_METHOD_POST, query: createQuery(options), body: Array.isArray(sql) ? sql : [sql], }) } }
JavaScript
class BookList extends Component{ static propTypes = { books: PropTypes.array, showTag: PropTypes.bool.isRequired } handleBookShelfChange = (book, toShelf) => { this.props.onBookShelfChange(book, toShelf) } render(){ return ( <ol className="books-grid"> { this.props.books && this.props.books.sort(sortBy('title')).map(book => (<Book key={book.id} id={book.id} showTag={this.props.showTag} title={book.title} publisher={book.publisher} authors={book.authors || []} thumbnail={(book.imageLinks && book.imageLinks.thumbnail ? book.imageLinks.thumbnail : CoverImageNotAvailable)} onBookShelfChange={this.handleBookShelfChange} shelf={book.shelf || 'none'}/>) ) } </ol> ) } }
JavaScript
class ModalPopup extends Component { /** * Base class for modal popup UI components. This can also be used as * a standalone component to render a modal popup with an empty div. * * WARNING: ModalPopup is only guaranteed to work when it is rendered * directly in the 'body' element. * * The Html structure of the modal popup is: * <pre> * Element Function Class-name, goog-modalpopup = default * ---------------------------------------------------------------------------- * - iframe Iframe mask goog-modalpopup-bg * - div Background mask goog-modalpopup-bg * - div Modal popup area goog-modalpopup * - span Tab catcher * </pre> * @param {boolean=} opt_useIframeMask Work around windowed controls z-index * issue by using an iframe instead of a div for bg element. * @param {DomHelper=} opt_domHelper Optional DOM helper; see {@link * Component} for semantics. */ constructor(opt_useIframeMask, opt_domHelper) { super(opt_domHelper); /** * Focus handler. It will be initialized in enterDocument. * @type {?FocusHandler} * @private */ this.focusHandler_ = null; /** * Whether the modal popup is visible. * @type {boolean} * @private */ this.visible_ = false; /** * Element for the background which obscures the UI and blocks events. * @type {?Element} * @private */ this.bgEl_ = null; /** * Iframe element that is only used for IE as a workaround to keep select-type * elements from burning through background. * @type {?Element} * @private */ this.bgIframeEl_ = null; /** * Element used to catch focus and prevent the user from tabbing out * of the popup. * @type {?Element} * @private */ this.tabCatcherElement_ = null; /** * Whether the modal popup is in the process of wrapping focus from the top of * the popup to the last tabbable element. * @type {boolean} * @private */ this.backwardTabWrapInProgress_ = false; /** * Transition to show the popup. * @type {Transition} * @private */ this.popupShowTransition_ = null; /** * Transition to hide the popup. * @type {Transition} * @private */ this.popupHideTransition_ = null; /** * Transition to show the background. * @type {Transition} * @private */ this.bgShowTransition_ = null; /** * Transition to hide the background. * @type {Transition} * @private */ this.bgHideTransition_ = null; /** * Helper object to control aria visibility of the rest of the page. * @type {ModalAriaVisibilityHelper} * @private */ this.modalAriaVisibilityHelper_ = null; /** * Whether the modal popup should use an iframe as the background * element to work around z-order issues. * @type {boolean} * @private */ this.useIframeMask_ = !!opt_useIframeMask; /** * The element that had focus before the popup was displayed. * @type {?Element} * @private */ this.lastFocus_ = null; /** * The animation task that resizes the background, scheduled to run in the * next animation frame. * @type {function(...?)} * @private */ this.resizeBackgroundTask_ = animationFrame.createTask( {mutate: this.resizeBackground_}, this); } /** * @return {string} Base CSS class for this component. * @protected */ getCssClass() { return google.getCssName('goog-modalpopup'); }; /** * Returns the background iframe mask element, if any. * @return {Element} The background iframe mask element, may return * null/undefined if the modal popup does not use iframe mask. */ getBackgroundIframe() { return this.bgIframeEl_; }; /** * Returns the background mask element. * @return {Element} The background mask element. */ getBackgroundElement() { return this.bgEl_; }; /** * Creates the initial DOM representation for the modal popup. * @override */ createDom() { // Create the modal popup element, and make sure it's hidden. super.createDom(); var element = this.getElement(); asserts.assert(element); var allClasses = strings.trim(this.getCssClass()).split(' '); classlist.addAll(element, allClasses); googdom.setFocusableTabIndex(element, true); style.setElementShown(element, false); // Manages the DOM for background mask elements. this.manageBackgroundDom_(); this.createTabCatcher_(); }; /** * Creates and disposes of the DOM for background mask elements. * @private */ manageBackgroundDom_() { if (this.useIframeMask_ && !this.bgIframeEl_) { // IE renders the iframe on top of the select elements while still // respecting the z-index of the other elements on the page. See // http://support.microsoft.com/kb/177378 for more information. // Flash and other controls behave in similar ways for other browsers this.bgIframeEl_ = iframe.createBlank(this.getDomHelper()); this.bgIframeEl_.className = google.getCssName(this.getCssClass(), 'bg'); style.setElementShown(this.bgIframeEl_, false); style.setOpacity(this.bgIframeEl_, 0); } // Create the backgound mask, initialize its opacity, and make sure it's // hidden. if (!this.bgEl_) { this.bgEl_ = this.getDomHelper().createDom( TagName.DIV, google.getCssName(this.getCssClass(), 'bg')); style.setElementShown(this.bgEl_, false); } }; /** * Creates the tab catcher element. * @private */ createTabCatcher_() { // Creates tab catcher element. if (!this.tabCatcherElement_) { this.tabCatcherElement_ = this.getDomHelper().createElement(TagName.SPAN); style.setElementShown(this.tabCatcherElement_, false); googdom.setFocusableTabIndex(this.tabCatcherElement_, true); this.tabCatcherElement_.style.position = 'absolute'; } }; /** * Allow a shift-tab from the top of the modal popup to the last tabbable * element by moving focus to the tab catcher. This should be called after * catching a wrapping shift-tab event and before allowing it to propagate, so * that focus will land on the last tabbable element before the tab catcher. * @protected */ setupBackwardTabWrap() { this.backwardTabWrapInProgress_ = true; try { this.tabCatcherElement_.focus(); } catch (e) { // Swallow this. IE can throw an error if the element can not be focused. } // Reset the flag on a timer in case anything goes wrong with the followup // event. Timer.callOnce(this.resetBackwardTabWrap_, 0, this); }; /** * Resets the backward tab wrap flag. * @private */ resetBackwardTabWrap_() { this.backwardTabWrapInProgress_ = false; }; /** * Renders the background mask. * @private */ renderBackground_() { asserts.assert(!!this.bgEl_, 'Background element must not be null.'); if (this.bgIframeEl_) { googdom.insertSiblingBefore(this.bgIframeEl_, this.getElement()); } googdom.insertSiblingBefore(this.bgEl_, this.getElement()); }; /** @override */ canDecorate(element) { // Assume we can decorate any DIV. return !!element && element.tagName == TagName.DIV; }; /** @override */ decorateInternal(element) { // Decorate the modal popup area element. super.decorateInternal(element); var allClasses = strings.trim(this.getCssClass()).split(' '); classlist.addAll(asserts.assert(this.getElement()), allClasses); // Create the background mask... this.manageBackgroundDom_(); this.createTabCatcher_(); // Make sure the decorated modal popup is focusable and hidden. googdom.setFocusableTabIndex(this.getElement(), true); style.setElementShown(this.getElement(), false); }; /** @override */ enterDocument() { this.renderBackground_(); super.enterDocument(); googdom.insertSiblingAfter(this.tabCatcherElement_, this.getElement()); this.focusHandler_ = new FocusHandler(this.getDomHelper().getDocument()); // We need to watch the entire document so that we can detect when the // focus is moved out of this modal popup. this.getHandler().listen( this.focusHandler_, EventType.FOCUSIN, this.onFocus); this.setA11YDetectBackground(false); }; /** @override */ exitDocument() { if (this.isVisible()) { this.setVisible(false); } dispose(this.focusHandler_); super.exitDocument(); googdom.removeNode(this.bgIframeEl_); googdom.removeNode(this.bgEl_); googdom.removeNode(this.tabCatcherElement_); }; /** * Sets the visibility of the modal popup box and focus to the popup. * @param {boolean} visible Whether the modal popup should be visible. */ setVisible(visible) { asserts.assert( this.isInDocument(), 'ModalPopup must be rendered first.'); if (visible == this.visible_) { return; } if (this.popupShowTransition_) this.popupShowTransition_.stop(); if (this.bgShowTransition_) this.bgShowTransition_.stop(); if (this.popupHideTransition_) this.popupHideTransition_.stop(); if (this.bgHideTransition_) this.bgHideTransition_.stop(); if (this.isInDocument()) { this.setA11YDetectBackground(visible); } if (visible) { this.show_(); } else { this.hide_(); } }; /** * Sets aria-hidden on the rest of the page to restrict screen reader focus. * Top-level elements with an explicit aria-hidden state are not altered. * @param {boolean} hide Whether to hide or show the rest of the page. * @protected */ setA11YDetectBackground(hide) { if (!this.modalAriaVisibilityHelper_) { this.modalAriaVisibilityHelper_ = new ModalAriaVisibilityHelper( this.getElementStrict(), this.dom_); } this.modalAriaVisibilityHelper_.setBackgroundVisibility(hide); }; /** * Sets the transitions to show and hide the popup and background. * @param {!Transition} popupShowTransition Transition to show the * popup. * @param {!Transition} popupHideTransition Transition to hide the * popup. * @param {!Transition} bgShowTransition Transition to show * the background. * @param {!Transition} bgHideTransition Transition to hide * the background. */ setTransition( popupShowTransition, popupHideTransition, bgShowTransition, bgHideTransition) { this.popupShowTransition_ = popupShowTransition; this.popupHideTransition_ = popupHideTransition; this.bgShowTransition_ = bgShowTransition; this.bgHideTransition_ = bgHideTransition; }; /** * Shows the popup. * @private */ show_() { if (!this.dispatchEvent(PopupBaseEventType.BEFORE_SHOW)) { return; } try { this.lastFocus_ = this.getDomHelper().getDocument().activeElement; } catch (e) { // Focus-related actions often throw exceptions. // Sample past issue: https://bugzilla.mozilla.org/show_bug.cgi?id=656283 } this.resizeBackground_(); this.reposition(); // Listen for keyboard and resize events while the modal popup is visible. this.getHandler() .listen( this.getDomHelper().getWindow(), EventsEventType.RESIZE, this.resizeBackground_) .listen( this.getDomHelper().getWindow(), EventsEventType.ORIENTATIONCHANGE, this.resizeBackgroundTask_); this.showPopupElement_(true); this.focus(); this.visible_ = true; if (this.popupShowTransition_ && this.bgShowTransition_) { goog_events.listenOnce( /** @type {!EventsEventTarget} */ (this.popupShowTransition_), TransitionEventType.END, this.onShow, false, this); this.bgShowTransition_.play(); this.popupShowTransition_.play(); } else { this.onShow(); } }; /** * Hides the popup. * @private */ hide_() { if (!this.dispatchEvent(PopupBaseEventType.BEFORE_HIDE)) { return; } // Stop listening for keyboard and resize events while the modal // popup is hidden. this.getHandler() .unlisten( this.getDomHelper().getWindow(), EventsEventType.RESIZE, this.resizeBackground_) .unlisten( this.getDomHelper().getWindow(), EventsEventType.ORIENTATIONCHANGE, this.resizeBackgroundTask_); // Set visibility to hidden even if there is a transition. This // reduces complexity in subclasses who may want to override // setVisible (such as goog.ui.Dialog). this.visible_ = false; if (this.popupHideTransition_ && this.bgHideTransition_) { goog_events.listenOnce( /** @type {!EventsEventTarget} */ (this.popupHideTransition_), TransitionEventType.END, this.onHide, false, this); this.bgHideTransition_.play(); // The transition whose END event you are listening to must be played last // to prevent errors when disposing on hide event, which occur on browsers // that do not support CSS3 transitions. this.popupHideTransition_.play(); } else { this.onHide(); } this.returnFocus_(); }; /** * Attempts to return the focus back to the element that had it before the popup * was opened. * @private */ returnFocus_() { try { var dom = this.getDomHelper(); var body = dom.getDocument().body; var active = dom.getDocument().activeElement || body; if (!this.lastFocus_ || this.lastFocus_ == body) { this.lastFocus_ = null; return; } // We only want to move the focus if we actually have it, i.e.: // - if we immediately hid the popup the focus should have moved to the // body element // - if there is a hiding transition in progress the focus would still be // within the dialog and it is safe to move it if the current focused // element is a child of the dialog if (active == body || dom.contains(this.getElement(), active)) { this.lastFocus_.focus(); } } catch (e) { // Swallow this. IE can throw an error if the element can not be focused. } // Explicitly want to null this out even if there was an error focusing to // avoid bleed over between dialog invocations. this.lastFocus_ = null; }; /** * Shows or hides the popup element. * @param {boolean} visible Shows the popup element if true, hides if false. * @private */ showPopupElement_(visible) { if (this.bgIframeEl_) { style.setElementShown(this.bgIframeEl_, visible); } if (this.bgEl_) { style.setElementShown(this.bgEl_, visible); } style.setElementShown(this.getElement(), visible); style.setElementShown(this.tabCatcherElement_, visible); }; /** * Called after the popup is shown. If there is a transition, this * will be called after the transition completed or stopped. * @protected */ onShow() { this.dispatchEvent(PopupBaseEventType.SHOW); }; /** * Called after the popup is hidden. If there is a transition, this * will be called after the transition completed or stopped. * @protected */ onHide() { this.showPopupElement_(false); this.dispatchEvent(PopupBaseEventType.HIDE); }; /** * @return {boolean} Whether the modal popup is visible. */ isVisible() { return this.visible_; }; /** * Focuses on the modal popup. */ focus() { this.focusElement_(); }; /** * Make the background element the size of the document. * * NOTE(user): We must hide the background element before measuring the * document, otherwise the size of the background will stop the document from * shrinking to fit a smaller window. This does cause a slight flicker in Linux * browsers, but should not be a common scenario. * @private */ resizeBackground_() { if (this.bgIframeEl_) { style.setElementShown(this.bgIframeEl_, false); } if (this.bgEl_) { style.setElementShown(this.bgEl_, false); } var doc = this.getDomHelper().getDocument(); var win = googdom.getWindow(doc) || window; // Take the max of document height and view height, in case the document does // not fill the viewport. Read from both the body element and the html element // to account for browser differences in treatment of absolutely-positioned // content. var viewSize = googdom.getViewportSize(win); var w = Math.max( viewSize.width, Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth)); var h = Math.max( viewSize.height, Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight)); if (this.bgIframeEl_) { style.setElementShown(this.bgIframeEl_, true); style.setSize(this.bgIframeEl_, w, h); } if (this.bgEl_) { style.setElementShown(this.bgEl_, true); style.setSize(this.bgEl_, w, h); } }; /** * Centers the modal popup in the viewport, taking scrolling into account. */ reposition() { // TODO(chrishenry): Make this use google.positioning as in PopupBase? // Get the current viewport to obtain the scroll offset. var doc = this.getDomHelper().getDocument(); var win = googdom.getWindow(doc) || window; if (style.getComputedPosition(this.getElement()) == 'fixed') { var x = 0; var y = 0; } else { var scroll = this.getDomHelper().getDocumentScroll(); var x = scroll.x; var y = scroll.y; } var popupSize = style.getSize(this.getElement()); var viewSize = googdom.getViewportSize(win); // Make sure left and top are non-negatives. var left = Math.max(x + viewSize.width / 2 - popupSize.width / 2, 0); var top = Math.max(y + viewSize.height / 2 - popupSize.height / 2, 0); style.setPosition(this.getElement(), left, top); // We place the tab catcher at the same position as the dialog to // prevent IE from scrolling when users try to tab out of the dialog. style.setPosition(this.tabCatcherElement_, left, top); }; /** * Handles focus events. Makes sure that if the user tabs past the * elements in the modal popup, the focus wraps back to the beginning, and that * if the user shift-tabs past the front of the modal popup, focus wraps around * to the end. * @param {EventsBrowserEvent} e Browser's event object. * @protected */ onFocus(e) { if (this.backwardTabWrapInProgress_) { this.resetBackwardTabWrap_(); } else if (e.target == this.tabCatcherElement_) { Timer.callOnce(this.focusElement_, 0, this); } }; /** * Returns the magic tab catcher element used to detect when the user has * rolled focus off of the popup content. It is automatically created during * the createDom method() and can be used by subclasses to implement custom * tab-loop behavior. * @return {Element} The tab catcher element. * @protected */ getTabCatcherElement() { return this.tabCatcherElement_; }; /** * Moves the focus to the modal popup. * @private */ focusElement_() { try { if (userAgent.IE) { // In IE, we must first focus on the body or else focussing on a // sub-element will not work. this.getDomHelper().getDocument().body.focus(); } this.getElement().focus(); } catch (e) { // Swallow this. IE can throw an error if the element can not be focused. } }; /** @override */ disposeInternal() { dispose(this.popupShowTransition_); this.popupShowTransition_ = null; dispose(this.popupHideTransition_); this.popupHideTransition_ = null; dispose(this.bgShowTransition_); this.bgShowTransition_ = null; dispose(this.bgHideTransition_); this.bgHideTransition_ = null; super.disposeInternal(); }; }
JavaScript
class AttributeTypeCode { static Boolean = 1; static Date = 2; static DateTime = 3; static Decimal = 4; static Email = 5; static Int = 6; static Phone = 7; static String = 8; static Text = 9; static Url = 10; static Currency = 11; static Time = 12; static Enum = 13; static 1 = "Boolean"; static 2 = "Date"; static 3 = "DateTime"; static 4 = "Decimal"; static 5 = "Email"; static 6 = "Int"; static 7 = "Phone"; static 8 = "String"; static 9 = "Text"; static 10 = "Url"; static 11 = "Currency"; static 12 = "Time"; static 13 = "Enum"; }
JavaScript
class ObjectTransformer extends Stream.Transform { constructor(transformations, description, silent, options) { super(object.merge({ objectMode: true, highWaterMark: 1000 }, (options || { }))); assert.argumentIsArray(transformations, 'transformations', Transformation); assert.argumentIsOptional(description, 'description', String); assert.argumentIsOptional(silent, 'silent', Boolean); assert.argumentIsOptional(options, 'options', Object); this._tranformations = transformations; this._description = description || 'Object Transformer'; this._silent = is.boolean(silent) && silent; let delegate; if (transformations.every(t => t.synchronous)) { delegate = processSynchronous.bind(this); } else { delegate = processAsynchronous.bind(this); } this._delegate = delegate; this._counter = 0; } get transformerCount() { return this._tranformations.length; } _transform(chunk, encoding, callback) { this._delegate(chunk, callback); } /** * Adds a new {@link Transformer} instance. * * @public * @param {Transformation} * @returns {ObjectTransformer} */ addTransformation(transformation) { assert.argumentIsRequired(transformation, 'transformation', Transformation, 'Transformation'); return new ObjectTransformer(this._tranformations.concat([ transformation ]), this._description, this._silent); } static define(description, silent, options) { return new ObjectTransformer([ ], description, silent, options); } toString() { return '[ObjectTransformer]'; } }
JavaScript
class AppAux extends React.Component { /** * Constructor * @param {*} props */ constructor(props){ super(props); this.state = { modalTask: false, modalType: null, showCompleted: false, } } /** * Cuando el componente se monta */ componentDidMount() { try { // Si no hay usuario logueado redirigo al login if (!this.props.user.id) { return this.props.history.push('/login'); } // Cargar listado de tareas Axios.get('/tasklists', { headers: { 'Authorization': 'bearer ' + this.props.user.token }}) .then (response => { if (response.status === 200) { this.props.loadLists(response.data.results); } }) // Resize de la aplicación window.addEventListener("resize", this.resizeEventHandler); // Detectar el ESC para cerrar el import document.addEventListener("keydown", this.keyDownEventHandler); // Sincronizado cada 15 segundos setInterval(() => { this.syncNowEventHandler() }, 15000); } catch (error) { console.log(error); } } /** * Render */ render() { return ( <div className='App'> <SideBarContainer user={this.props.user} createTaskListEventHandler={this.createTaskListEventHandler} syncNowEventHandler={this.syncNowEventHandler} /> <TodoSectionContainer user={this.props.user} shareTaskListEventHandler={this.shareTaskListEventHandler} /> { this.props.user.email && <ModalTaskList ref={this.modal} visible={this.state.modalTask} type={this.state.modalType} title={this.state.modalType==='UPDATE'?'Share TaskList with your friends':'Create a new TaskList'} taskListName={this.state.modalType==='UPDATE'?this.props.selected.description:''} friends={this.props.user.friends} members={this.state.modalType==='UPDATE'?this.props.selected.members:[{ id: this.props.user.id, name: this.props.user.name, email: this.props.user.email, avatar: this.props.user.avatar}] } owner={this.state.modalType==='UPDATE'?this.props.selected.owner:this.props.user} onClose={() => this.setState({modalTask: false, modalType: null})} onAccept={this.modalTaskListAccept}/> } </div> ); } /** * Resize de la app */ resizeEventHandler = () => { if (window.innerWidth < 750 && !this.props.collapsed) { this.props.collapseSideBar(); } else if (window.innerWidth >= 750 && this.props.collapsed) { this.props.collapseSideBar(); } } /** * Close modal */ keyDownEventHandler = (ev) => { if (ev.keyCode === 27 && this.state.modalTask) { this.setState({modalTask: !this.state.modalTask}); } } /** * Click en compartir task list */ shareTaskListEventHandler = () => { // Sólo se permite modificar una tarea de la que seas propietario if(this.props.selected.owner && this.props.selected.owner.email === this.props.user.email) { this.setState({modalTask: true, modalType: 'UPDATE'}); } else { alert('Sólo el propietario de la lista puede invitar a otras personas'); } } /** * Click en crear una tasklist */ createTaskListEventHandler = () => { this.setState({modalTask: true, modalType: 'CREATE'}) } /** * * Gestiona el evento de aceptación del modal de tasklist (creación o edición de lista) * @param {String} members Nombre descriptivo de la lista * @param {Array} members Miembros a añadir a la lista */ modalTaskListAccept = async (description, members) => { try { // Creo un array de miembros unicamente con el _id const membersFiltered = []; members.filter(m=>m.newMember).map(m=>membersFiltered.push(m.id)); // Dependiendo de la operación switch (this.state.modalType) { // Creo una nueva lista case 'CREATE': { const result = await Axios.post('/tasklists', null, { headers: { 'Authorization': 'bearer ' + this.props.user.token }, data: { description: description, members: membersFiltered } }); if (result.status === 200) { this.props.addTaskList(result.data.result); this.setState({modalTask: false}); } break; } // Actualizo la lista case 'UPDATE': { const result = await Axios.put(`/tasklists/${this.props.selected.id}`, null, { headers: { 'Authorization': 'bearer ' + this.props.user.token }, data: { members: membersFiltered } }); if (result.status === 200) { this.props.addMembers(members); this.setState({modalTask: false}); } break; } // Error incontrolado default: { alert('Error incontrolado'); break; } } } catch (error) { console.log(error) } } /** * Sincronizar datos con la API Rest */ syncNowEventHandler = () => { try { // Cargar listado de tareas Axios.get('/tasklists', { headers: { 'Authorization': 'bearer ' + this.props.user.token }}) .then (response => { if (response.status === 200) { this.props.loadLists(response.data.results); } }) } catch (error) { console.log(error); } } /** * Sort To-Dos * (NOT IMPLEMENTED YET. Issue #5 ) */ sortTodosEventHandler = () => alert('Sort todos not implemented yet'); }
JavaScript
class MarpatError extends Error { constructor(message) { super(message); // Extending Error is weird and does not propagate `message` Object.defineProperty(this, 'message', { enumerable: false, value: message }); Object.defineProperty(this, 'name', { enumerable: false, value: this.constructor.name }); } }
JavaScript
class ValidationError extends MarpatError { constructor(message) { super(message); } }
JavaScript
class ConnectionError extends MarpatError { constructor(message) { super(message); } }
JavaScript
class MotorBike extends v{ static work(){ console.log("motor bike runs on 2 wheels") } constructor(){ super().Run(); } }
JavaScript
class AutomadGallery { constructor({data, api}) { var create = Automad.util.create; this.api = api; this.data = { globs: data.globs || '*.jpg, *.png, *.gif', width: data.width || 250, stretched: data.stretched !== undefined ? data.stretched : true, cleanBottom: data.cleanBottom !== undefined ? data.cleanBottom : true }; this.inputs = { globs: create.editable(['cdx-input'], 'Enter one or more glob patterns', this.data.globs), width: create.editable(['cdx-input'], 'Image width in px', this.data.width) }; var icon = document.createElement('div'), title = document.createElement('div'); icon.innerHTML = AutomadGallery.toolbox.icon; icon.classList.add('am-block-icon'); title.innerHTML = AutomadGallery.toolbox.title; title.classList.add('am-block-title'); this.wrapper = document.createElement('div'); this.wrapper.classList.add('uk-panel', 'uk-panel-box'); this.wrapper.appendChild(icon); this.wrapper.appendChild(title); this.wrapper.appendChild(document.createElement('hr')); this.wrapper.appendChild(create.label('Pattern')); this.wrapper.appendChild(this.inputs.globs); this.wrapper.appendChild(create.label('Image Width')); this.wrapper.appendChild(this.inputs.width); this.settings = [ { name: 'stretched', title: 'Full Width', icon: '<svg width="17" height="10" viewBox="0 0 17 10"><path d="M13.568 5.925H4.056l1.703 1.703a1.125 1.125 0 0 1-1.59 1.591L.962 6.014A1.069 1.069 0 0 1 .588 4.26L4.38.469a1.069 1.069 0 0 1 1.512 1.511L4.084 3.787h9.606l-1.85-1.85a1.069 1.069 0 1 1 1.512-1.51l3.792 3.791a1.069 1.069 0 0 1-.475 1.788L13.514 9.16a1.125 1.125 0 0 1-1.59-1.591l1.644-1.644z"/></svg>' }, { name: 'cleanBottom', title: 'Clean Bottom Edge', icon: '<svg width="18px" height="16px" viewBox="-50 68.5 18 16"><path d="M-32,79.5c0,0.553-0.448,1-1,1h-6c-0.552,0-1-0.447-1-1v-4c0-0.553,0.448-1,1-1h6c0.552,0,1,0.447,1,1V79.5z"/><path d="M-32,71.5c0,0.553-0.448,1-1,1h-6c-0.552,0-1-0.447-1-1v-2c0-0.553,0.448-1,1-1h6c0.552,0,1,0.447,1,1V71.5z"/><path d="M-32,83.521c0,0.541-0.438,0.979-0.979,0.979h-16.041c-0.541,0-0.979-0.438-0.979-0.979l0,0 c0-0.541,0.438-0.979,0.979-0.979h16.041C-32.438,82.541-32,82.979-32,83.521L-32,83.521z"/><path d="M-50,69.5c0-0.553,0.448-1,1-1h6c0.552,0,1,0.447,1,1v4c0,0.553-0.448,1-1,1h-6c-0.552,0-1-0.447-1-1V69.5z"/><path d="M-50,77.5c0-0.553,0.448-1,1-1h6c0.552,0,1,0.447,1,1v2c0,0.553-0.448,1-1,1h-6c-0.552,0-1-0.447-1-1V77.5z"/></svg>' } ]; Promise.resolve().then(() => { this.api.blocks.stretchBlock(this.api.blocks.getCurrentBlockIndex(), this.data.stretched); }); } static get toolbox() { return { title: 'Gallery', icon: '<svg width="18px" height="15px" viewBox="0 0 18 15"><path d="M14,0H4C1.791,0,0,1.791,0,4v7c0,2.209,1.791,4,4,4h10c2.209,0,4-1.791,4-4V4C18,1.791,16.209,0,14,0z M4,2h4v6H2V4 C2,2.897,2.897,2,4,2z M4,13c-1.103,0-2-0.897-2-2v-1h6v3H4z M16,11c0,1.103-0.897,2-2,2h-4V7h6V11z M16,5h-6V2h4 c1.103,0,2,0.897,2,2V5z"/></svg>' }; } render() { return this.wrapper; } save() { var stripNbsp = Automad.util.stripNbsp; return Object.assign(this.data, { globs: stripNbsp(this.inputs.globs.innerHTML), width: parseInt(stripNbsp(this.inputs.width.innerHTML)) }); } renderSettings() { var wrapper = document.createElement('div'), block = this; wrapper.classList.add('cdx-settings-1-2'); this.settings.forEach(function (tune) { var button = document.createElement('div'); button.classList.add('cdx-settings-button'); button.classList.toggle('cdx-settings-button--active', block.data[tune.name]); button.innerHTML = tune.icon; wrapper.appendChild(button); button.addEventListener('click', function () { block.toggleTune(tune.name); button.classList.toggle('cdx-settings-button--active'); }); block.api.tooltip.onHover(button, tune.title, { placement: 'top' }); }); return wrapper; } toggleTune(tune) { this.data[tune] = !this.data[tune]; if (tune == 'stretched') { this.api.blocks.stretchBlock(this.api.blocks.getCurrentBlockIndex(), this.data.stretched); } } static get sanitize() { return { globs: false, width: false }; } }
JavaScript
class NodeAdapter { /** * @param options Environment-specific options */ constructor(options) { /** * Holds the Storage instance associated with this instance */ this._storage = null; this.options = Object.assign({}, options); } /** * Given a relative path, returns an absolute url using the instance base URL */ relative(path) { return new URL(path, this.getUrl().href).href; } /** * Returns the protocol of the current request ("http" or "https") */ getProtocol() { const req = this.options.request; const proto = req.socket.encrypted ? "https" : "http"; return req.headers["x-forwarded-proto"] || proto; } /** * Given the current environment, this method must return the current url * as URL instance. In Node we might be behind a proxy! */ getUrl() { const req = this.options.request; let host = req.headers.host; if (req.headers["x-forwarded-host"]) { host = req.headers["x-forwarded-host"]; if (req.headers["x-forwarded-port"]) { host += ":" + req.headers["x-forwarded-port"]; } } const protocol = this.getProtocol(); const orig = String(req.headers["x-original-uri"] || req.url); return new URL(orig, protocol + "://" + host); } /** * Given the current environment, this method must redirect to the given * path * @param location The path to redirect to */ redirect(location) { this.options.response.writeHead(302, { location }); this.options.response.end(); } /** * Returns a ServerStorage instance */ getStorage() { if (!this._storage) { if (this.options.storage) { if (typeof this.options.storage == "function") { this._storage = this.options.storage(this.options); } else { this._storage = this.options.storage; } } else { this._storage = new ServerStorage_1.default(this.options.request); } } return this._storage; } /** * Base64 to ASCII string */ btoa(str) { // The "global." makes Webpack understand that it doesn't have to // include the Buffer code in the bundle return global.Buffer.from(str).toString("base64"); } /** * ASCII string to Base64 */ atob(str) { // The "global." makes Webpack understand that it doesn't have to // include the Buffer code in the bundle return global.Buffer.from(str, "base64").toString("ascii"); } /** * Returns a reference to the AbortController constructor. In browsers, * AbortController will always be available as global (native or polyfilled) */ getAbortController() { return cjs_ponyfill_1.AbortController; } /** * Creates and returns adapter-aware SMART api. Not that while the shape of * the returned object is well known, the arguments to this function are not. * Those who override this method are free to require any environment-specific * arguments. For example in node we will need a request, a response and * optionally a storage or storage factory function. */ getSmartApi() { return { ready: (...args) => smart_1.ready(this, ...args), authorize: options => smart_1.authorize(this, options), init: options => smart_1.init(this, options), client: state => new Client_1.default(this, state), options: this.options }; } }