language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class NodeDoppioDispatcher extends CommonDispatcher { constructor(javapoly) { super(javapoly); } initDoppioManager(javapoly) { return Promise.resolve(new NodeDoppioManager(javapoly)); } postMessage(messageType, priority, data, callback) { const id = this.javaPolyIdCount++; this.handleIncomingMessage(id, priority, messageType, data, callback); } reflect(jsObj) { return jsObj; } unreflect(result) { if ((!!result) && (typeof(result) === "object") && (!!result._javaObj)) { const className = result._javaObj.getClass().className; if (className === "Lcom/javapoly/DoppioJSObject;" || className === "Lcom/javapoly/DoppioJSPrimitive;") { return result._javaObj["com/javapoly/DoppioJSValue/rawValue"]; } } return result; } }
JavaScript
class removeclass { constructor(ele, classname) { this.arrclass = ele.className.split(' '); this.index = this.arrclass.indexOf(classname); } init() { if (this.index !== -1) { this.arrclass.splice(this.index, 1); } //[box1,box3] ele.className = this.arrclass.join(' '); } }
JavaScript
class PutClusterCapacityProvidersCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "ECSClient"; const commandName = "PutClusterCapacityProvidersCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.PutClusterCapacityProvidersRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.PutClusterCapacityProvidersResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1PutClusterCapacityProvidersCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1PutClusterCapacityProvidersCommand(output, context); } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.installApp = this.installApp.bind(this); this.selectRow = this.selectRow.bind(this); this.showQRCode = this.showQRCode.bind(this); const device = new DeviceDetector().parse(navigator.userAgent); this.state = { isLoading: true, url: "config.json", device: device, list: [], current: null, isInstalling: false, headerTitle: "很高兴邀请您安装Superbuy App,测试并反馈问题,便于我们及时解决您遇到的问题,十分谢谢!Thanks♪(・ω・)ノ" }; this.ref = React.createRef() } componentDidMount () { const { url, device, headerTitle } = this.state; fetch(url) .then(res => res.json()) .then(json => { const title = !json["title"] ? headerTitle : json["title"] const ipaList = json["ipaList"] || [] const apkList = json["apkList"] || [] const appList = json["appList"] || [] let list = [] if (device.os.name === 'iOS') { list = [...ipaList]; } else if (device.os.name === 'Android') { list = [...apkList]; } else if (device.device.type === 'desktop') { // pc list = [...ipaList, ...apkList, ...appList] } list = [...list].sort((a, b) => a.time < b.time ? 1 : -1) this.setState({isLoading: false, headerTitle: title, list: [...list], current: list.length ? list[0] : null}) }); this.showQRCode(); } showQRCode() { const canvas = this.ref.current; if (canvas) { QRCode.toCanvas({ canvas: canvas, content: window.location.href, width: 260, logo: { src: 'icon.png', radius: 8 } }) } } installApp () { const { current, device } = this.state; if (current) { if (device.os.name === 'iOS') { window.location.href = "itms-services://?action=download-manifest&url=" + current.domain + current.path + "manifest.plist"; setTimeout(() => { this.setState({isInstalling: true}) }, 1000); } else { window.location.href = current.domain + current.path + current.name; } } console.log(this.refs.qrcode) } selectRow (value) { this.setState({current: value}) } render() { const { isLoading, list, current, isInstalling, headerTitle, device } = this.state; const obj = current ? current : {version: "", build: 0, size: 0, time: 0, desc: "", name: "*.ipa"} const iconClassName = obj.name.indexOf(".apk") !== -1 ? "fa fa-android" : "fa fa-apple"; return ( <LoadingOverlay active={isLoading} spinner text='Loading...'> <div className="App"> <p>{headerTitle}</p> <img src={"icon.png"} className="App-icon" alt={""}/> <p className="App-detail-text"> 版本:{obj.version} (build {obj.build}) &nbsp;&nbsp; 大小:{(obj.size/1024/1024).toFixed(2)} MB &nbsp;&nbsp; 更新时间:{format('yyyy-MM-dd hh:mm:ss', new Date(obj.time * 1000))} </p> <div className="App-update-desc">{obj.desc}</div> { !current ? <p>Sorry,未找到任何软件包!</p> : <button id="install-app" className="App-install-button" onClick={this.installApp}> <i className={iconClassName} aria-hidden="true"> <span className="App-install-button-text"> {isInstalling ? "正在安装..." : "安装App"}</span> </i> </button> } { device.os.name === 'iOS' || true ? <a href="https://www.pgyer.com/tools/udid" className="App-help">安装遇到问题?</a> : null } <canvas ref={this.ref} /> <div className="App-line"> </div> <p>历史版本</p> <div className="App-history-version"> { list.map((value, index) => { const className = index % 2 === 0 ? "App-box-0" : "App-box-1"; const iconClassName = value.name.indexOf(".apk") !== -1 ? "fa fa-android" : "fa fa-apple"; return ( <div key={index} className={className} onClick={()=>{this.selectRow(value)}}> { device.device.type === 'desktop' && <i style={{marginRight: "10%"}} className={iconClassName} aria-hidden="true"> {value.name}</i> } <p style={{marginRight: "10%"}}>{value.version} (build {value.build} )</p> <p>{format('yyyy-MM-dd hh:mm:ss', new Date(value.time * 1000))}</p> </div> ) }) } </div> </div> </LoadingOverlay> ); } }
JavaScript
class CSSBackdrop extends BaseDynamicComponent { /** * @param {?} el * @param {?} renderer */ constructor(el, renderer) { super(el, renderer); this.activateAnimationListener(); const /** @type {?} */ style = { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }; Object.keys(style).forEach(k => this.setStyle(k, style[k])); } }
JavaScript
class GenerateDay extends React.Component { render = () => { let color = 'rgb(227, 231, 229)'; let data = []; try { data = this.props.data[this.props.year][months.indexOf(this.props.month)][ this.props.date ]; if (data === undefined) { data = []; } } catch (TypeError) { // perform nothing. } color = contribution_color(data.length); let pad = getPadding(); return ( <div className="day" style={{ background: color, padding: 6 + pad }} onClick={() => { this.props.set({ activity: data.toString(), }); }} > <div className="tooltip"> {data.length} {data.length === 1 ? 'Contribution' : 'Contributions'} on {this.props.month} {this.props.date}, {this.props.year} </div> </div> ); }; }
JavaScript
class GenerateMonth extends React.Component { render = () => { let days = getDaysInMonth(this.props.year, this.props.month); let items = []; for (let i = 1; i <= days; i++) { let item = []; while (i % 8 !== 0 && i <= days) { item.push( <GenerateDay key={i} date={i} month={this.props.month} year={this.props.year} data={this.props.data} set={this.props.set} /> ); i++; } if (days !== 8 * items.length + item.length) { item.push( <GenerateDay key={i} date={i} month={this.props.month} year={this.props.year} data={this.props.data} set={this.props.set} /> ); } items.push( <div className="flex-col" key={i}> {item} </div> ); } return ( <div style={{ textAlign: 'center' }}> <span className="contribution_text">{this.props.month}</span> <div className="flex-row">{items}</div> </div> ); }; }
JavaScript
class UserContribution extends React.Component { format = () => { /** * Format the received data to the proper format. * @returns {Object} formatted data. */ var rv = {}; for (let i of this.props.data) { let date = new Date(i.time); let year = date.getFullYear(); if (!(year in rv)) { rv[year] = {}; } let month = date.getMonth(); if (!(month in rv[year])) { rv[year][month] = {}; } let day = date.getDate(); if (!(day in rv[year][month])) { rv[year][month][day] = []; } rv[year][month][day].push(i.time); } return rv; }; render = () => { var render_months = []; if (!this.props.loading) { let data = this.format(); let approx_days = get_num_days( new Date(this.props.start_time), new Date(this.props.end_time) ); let numb_months = get_num_months(approx_days); let count_month = numb_months + 1; let shouldNotRemoveFirstMonthInArr = true, year = new Date(this.props.end_time), end_month = year.getMonth(); year = year.getFullYear(); while (count_month > 0) { try { //########### decide if we should remove the first month in render_months or not ######### shouldNotRemoveFirstMonthInArr = count_month !== 1 && render_months.length !== numb_months; let monthHasContribution = Object.getOwnPropertyNames(data[year][end_month]).length !== 0; shouldNotRemoveFirstMonthInArr = shouldNotRemoveFirstMonthInArr || monthHasContribution; //###################################################################################### } catch { // Do nothing } if (shouldNotRemoveFirstMonthInArr) { render_months.unshift( <GenerateMonth month={months[end_month]} key={count_month} year={year} data={data} set={this.props.set} /> ); } count_month -= 1; end_month -= 1; if (end_month === -1) { end_month = 11; year = new Date(this.props.start_time).getFullYear(); } } } return ( <React.Fragment> {!this.props.loading ? ( <span className="user_contribution_text"> {this.props.data.length} </span> ) : ( '' )} <div className="user_activity"> {this.props.loading ? ( <div> <Placeholder fluid className="load"> <Placeholder.Line /> </Placeholder> <Placeholder fluid className="load"> <Placeholder.Line /> </Placeholder> <Placeholder fluid className="load"> <Placeholder.Line /> </Placeholder> <Placeholder fluid className="load"> <Placeholder.Line /> </Placeholder> </div> ) : ( <React.Fragment> <div className="render_activity">{render_months}</div> <div style={{ right: '5%', position: 'absolute' }}> <div> <span className="contribution_text">Less</span> <div className="day" style={{ padding: 6 + getPadding(), display: 'inline-block', background: contributionColors.none, }} /> <div className="day" style={{ padding: 6 + getPadding(), display: 'inline-block', background: contributionColors.level1, }} /> <div className="day" style={{ padding: 6 + getPadding(), display: 'inline-block', background: contributionColors.level2, }} /> <div className="day" style={{ padding: 6 + getPadding(), display: 'inline-block', background: contributionColors.level3, }} /> <span className="contribution_text">More</span> </div> </div> </React.Fragment> )} </div> </React.Fragment> ); }; }
JavaScript
class RecurrenceCombo extends RecurrenceFrequencyCombo { static get $name() { return 'RecurrenceCombo'; } // Factoryable type name static get type() { return 'recurrencecombo'; } static get defaultConfig() { return { customValue : 'custom', placeholder : 'None', // TODO: draw a splitting line splitCls : 'b-recurrencecombo-split', items : true, highlightExternalChange : false }; } buildLocalizedItems() { const me = this; return [ { value : 'none', text : me.L('L{None}') }, ...super.buildLocalizedItems(), { value : me.customValue, text : me.L('L{Custom}'), cls : me.splitCls } ]; } set value(value) { // Use 'none' instead of falsy value value = value || 'none'; super.value = value; } get value() { return super.value; } set recurrence(recurrence) { const me = this; if (recurrence) { me.value = me.isCustomRecurrence(recurrence) ? me.customValue : recurrence.frequency; } else { me.value = null; } } isCustomRecurrence(recurrence) { const { interval, days, monthDays, months } = recurrence; return Boolean(interval > 1 || (days && days.length) || (monthDays && monthDays.length) || (months && months.length)); } }
JavaScript
class Geocoder extends Component { constructor(props) { super(props); this.state = { results: [], focus: null, searchTime: new Date(), showList: false, inputValue: "", typedInput: "", }; this.onInput = this.onInput.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.onResult = this.onResult.bind(this); } componentWillMount() { this.setState({ inputValue: this.props.defaultValue }); } componentDidMount() { document.addEventListener("click", (e) => { if (this.state.showList && !this.container.contains(e.target)) { this.setState({ showList: false }); } }); } search( endpoint, source, accessToken, proximity, bbox, types, query, callback ) { var searchTime = new Date(); var uri = endpoint + "/geocoding/v5/" + source + "/" + encodeURIComponent(query) + ".json" + "?access_token=" + accessToken + (proximity ? "&proximity=" + proximity : "") + (bbox ? "&bbox=" + bbox : "") + (types ? "&types=" + encodeURIComponent(types) : ""); xhr( { uri: uri, json: true, }, function (err, res, body) { callback(err, res, body, searchTime); } ); } onInput(e) { var value = e.target.value; this.setState({ showList: true, inputValue: value, typedInput: value, }); this.props.onInputChange(value); if (value === "") { this.setState({ results: [], focus: null, }); } else { this.search( this.props.endpoint, this.props.source, this.props.accessToken, this.props.proximity, this.props.bbox, this.props.types, value, this.onResult ); } } moveFocus(dir) { var focus = this.state.focus === null ? 0 : Math.max( -1, Math.min(this.state.results.length - 1, this.state.focus + dir) ); var inputValue = focus === -1 ? this.state.typedInput : this.state.results[focus].place_name; this.setState({ focus: focus, inputValue: inputValue, showList: true, }); this.props.onInputChange(inputValue); } acceptFocus() { if (this.state.focus !== null && this.state.focus !== -1) { var inputValue = this.state.results[this.state.focus].place_name; this.setState({ showList: false, inputValue: inputValue }); this.props.onInputChange(inputValue); this.props.onSelect(this.state.results[this.state.focus]); } } onKeyDown(e) { switch (e.which) { // up case 38: e.preventDefault(); this.moveFocus(-1); break; // down case 40: e.preventDefault(); this.moveFocus(1); break; // tab case 9: this.acceptFocus(); break; // esc case 27: this.setState({ showList: false, results: [] }); break; // accept case 13: if (this.state.results.length > 0 && this.state.focus == null) { this.clickOption(this.state.results[0], 0); } this.acceptFocus(); e.preventDefault(); break; default: break; } } onResult(err, res, body, searchTime) { // searchTime is compared with the last search to set the state // to ensure that a slow xhr response does not scramble the // sequence of autocomplete display. if (!err && body && body.features && this.state.searchTime <= searchTime) { this.setState({ searchTime: searchTime, results: body.features, focus: 0, }); this.props.onSuggest(this.state.results); } } clickOption(place, index, e) { if (e) { e.preventDefault(); } this.props.onInputChange(place.place_name); this.props.onSelect(place); this.setState({ focus: index, showList: false, inputValue: place.place_name, }); } render() { const { endpoint, defaultValue, source, inputPosition, inputPlaceholder, onSelect, onSuggest, onInputChange, accessToken, proximity, bbox, types, ...inputProps } = this.props; var input = React.createElement("input", { ...inputProps, ref: "input", // onInput: this.onInput, onKeyDown: this.onKeyDown, type: "text", // defaultValue: this.state.inputValue value: this.state.inputValue, onChange: this.onInput, }); return React.createElement( "div", { ref: (ref) => { this.container = ref; }, className: "mapbox-autocomplete-container", }, this.props.inputPosition === "top" && input, React.createElement( "div", { className: [ "mapbox-autocomplete", this.state.showList && "is-open", ].join(" "), }, this.state.results.map((result, i) => { return React.createElement( "div", { key: result.id, onClick: this.clickOption.bind(this, result, i), className: [ "item", i === this.state.focus ? "selected" : "", ].join(" "), }, React.createElement("span", {}, result.place_name) ); }) ), this.props.inputPosition === "bottom" && input ); } }
JavaScript
class CinemaRoutes extends Route { constructor(app) { super(app); //Rajoute tout les handlers avec les routes de la resource cinema à l'application express. app.post('/cinemas/', this.post); app.get('/cinemas/', this.getAll); app.put('/cinemas/:uuid', this.put); app.get('/cinemas/:uuid', this.get); app.get('/cinemas/:uuid/horaires/', this.getHoraires); } //Handler post sur la resource cinema. post(req, res) { //Réponse de base. super.createResponse(res); let isBody = true; //Body pour savoir si on veut retourner une représentation de l'objet au client une fois rajouté. if (req.query._body && req.query._body === 'false') { isBody = false; } //Exécute les règles de validation de l'objet cinema. req.checkBody(validationCinema.Required()); //Vérifie si une erreur de validation c'est produite. var errorValidation = req.validationErrors(); if (errorValidation) { //Erreur de validation. res.status(500); let error = super.createError(500, "Erreur de validation", errorValidation); res.send(error); return; } //Crée un nouveau uuid v4. req.body.uuid = uuid.v4(); let query = queries.insertCinema(req.body); //Exécute la requête en bd. connexion.query(query, (error, result) => { if (error) { res.status(500); let errorMessage = super.createError(500, "Erreur de Serveur", error); res.send(errorMessage); } else { //Réutilise le même body de la requête client pour envoyer une représentation de l'objet créé. cinemaLogic.linking(req.body); //Crée une collection vide d'horaires. req.body.horaires = []; res.status(201); res.location(req.body.url); //Techniquement on ne devrait pas travailler pour rien et faire ce if plus tôt. if (isBody) { res.send(req.body); } else { res.send(); } } }); } //Handler get sur la collection cinema getAll(req, res) { //Réponse de base. super.createResponse(res); let query = queries.selectCinemas(null, null); //Exécute la requête en bd. connexion.query(query, (error, rows, fields) => { if (error) { res.status(500); let errorResponse = super.createError(500, "Erreur Serveur", error); res.send(errorResponse); } else { res.status(200); //Async itératif sur tout les cinéma retourné par la bd. async.each(rows, (cinema, next) => { let uuid = cinema.uuid; cinemaLogic.linking(cinema); //Récupère tout les horaires du cinema. et applique la vue link. horaireLogic.retrieveView(uuid, 'link', null, null, (resultHoraire) => { if (resultHoraire.error) { //Gestion } else { //Rajoute une liste d'objet horaires au cinema. cinemaLogic.addHoraires(cinema, resultHoraire.horaires); } next(); }); }, function SendResponse() { res.send(rows); }); } }); } //Handler put de la resource cinema. put(req, res) { //Réponse de base. super.createResponse(res); //Lance les règles de validation d'un objet cinema. req.checkBody(validationCinema.Required()); //Vérifie si une erreur de validation c'est produite. var errorValidation = req.validationErrors(); if (errorValidation) { //Erreur de validation. res.status(500); let error = super.createError(500, "Erreur de validation", errorValidation); res.send(error); return; } //Plus simple à travailler si l'objet lui même contient l'uuid de la requête. req.body.uuid = req.params.uuid; //Fait la mise à jour complète de l'objet cinema en bd et récupère une représentation. cinemaLogic.handlePut(req.body, (result) => { if (result.error) { res.status(500); let errorResponse = super.createError(500, "Erreur Serveur", result.error); res.send(errorResponse); } else { res.status(200); res.send(result.cinema); } }); } //Handler get sur la resource cinema. get(req, res) { //Réponse de base. super.createResponse(res); let fields = null; //Fields if (req.query.fields) { fields = req.query.fields; //Prépare la chaîne string en séparant les éléments séparé par une virgule un à un. //Enregistre la liste de string résultante. fields = super.prepareFields(fields); } //Récupère l'objet cinema en bd à partir de son uuid. cinemaLogic.retrieve(req.params.uuid, (result) => { if (result.error) { res.status(500); let errorResponse = super.createError(500, "Erreur Serveur", result.error); res.send(errorResponse); } else if (result.length === 0) { res.status(404); res.send(); } else { res.status(200); let cinemaResponse = result.cinema; //Récupère les horaires du cinema et applique la vue link. horaireLogic.retrieveView(req.params.uuid, 'link', null, null, (resultHoraire) => { if (resultHoraire.error) { //Gestion } else { cinemaLogic.addHoraires(cinemaResponse, resultHoraire.horaires); } //Si fields est utilisé if (fields) { //Applique fields en filtrant les champs de l'objet cinema qui n'intéresse pas le client. cinemaLogic.handleFields(cinemaResponse, fields, (cinemaResponse) => { res.send(cinemaResponse); }); } else { res.send(cinemaResponse); } }); } }); } //Handler get des horaires de la resource cinema. getHoraires(req, res) { //Réponse de base. super.createResponse(res); //Récupère les horaires du cinema spécifié par uuid en appliquant la vue default. horaireLogic.retrieveView(req.params.uuid, 'default', null, null, (result) => { if (result.error) { res.status(500); let errorResponse = super.createError(500, "Erreur Serveur", result.error); res.send(errorResponse); } else if (result.length === 0) { res.status(404); res.send(); } else { res.status(200); res.send(result.horaires); } }); } }
JavaScript
class ItemShare { /** * Creates a representation of a shared item * @param {Number} id Item's id (unique on owner device) * @param {String} name Item's name * @param {ItemType} type Item's type * @param {String} [fullName] Optional item's full name (name and extension - null for folder) * @param {String} [extension] Optional item's extension (null for folder) * @param {String} [size] Optional item's size (expressed in Bytes, KB, MB, GB etc. - null for folder) * @param {Number} [bytes] Optional item's total bytes (null for folder) * @param {Number} [totFiles] Optional item's total files (null for file) * @param {String} [tag] Optional description to more easily identify one or more files */ constructor(id, name, type, fullName, extension, size, bytes, totFiles, tag) { this.id = id; this.name = name; this.type = type; this.fullName = fullName; this.extension = extension; this.size = size; this.bytes = bytes; this.totFiles = totFiles; this.tag = tag; } }
JavaScript
class DLCSLoginPanel extends React.Component { constructor(props) { super(props); this.state = { endpoint: this.props.endpoint || '', customer: this.props.customer || '', api_id: this.props.api_id || '', api_secret: this.props.api_secret || '', error: '', }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onChange(ev) { const newState = {}; newState[ev.target.name] = ev.target.value; this.setState(newState); } onSubmit(ev) { ev.preventDefault(); const self = this; this.setState({ error: '', }); let headers = new Headers(); const { endpoint, customer } = this.state; const url = `${endpoint}/customers/${customer}`.replace( '//customers', '/customers' ); const auth = btoa(`${this.state.api_id}:${this.state.api_secret}`); headers.append('Authorization', `Basic ${auth}`); fetch(url, { method: 'GET', headers: headers, }) .then(response => response.json()) .then(response => { if ( !response || response.success === 'false' || response.success === false ) { self.setState({ error: 'Invalid credentials', }); } else { if (self.props.loginCallback) { const session = { dlcs_url: url, auth: auth, userName: response.displayName, }; if (localStorage) { localStorage.setItem('dlcsSession', JSON.stringify(session)); } self.props.loginCallback(session); } } }) .catch(err => { self.setState({ error: err, }); }); } render() { const { classes } = this.props; return ( <div className={classes.root}> <TextField label="DLCS Endpoint" type="url" name="endpoint" value={this.state.endpoint} onChange={this.onChange} margin="dense" variant="outlined" /> <TextField label="DLCS Customer Id" type="number" min="0" name="customer" value={this.state.customer} onChange={this.onChange} margin="dense" variant="outlined" /> <TextField label="DLCS API ID" type="text" name="api_id" value={this.state.api_id} onChange={this.onChange} margin="dense" variant="outlined" /> <TextField label="DLCS API Secret" type="password" name="api_secret" value={this.state.api_secret} onChange={this.onChange} margin="dense" variant="outlined" /> <Button onClick={this.onSubmit}>Login</Button> {this.state.error !== '' ? ( <div className="dlcs-login-panel__error">{this.state.error}</div> ) : ( '' )} </div> ); } }
JavaScript
class XYZColor { /** * Creates new XYZ color. * @param x - x-component in the range [0, 1]. * @param y - y-component in the range [0, 1]. * @param z - z-component in the range [0, 1]. */ constructor(x, y, z) { this.values = [x, y, z]; } /** * The x-component of the color. */ get x() { return this.values[0]; } /** * The y-component of the color. */ get y() { return this.values[1]; } /** * The z-component of the color. */ get z() { return this.values[2]; } /** * Return a copy of color values in array format as [x, y, z]. */ toArray() { // copy return this.values.map((v) => v); } /** * Trasforms color to the RGB format. */ toRGB() { const [x, y, z] = this.values; const r = +3.2406255 * x - 1.5372080 * y - 0.4986286 * z; const g = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; const b = +0.0557101 * x - 0.2040211 * y + 1.0569959 * z; return new RGBColor_1.RGBColor(r, g, b); } /** * Trasforms color to the sRGB format. */ toSRGB() { return this.toRGB().toSRGB(); } /** * Trasforms color to the CIE LAB format. */ toLAB() { const x = this.x / XYZColor.D65.x; const y = this.y / XYZColor.D65.y; const z = this.z / XYZColor.D65.z; const xyz = [x, y, z].map((v) => { if (v > 0.008856451) { return v ** (1 / 3); } else { return 7.787037 * v + 16 / 116; } }); return new LABColor_1.LABColor((116 * xyz[1] - 16) / 100, 5 * (xyz[0] - xyz[1]), 2 * (xyz[1] - xyz[2])); } }
JavaScript
class ChangeKeySigned extends Abstract { /** * Gets the optype. * * @returns {number} */ get opType() { return 7; } /** * Constructor. * * @param {Account|AccountNumber|Number|String} accountSigner * @param {Account|AccountNumber|Number|String} accountTarget * @param {PublicKey} newPublicKey */ constructor(accountSigner, accountTarget, newPublicKey) { super(); this[P_SIGNER] = new AccountNumber(accountSigner); this[P_TARGET] = new AccountNumber(accountTarget); this[P_NEW_PUBLIC_KEY] = newPublicKey; } /** * Gets the account number of the signer. * * @return {AccountNumber} */ get signer() { return this[P_SIGNER]; } /** * Gets the account number of the account to be changed. * * @return {AccountNumber} */ get target() { return this[P_TARGET]; } /** * Gets the new public key of the target account. * * @return {PublicKey} */ get newPublicKey() { return this[P_NEW_PUBLIC_KEY]; } }
JavaScript
class BaseGenerator { /** * Base generator * @param {string} moduleName is the new module name that has to be code generated. * @param {string} moduleId is the new module id derived from module name. */ constructor(moduleName, moduleId) { this.moduleName = moduleName; this.moduleId = moduleId; } }
JavaScript
class Rule extends tslint_1.Rules.TypedRule { applyWithProgram(sourceFile, program) { return this.applyWithWalker(new Walker(sourceFile, this.getOptions(), program)); } }
JavaScript
class Server extends Entity { hasOne() { return { 'webServer': ModelTypes.MODEL_TYPE_WEB_SERVER, }; } }
JavaScript
class Node { /** * Create an empty node. * @param {Node} token - The token for this node. * @param {Node} parent - The parent node of this node. */ constructor(token, parent) { this.id = Node.counter; Node.counter += 1; this.token = token; this.parent = parent; this.children = []; } /** * Add a child. * @param {Node} node - The child node. * @return {Node} - The child node. */ add(node) { this.children.push(node); return node; } /** * Create a child. * @param {Token} [token] - The token for the child node. * @return {Node} - The child node. */ spawn(token) { return this.add(new Node(token, this)); } /** * Clone the node and its child. * @return {Node} - The clone. */ clone() { const clone = new Node(this.token, this.parent); clone.children = this.children.map(child => child.clone()); return clone; } /** * Add this node to any nodes that don't have children. * @return {Node} - The node to terminate other nodes to. */ terminate(node, history = {}) { if (history[this.id]) return; Object.assign(history, { [this.id]: true }); if (this.children.length) this.children.forEach(child => child.terminate(node, history)); else this.add(node); } end(history = {}) { if (history[this.id]) return this; Object.assign(history, { [this.id]: true }); if (this.children.length) return this.children[0].end(history); return this; } list(history = {}) { if (history[this.id]) return []; Object.assign(history, { [this.id]: true }); const nodes = [this]; this.children.forEach(child => nodes.push(...child.list(history))); return nodes; } /** * Find paths to nodes that matches the given character. * @param {String} character - The character to match tokens against. * @returns {Path[]} - The paths that the character matches. */ find(character, results, emptyNodes = {}) { this.children.forEach((child) => { if (!child.token) { // Only visit empty loops once. if (emptyNodes[child.id]) return null; // Pass through nodes with no token. return child.find(character, results, Object.assign({ [child.id]: true }, emptyNodes)); } // If the character matches the token, use it and give it a score of one. if (child.token.match(character)) { return results.push(new Path(child, character, 1)); } // If there is only one path, use it and give it a score of zero. const onlyOnePath = (child.token.choices === 1); if (onlyOnePath) { return results.push(new Path(child, child.token.value, 0)); } }); } /** * Find a random path that this node leads to. * @returns {Path} - The path. */ sample() { const paths = this.children.map((child) => { // Pass through nodes with no token. if (!child.token) return child.sample(); // Use a random character that matches the token. return new Path(child, child.token.sample(), 1); }); if (paths.length === 0) return null; return sample(paths); } }
JavaScript
class TimeScale extends Component { /** * Prop types for `<TimeScale />`. * @prop {Integer} value - Value of slider. * @prop {Function} onChange - Callback to run when slider changes. */ static propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired } static values = [ '0.33', '0.5', '0.66', '1', '1.5', '2', '3', '4' ] constructor(props) { super(props); this.state = { textValue: props.value }; } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ textValue: nextProps.value }); } } handleRangeChange = event => { const {values} = this.constructor; this.props.onChange(values[event.target.value]); } handleTextChange = event => { this.setState({ textValue: event.target.value }); } handleTextConfirm = event => { if (event.key === 'Enter') { this.props.onChange(event.target.value); } } render() { const {values} = this.constructor; const {value} = this.props; const {textValue} = this.state; return ( <div className="scale"> <input type="range" min="0" max={values.length} value={values.indexOf(value)} onChange={this.handleRangeChange}/> <input type="number" value={textValue} onChange={this.handleTextChange} onKeyUp={this.handleTextConfirm}/> </div> ); } }
JavaScript
class CoreClient extends Client { /** * @param {MessageTransport} transport */ constructor (transport) { super('core', ['add', 'addAll', 'cat', 'ls'], transport) } /** * Import files and data into IPFS. * * If you pass binary data like `Uint8Array` it is recommended to provide * `transfer: [input.buffer]` which would allow transferring it instead of * copying. * * @type {import('.').Implements<typeof import('ipfs-core/src/components/add-all')>} */ async * addAll (input, options = {}) { const { timeout, signal } = options const transfer = [...(options.transfer || [])] const progress = options.progress ? encodeCallback(options.progress, transfer) : undefined const result = await this.remote.addAll({ ...options, input: encodeAddAllInput(input, transfer), progress, transfer, timeout, signal }) yield * decodeIterable(result.data, decodeAddedData) } /** * Add file to IPFS. * * If you pass binary data like `Uint8Array` it is recommended to provide * `transfer: [input.buffer]` which would allow transferring it instead of * copying. * * @type {import('.').Implements<typeof import('ipfs-core/src/components/add')>} */ async add (input, options = {}) { const { timeout, signal } = options const transfer = [...(options.transfer || [])] const progress = options.progress ? encodeCallback(options.progress, transfer) : undefined const result = await this.remote.add({ ...options, input: encodeAddInput(input, transfer), progress, transfer, timeout, signal }) return decodeAddedData(result.data) } /** * Returns content addressed by a valid IPFS Path. * * @param {string|CID} inputPath * @param {Object} [options] * @param {number} [options.offset] * @param {number} [options.length] * @param {number} [options.timeout] * @param {AbortSignal} [options.signal] * @returns {AsyncIterable<Uint8Array>} */ async * cat (inputPath, options = {}) { const input = CID.isCID(inputPath) ? encodeCID(inputPath) : inputPath const result = await this.remote.cat({ ...options, path: input }) yield * decodeIterable(result.data, identity) } /** * Returns content addressed by a valid IPFS Path. * * @param {string|CID} inputPath * @param {Object} [options] * @param {boolean} [options.recursive] * @param {boolean} [options.preload] * @param {number} [options.timeout] * @param {AbortSignal} [options.signal] * @returns {AsyncIterable<LsEntry>} */ async * ls (inputPath, options = {}) { const input = CID.isCID(inputPath) ? encodeCID(inputPath) : inputPath const result = await this.remote.ls({ ...options, path: input }) yield * decodeIterable(result.data, decodeLsEntry) } }
JavaScript
class BooksApp extends React.Component { constructor(props) { super(props); this.state = { books: [] }; } //added componentDidMount lifecycle event L4 componentDidMount() { BooksAPI.getAll().then(books => { this.setState({ books: books }); }); } //update state with setState(Lesson 3:State Management) bookUpdate = (book, shelf) => { BooksAPI.update(book, shelf).then(resp => { book.shelf = shelf; this.setState(state => ({ books: state.books.filter(b => b.id !== book.id).concat(book) })); }); }; //Dynamically Render Pages (This method breaks the back button so we don't use it)L5 Managing App Location with React. // history-The BrowserRouter Component L5 //Route- The Route Component works L5(Route is used.Use exact to get the correct path) render() { return ( <div className="app"> <Route exact path="/" render={() => ( <MainPage books={this.state.books} bookUpdate={this.bookUpdate} /> )} /> <Route exact path="/search" render={() => ( <SearchPage books={this.state.books} bookUpdate={this.bookUpdate} /> )} /> </div> ); } }
JavaScript
class SeekBar extends Slider { /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ constructor(player, options) { super(player, options); this.update = Fn.throttle(Fn.bind(this, this.update), 50); this.on(player, ['timeupdate', 'ended'], this.update); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ createEl() { return super.createEl('div', { className: 'vjs-progress-holder' }, { 'aria-label': this.localize('Progress Bar') }); } /** * Update the seek bar's UI. * * @param {EventTarget~Event} [event] * The `timeupdate` or `ended` event that caused this to run. * * @listens Player#timeupdate * @listens Player#ended */ update() { const percent = super.update(); const duration = this.player_.duration(); // Allows for smooth scrubbing, when player can't keep up. const time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2)); // human readable value of progress bar (time complete) this.el_.setAttribute('aria-valuetext', formatTime(time, duration)); // Update the `PlayProgressBar`. this.bar.update(Dom.getBoundingClientRect(this.el_), percent); return percent; } /** * Get the percentage of media played so far. * * @return {number} * The percentage of media played so far (0 to 1). */ getPercent() { // Allows for smooth scrubbing, when player can't keep up. const time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); const percent = time / this.player_.duration(); return percent >= 1 ? 1 : percent; } /** * Handle mouse down on seek bar * * @param {EventTarget~Event} event * The `mousedown` event that caused this to run. * * @listens mousedown */ handleMouseDown(event) { this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); super.handleMouseDown(event); } /** * Handle mouse move on seek bar * * @param {EventTarget~Event} event * The `mousemove` event that caused this to run. * * @listens mousemove */ handleMouseMove(event) { let newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); } /** * Handle mouse up on seek bar * * @param {EventTarget~Event} event * The `mouseup` event that caused this to run. * * @listens mouseup */ handleMouseUp(event) { super.handleMouseUp(event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } } /** * Move more quickly fast forward for keyboard-only users */ stepForward() { this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS); } /** * Move more quickly rewind for keyboard-only users */ stepBack() { this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS); } /** * Toggles the playback state of the player * This gets called when enter or space is used on the seekbar * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called * */ handleAction(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } } /** * Called when this SeekBar has focus and a key gets pressed down. By * default it will call `this.handleAction` when the key is space or enter. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ handleKeyPress(event) { // Support Space (32) or Enter (13) key operation to fire a click event if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleAction(event); } else if (super.handleKeyPress) { // Pass keypress handling up for unsupported keys super.handleKeyPress(event); } } }
JavaScript
class Publisher { /** * Create an event Publisher. * @param {string} kubeMQHost - The KubeMQ address. * @param {number} kubeMQGrpcPort - The KubeMQ Grpc exposed port. * @param {string} client - The publisher ID, for tracing. * @param {string} channelName - The pub sub communication channel. * @param {boolean} isSecure - Using TLS secure KubeMQ. */ constructor(kubeMQHost, kubeMQRestPort, client, channelName,isSecure) { this.PubSub = new PubSub(kubeMQHost, kubeMQRestPort, client, channelName,false,undefined,isSecure); } /** * publish event. * @param {event} event - The data to publish. */ send(event) { return this.PubSub.send(event); } /** * stream events, keep and open stream to stream event. * @param {EventEmitter} event_emitter - Emits on('message'}. */ openStream() { return this.PubSub.openStream(); } stream(event){ return this.PubSub.stream(event); } closeStream(){ return this.PubSub.closeStream(); } }
JavaScript
class LoadersBase extends EventEmitter { /** * Create a Loader. * @param {dom} container - The dom container of loader. * @param {object} ProgressBar - The progressbar of loader. */ constructor(container = null, ProgressBar = HelpersProgressBar) { super(); this._loaded = -1; this._totalLoaded = -1; this._parsed = -1; this._totalParsed = -1; this._data = []; this._container = container; this._progressBar = null; if (this._container && ProgressBar) { this._progressBar = new ProgressBar(this._container); } } /** * free the reference. */ free() { this._data = []; this._container = null; // this._helpersProgressBar = null; if (this._progressBar) { this._progressBar.free(); this._progressBar = null; } } /** * load the resource by url. * @param {string} url - resource url. * @param {Map} requests - used for cancellation. * @return {promise} promise. */ fetch(url, requests) { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open('GET', url); request.crossOrigin = true; request.responseType = 'arraybuffer'; request.onloadstart = event => { // emit 'fetch-start' event this.emit('fetch-start', { file: url, time: new Date(), }); }; request.onload = event => { if (request.status === 200 || request.status === 0) { this._loaded = event.loaded; this._totalLoaded = event.total; // will be removed after eventer set up if (this._progressBar) { this._progressBar.update(this._loaded, this._totalLoaded, 'load', url); } let buffer = request.response; let response = { url, buffer, }; // emit 'fetch-success' event this.emit('fetch-success', { file: url, time: new Date(), totalLoaded: event.total, }); resolve(response); } else { reject(request.statusText); } }; request.onerror = () => { // emit 'fetch-error' event this.emit('fetch-error', { file: url, time: new Date(), }); reject(request.statusText); }; request.onabort = event => { // emit 'fetch-abort' event this.emit('fetch-abort', { file: url, time: new Date(), }); reject(request.statusText || 'Aborted'); }; request.ontimeout = () => { // emit 'fetch-timeout' event this.emit('fetch-timeout', { file: url, time: new Date(), }); reject(request.statusText); }; request.onprogress = event => { this._loaded = event.loaded; this._totalLoaded = event.total; // emit 'fetch-progress' event this.emit('fetch-progress', { file: url, total: event.total, loaded: event.loaded, time: new Date(), }); // will be removed after eventer set up if (this._progressBar) { this._progressBar.update(this._loaded, this._totalLoaded, 'load', url); } }; request.onloadend = event => { // emit 'fetch-end' event this.emit('fetch-end', { file: url, time: new Date(), }); // just use onload when success and onerror when failure, etc onabort // reject(request.statusText); }; if (requests instanceof Map) { requests.set(url, request); } request.send(); }); } /** * parse the data loaded * SHOULD BE implementd by detail loader. * @param {object} response - loaded data. * @return {promise} promise. */ parse(response) { return new Promise((resolve, reject) => { resolve(response); }); } /** * default load sequence group promise. * @param {array} url - resource url. * @param {Map} requests - used for cancellation. * @return {promise} promise. */ loadSequenceGroup(url, requests) { const fetchSequence = []; url.forEach(file => { fetchSequence.push(this.fetch(file, requests)); }); return Promise.all(fetchSequence) .then(rawdata => { return this.parse(rawdata); }) .then(data => { this._data.push(data); return data; }) .catch(function(error) { if (error === 'Aborted') { return; } window.console.log('oops... something went wrong...'); window.console.log(error); }); } /** * default load sequence promise. * @param {string} url - resource url. * @param {Map} requests - used for cancellation. * @return {promise} promise. */ loadSequence(url, requests) { return this.fetch(url, requests) .then(rawdata => { return this.parse(rawdata); }) .then(data => { this._data.push(data); return data; }) .catch(function(error) { if (error === 'Aborted') { return; } window.console.log('oops... something went wrong...'); window.console.log(error); }); } /** * load the data by url(urls) * @param {string|array} url - resource url. * @param {Map} requests - used for cancellation. * @return {promise} promise */ load(url, requests) { // if we load a single file, convert it to an array if (!Array.isArray(url)) { url = [url]; } if (this._progressBar) { this._progressBar.totalFiles = url.length; this._progressBar.requests = requests; } // emit 'load-start' event this.emit('load-start', { files: url, time: new Date(), }); const loadSequences = []; url.forEach(file => { if (!Array.isArray(file)) { loadSequences.push(this.loadSequence(file, requests)); } else { loadSequences.push(this.loadSequenceGroup(file, requests)); } }); return Promise.all(loadSequences); } /** * Set data * @param {array} data */ set data(data) { this._data = data; } /** * Get data * @return {array} data loaded */ get data() { return this._data; } }
JavaScript
class TemplateCover extends React.Component { constructor(props) { super(props); this.state = { video: MEDIA_HIDDEN, featureLang: 0, }; } getVideo(index, headerEndIndex) { if (index < headerEndIndex) { return this.props.cover.headerVideos[index]; } else if (index >= 0) { return this.props.cover.videos[index - headerEndIndex]; } else { return null; } } onVideoClickHandler(index) { const buffer = this.props.cover.headerVideos ? this.props.cover.headerVideos.length : 0; return () => { this.setState({ video: index + buffer, }); }; } renderFeature() { const { featureVideo } = this.props.cover; const { featureLang } = this.state; const { translations } = featureVideo; const source = featureLang === 0 ? featureVideo : { ...translations[featureLang - 1], poster: featureVideo.poster, }; return ( <div> <div className="banner-trans right-overlay"> {translations && translations.map((trans, idx) => { const langIdx = idx + 1; // default lang idx is 0 if (featureLang !== langIdx) { return ( <div key={trans.code} onClick={() => this.setState({ featureLang: langIdx })} className="trans-button" > {trans.code} </div> ); } else { return ( <div key="ENG" onClick={() => this.setState({ featureLang: 0 })} className="trans-button" > ENG </div> ); } })} </div> <Player className="source-video" poster={source.poster} playsInline src={source.file} /> </div> ); } renderHeaderVideos() { const { headerVideos } = this.props.cover; return ( <div className="row"> {headerVideos.slice(0, 2).map((media, index) => ( <div key={index} className="cell plain" onClick={() => this.setState({ video: index })} > {media.buttonTitle} </div> ))} </div> ); } renderButton(button, yellow) { return ( <div className="row"> <a className={`cell ${yellow ? "yellow" : "plain"}`} href={button.href}> {button.title} </a> </div> ); } renderMediaOverlay() { const video = this.getVideo( this.state.video, this.props.cover.headerVideos ? this.props.cover.headerVideos.length : 0 ); return ( <MediaOverlay opaque source={{ title: video.title, desc: video.desc, paths: [video.file], poster: video.poster, }} translations={video.translations} onCancel={() => this.setState({ video: MEDIA_HIDDEN })} /> ); } render() { if (!this.props.cover) { return ( <div className="default-cover-container"> You haven't specified any cover props. Put them in the values that overwrite the store in <code>app.cover</code> </div> ); } const { videos, footerButton } = this.props.cover; const { showing } = this.props; return ( <div className="default-cover-container"> <div className={showing ? "cover-header" : "cover-header minimized"}> <a className="cover-logo-container" href="https://forensic-architecture.org" > {/* <img */} {/* className="cover-logo" */} {/* src={falogo} */} {/* alt="Forensic Architecture logo" */} {/* /> */} </a> <a className="cover-logo-container" href="https://bellingcat.com"> <img className="cover-logo" src={bcatlogo} alt="Bellingcat logo" /> </a> </div> <div className="cover-content"> {this.props.cover.bgVideo ? ( <div className={`fullscreen-bg ${!this.props.showing ? "hidden" : ""}`} > <video loop muted autoPlay preload="auto" className="fullscreen-bg__video" > <source src={this.props.cover.bgVideo} type="video/mp4" /> </video> </div> ) : null} <h2 style={{ margin: 0 }} dangerouslySetInnerHTML={{ __html: marked(this.props.cover.title) }} /> {this.props.cover.subtitle ? ( <h3 style={{ marginTop: 0 }}>{this.props.cover.subtitle}</h3> ) : null} {this.props.cover.subsubtitle ? ( <h5>{this.props.cover.subsubtitle}</h5> ) : null} {this.props.cover.featureVideo ? this.renderFeature() : null} <div className="hero thin"> {this.props.cover.headerVideos ? this.renderHeaderVideos() : null} {this.props.cover.headerButton ? this.renderButton(this.props.cover.headerButton) : null} <div className="row"> <div className="cell yellow" onClick={this.props.showAppHandler}> {this.props.cover.exploreButton} </div> </div> </div> {Array.isArray(this.props.cover.description) ? ( this.props.cover.description.map((e, index) => ( <div key={index} className="md-container" dangerouslySetInnerHTML={{ __html: marked(e) }} /> )) ) : ( <div className="md-container" dangerouslySetInnerHTML={{ __html: marked(this.props.cover.description), }} /> )} {videos ? ( <div className="hero"> <div className="row"> {/* NOTE: only take first four videos, drop any others for style reasons */} {videos && videos.slice(0, 2).map((media, index) => ( <div key={index} className="cell small" onClick={this.onVideoClickHandler(index)} > {media.buttonTitle} <br /> {media.buttonSubtitle} </div> ))} </div> <div className="row"> {videos.length > 2 && this.props.cover.videos.slice(2, 4).map((media, index) => ( <div key={index} className="cell small" onClick={this.onVideoClickHandler(index + 2)} > {media.buttonTitle} <br /> {media.buttonSubtitle} </div> ))} </div> </div> ) : null} {footerButton ? ( <div className="hero"> <div className="row">{this.renderButton(footerButton)}</div> </div> ) : null} </div> {this.state.video !== MEDIA_HIDDEN ? this.renderMediaOverlay() : null} </div> ); } }
JavaScript
class SslConfiguration { /** * Create a SslConfiguration. * @member {string} [status] SSL status. Allowed values are Enabled and * Disabled. Possible values include: 'Enabled', 'Disabled'. Default value: * 'Enabled' . * @member {string} [cert] The SSL cert data in PEM format encoded as base64 * string * @member {string} [key] The SSL key data in PEM format encoded as base64 * string. This is not returned in response of GET/PUT on the resource. To * see this please call listKeys API. * @member {string} [cname] The CName of the certificate. */ constructor() { } /** * Defines the metadata of SslConfiguration * * @returns {object} metadata of SslConfiguration * */ mapper() { return { required: false, serializedName: 'SslConfiguration', type: { name: 'Composite', className: 'SslConfiguration', modelProperties: { status: { required: false, serializedName: 'status', defaultValue: 'Enabled', type: { name: 'String' } }, cert: { required: false, serializedName: 'cert', type: { name: 'String' } }, key: { required: false, serializedName: 'key', type: { name: 'String' } }, cname: { required: false, serializedName: 'cname', type: { name: 'String' } } } } }; } }
JavaScript
class Store { constructor(opt = {}) { let scope = new Store.Scope({ store: this, opt, }); Object.defineProperty(this, 'scope', { enumerable: true, configurable: false, writable: false, value: scope, }); dpsp(scope, this, 'getState'); dpsp(scope, this, 'setState'); dpsp(scope, this, 'replaceState'); this._mount(); } _dispatch(payload, obj) { return this.scope.dispatch(payload, obj); } _save(obj, payload) { return this.scope.save(obj, payload); } /** * Called in the constructor to mount the decorators. * After construction, this method is undefined. */ _mount() { // hooks let h = []; for (let k in this._mount) { let m = this._mount[k]; if (m.type === 'action') { this.scope.mountAction(m.name, m.fn); continue; } if (m.type === 'hook') { h.push(m); } } // mount the hooks after all actions are mounted for (let i = 0, ln = h.length; i < ln; i++) { this[h[i].actionName].hooks.push(this[h[i].key]); } // disable this method // NOTE: delete instance property has not effect, // because it use the parent this._mount = undefined; } }
JavaScript
class Plugins { constructor(aurelia) { this.aurelia = aurelia; this.info = []; this.processed = false; } /** * Configures a plugin before Aurelia starts. * * @method plugin * @param {moduleId} moduleId The ID of the module to configure. * @param {config} config The configuration for the specified module. * @return {Plugins} Returns the current Plugins instance. */ plugin(moduleId, config) { var plugin = { moduleId: moduleId, config: config || {} }; if (this.processed) { loadPlugin(this.aurelia, this.aurelia.loader, plugin); } else { this.info.push(plugin); } return this; } _process() { var aurelia = this.aurelia, loader = aurelia.loader, info = this.info, current; if (this.processed) { return; } var next = () => { if (current = info.shift()) { return loadPlugin(aurelia, loader, current).then(next); } this.processed = true; return Promise.resolve(); }; return next(); } }
JavaScript
class Portfolio { constructor(config, api) { _.bindAll(this); this.config = config; this.api = api; this.balances = {}; this.fee = null; } getBalance(fund) { return this.getFund(fund).amount; } // return the [fund] based on the data we have in memory getFund(fund) { return _.find(this.balances, function(f) { return f.name === fund}); } // convert into the portfolio expected by the performanceAnalyzer convertBalances(asset,currency) { // rename? var asset = _.find(this.balances, a => a.name === this.config.asset).amount; var currency = _.find(this.balances, a => a.name === this.config.currency).amount; return { currency, asset, balance: currency + (asset * this.ticker.bid) } } setBalances(callback) { let set = (err, fullPortfolio) => { if(err) { console.log(err); throw new errors.ExchangeError(err); } // only include the currency/asset of this market if (this.config.currency && this.config.asset) { this.balances = [ this.config.currency, this.config.asset ] .map(name => { let item = _.find(fullPortfolio, {name}); if(!item) { // assume we have 0 item = { name, amount: 0 }; } return item; }); } else { console.log(fullPortfolio); this.balances = fullPortfolio; } if(_.isFunction(callback)) callback(); } this.api.getPortfolio(set); } setFee(callback) { this.api.getFee((err, fee) => { if(err) throw new errors.ExchangeError(err); this.fee = fee; if(_.isFunction(callback)) callback(); }); } setTicker(ticker) { this.ticker = ticker; } }
JavaScript
class LocalStorageConfig { constructor(defaults, whitelist){ this.whitelist = whitelist || [] defaults = defaults || {} this.basePath = defaults.basePath || 'dataparty-api' this.defaults = defaults || {} this.defaults.logicalSeparator = '.' } start () { return Promise.resolve(this) } clear () { localStorage.setItem(this.basePath, JSON.stringify({})) } readAll(){ try{ return Object.assign( {}, this.defaults, JSON.parse( localStorage.getItem(this.basePath) || '{}' ) ) } catch(err){ return {} } } read(key){ logger('reading path: ' + key) return reach( this.readAll(), key) } async write(key, value){ let data = this.readAll() deepSet(data, key, value) localStorage.setItem(this.basePath, JSON.stringify(data)) return } exists(key){ return (read(key) !== undefined) } async save(){ return } }
JavaScript
class Account { constructor(accountId, sequence) { if (StrKey.isValidMed25519PublicKey(accountId)) { throw new Error('accountId is an M-address; use MuxedAccount instead'); } if (!StrKey.isValidEd25519PublicKey(accountId)) { throw new Error('accountId is invalid'); } if (!isString(sequence)) { throw new Error('sequence must be of type string'); } this._accountId = accountId; this.sequence = new BigNumber(sequence); } /** * Returns Stellar account ID, ex. * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. * @returns {string} */ accountId() { return this._accountId; } /** * @returns {string} sequence number for the account as a string */ sequenceNumber() { return this.sequence.toString(); } /** * Increments sequence number in this object by one. * @returns {void} */ incrementSequenceNumber() { this.sequence = this.sequence.add(1); } /** * Creates a muxed "sub"account with this base address and an ID set. * * @param {string} id - the ID of the new muxed account * @return {MuxedAccount} a new instance w/ the specified parameters * * @see MuxedAccount */ createSubaccount(id) { return new MuxedAccount(this, id); } }
JavaScript
class MuxedAccount { constructor(baseAccount, id) { const accountId = baseAccount.accountId(); if (!StrKey.isValidEd25519PublicKey(accountId)) { throw new Error('accountId is invalid'); } this.account = baseAccount; this._muxedXdr = encodeMuxedAccount(accountId, id); this._mAddress = encodeMuxedAccountToAddress(this._muxedXdr, true); this._id = id; } /** * Parses an M-address into a MuxedAccount object. * * @param {string} mAddress - an M-address to transform * @param {string} sequenceNum - the sequence number of the underlying {@link * Account}, to use for the underlying base account (@link * MuxedAccount.baseAccount). If you're using the SDK, you can use * `server.loadAccount` to fetch this if you don't know it. * * @return {MuxedAccount} */ static fromAddress(mAddress, sequenceNum) { const muxedAccount = decodeAddressToMuxedAccount(mAddress, true); const gAddress = encodeMuxedAccountToAddress(muxedAccount, false); const id = muxedAccount .med25519() .id() .toString(); return new MuxedAccount(new Account(gAddress, sequenceNum), id); } /** * @return {Account} the underlying account object shared among all muxed * accounts with this Stellar address */ baseAccount() { return this.account; } /** * @return {string} the M-address representing this account's (G-address, ID) */ accountId() { return this._mAddress; } id() { return this._id; } setId(id) { if (!isString(id)) { throw new Error('id should be a string representing a number (uint64)'); } this._muxedXdr.med25519().id(xdr.Uint64.fromString(id)); this._mAddress = encodeMuxedAccountToAddress(this._muxedXdr, true); this._id = id; return this; } /** * Accesses the underlying account's sequence number. * @return {string} strigified sequence number for the underlying account */ sequenceNumber() { return this.account.sequenceNumber(); } /** * Increments the underlying account's sequence number by one. * @return {void} */ incrementSequenceNumber() { return this.account.incrementSequenceNumber(); } /** * Creates another muxed "sub"account from the base with a new ID set * * @param {string} id - the ID of the new muxed account * @return {MuxedAccount} a new instance w/ the specified parameters */ createSubaccount(id) { return new MuxedAccount(this.account, id); } /** * @return {xdr.MuxedAccount} the XDR object representing this muxed account's * G-address and uint64 ID */ toXDRObject() { return this._muxedXdr; } equals(otherMuxedAccount) { return this.accountId() === otherMuxedAccount.accountId(); } }
JavaScript
class HeroDesignerTemplate { getTemplate(template) { let baseTemplate = null; let subTemplate = null; if (typeof template === 'string') { baseTemplate = template.endsWith('6E.hdt') ? mainSixth : main; switch (template) { case 'builtIn.AI.hdt': subTemplate = ai; break; case 'builtIn.AI6E.hdt': subTemplate = aiSixth; break; case 'builtIn.Automaton.hdt': subTemplate = automaton; break; case 'builtIn.Automaton6E.hdt': subTemplate = automatonSixth; break; case 'builtIn.Computer.hdt': subTemplate = computer; break; case 'builtIn.Computer6E.hdt': subTemplate = computerSixth; break; case 'builtIn.Heroic.hdt': subTemplate = heroic; break; case 'builtIn.Heroic6E.hdt': subTemplate = heroicSixth; break; case 'builtIn.Normal.hdt': subTemplate = normal; break; case 'builtIn.Superheroic.hdt': subTemplate = superheroic; break; case 'builtIn.Superheroic6E.hdt': subTemplate = superheroicSixth; break; default: common.toast(`${template} is not recognized`); } } else { baseTemplate = template.extends.endsWith('6E.hdt') ? mainSixth : main; subTemplate = template; } return subTemplate === null ? baseTemplate : this._finalizeTemplate(baseTemplate, subTemplate); } _finalizeTemplate(baseTemplate, subTemplate) { let finalTemplate = JSON.parse(JSON.stringify(baseTemplate)); finalTemplate = this._finalizeCharacteristics(finalTemplate, subTemplate); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'skills', 'skill'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'skillEnhancers', 'enhancer'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'martialArts', 'maneuver'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'perks', 'perk'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'talents', 'talent'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'powers', 'power'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'modifiers', 'modifier'); finalTemplate = this._finalizeItems(finalTemplate, subTemplate, 'disadvantages', 'disad'); return finalTemplate; } _finalizeCharacteristics(finalTemplate, subTemplate) { if (subTemplate.characteristics !== null) { if (subTemplate.characteristics.remove) { if (Array.isArray(subTemplate.characteristics.remove)) { for (let characteristic of subTemplate.characteristics.remove) { delete finalTemplate.characteristics[characteristic]; } } else { delete finalTemplate.characteristics[subTemplate.characteristics.remove]; } } if (subTemplate.characteristics) { for (let [key, characteristic] of Object.entries(subTemplate.characteristics)) { finalTemplate.characteristics[key] = characteristic; } } } return finalTemplate; } _finalizeItems(finalTemplate, subTemplate, key, subKey) { if (subTemplate[key] !== null) { if (subTemplate[key].remove) { let filtered = []; if (Array.isArray(subTemplate[key].remove)) { filtered = finalTemplate[key][subKey].filter((item, index) => { return !subTemplate[key].remove.includes(item.xmlid.toUpperCase()); }); } else { filtered = finalTemplate[key][subKey].filter((item, index) => { return subTemplate[key].remove !== item.xmlid.toUpperCase(); }); } finalTemplate[key][subKey] = filtered; } if (subTemplate[key][subKey]) { if (Array.isArray(subTemplate[key][subKey])) { for (let item of subTemplate[key][subKey]) { if (Array.isArray(finalTemplate[key][subKey])) { finalTemplate[key][subKey].push(item); } else { let list = [finalTemplate[key][subKey]]; list.push(item); finalTemplate[key][subKey] = list; } } } else { if (Array.isArray(finalTemplate[key][subKey])) { finalTemplate[key][subKey].push(subTemplate[key][subKey]); } else { let list = [finalTemplate[key][subKey]]; list.push(subTemplate[key][subKey]); finalTemplate[key][subKey] = list; } } } } return finalTemplate; } }
JavaScript
class OverrideKindSymbol { constructor(sym, kindOverride) { this.sym = sym; this.kind = kindOverride; } get name() { return this.sym.name; } get language() { return this.sym.language; } get type() { return this.sym.type; } get container() { return this.sym.container; } get public() { return this.sym.public; } get callable() { return this.sym.callable; } get nullable() { return this.sym.nullable; } get definition() { return this.sym.definition; } members() { return this.sym.members(); } signatures() { return this.sym.signatures(); } selectSignature(types) { return this.sym.selectSignature(types); } indexed(argument) { return this.sym.indexed(argument); } }
JavaScript
class ReflectorModuleModuleResolutionHost { constructor(host, getProgram) { this.host = host; this.getProgram = getProgram; // Note: verboseInvalidExpressions is important so that // the collector will collect errors instead of throwing this.metadataCollector = new MetadataCollector({ verboseInvalidExpression: true }); if (host.directoryExists) this.directoryExists = directoryName => this.host.directoryExists(directoryName); } fileExists(fileName) { return !!this.host.getScriptSnapshot(fileName); } readFile(fileName) { let snapshot = this.host.getScriptSnapshot(fileName); if (snapshot) { return snapshot.getText(0, snapshot.getLength()); } // Typescript readFile() declaration should be `readFile(fileName: string): string | undefined return undefined; } getSourceFileMetadata(fileName) { const sf = this.getProgram().getSourceFile(fileName); return sf ? this.metadataCollector.getMetadata(sf) : undefined; } cacheMetadata(fileName) { // Don't cache the metadata for .ts files as they might change in the editor! return fileName.endsWith('.d.ts'); } }
JavaScript
class DummyHtmlParser extends HtmlParser { parse(source, url, parseExpansionForms = false, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) { return new ParseTreeResult([], []); } }
JavaScript
class TypeScriptServiceHost { constructor(host, tsService) { this.host = host; this.tsService = tsService; this._staticSymbolCache = new StaticSymbolCache(); this._typeCache = []; this.modulesOutOfDate = true; this.fileVersions = new Map(); } setSite(service) { this.service = service; } /** * Angular LanguageServiceHost implementation */ get resolver() { this.validate(); let result = this._resolver; if (!result) { const moduleResolver = new NgModuleResolver(this.reflector); const directiveResolver = new DirectiveResolver(this.reflector); const pipeResolver = new PipeResolver(this.reflector); const elementSchemaRegistry = new DomElementSchemaRegistry(); const resourceLoader = new DummyResourceLoader(); const urlResolver = createOfflineCompileUrlResolver(); const htmlParser = new DummyHtmlParser(); // This tracks the CompileConfig in codegen.ts. Currently these options // are hard-coded. const config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false }); const directiveNormalizer = new DirectiveNormalizer(resourceLoader, urlResolver, htmlParser, config); result = this._resolver = new CompileMetadataResolver(config, htmlParser, moduleResolver, directiveResolver, pipeResolver, new JitSummaryResolver(), elementSchemaRegistry, directiveNormalizer, new ɵConsole(), this._staticSymbolCache, this.reflector, (error, type) => this.collectError(error, type && type.filePath)); } return result; } getTemplateReferences() { this.ensureTemplateMap(); return this.templateReferences || []; } getTemplateAt(fileName, position) { let sourceFile = this.getSourceFile(fileName); if (sourceFile) { this.context = sourceFile.fileName; let node = this.findNode(sourceFile, position); if (node) { return this.getSourceFromNode(fileName, this.host.getScriptVersion(sourceFile.fileName), node); } } else { this.ensureTemplateMap(); // TODO: Cannocalize the file? const componentType = this.fileToComponent.get(fileName); if (componentType) { return this.getSourceFromType(fileName, this.host.getScriptVersion(fileName), componentType); } } return undefined; } getAnalyzedModules() { this.updateAnalyzedModules(); return this.ensureAnalyzedModules(); } ensureAnalyzedModules() { let analyzedModules = this.analyzedModules; if (!analyzedModules) { if (this.host.getScriptFileNames().length === 0) { analyzedModules = { files: [], ngModuleByPipeOrDirective: new Map(), ngModules: [], }; } else { const analyzeHost = { isSourceFile(filePath) { return true; } }; const programFiles = this.program.getSourceFiles().map(sf => sf.fileName); analyzedModules = analyzeNgModules(programFiles, analyzeHost, this.staticSymbolResolver, this.resolver); } this.analyzedModules = analyzedModules; } return analyzedModules; } getTemplates(fileName) { this.ensureTemplateMap(); const componentType = this.fileToComponent.get(fileName); if (componentType) { const templateSource = this.getTemplateAt(fileName, 0); if (templateSource) { return [templateSource]; } } else { let version$$1 = this.host.getScriptVersion(fileName); let result = []; // Find each template string in the file let visit = (child) => { let templateSource = this.getSourceFromNode(fileName, version$$1, child); if (templateSource) { result.push(templateSource); } else { forEachChild(child, visit); } }; let sourceFile = this.getSourceFile(fileName); if (sourceFile) { this.context = sourceFile.path || sourceFile.fileName; forEachChild(sourceFile, visit); } return result.length ? result : undefined; } } getDeclarations(fileName) { const result = []; const sourceFile = this.getSourceFile(fileName); if (sourceFile) { let visit = (child) => { let declaration = this.getDeclarationFromNode(sourceFile, child); if (declaration) { result.push(declaration); } else { forEachChild(child, visit); } }; forEachChild(sourceFile, visit); } return result; } getSourceFile(fileName) { return this.tsService.getProgram().getSourceFile(fileName); } updateAnalyzedModules() { this.validate(); if (this.modulesOutOfDate) { this.analyzedModules = null; this._reflector = null; this.templateReferences = null; this.fileToComponent = null; this.ensureAnalyzedModules(); this.modulesOutOfDate = false; } } get program() { return this.tsService.getProgram(); } get checker() { let checker = this._checker; if (!checker) { checker = this._checker = this.program.getTypeChecker(); } return checker; } validate() { const program = this.program; if (this.lastProgram !== program) { // Invalidate file that have changed in the static symbol resolver const invalidateFile = (fileName) => this._staticSymbolResolver.invalidateFile(fileName); this.clearCaches(); const seen = new Set(); for (let sourceFile of this.program.getSourceFiles()) { const fileName = sourceFile.fileName; seen.add(fileName); const version$$1 = this.host.getScriptVersion(fileName); const lastVersion = this.fileVersions.get(fileName); if (version$$1 != lastVersion) { this.fileVersions.set(fileName, version$$1); if (this._staticSymbolResolver) { invalidateFile(fileName); } } } // Remove file versions that are no longer in the file and invalidate them. const missing = Array.from(this.fileVersions.keys()).filter(f => !seen.has(f)); missing.forEach(f => this.fileVersions.delete(f)); if (this._staticSymbolResolver) { missing.forEach(invalidateFile); } this.lastProgram = program; } } clearCaches() { this._checker = null; this._typeCache = []; this._resolver = null; this.collectedErrors = null; this.modulesOutOfDate = true; } ensureTemplateMap() { if (!this.fileToComponent || !this.templateReferences) { const fileToComponent = new Map(); const templateReference = []; const ngModuleSummary = this.getAnalyzedModules(); const urlResolver = createOfflineCompileUrlResolver(); for (const module of ngModuleSummary.ngModules) { for (const directive of module.declaredDirectives) { const { metadata } = this.resolver.getNonNormalizedDirectiveMetadata(directive.reference); if (metadata.isComponent && metadata.template && metadata.template.templateUrl) { const templateName = urlResolver.resolve(this.reflector.componentModuleUrl(directive.reference), metadata.template.templateUrl); fileToComponent.set(templateName, directive.reference); templateReference.push(templateName); } } } this.fileToComponent = fileToComponent; this.templateReferences = templateReference; } } getSourceFromDeclaration(fileName, version$$1, source, span, type, declaration, node, sourceFile) { let queryCache = undefined; const t = this; if (declaration) { return { version: version$$1, source, span, type, get members() { return getClassMembersFromDeclaration(t.program, t.checker, sourceFile, declaration); }, get query() { if (!queryCache) { const pipes = t.service.getPipesAt(fileName, node.getStart()); queryCache = getSymbolQuery(t.program, t.checker, sourceFile, () => getPipesTable(sourceFile, t.program, t.checker, pipes)); } return queryCache; } }; } } getSourceFromNode(fileName, version$$1, node) { let result = undefined; const t = this; switch (node.kind) { case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.StringLiteral: let [declaration, decorator] = this.getTemplateClassDeclFromNode(node); if (declaration && declaration.name) { const sourceFile = this.getSourceFile(fileName); return this.getSourceFromDeclaration(fileName, version$$1, this.stringOf(node) || '', shrink(spanOf$1(node)), this.reflector.getStaticSymbol(sourceFile.fileName, declaration.name.text), declaration, node, sourceFile); } break; } return result; } getSourceFromType(fileName, version$$1, type) { let result = undefined; const declaration = this.getTemplateClassFromStaticSymbol(type); if (declaration) { const snapshot = this.host.getScriptSnapshot(fileName); if (snapshot) { const source = snapshot.getText(0, snapshot.getLength()); result = this.getSourceFromDeclaration(fileName, version$$1, source, { start: 0, end: source.length }, type, declaration, declaration, declaration.getSourceFile()); } } return result; } get reflectorHost() { let result = this._reflectorHost; if (!result) { if (!this.context) { // Make up a context by finding the first script and using that as the base dir. const scriptFileNames = this.host.getScriptFileNames(); if (0 === scriptFileNames.length) { throw new Error('Internal error: no script file names found'); } this.context = scriptFileNames[0]; } // Use the file context's directory as the base directory. // The host's getCurrentDirectory() is not reliable as it is always "" in // tsserver. We don't need the exact base directory, just one that contains // a source file. const source = this.tsService.getProgram().getSourceFile(this.context); if (!source) { throw new Error('Internal error: no context could be determined'); } const tsConfigPath = findTsConfig(source.fileName); const basePath = dirname(tsConfigPath || this.context); const options = { basePath, genDir: basePath }; const compilerOptions = this.host.getCompilationSettings(); if (compilerOptions && compilerOptions.baseUrl) { options.baseUrl = compilerOptions.baseUrl; } if (compilerOptions && compilerOptions.paths) { options.paths = compilerOptions.paths; } result = this._reflectorHost = new ReflectorHost(() => this.tsService.getProgram(), this.host, options); } return result; } collectError(error, filePath) { if (filePath) { let errorMap = this.collectedErrors; if (!errorMap || !this.collectedErrors) { errorMap = this.collectedErrors = new Map(); } let errors = errorMap.get(filePath); if (!errors) { errors = []; this.collectedErrors.set(filePath, errors); } errors.push(error); } } get staticSymbolResolver() { let result = this._staticSymbolResolver; if (!result) { this._summaryResolver = new AotSummaryResolver({ loadSummary(filePath) { return null; }, isSourceFile(sourceFilePath) { return true; }, toSummaryFileName(sourceFilePath) { return sourceFilePath; }, fromSummaryFileName(filePath) { return filePath; }, }, this._staticSymbolCache); result = this._staticSymbolResolver = new StaticSymbolResolver(this.reflectorHost, this._staticSymbolCache, this._summaryResolver, (e, filePath) => this.collectError(e, filePath)); } return result; } get reflector() { let result = this._reflector; if (!result) { const ssr = this.staticSymbolResolver; result = this._reflector = new StaticReflector(this._summaryResolver, ssr, [], [], (e, filePath) => this.collectError(e, filePath)); } return result; } getTemplateClassFromStaticSymbol(type) { const source = this.getSourceFile(type.filePath); if (source) { const declarationNode = forEachChild(source, child => { if (child.kind === SyntaxKind.ClassDeclaration) { const classDeclaration = child; if (classDeclaration.name != null && classDeclaration.name.text === type.name) { return classDeclaration; } } }); return declarationNode; } return undefined; } /** * Given a template string node, see if it is an Angular template string, and if so return the * containing class. */ getTemplateClassDeclFromNode(currentToken) { // Verify we are in a 'template' property assignment, in an object literal, which is an call // arg, in a decorator let parentNode = currentToken.parent; // PropertyAssignment if (!parentNode) { return TypeScriptServiceHost.missingTemplate; } if (parentNode.kind !== SyntaxKind.PropertyAssignment) { return TypeScriptServiceHost.missingTemplate; } else { // TODO: Is this different for a literal, i.e. a quoted property name like "template"? if (parentNode.name.text !== 'template') { return TypeScriptServiceHost.missingTemplate; } } parentNode = parentNode.parent; // ObjectLiteralExpression if (!parentNode || parentNode.kind !== SyntaxKind.ObjectLiteralExpression) { return TypeScriptServiceHost.missingTemplate; } parentNode = parentNode.parent; // CallExpression if (!parentNode || parentNode.kind !== SyntaxKind.CallExpression) { return TypeScriptServiceHost.missingTemplate; } const callTarget = parentNode.expression; let decorator = parentNode.parent; // Decorator if (!decorator || decorator.kind !== SyntaxKind.Decorator) { return TypeScriptServiceHost.missingTemplate; } let declaration = decorator.parent; // ClassDeclaration if (!declaration || declaration.kind !== SyntaxKind.ClassDeclaration) { return TypeScriptServiceHost.missingTemplate; } return [declaration, callTarget]; } getCollectedErrors(defaultSpan, sourceFile) { const errors = (this.collectedErrors && this.collectedErrors.get(sourceFile.fileName)); return (errors && errors.map((e) => { const line = e.line || (e.position && e.position.line); const column = e.column || (e.position && e.position.column); const span = spanAt(sourceFile, line, column) || defaultSpan; if (isFormattedError(e)) { return errorToDiagnosticWithChain(e, span); } return { message: e.message, span }; })) || []; } getDeclarationFromNode(sourceFile, node) { if (node.kind == SyntaxKind.ClassDeclaration && node.decorators && node.name) { for (const decorator of node.decorators) { if (decorator.expression && decorator.expression.kind == SyntaxKind.CallExpression) { const classDeclaration = node; if (classDeclaration.name) { const call = decorator.expression; const target = call.expression; const type = this.checker.getTypeAtLocation(target); if (type) { const staticSymbol = this.reflector.getStaticSymbol(sourceFile.fileName, classDeclaration.name.text); try { if (this.resolver.isDirective(staticSymbol)) { const { metadata } = this.resolver.getNonNormalizedDirectiveMetadata(staticSymbol); const declarationSpan = spanOf$1(target); return { type: staticSymbol, declarationSpan, metadata, errors: this.getCollectedErrors(declarationSpan, sourceFile) }; } } catch (e) { if (e.message) { this.collectError(e, sourceFile.fileName); const declarationSpan = spanOf$1(target); return { type: staticSymbol, declarationSpan, errors: this.getCollectedErrors(declarationSpan, sourceFile) }; } } } } } } } } stringOf(node) { switch (node.kind) { case SyntaxKind.NoSubstitutionTemplateLiteral: return node.text; case SyntaxKind.StringLiteral: return node.text; } } findNode(sourceFile, position) { function find(node) { if (position >= node.getStart() && position < node.getEnd()) { return forEachChild(node, find) || node; } } return find(sourceFile); } }
JavaScript
class DiagnosticIdResponse { /** * Create a DiagnosticIdResponse. * @property {string} [diagnosticId] diagnostic id */ constructor() { } /** * Defines the metadata of DiagnosticIdResponse * * @returns {object} metadata of DiagnosticIdResponse * */ mapper() { return { required: false, serializedName: 'DiagnosticIdResponse', type: { name: 'Composite', className: 'DiagnosticIdResponse', modelProperties: { diagnosticId: { required: false, serializedName: 'diagnostic_id', type: { name: 'String' } } } } }; } }
JavaScript
class CustomCode { /** * Get Tool toolbox settings * icon - Tool icon's SVG * title - title to show in toolbox * * @return {{icon: string, title: string}} */ static get toolbox() { return { icon: `<svg width="14" height="14" viewBox="0 -1 14 14" xmlns="http://www.w3.org/2000/svg" > <path d="M3.177 6.852c.205.253.347.572.427.954.078.372.117.844.117 1.417 0 .418.01.725.03.92.02.18.057.314.107.396.046.075.093.117.14.134.075.027.218.056.42.083a.855.855 0 0 1 .56.297c.145.167.215.38.215.636 0 .612-.432.934-1.216.934-.457 0-.87-.087-1.233-.262a1.995 1.995 0 0 1-.853-.751 2.09 2.09 0 0 1-.305-1.097c-.014-.648-.029-1.168-.043-1.56-.013-.383-.034-.631-.06-.733-.064-.263-.158-.455-.276-.578a2.163 2.163 0 0 0-.505-.376c-.238-.134-.41-.256-.519-.371C.058 6.76 0 6.567 0 6.315c0-.37.166-.657.493-.846.329-.186.56-.342.693-.466a.942.942 0 0 0 .26-.447c.056-.2.088-.42.097-.658.01-.25.024-.85.043-1.802.015-.629.239-1.14.672-1.522C2.691.19 3.268 0 3.977 0c.783 0 1.216.317 1.216.921 0 .264-.069.48-.211.643a.858.858 0 0 1-.563.29c-.249.03-.417.076-.498.126-.062.04-.112.134-.139.291-.031.187-.052.562-.061 1.119a8.828 8.828 0 0 1-.112 1.378 2.24 2.24 0 0 1-.404.963c-.159.212-.373.406-.64.583.25.163.454.342.612.538zm7.34 0c.157-.196.362-.375.612-.538a2.544 2.544 0 0 1-.641-.583 2.24 2.24 0 0 1-.404-.963 8.828 8.828 0 0 1-.112-1.378c-.009-.557-.03-.932-.061-1.119-.027-.157-.077-.251-.14-.29-.08-.051-.248-.096-.496-.127a.858.858 0 0 1-.564-.29C8.57 1.401 8.5 1.185 8.5.921 8.5.317 8.933 0 9.716 0c.71 0 1.286.19 1.72.574.432.382.656.893.671 1.522.02.952.033 1.553.043 1.802.009.238.041.458.097.658a.942.942 0 0 0 .26.447c.133.124.364.28.693.466a.926.926 0 0 1 .493.846c0 .252-.058.446-.183.58-.109.115-.281.237-.52.371-.21.118-.377.244-.504.376-.118.123-.212.315-.277.578-.025.102-.045.35-.06.733-.013.392-.027.912-.042 1.56a2.09 2.09 0 0 1-.305 1.097c-.2.323-.486.574-.853.75a2.811 2.811 0 0 1-1.233.263c-.784 0-1.216-.322-1.216-.934 0-.256.07-.47.214-.636a.855.855 0 0 1 .562-.297c.201-.027.344-.056.418-.083.048-.017.096-.06.14-.134a.996.996 0 0 0 .107-.396c.02-.195.031-.502.031-.92 0-.573.039-1.045.117-1.417.08-.382.222-.701.427-.954z" /> </svg>`, title: "Code" }; } /** * Empty Quote is not empty Block * @public * @returns {boolean} */ static get contentless() { return true; } /** * Allow to press Enter inside the Quote * @public * @returns {boolean} */ static get enableLineBreaks() { return true; } /** * Default placeholder for quote caption * * @public * @returns {string} */ // static get DEFAULT_CAPTION_PLACEHOLDER() { // return "Enter a caption"; // } /** * Tool`s styles * * @returns {{baseClass: string, wrapper: string, quote: string, input: string, caption: string, settingsButton: string, settingsButtonActive: string}} */ get CSS() { return { baseClass: this.api.styles.block, input: this.api.styles.input, wrapper: "ce-code", textarea: "ce-code__textarea" }; } static get sanitize() { return { input: { br: true } }; } /** * Tool`s settings properties * * @returns {*[]} */ /** * Render plugin`s main Element and fill it with saved data * * @param {{data: QuoteData, config: QuoteConfig, api: object}} * data — previously saved data * config - user config for Tool * api - Editor.js API */ constructor({ data, config, api }) { // const { ALIGNMENTS, DEFAULT_ALIGNMENT } = Quote; this.select = null; this.api = api; this.language = config.languageArray; // this.quotePlaceholder = // this.captionPlaceholder = this.data = { code: data.code || "", language: data.language || "" }; } /** * Create Quote Tool container with inputs * * @returns {Element} */ render() { const container = this._make("div", [this.CSS.baseClass, this.CSS.wrapper]); const code = this._make("textarea", [this.CSS.textarea, this.CSS.input], { textContent: this.data.code }); const select = this._makeSelect(this.language); container.appendChild(code); container.appendChild(select); this.select = new SlimSelect({ select: select, showContent: "down", // 'auto', 'up' or 'down' showSearch: false }); this.select.set(this.data.language) return container; } onPaste(event) { const content = event.detail.data; this.data = { code: content.textContent }; } /** * Extract Quote data from Quote Tool element * * @param {HTMLDivElement} quoteElement - element to save * @returns {QuoteData} */ save(quoteElement) { const code = quoteElement.querySelector(`.${this.CSS.textarea}`); return { code: code.value, language: this.select.selected() ? this.select.selected().toLowerCase() : "" }; } /** * Helper for making Elements with attributes * * @param {string} tagName - new Element tag name * @param {array|string} classNames - list or name of CSS classname(s) * @param {Object} attributes - any attributes * @return {Element} */ _makeSelect(array) { // let el = document.createElement("div"); // el.classList.add("custom-select"); let select = document.createElement("select"); for (let i = 0; i < array.length; i++) { let option = document.createElement("option"); //add style in future option.value = array[i].value; option.text = array[i].title; select.appendChild(option); } return select; // el.appendChild(select); } _make(tagName, classNames = null, attributes = {}) { let el = document.createElement(tagName); if (Array.isArray(classNames)) { el.classList.add(...classNames); } else if (classNames) { el.classList.add(classNames); } for (let attrName in attributes) { el[attrName] = attributes[attrName]; } return el; } }
JavaScript
class PersonPersonDisplayPanel extends (BasePanel) { /** * flow is ready lifecycle method */ _FBPReady() { super._FBPReady(); //this._FBPTraceWires(); } /** * Inject hts for the PersonService agent. * * Use this, if you do not work with a panel coordinator. */ htsIn(hts){ this._FBPTriggerWire("--htsIn",hts); } static get styles() { // language=CSS return Theme.getThemeForComponent('PanelBaseTheme') || css` :host { display: block; height: 100%; background-color: var(--surface-light); color: var(--on-surface); padding-top: var(--spacing); box-sizing: border-box; overflow: hidden; } :host([hidden]) { display: none; } furo-form { margin-bottom: var(--spacing); } ` } /** * @private * @returns {TemplateResult} */ render() { // language=HTML return html` <furo-vertical-flex> <furo-form flex scroll> <person-person-display flex ƒ-bind-data="--entity(*.data)"></person-person-display> </furo-form> </furo-vertical-flex> <furo-entity-agent service="PersonService" @-response="--response" ƒ-hts-in="--navNode(*._value.link), --htsIn" ƒ-bind-request-data="--entity(*.data)" load-on-hts-in></furo-entity-agent> <furo-data-object type="person.PersonEntity" @-object-ready="--entity" ƒ-reset="--resetReq" ƒ-inject-raw="--response"></furo-data-object> `; } }
JavaScript
class RawData { //********************************************************************************** /** * Constructor for "Repeated" class * @param {Object} [parameters={}] * @property {string} [name] * @property {boolean} [optional] */ constructor(parameters = {}) { this.data = (0, _pvutils.getParametersValue)(parameters, "data", new ArrayBuffer(0)); } //********************************************************************************** /** * Base function for converting block from BER encoded array of bytes * @param {!ArrayBuffer} inputBuffer ASN.1 BER encoded array * @param {!number} inputOffset Offset in ASN.1 BER encoded array where decoding should be started * @param {!number} inputLength Maximum length of array of bytes which can be using in this function * @returns {number} Offset after least decoded byte */ fromBER(inputBuffer, inputOffset, inputLength) { this.data = inputBuffer.slice(inputOffset, inputLength); return inputOffset + inputLength; } //********************************************************************************** /** * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) * @param {boolean} [sizeOnly=false] Flag that we need only a size of encoding, not a real array of bytes * @returns {ArrayBuffer} */ toBER(sizeOnly = false) { return this.data; } //********************************************************************************** }
JavaScript
class AttributeMutationEvent extends StyleAwareMixin(MutationEvent) { /** * * @param {String} attributeName The name of the attribute being modified * @param {Element|Node} [node] The HTML element that is being modified (required for capture) * @param {Summary} [summary] The mutation summary */ constructor(attributeName, node = null, summary = null) { super(node, summary); this.event.attributeName = attributeName; } /** * {@inheritDoc} * @see MutationEvent.capture */ capture() { return super.capture().then(() => { let value = this.getAttributeValue(); if (value instanceof Object) { value = Object.keys(value).reduce((obj, key) => { if (!isNaN(value[key])) { obj[key] = value[key]; } return obj; }, {}); } this.metadata.attributeValue = value; }); } /** * {@inheritDoc} * @see MutationEvent.playback */ playback() { return super.playback().then(() => { this.setAttributeValue(); }); } /** * Get the attribute value * @returns {*} */ getAttributeValue() { let el = this.el; if (this.isDocument) { el = this.window.document; } if (this.isWindow || !el) { return null; } switch (this.event.attributeName) { case 'style' : return el.style; case 'class' : return el.className; default : return el.getAttribute(this.event.attributeName); } } /** * Set the attribute value (for playback) * @returns {void} */ setAttributeValue() { let el = this.el; if (this.isDocument) { el = this.window.document; } if (this.isWindow || !el) { return; } switch (this.event.attributeName) { case 'style' : this.applyStyles(this.metadata.attributeValue, el); break; case 'class' : el.className = this.metadata.attributeValue; break; default : el.setAttribute(this.event.attributeName, this.metadata.attributeValue); } } }
JavaScript
class RebuildTasksControl extends Component { state = { confirming: false, removeUnmatchedTasks: false, localFilename: null, localFile: null, } initiateConfirmation = () => this.setState({ confirming: true }) toggleRemoveUnmatchedTasks = () => { this.setState({ removeUnmatchedTasks: !this.state.removeUnmatchedTasks }) } resetState = () => { this.setState({ confirming: false, removeUnmatchedTasks: false, localFilename: null, localFile: null, }) } proceed = () => { const removeUnmatched = this.state.removeUnmatchedTasks const updatedFile = this.state.localFile ? this.state.localFile.file : null this.resetState() const deleteStepIfRequested = removeUnmatched ? this.props.deleteIncompleteTasks(this.props.challenge) : Promise.resolve() deleteStepIfRequested.then(() => { this.props.rebuildChallenge(this.props.challenge, updatedFile, this.state.dataOriginDate) }) } render() { if (!this.props.challenge) { return null } const challenge = AsManageableChallenge(this.props.challenge) let fileUploadArea = null if (challenge.dataSource() === 'local') { const uploadContext = {} fileUploadArea = DropzoneTextUpload({ id: 'geojson', required: true, readonly: false, formContext: uploadContext, onChange: filename => { this.setState({ localFilename: filename, localFile: uploadContext.geojson, }) }, }) } let originDateField = null // Only offer an option to change the source origin date if it's a local file // we are uploading. if (challenge.dataSource() === 'local') { originDateField = <div className="form-group field field-string mr-mt-2"> <label className="control-label"> <FormattedMessage {...messages.dataOriginDateLabel} /> </label> <input className="form-control" type="date" label={this.props.intl.formatMessage(messages.dataOriginDateLabel)} onChange={e => this.setState({dataOriginDate: e.target.value})} value={this.state.dataOriginDate || challenge.dataOriginDate} /> </div> } return ( <div className="rebuild-tasks-control"> {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} <a onClick={this.initiateConfirmation} className="mr-text-green-lighter hover:mr-text-white mr-mr-4" > <FormattedMessage {...messages.label} /> </a> {this.state.confirming && ( <Modal className="rebuild-tasks-control__modal" onClose={this.resetState} isActive={this.state.confirming} > <article className="message"> <div className="message-header"> <FormattedMessage {...messages.modalTitle} /> </div> <div className="message-body"> <div className="rebuild-tasks-control__explanation"> <p className="rebuild-tasks-control__explanation__intro"> <FormattedMessage {...messages[challenge.dataSource()]} /> </p> <div className="rebuild-tasks-control__explanation__steps"> <MarkdownContent markdown={this.props.intl.formatMessage( messages.explanation )} /> </div> <p className="rebuild-tasks-control__warning"> <FormattedMessage {...messages.warning} /> </p> <div className="rebuild-tasks-control__moreInfo"> <MarkdownContent markdown={this.props.intl.formatMessage( messages.moreInfo )} /> </div> </div> <div className="rebuild-tasks-control__options"> <div className="rebuild-tasks-control__remove-unmatched-option"> <input type="checkbox" className="mr-mr-1" checked={this.state.removeUnmatchedTasks} onChange={this.toggleRemoveUnmatchedTasks} /> <label className="mr-text-blue-light"> <FormattedMessage {...messages.removeUnmatchedLabel} /> </label> </div> {fileUploadArea && ( <div className="rebuild-tasks-control__upload-geojson"> <form className="rjsf">{fileUploadArea}</form> </div> )} {originDateField} </div> <div className="rebuild-tasks-control__modal-controls"> <button className="button is-secondary is-outlined rebuild-tasks-control__cancel-control" onClick={this.resetState} > <FormattedMessage {...messages.cancel} /> </button> <button className="button is-danger is-outlined rebuild-tasks-control__proceed-control" onClick={this.proceed} > <FormattedMessage {...messages.proceed} /> </button> </div> </div> </article> </Modal> )} </div> ) } }
JavaScript
class TimeInput extends Component { static displayName = 'TimeInput'; static propTypes = { /** Should time be shown as "--:--" when disabled */ dashesWhenDisabled: PropTypes.bool, dataHook: PropTypes.string, /** The control's starting time */ defaultValue: PropTypes.object, /** 24h mode */ disableAmPm: PropTypes.bool, /** Is disabled */ disabled: PropTypes.bool, /** Called upon blur */ onChange: PropTypes.func, /** Display in RTL */ rtl: PropTypes.bool, style: PropTypes.object, /** The input width behavior, as 'auto' it will shrink, at '100%' it will grow */ width: PropTypes.oneOf(['auto', '100%']), /** Number of minutes to be changed on arrow click */ minutesStep: PropTypes.number, /** Custom suffix, located before ticker */ customSuffix: PropTypes.node, /** Error flag */ status: PropTypes.oneOf(['error', 'warning', 'loading']), /** When set to true, this input won't display status suffix */ hideStatusSuffix: PropTypes.bool, /** The status message to display when hovering the status icon, if not given or empty there will be no tooltip */ statusMessage: PropTypes.node, /** Display seconds */ showSeconds: PropTypes.bool, }; static defaultProps = { defaultValue: moment(), onChange: () => {}, style: {}, disableAmPm: false, disabled: false, dashesWhenDisabled: false, minutesStep: 20, width: 'auto', showSeconds: false, }; constructor(props) { super(props); this.state = { focus: false, lastCaretIdx: 0, hover: false, ...this._getInitTime( this.props.defaultValue, this.props.showSeconds, this.props.disableAmPm, ), }; } UNSAFE_componentWillReceiveProps(nextProps) { if (this._shouldUpdateState(nextProps)) { this.setState( this._getInitTime( nextProps.defaultValue, nextProps.showSeconds, nextProps.disableAmPm, ), ); } } _shouldUpdateState(nextProps) { return ( nextProps.defaultValue !== this.props.defaultValue || nextProps.showSeconds !== this.props.showSeconds || nextProps.disableAmPm !== this.props.disableAmPm ); } _isAmPmMode(disableAmPm) { return ( !disableAmPm && moment('2016-04-03 13:14:00').format('LT').indexOf('PM') !== -1 ); } _getInitTime(value, showSeconds, disableAmPm) { let time = value || moment(), am = time.hours() < 12; const ampmMode = this._isAmPmMode(disableAmPm); ({ time, am } = this._normalizeTime(am, time, ampmMode)); const text = this._formatTime(time, ampmMode, showSeconds); return { time, am, text, ampmMode }; } _momentizeState(timeSet) { let time, am; const { ampmMode } = this.state; if (timeSet) { ({ time, am } = timeSet); } else { ({ time, am } = this.state); } let hours = time.hours(); if (ampmMode && !am && hours < 12) { hours += 12; } if (ampmMode && am && hours === 12) { hours = 0; } const momentized = moment(); momentized.hours(hours); momentized.minutes(time.minutes()); momentized.seconds(0); return momentized; } _bubbleOnChange(timeSet) { const time = this._momentizeState(timeSet); this.props.onChange(time); } _timeStep(direction) { const time = this._momentizeState(); const timeUnit = this.state.lastFocusedTimeUnit || 'minutes'; const amount = timeUnit === 'hours' ? 1 : this.props.minutesStep; time.add(direction * amount, timeUnit); const am = time.hours() < 12; this._updateDate({ am, time }); } _formatTime( time, ampmMode = this.state.ampmMode, showSeconds = this.props.showSeconds, ) { const withSeconds = showSeconds ? ':ss' : ''; return ampmMode ? time.format(`hh:mm${withSeconds}`) : time.format(`HH:mm${withSeconds}`); } _getFocusedTimeUnit(caretIdx, currentValue) { let colonIdx = currentValue.indexOf(':'); colonIdx = Math.max(0, colonIdx); return caretIdx <= colonIdx ? 'hours' : 'minutes'; } _normalizeTime(am, time, ampmMode = this.state.ampmMode) { const hours = time.hours(); if (ampmMode) { if (hours === 0) { return { time: time.clone().hours(12), am: true }; } if (hours > 12) { return { time: time.clone().hours(hours - 12), am: false }; } } return { time: time.clone().hours(hours), am }; } _updateDate({ time, am }) { am = isUndefined(am) ? this.state.am : am; let newTime = moment(time, 'HH:mm'); newTime = newTime.isValid() ? newTime : this.state.time; const normalizedTime = this._normalizeTime(am, newTime); ({ time, am } = normalizedTime); const text = this._formatTime(time); this.setState({ time, am, text }); this._bubbleOnChange({ time, am }); } _handleAmPmClick = () => !this.props.disabled && this._updateDate({ am: !this.state.am }); _handleFocus = input => this.setState({ focus: true, lastFocus: input }); _handleBlur = () => { this.setState({ focus: false }); this._updateDate({ time: this.state.text }); }; _handleInputChange = e => { // that is why cursor is jumping // https://github.com/facebook/react/issues/955#issuecomment-327069204 const isDisabled = this.props.disabled && this.props.dashesWhenDisabled; const isInvalid = /[^0-9 :]/.test(e.target.value); if (isDisabled || isInvalid) { e.preventDefault(); return; } return this.setState({ text: e.target.value, }); }; _handleHover = hover => this.setState({ hover }); _handleMinus = () => this._timeStep(-1); _handlePlus = () => this._timeStep(1); _handleInputBlur = ({ target }) => { if (this.props.disabled && this.props.dashesWhenDisabled) { return; } const caretIdx = target.selectionEnd || 0; let lastFocusedTimeUnit; if (caretIdx >= 0) { lastFocusedTimeUnit = this._getFocusedTimeUnit(caretIdx, target.value); } this.setState({ lastCaretIdx: caretIdx, lastFocusedTimeUnit }); this._updateDate({ time: target.value }); }; _renderTimeTextbox() { const { customSuffix, disabled, dashesWhenDisabled, width, rtl, status, hideStatusSuffix, statusMessage, } = this.props; const text = disabled && dashesWhenDisabled ? '-- : --' : this.state.text; const suffix = ( <Input.Group> <FontUpgradeContext.Consumer> {({ active: isMadefor }) => ( <Box alignItems="center" justifyContent="space-between"> <Box verticalAlign="middle" flexGrow={0} marginRight="6px"> {this.state.ampmMode && ( <Text weight={isMadefor ? 'thin' : 'normal'} skin={disabled ? 'disabled' : 'standard'} className={classes.ampm} onClick={this._handleAmPmClick} dataHook={dataHooks.amPmIndicator} > {this.state.am ? 'am' : 'pm'} </Text> )} </Box> <Box align="right" verticalAlign="middle" className={classes.suffixEndWrapper} > {customSuffix && ( <Box marginRight="6px" width="max-content"> {typeof customSuffix === 'string' ? ( <Text weight={isMadefor ? 'thin' : 'normal'} light secondary dataHook={dataHooks.customSuffix} > {customSuffix} </Text> ) : ( <span data-hook={dataHooks.customSuffix}> {customSuffix} </span> )} </Box> )} <Input.Ticker upDisabled={disabled} downDisabled={disabled} onUp={this._handlePlus} onDown={this._handleMinus} dataHook={dataHooks.ticker} /> </Box> </Box> )} </FontUpgradeContext.Consumer> </Input.Group> ); return ( <Input ref="input" rtl={rtl} value={text} className={width === 'auto' ? classes.input : undefined} onFocus={this._handleFocus} onChange={this._handleInputChange} onBlur={this._handleInputBlur} dataHook={dataHooks.input} disabled={disabled} suffix={suffix} status={status} hideStatusSuffix={hideStatusSuffix} statusMessage={statusMessage} /> ); } render() { const { className, style, dataHook, rtl, disabled, width, showSeconds, } = this.props; const { focus, hover } = this.state; return ( <div className={st(classes.root, { disabled, rtl, showSeconds }, className)} style={style} data-hook={dataHook} > <div onMouseOver={() => this._handleHover(true)} onMouseOut={() => this._handleHover(false)} className={st( classes.time, { focus, hover: hover && !focus, stretch: width === '100%', }, className, )} > {this._renderTimeTextbox()} </div> </div> ); } }
JavaScript
class CloudServicesCoreMock extends CloudServicesCore { createToken( tokenUrlOrRefreshToken ) { return new TokenMock( tokenUrlOrRefreshToken ); } }
JavaScript
class BufferHelper { static isBuffered(media,position) { if (media) { let buffered = media.buffered; for (let i = 0; i < buffered.length; i++) { if (position >= buffered.start(i) && position <= buffered.end(i)) { return true; } } } return false; } static bufferInfo(media, pos,maxHoleDuration) { if (media) { var vbuffered = media.buffered, buffered = [],i; for (i = 0; i < vbuffered.length; i++) { buffered.push({start: vbuffered.start(i), end: vbuffered.end(i)}); } return this.bufferedInfo(buffered,pos,maxHoleDuration); } else { return {len: 0, start: 0, end: 0, nextStart : undefined} ; } } static bufferedInfo(buffered,pos,maxHoleDuration) { var buffered2 = [], // bufferStart and bufferEnd are buffer boundaries around current video position bufferLen,bufferStart, bufferEnd,bufferStartNext,i; // sort on buffer.start/smaller end (IE does not always return sorted buffered range) buffered.sort(function (a, b) { var diff = a.start - b.start; if (diff) { return diff; } else { return b.end - a.end; } }); // there might be some small holes between buffer time range // consider that holes smaller than maxHoleDuration are irrelevant and build another // buffer time range representations that discards those holes for (i = 0; i < buffered.length; i++) { var buf2len = buffered2.length; if(buf2len) { var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) if((buffered[i].start - buf2end) < maxHoleDuration) { // merge overlapping time ranges // update lastRange.end only if smaller than item.end // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) if(buffered[i].end > buf2end) { buffered2[buf2len - 1].end = buffered[i].end; } } else { // big hole buffered2.push(buffered[i]); } } else { // first value buffered2.push(buffered[i]); } } for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) { var start = buffered2[i].start, end = buffered2[i].end; //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); if ((pos + maxHoleDuration) >= start && pos < end) { // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length bufferStart = start; bufferEnd = end; bufferLen = bufferEnd - pos; } else if ((pos + maxHoleDuration) < start) { bufferStartNext = start; break; } } return {len: bufferLen, start: bufferStart, end: bufferEnd, nextStart : bufferStartNext}; } }
JavaScript
class ListSeparatorView extends View { /** * @inheritDoc */ constructor( locale ) { super( locale ); this.setTemplate( { tag: 'li', attributes: { class: [ 'ck', 'ck-list__separator' ] } } ); } }
JavaScript
class Guild { constructor(client, data) { /** * The client that created the instance of the guild * @name Guild#client * @type {Client} * @readonly */ Object.defineProperty(this, 'client', { value: client }); /** * A collection of members that are in this guild. The key is the member's ID, the value is the member * @type {Collection<Snowflake, GuildMember>} */ this.members = new Collection(); /** * A collection of channels that are in this guild. The key is the channel's ID, the value is the channel * @type {Collection<Snowflake, GuildChannel>} */ this.channels = new Collection(); /** * A collection of roles that are in this guild. The key is the role's ID, the value is the role * @type {Collection<Snowflake, Role>} */ this.roles = new Collection(); /** * A collection of presences in this guild * @type {Collection<Snowflake, Presence>} */ this.presences = new Collection(); /** * Whether the bot has been removed from the guild * @type {boolean} */ this.deleted = false; if (!data) return; if (data.unavailable) { /** * Whether the guild is available to access. If it is not available, it indicates a server outage * @type {boolean} */ this.available = false; /** * The Unique ID of the guild, useful for comparisons * @type {Snowflake} */ this.id = data.id; } else { this.setup(data); if (!data.channels) this.available = false; } } /* eslint-disable complexity */ /** * Sets up the guild. * @param {*} data The raw data of the guild * @private */ setup(data) { /** * The name of the guild * @type {string} */ this.name = data.name; /** * The hash of the guild icon * @type {?string} */ this.icon = data.icon; /** * The hash of the guild splash image (VIP only) * @type {?string} */ this.splash = data.splash; /** * The region the guild is located in * @type {string} */ this.region = data.region; /** * The full amount of members in this guild * @type {number} */ this.memberCount = data.member_count || this.memberCount; /** * Whether the guild is "large" (has more than 250 members) * @type {boolean} */ this.large = Boolean('large' in data ? data.large : this.large); /** * An array of guild features * @type {Object[]} */ this.features = data.features; /** * The ID of the application that created this guild (if applicable) * @type {?Snowflake} */ this.applicationID = data.application_id; /** * The time in seconds before a user is counted as "away from keyboard" * @type {?number} */ this.afkTimeout = data.afk_timeout; /** * The ID of the voice channel where AFK members are moved * @type {?string} */ this.afkChannelID = data.afk_channel_id; /** * The ID of the system channel * @type {?Snowflake} */ this.systemChannelID = data.system_channel_id; /** * Whether embedded images are enabled on this guild * @type {boolean} */ this.embedEnabled = data.embed_enabled; /** * The verification level of the guild * @type {number} */ this.verificationLevel = data.verification_level; /** * The explicit content filter level of the guild * @type {number} */ this.explicitContentFilter = data.explicit_content_filter; /** * The required MFA level for the guild * @type {number} */ this.mfaLevel = data.mfa_level; /** * The timestamp the client user joined the guild at * @type {number} */ this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp; /** * The value set for a guild's default message notifications * @type {DefaultMessageNotifications|number} */ this.defaultMessageNotifications = Constants.DefaultMessageNotifications[data.default_message_notifications] || data.default_message_notifications; /** * The type of premium tier: * * 0: NONE * * 1: TIER_1 * * 2: TIER_2 * * 3: TIER_3 * @typedef {number} PremiumTier */ /** * The premium tier on this guild * @type {PremiumTier} */ this.premiumTier = data.premium_tier; /** * The total number of users currently boosting this server * @type {?number} * @name Guild#premiumSubscriptionCount */ if (typeof data.premium_subscription_count !== 'undefined') { this.premiumSubscriptionCount = data.premium_subscription_count; } /** * The hash of the guild banner * @type {?string} */ this.banner = data.banner; /** * The description of the guild, if any * @type {?string} */ this.description = data.description; /** * The embed channel ID, if enabled * @type {?string} * @name Guild#embedChannelID */ if (typeof data.embed_channel_id !== 'undefined') this.embedChannelID = data.embed_channel_id; /** * The maximum amount of members the guild can have * <info>You will need to fetch the guild using {@link Guild#fetch} if you want to receive this parameter</info> * @type {?number} * @name Guild#maximumMembers */ if (typeof data.max_members !== 'undefined') this.maximumMembers = data.max_members || 250000; /** * The maximum amount of presences the guild can have * <info>You will need to fetch the guild using {@link Guild#fetch} if you want to receive this parameter</info> * @type {?number} * @name Guild#maximumPresences */ if (typeof data.max_presences !== 'undefined') this.maximumPresences = data.max_presences || 5000; /** * Whether widget images are enabled on this guild * @type {?boolean} * @name Guild#widgetEnabled */ if (typeof data.widget_enabled !== 'undefined') this.widgetEnabled = data.widget_enabled; /** * The widget channel ID, if enabled * @type {?string} * @name Guild#widgetChannelID */ if (typeof data.widget_channel_id !== 'undefined') this.widgetChannelID = data.widget_channel_id; /** * The vanity URL code of the guild, if any * @type {?string} */ this.vanityURLCode = data.vanity_url_code; this.id = data.id; this.available = !data.unavailable; this.features = data.features || this.features || []; if (data.members) { this.members.clear(); for (const guildUser of data.members) this._addMember(guildUser, false); } if (data.owner_id) { /** * The user ID of this guild's owner * @type {Snowflake} */ this.ownerID = data.owner_id; } if (data.channels) { this.channels.clear(); for (const channel of data.channels) this.client.dataManager.newChannel(channel, this); } if (data.roles) { this.roles.clear(); for (const role of data.roles) { const newRole = new Role(this, role); this.roles.set(newRole.id, newRole); } } if (data.presences) { for (const presence of data.presences) { this._setPresence(presence.user.id, presence); } } this._rawVoiceStates = new Collection(); if (data.voice_states) { for (const voiceState of data.voice_states) { this._rawVoiceStates.set(voiceState.user_id, voiceState); const member = this.members.get(voiceState.user_id); const voiceChannel = this.channels.get(voiceState.channel_id); if (member && voiceChannel) { member.serverMute = voiceState.mute; member.serverDeaf = voiceState.deaf; member.selfMute = voiceState.self_mute; member.selfDeaf = voiceState.self_deaf; member.selfStream = voiceState.self_stream || false; member.voiceSessionID = voiceState.session_id; member.voiceChannelID = voiceState.channel_id; voiceChannel.members.set(member.user.id, member); } } } if (!this.emojis) { /** * A collection of emojis that are in this guild * The key is the emoji's ID, the value is the emoji * @type {Collection<Snowflake, Emoji>} */ this.emojis = new Collection(); for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji)); } else { this.client.actions.GuildEmojisUpdate.handle({ guild_id: this.id, emojis: data.emojis, }); } } /** * The timestamp the guild was created at * @type {number} * @readonly */ get createdTimestamp() { return Snowflake.deconstruct(this.id).timestamp; } /** * The time the guild was created * @type {Date} * @readonly */ get createdAt() { return new Date(this.createdTimestamp); } /** * Embed channel for this guild * @type {?TextChannel} * @readonly */ get embedChannel() { return this.channels.get(this.embedChannelID) || null; } /** * Widget channel for this guild * @type {?TextChannel} * @readonly */ get widgetChannel() { return this.channels.get(this.widgetChannelID) || null; } /** * The time the client user joined the guild * @type {Date} * @readonly */ get joinedAt() { return new Date(this.joinedTimestamp); } /** * If this guild is verified * @type {boolean} * @readonly */ get verified() { return this.features.includes('VERIFIED'); } /** * The URL to this guild's icon * @type {?string} * @readonly */ get iconURL() { if (!this.icon) return null; return Constants.Endpoints.Guild(this).Icon(this.client.options.http.cdn, this.icon); } /** * The URL to this guild's banner. * @type {?string} * @readonly */ get bannerURL() { if (!this.banner) return null; return Constants.Endpoints.Guild(this).Banner(this.client.options.http.cdn, this.banner); } /** * The acronym that shows up in place of a guild icon. * @type {string} * @readonly */ get nameAcronym() { return this.name.replace(/\w+/g, name => name[0]).replace(/\s/g, ''); } /** * The URL to this guild's splash * @type {?string} * @readonly */ get splashURL() { if (!this.splash) return null; return Constants.Endpoints.Guild(this).Splash(this.client.options.http.cdn, this.splash); } /** * The owner of the guild * @type {?GuildMember} * @readonly */ get owner() { return this.members.get(this.ownerID); } /** * AFK voice channel for this guild * @type {?VoiceChannel} * @readonly */ get afkChannel() { return this.client.channels.get(this.afkChannelID) || null; } /** * System channel for this guild * @type {?GuildChannel} * @readonly */ get systemChannel() { return this.client.channels.get(this.systemChannelID) || null; } /** * If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection * @type {?VoiceConnection} * @readonly */ get voiceConnection() { if (this.client.browser) return null; return this.client.voice.connections.get(this.id) || null; } /** * The position of this guild * <warn>This is only available when using a user account.</warn> * @type {?number} * @readonly * @deprecated */ get position() { if (this.client.user.bot) return null; if (!this.client.user.settings.guildPositions) return null; return this.client.user.settings.guildPositions.indexOf(this.id); } /** * Whether the guild is muted * <warn>This is only available when using a user account.</warn> * @type {?boolean} * @readonly * @deprecated */ get muted() { if (this.client.user.bot) return null; try { return this.client.user.guildSettings.get(this.id).muted; } catch (err) { return false; } } /** * The type of message that should notify you * <warn>This is only available when using a user account.</warn> * @type {?MessageNotificationType} * @readonly * @deprecated */ get messageNotifications() { if (this.client.user.bot) return null; try { return this.client.user.guildSettings.get(this.id).messageNotifications; } catch (err) { return null; } } /** * Whether to receive mobile push notifications * <warn>This is only available when using a user account.</warn> * @type {?boolean} * @readonly * @deprecated */ get mobilePush() { if (this.client.user.bot) return null; try { return this.client.user.guildSettings.get(this.id).mobilePush; } catch (err) { return false; } } /** * Whether to suppress everyone messages * <warn>This is only available when using a user account.</warn> * @type {?boolean} * @readonly * @deprecated */ get suppressEveryone() { if (this.client.user.bot) return null; try { return this.client.user.guildSettings.get(this.id).suppressEveryone; } catch (err) { return null; } } /** * The `@everyone` role of the guild * @type {Role} * @readonly */ get defaultRole() { return this.roles.get(this.id); } /** * The client user as a GuildMember of this guild * @type {?GuildMember} * @readonly */ get me() { return this.members.get(this.client.user.id); } /** * Fetches a collection of roles in the current guild sorted by position * @type {Collection<Snowflake, Role>} * @readonly * @private */ get _sortedRoles() { return this._sortPositionWithID(this.roles); } /** * Returns the GuildMember form of a User object, if the user is present in the guild. * @param {UserResolvable} user The user that you want to obtain the GuildMember of * @returns {?GuildMember} * @example * // Get the guild member of a user * const member = guild.member(message.author); */ member(user) { return this.client.resolver.resolveGuildMember(this, user); } /** * Fetches this guild. * @returns {Promise<Guild>} */ fetch() { return this.client.rest.methods.getGuild(this).then(data => { this.setup(data); return this; }); } /** * An object containing information about a guild member's ban. * @typedef {Object} BanInfo * @property {User} user User that was banned * @property {?string} reason Reason the user was banned */ /** * Fetch a ban for a user. * @returns {Promise<BanInfo>} * @param {UserResolvable} user The user to fetch the ban for * @example * // Get ban * guild.fetchBan(message.author) * .then(({ user, reason }) => console.log(`${user.tag} was banned for the reason: ${reason}.`)) * .catch(console.error); */ fetchBan(user) { return this.client.rest.methods.getGuildBan(this, user); } /** * Fetch a collection of banned users in this guild. * @returns {Promise<Collection<Snowflake, User|BanInfo>>} * @param {boolean} [withReasons=false] Whether or not to include the ban reason(s) * @example * // Fetch bans in guild * guild.fetchBans() * .then(bans => console.log(`This guild has ${bans.size} bans`)) * .catch(console.error); */ fetchBans(withReasons = false) { if (withReasons) return this.client.rest.methods.getGuildBans(this); return this.client.rest.methods.getGuildBans(this) .then(bans => { const users = new Collection(); for (const ban of bans.values()) users.set(ban.user.id, ban.user); return users; }); } /** * Fetches a collection of integrations to this guild. * Resolves with a collection mapping integrations by their ids. * @returns {Promise<Collection<string, Integration>>} * @example * // Fetch integrations * guild.fetchIntegrations() * .then(integrations => console.log(`Fetched ${integrations.size} integrations`)) * .catch(console.error); */ fetchIntegrations() { return this.client.rest.methods.getIntegrations(this).then(data => data.reduce((collection, integration) => collection.set(integration.id, new Integration(this.client, integration, this)), new Collection()) ); } /** * The data for creating an integration. * @typedef {Object} IntegrationData * @property {string} id The integration id * @property {string} type The integration type */ /** * Creates an integration by attaching an integration object * @param {IntegrationData} data The data for thes integration * @param {string} reason Reason for creating the integration * @returns {Promise<Guild>} */ createIntegration(data, reason) { return this.client.rest.methods.createIntegration(this, data, reason) .then(() => this); } /** * Fetch a collection of invites to this guild. * Resolves with a collection mapping invites by their codes. * @returns {Promise<Collection<string, Invite>>} * @example * // Fetch invites * guild.fetchInvites() * .then(invites => console.log(`Fetched ${invites.size} invites`)) * .catch(console.error); * @example * // Fetch invite creator by their id * guild.fetchInvites() * .then(invites => console.log(invites.find(invite => invite.inviter.id === '84484653687267328'))) * .catch(console.error); */ fetchInvites() { return this.client.rest.methods.getGuildInvites(this); } /** * Fetches the vanity url invite code to this guild. * Resolves with a string matching the vanity url invite code, not the full url. * @returns {Promise<string>} * @example * // Fetch invites * guild.fetchVanityCode() * .then(code => { * console.log(`Vanity URL: https://discord.gg/${code}`); * }) * .catch(console.error); */ fetchVanityCode() { if (!this.features.includes('VANITY_URL')) { return Promise.reject(new Error('This guild does not have the VANITY_URL feature enabled.')); } return this.client.rest.methods.getGuildVanityCode(this); } /** * Fetch all webhooks for the guild. * @returns {Promise<Collection<Snowflake, Webhook>>} * @example * // Fetch webhooks * guild.fetchWebhooks() * .then(webhooks => console.log(`Fetched ${webhooks.size} webhooks`)) * .catch(console.error); */ fetchWebhooks() { return this.client.rest.methods.getGuildWebhooks(this); } /** * Fetch available voice regions. * @returns {Promise<Collection<string, VoiceRegion>>} * @example * // Fetch voice regions * guild.fetchVoiceRegions() * .then(console.log) * .catch(console.error); */ fetchVoiceRegions() { return this.client.rest.methods.fetchVoiceRegions(this.id); } /** * The Guild Embed object * @typedef {Object} GuildEmbedData * @property {boolean} enabled Whether the embed is enabled * @property {?ChannelResolvable} channel The embed channel */ /** * Fetches the guild embed. * @returns {Promise<GuildEmbedData>} * @example * // Fetches the guild embed * guild.fetchEmbed() * .then(embed => console.log(`The embed is ${embed.enabled ? 'enabled' : 'disabled'}`)) * .catch(console.error); */ fetchEmbed() { return this.client.rest.methods.fetchEmbed(this.id); } /** * Fetch audit logs for this guild. * @param {Object} [options={}] Options for fetching audit logs * @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry * @param {Snowflake|GuildAuditLogsEntry} [options.after] Limit to entries from after specified entry * @param {number} [options.limit] Limit number of entries * @param {UserResolvable} [options.user] Only show entries involving this user * @param {AuditLogAction} [options.type] Only show entries involving this action type * @returns {Promise<GuildAuditLogs>} * @example * // Output audit log entries * guild.fetchAuditLogs() * .then(audit => console.log(audit.entries.first())) * .catch(console.error); */ fetchAuditLogs(options) { return this.client.rest.methods.getGuildAuditLogs(this, options); } /** * Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission. * @param {UserResolvable} user User to add to the guild * @param {Object} options Options for the addition * @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the * bot's application * @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`) * @param {Collection<Snowflake, Role>|Role[]|Snowflake[]} [options.roles] Roles to add to the member * (requires `MANAGE_ROLES`) * @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`) * @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`) * @returns {Promise<GuildMember>} */ addMember(user, options) { user = this.client.resolver.resolveUserID(user); if (this.members.has(user)) return Promise.resolve(this.members.get(user)); return this.client.rest.methods.putGuildMember(this, user, options); } /** * Fetch a single guild member from a user. * @param {UserResolvable} user The user to fetch the member for * @param {boolean} [cache=true] Insert the member into the members cache * @returns {Promise<GuildMember>} * @example * // Fetch a guild member * guild.fetchMember(message.author) * .then(console.log) * .catch(console.error); */ fetchMember(user, cache = true) { const userID = this.client.resolver.resolveUserID(user); if (!userID) return Promise.reject(new Error('Invalid id provided.')); const member = this.members.get(userID); if (member && member.joinedTimestamp) return Promise.resolve(member); return this.client.rest.methods.getGuildMember(this, userID, cache); } /** * Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members, * this should not be necessary. * @param {string} [query=''] Limit fetch to members with similar usernames * @param {number} [limit=0] Maximum number of members to request * @returns {Promise<Guild>} * @example * // Fetch guild members * guild.fetchMembers() * .then(console.log) * .catch(console.error); * @example * // Fetches a maximum of 1 member with the given query * guild.fetchMembers('hydrabolt', 1) * .then(console.log) * .catch(console.error); */ fetchMembers(query = '', limit = 0) { return new Promise((resolve, reject) => { if (this.memberCount === this.members.size) { resolve(this); return; } this.client.ws.send({ op: Constants.OPCodes.REQUEST_GUILD_MEMBERS, d: { guild_id: this.id, query, limit, }, }); const handler = (members, guild) => { if (guild.id !== this.id) return; if (this.memberCount === this.members.size || members.length < 1000) { this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler); resolve(this); } }; this.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler); this.client.setTimeout(() => reject(new Error('Members didn\'t arrive in time.')), 120 * 1000); }); } /** * Performs a search within the entire guild. * <warn>This is only available when using a user account.</warn> * @param {MessageSearchOptions} [options={}] Options to pass to the search * @returns {Promise<MessageSearchResult>} * @deprecated * @example * guild.search({ * content: 'discord.js', * before: '2016-11-17' * }) * .then(res => { * const hit = res.messages[0].find(m => m.hit).content; * console.log(`I found: **${hit}**, total results: ${res.totalResults}`); * }) * .catch(console.error); */ search(options = {}) { return this.client.rest.methods.search(this, options); } /** * The data for editing a guild. * @typedef {Object} GuildEditData * @property {string} [name] The name of the guild * @property {string} [region] The region of the guild * @property {number} [verificationLevel] The verification level of the guild * @property {number} [explicitContentFilter] The level of the explicit content filter * @property {ChannelResolvable} [afkChannel] The AFK channel of the guild * @property {ChannelResolvable} [systemChannel] The system channel of the guild * @property {number} [afkTimeout] The AFK timeout of the guild * @property {Base64Resolvable} [icon] The icon of the guild * @property {Base64Resolvable} [banner] The banner of the guild * @property {GuildMemberResolvable} [owner] The owner of the guild * @property {Base64Resolvable} [splash] The splash screen of the guild */ /** * Updates the guild with new information - e.g. a new name. * @param {GuildEditData} data The data to update the guild with * @param {string} [reason] Reason for editing the guild * @returns {Promise<Guild>} * @example * // Set the guild name and region * guild.edit({ * name: 'Discord Guild', * region: 'london', * }) * .then(g => console.log(`Changed guild name to ${g} and region to ${g.region}`)) * .catch(console.error); */ edit(data, reason) { const _data = {}; if (data.name) _data.name = data.name; if (data.region) _data.region = data.region; if (typeof data.verificationLevel !== 'undefined') _data.verification_level = Number(data.verificationLevel); if (typeof data.afkChannel !== 'undefined') { _data.afk_channel_id = this.client.resolver.resolveChannelID(data.afkChannel); } if (typeof data.systemChannel !== 'undefined') { _data.system_channel_id = this.client.resolver.resolveChannelID(data.systemChannel); } if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout); if (typeof data.icon !== 'undefined') _data.icon = data.icon; if (data.owner) _data.owner_id = this.client.resolver.resolveUser(data.owner).id; if (typeof data.splash !== 'undefined') _data.splash = data.splash; if (typeof data.banner !== 'undefined') _data.banner = data.banner; if (typeof data.explicitContentFilter !== 'undefined') { _data.explicit_content_filter = Number(data.explicitContentFilter); } if (typeof data.defaultMessageNotifications !== 'undefined') { _data.default_message_notifications = typeof data.defaultMessageNotifications === 'string' ? Constants.DefaultMessageNotifications.indexOf(data.defaultMessageNotifications) : Number(data.defaultMessageNotifications); } return this.client.rest.methods.updateGuild(this, _data, reason); } /** * Sets a new guild banner. * @param {BufferResolvable|Base64Resolvable} banner The new banner of the guild * @param {string} [reason] Reason for changing the guild's banner * @returns {Guild} */ setBanner(banner, reason) { return this.client.resolver.resolveImage(banner).then(data => this.edit({ banner: data }, reason)); } /** * Edit the level of the explicit content filter. * @param {number} explicitContentFilter The new level of the explicit content filter * @param {string} [reason] Reason for changing the level of the guild's explicit content filter * @returns {Promise<Guild>} */ setExplicitContentFilter(explicitContentFilter, reason) { return this.edit({ explicitContentFilter }, reason); } /** * Edits the setting of the default message notifications of the guild. * @param {DefaultMessageNotifications|number} defaultMessageNotifications * The new setting for the default message notifications * @param {string} [reason] Reason for changing the setting of the default message notifications * @returns {Promise<Guild>} */ setDefaultMessageNotifications(defaultMessageNotifications, reason) { return this.edit({ defaultMessageNotifications }, reason); } /** * Edit the name of the guild. * @param {string} name The new name of the guild * @param {string} [reason] Reason for changing the guild's name * @returns {Promise<Guild>} * @example * // Edit the guild name * guild.setName('Discord Guild') * .then(g => console.log(`Updated guild name to ${g}`)) * .catch(console.error); */ setName(name, reason) { return this.edit({ name }, reason); } /** * Edit the region of the guild. * @param {string} region The new region of the guild * @param {string} [reason] Reason for changing the guild's region * @returns {Promise<Guild>} * @example * // Edit the guild region * guild.setRegion('london') * .then(g => console.log(`Updated guild region to ${g.region}`)) * .catch(console.error); */ setRegion(region, reason) { return this.edit({ region }, reason); } /** * Edit the verification level of the guild. * @param {number} verificationLevel The new verification level of the guild * @param {string} [reason] Reason for changing the guild's verification level * @returns {Promise<Guild>} * @example * // Edit the guild verification level * guild.setVerificationLevel(1) * .then(g => console.log(`Updated guild verification level to ${g.verificationLevel}`)) * .catch(console.error); */ setVerificationLevel(verificationLevel, reason) { return this.edit({ verificationLevel }, reason); } /** * Edit the AFK channel of the guild. * @param {ChannelResolvable} afkChannel The new AFK channel * @param {string} [reason] Reason for changing the guild's AFK channel * @returns {Promise<Guild>} * @example * // Edit the guild AFK channel * guild.setAFKChannel(channel) * .then(g => console.log(`Updated guild AFK channel to ${g.afkChannel.name}`)) * .catch(console.error); */ setAFKChannel(afkChannel, reason) { return this.edit({ afkChannel }, reason); } /** * Edit the system channel of the guild. * @param {ChannelResolvable} systemChannel The new system channel * @param {string} [reason] Reason for changing the guild's system channel * @returns {Promise<Guild>} */ setSystemChannel(systemChannel, reason) { return this.edit({ systemChannel }, reason); } /** * Edit the AFK timeout of the guild. * @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK * @param {string} [reason] Reason for changing the guild's AFK timeout * @returns {Promise<Guild>} * @example * // Edit the guild AFK channel * guild.setAFKTimeout(60) * .then(g => console.log(`Updated guild AFK timeout to ${g.afkTimeout}`)) * .catch(console.error); */ setAFKTimeout(afkTimeout, reason) { return this.edit({ afkTimeout }, reason); } /** * Set a new guild icon. * @param {Base64Resolvable|BufferResolvable} icon The new icon of the guild * @param {string} [reason] Reason for changing the guild's icon * @returns {Promise<Guild>} * @example * // Edit the guild icon * guild.setIcon('./icon.png') * .then(console.log) * .catch(console.error); */ setIcon(icon, reason) { return this.client.resolver.resolveImage(icon).then(data => this.edit({ icon: data, reason })); } /** * Sets a new owner of the guild. * @param {GuildMemberResolvable} owner The new owner of the guild * @param {string} [reason] Reason for setting the new owner * @returns {Promise<Guild>} * @example * // Edit the guild owner * guild.setOwner(guild.members.first()) * .then(g => console.log(`Updated the guild owner to ${g.owner.displayName}`)) * .catch(console.error); */ setOwner(owner, reason) { return this.edit({ owner }, reason); } /** * Set a new guild splash screen. * @param {BufferResolvable|Base64Resolvable} splash The new splash screen of the guild * @param {string} [reason] Reason for changing the guild's splash screen * @returns {Promise<Guild>} * @example * // Edit the guild splash * guild.setSplash('./splash.png') * .then(console.log) * .catch(console.error); */ setSplash(splash) { return this.client.resolver.resolveImage(splash).then(data => this.edit({ splash: data })); } /** * Sets the position of the guild in the guild listing. * <warn>This is only available when using a user account.</warn> * @param {number} position Absolute or relative position * @param {boolean} [relative=false] Whether to position relatively or absolutely * @returns {Promise<Guild>} * @deprecated */ setPosition(position, relative) { if (this.client.user.bot) { return Promise.reject(new Error('Setting guild position is only available for user accounts')); } return this.client.user.settings.setGuildPosition(this, position, relative); } /** * Marks all messages in this guild as read. * <warn>This is only available when using a user account.</warn> * @returns {Promise<Guild>} * @deprecated */ acknowledge() { return this.client.rest.methods.ackGuild(this); } /** * Allow direct messages from guild members. * <warn>This is only available when using a user account.</warn> * @param {boolean} allow Whether to allow direct messages * @returns {Promise<Guild>} * @deprecated */ allowDMs(allow) { const settings = this.client.user.settings; if (allow) return settings.removeRestrictedGuild(this); else return settings.addRestrictedGuild(this); } /** * Bans a user from the guild. * @param {UserResolvable} user The user to ban * @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a * string, the ban reason. Supplying an object allows you to do both. * @param {number} [options.days=0] Number of days of messages to delete * @param {string} [options.reason] Reason for banning * @returns {Promise<GuildMember|User|string>} Result object will be resolved as specifically as possible. * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot * be resolved, the user ID will be the result. * @example * // Ban a user by ID * guild.ban('some user ID') * .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild}`)) * .catch(console.error); * @example * // Ban a user by object with reason and days * guild.ban(user, { days: 7, reason: 'He needed to go' }) * .then(console.log) * .catch(console.error); */ ban(user, options = {}) { if (typeof options === 'number') { options = { reason: null, 'delete-message-days': options }; } else if (typeof options === 'string') { options = { reason: options, 'delete-message-days': 0 }; } if (options.days) options['delete-message-days'] = options.days; return this.client.rest.methods.banGuildMember(this, user, options); } /** * Unbans a user from the guild. * @param {UserResolvable} user The user to unban * @param {string} [reason] Reason for unbanning the user * @returns {Promise<User>} * @example * // Unban a user by ID (or with a user/guild member object) * guild.unban('some user ID') * .then(user => console.log(`Unbanned ${user.username} from ${guild}`)) * .catch(console.error); */ unban(user, reason) { return this.client.rest.methods.unbanGuildMember(this, user, reason); } /** * Prunes members from the guild based on how long they have been inactive. * @param {number} days Number of days of inactivity required to kick * @param {boolean} [dry=false] If true, will return number of users that will be kicked, without actually doing it * @param {string} [reason] Reason for this prune * @returns {Promise<number>} The number of members that were/will be kicked * @example * // See how many members will be pruned * guild.pruneMembers(12, true) * .then(pruned => console.log(`This will prune ${pruned} people!`)) * .catch(console.error); * @example * // Actually prune the members * guild.pruneMembers(12) * .then(pruned => console.log(`I just pruned ${pruned} people!`)) * .catch(console.error); */ pruneMembers(days, dry = false, reason) { if (typeof days !== 'number') throw new TypeError('Days must be a number.'); return this.client.rest.methods.pruneGuildMembers(this, days, dry, reason); } /** * Syncs this guild (already done automatically every 30 seconds). * <warn>This is only available when using a user account.</warn> * @deprecated */ sync() { if (!this.client.user.bot) this.client.syncGuilds([this]); } /** * Overwrites to use when creating a channel or replacing overwrites * @typedef {Object} ChannelCreationOverwrites * @property {PermissionResolvable} [allow] The permissions to allow * @property {PermissionResolvable} [allowed] The permissions to allow * **(deprecated)** * @property {PermissionResolvable} [deny] The permissions to deny * @property {PermissionResolvable} [denied] The permissions to deny * **(deprecated)** * @property {GuildMemberResolvable|RoleResolvable} id Member or role this overwrite is for */ /** * Creates a new channel in the guild. * @param {string} name The name of the new channel * @param {string|ChannelData} [typeOrOptions='text'] * The type of the new channel, one of `text`, `voice`, `category`, `news`, or `store`. **(deprecated, use options)** * Alternatively options for the new channel, overriding the following parameters. * @param {ChannelCreationOverwrites[]|Collection<Snowflake, PermissionOverwrites>} [permissionOverwrites] * Permission overwrites **(deprecated, use options)** * @param {string} [reason] Reason for creating this channel **(deprecated, use options)** * @returns {Promise<CategoryChannel|TextChannel|VoiceChannel>} * @example * // Create a new text channel * guild.createChannel('new-general', { type: 'text' }) * .then(console.log) * .catch(console.error); * @example * // Create a new category channel with permission overwrites * guild.createChannel('new-category', { * type: 'category', * permissionOverwrites: [{ * id: guild.id, * deny: ['MANAGE_MESSAGES'], * allow: ['SEND_MESSAGES'] * }] * }) * .then(console.log) * .catch(console.error); */ createChannel(name, typeOrOptions, permissionOverwrites, reason) { if (!typeOrOptions || (typeof typeOrOptions === 'string')) { if (typeOrOptions) { process.emitWarning( 'Guild#createChannel: Create channels with an options object instead of separate parameters', 'DeprecationWarning' ); } typeOrOptions = { type: typeOrOptions, permissionOverwrites, reason, }; } return this.client.rest.methods.createChannel(this, name, typeOrOptions); } /** * The data needed for updating a channel's position. * @typedef {Object} ChannelPosition * @property {ChannelResolvable} channel Channel to update * @property {number} position New position for the channel */ /** * Batch-updates the guild's channels' positions. * @param {ChannelPosition[]} channelPositions Channel positions to update * @returns {Promise<Guild>} * @example * guild.updateChannels([{ channel: channelID, position: newChannelIndex }]) * .then(g => console.log(`Updated channel positions for ${g}`)) * .catch(console.error); */ setChannelPositions(channelPositions) { channelPositions = channelPositions.map(({ channel, position }) => ({ id: channel.id || channel, position })); return this.client.rest.methods.setChannelPositions(this.id, channelPositions); } /** * The data needed for updating a role's position. * @typedef {Object} RolePosition * @property {RoleResolvable} role Role to update * @property {number} position New position for the role */ /** * Batch-updates the guild's role's positions. * @param {RolePosition[]} rolePositions Role positions to update * @returns {Promise<Guild>} */ setRolePositions(rolePositions) { rolePositions = rolePositions.map(({ role, position }) => ({ id: role.id || role, position })); return this.client.rest.methods.setRolePositions(this.id, rolePositions); } /** * Edits the guild's embed. * @param {GuildEmbedData} embed The embed for the guild * @param {string} [reason] Reason for changing the guild's embed * @returns {Promise<Guild>} */ setEmbed(embed, reason) { return this.client.rest.methods.updateEmbed(this.id, embed, reason) .then(() => this); } /** * Creates a new role in the guild with given information. * @param {RoleData} [data] The data to update the role with * @param {string} [reason] Reason for creating this role * @returns {Promise<Role>} * @example * // Create a new role * guild.createRole() * .then(role => console.log(`Created new role with name ${role.name}`)) * .catch(console.error); * @example * // Create a new role with data * guild.createRole({ * name: 'Super Cool People', * color: 'BLUE', * }) * .then(role => console.log(`Created new role with name ${role.name} and color ${role.color}`)) * .catch(console.error) */ createRole(data = {}, reason) { return this.client.rest.methods.createGuildRole(this, data, reason); } /** * Creates a new custom emoji in the guild. * @param {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @param {string} name The name for the emoji * @param {Collection<Snowflake, Role>|Role[]} [roles] Roles to limit the emoji to * @param {string} [reason] Reason for creating the emoji * @returns {Promise<Emoji>} The created emoji * @example * // Create a new emoji from a url * guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip') * .then(emoji => console.log(`Created new emoji with name ${emoji.name}`)) * .catch(console.error); * @example * // Create a new emoji from a file on your computer * guild.createEmoji('./memes/banana.png', 'banana') * .then(emoji => console.log(`Created new emoji with name ${emoji.name}`)) * .catch(console.error); */ createEmoji(attachment, name, roles, reason) { if (typeof attachment === 'string' && attachment.startsWith('data:')) { return this.client.rest.methods.createEmoji(this, attachment, name, roles, reason); } else { return this.client.resolver.resolveImage(attachment).then(data => this.client.rest.methods.createEmoji(this, data, name, roles, reason) ); } } /** * Delete an emoji. * @param {Emoji|string} emoji The emoji to delete * @param {string} [reason] Reason for deleting the emoji * @returns {Promise} * @deprecated */ deleteEmoji(emoji, reason) { if (typeof emoji === 'string') emoji = this.emojis.get(emoji); if (!(emoji instanceof Emoji)) throw new TypeError('Emoji must be either an instance of Emoji or an ID'); return emoji.delete(reason); } /** * Causes the client to leave the guild. * @returns {Promise<Guild>} * @example * // Leave a guild * guild.leave() * .then(g => console.log(`Left the guild ${g}`)) * .catch(console.error); */ leave() { return this.client.rest.methods.leaveGuild(this); } /** * Causes the client to delete the guild. * @returns {Promise<Guild>} * @example * // Delete a guild * guild.delete() * .then(g => console.log(`Deleted the guild ${g}`)) * .catch(console.error); */ delete() { return this.client.rest.methods.deleteGuild(this); } /** * Whether this guild equals another guild. It compares all properties, so for most operations * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often * what most users need. * @param {Guild} guild The guild to compare with * @returns {boolean} */ equals(guild) { let equal = guild && this.id === guild.id && this.available === !guild.unavailable && this.splash === guild.splash && this.region === guild.region && this.name === guild.name && this.memberCount === guild.member_count && this.large === guild.large && this.icon === guild.icon && Util.arraysEqual(this.features, guild.features) && this.ownerID === guild.owner_id && this.verificationLevel === guild.verification_level && this.embedEnabled === guild.embed_enabled; if (equal) { if (this.embedChannel) { if (this.embedChannel.id !== guild.embed_channel_id) equal = false; } else if (guild.embed_channel_id) { equal = false; } } return equal; } /** * When concatenated with a string, this automatically concatenates the guild's name instead of the guild object. * @returns {string} * @example * // Logs: Hello from My Guild! * console.log(`Hello from ${guild}!`); * @example * // Logs: Hello from My Guild! * console.log('Hello from ' + guild + '!'); */ toString() { return this.name; } _addMember(guildUser, emitEvent = true) { const existing = this.members.has(guildUser.user.id); if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user); guildUser.joined_at = guildUser.joined_at || 0; const member = new GuildMember(this, guildUser); this.members.set(member.id, member); if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) { const voiceState = this._rawVoiceStates.get(member.user.id); member.serverMute = voiceState.mute; member.serverDeaf = voiceState.deaf; member.selfMute = voiceState.self_mute; member.selfDeaf = voiceState.self_deaf; member.selfStream = voiceState.self_stream || false; member.voiceSessionID = voiceState.session_id; member.voiceChannelID = voiceState.channel_id; if (this.client.channels.has(voiceState.channel_id)) { this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member); } else { this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`); } } /** * Emitted whenever a user joins a guild. * @event Client#guildMemberAdd * @param {GuildMember} member The member that has joined a guild */ if (this.client.ws.connection.status === Constants.Status.READY && emitEvent && !existing) { this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member); } return member; } _updateMember(member, data) { const oldMember = Util.cloneObject(member); if (data.premium_since) member.premiumSinceTimestamp = new Date(data.premium_since).getTime(); if (data.roles) member._roles = data.roles; if (typeof data.nick !== 'undefined') member.nickname = data.nick; const notSame = member.nickname !== oldMember.nickname || member.premiumSinceTimestamp !== oldMember.premiumSinceTimestamp || !Util.arraysEqual(member._roles, oldMember._roles); if (this.client.ws.connection.status === Constants.Status.READY && notSame) { /** * Emitted whenever a guild member changes - i.e. new role, removed role, nickname. * @event Client#guildMemberUpdate * @param {GuildMember} oldMember The member before the update * @param {GuildMember} newMember The member after the update */ this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member); } return { old: oldMember, mem: member, }; } _removeMember(guildMember) { if (guildMember.voiceChannel) guildMember.voiceChannel.members.delete(guildMember.id); this.members.delete(guildMember.id); } _memberSpeakUpdate(user, speaking) { const member = this.members.get(user); if (member && member.speaking !== speaking) { member.speaking = speaking; /** * Emitted once a guild member starts/stops speaking. * @event Client#guildMemberSpeaking * @param {GuildMember} member The member that started/stopped speaking * @param {boolean} speaking Whether or not the member is speaking */ this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking); } } _setPresence(id, presence) { if (this.presences.get(id)) { this.presences.get(id).update(presence); return; } this.presences.set(id, new Presence(presence, this.client)); } /** * Set the position of a role in this guild. * @param {string|Role} role The role to edit, can be a role object or a role ID * @param {number} position The new position of the role * @param {boolean} [relative=false] Position Moves the role relative to its current position * @returns {Promise<Guild>} */ setRolePosition(role, position, relative = false) { if (typeof role === 'string') { role = this.roles.get(role); if (!role) return Promise.reject(new Error('Supplied role is not a role or snowflake.')); } position = Number(position); if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); let updatedRoles = this._sortedRoles.array(); Util.moveElementInArray(updatedRoles, role, position, relative); updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i })); return this.client.rest.methods.setRolePositions(this.id, updatedRoles); } /** * Set the position of a channel in this guild. * @param {string|GuildChannel} channel The channel to edit, can be a channel object or a channel ID * @param {number} position The new position of the channel * @param {boolean} [relative=false] Position Moves the channel relative to its current position * @returns {Promise<Guild>} */ setChannelPosition(channel, position, relative = false) { if (typeof channel === 'string') { channel = this.channels.get(channel); if (!channel) return Promise.reject(new Error('Supplied channel is not a channel or snowflake.')); } position = Number(position); if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); let updatedChannels = this._sortedChannels(channel.type).array(); Util.moveElementInArray(updatedChannels, channel, position, relative); updatedChannels = updatedChannels.map((c, i) => ({ id: c.id, position: i })); return this.client.rest.methods.setChannelPositions(this.id, updatedChannels); } /** * Fetches a collection of channels in the current guild sorted by position. * @param {string} type The channel type * @returns {Collection<Snowflake, GuildChannel>} * @private */ _sortedChannels(type) { return this._sortPositionWithID(this.channels.filter(c => { if (type === 'voice' && c.type === 'voice') return true; else if (type !== 'voice' && c.type !== 'voice') return true; else return type === c.type; })); } /** * Sorts a collection by object position or ID if the positions are equivalent. * Intended to be identical to Discord's sorting method. * @param {Collection} collection The collection to sort * @returns {Collection} * @private */ _sortPositionWithID(collection) { return collection.sort((a, b) => a.position !== b.position ? a.position - b.position : Long.fromString(b.id).sub(Long.fromString(a.id)).toNumber() ); } }
JavaScript
class BaseWebAudioPanner extends BaseWebAudioNode { /** * Creates a new spatializer that uses WebAudio's PannerNode. * @param id * @param stream * @param audioContext - the output WebAudio context */ constructor(id, source, audioContext, destination) { const panner = audioContext.createPanner(); super(id, source, audioContext, panner); this.node.panningModel = "HRTF"; this.node.distanceModel = "inverse"; this.node.coneInnerAngle = 360; this.node.coneOuterAngle = 0; this.node.coneOuterGain = 0; this.node.connect(destination); } /** * Sets parameters that alter spatialization. **/ setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime) { super.setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime); this.node.refDistance = this.minDistance; if (this.algorithm === "logarithmic") { algorithm = "inverse"; } this.node.distanceModel = algorithm; this.node.rolloffFactor = this.rolloff; } }
JavaScript
class StringDecoderImpl { constructor(encoding = 'utf8') { this.encoding = encoding; this.byteCount = 0; this.charLength = 1; } // the actual underlying implementation! end(buffer) { if (buffer && buffer.length !== 0) { return this.write(buffer); } return ''; } write(buffer) { if (buffer && buffer.length !== 0) { return buffer.toString(this.encoding); // single byte character encodings are a cinch } return ''; // no buffer, or empty } }
JavaScript
class MultiByteStringDecoderImpl extends StringDecoderImpl { constructor(encoding, bytesPerChar) { super(encoding); this.incomplete = Buffer.allocUnsafe(bytesPerChar); // temporary incomplete character buffer } /** * @typedef {Object} IncompleteCharObject * @property {integer} bytesNeeded bytes missing to complete the character * @property {integer} charLength bytes expected to complete the character * @property {integer} index location in the buffer where the character starts */ /** * Given a Buffer, sees if we have an incomplete "character" at the end of it. * Returns info on that: * - bytesNeeded: 0-3, number of bytes still remaining * - charLength: expected number of bytes for the incomplete character * - index: index in the buffer where the incomplete character begins * @param {Buffer} _buffer Buffer we are checking to see if it has an incompelte "character" at the end * @returns {IncompleteCharObject} */ _checkIncompleteBytes(_buffer) { throw new Error('subclasses must override!'); } _incompleteEnd() { throw new Error('subclasses must override!'); } _incompleteBufferEmptied() { // typically we reset byte count back to 0 and character length to 1 this.byteCount = 0; this.charLength = 1; } end(buffer) { let result = super.end(buffer); if (this.byteCount !== 0) { // we have incomplete characters! result += this._incompleteEnd(); } this._incompleteBufferEmptied(); // reset our internals to "wipe" the incomplete buffer return result; } write(buffer) { // first let's see if we had some multi-byte character we didn't finish... let char = ''; if (this.byteCount !== 0) { // we still needed some bytes to finish the character // How many bytes do we still need? charLength - bytes we received const left = this.charLength - this.byteCount; // need 4, have 1? then we have 3 "left" const bytesCopied = Math.min(left, buffer.length); // copy up to that many bytes // copy bytes from `buffer` to our incomplete buffer buffer.copy(this.incomplete, this.byteCount, 0, bytesCopied); this.byteCount += bytesCopied; // record how many more bytes we copied... if (bytesCopied < left) { // still need more bytes to complete! return ''; } // we were able to complete, yay! // grab the character we completed char = this.incomplete.slice(0, this.charLength).toString(this.encoding); // reset our counters this._incompleteBufferEmptied(); // do we have any bytes left in this buffer? if (bytesCopied === buffer.length) { return char; // if not, return the character we finished! } // we still have more bytes, so slice the buffer up buffer = buffer.slice(bytesCopied, buffer.length); } // check this buffer to see if it indicates we need more bytes? const incompleteCharData = this._checkIncompleteBytes(buffer); if (incompleteCharData.bytesNeeded === 0) { return char + buffer.toString(this.encoding); // no incomplete bytes, return any character we completed plus the buffer } // ok so the buffer holds an incomplete character at it's end this.charLength = incompleteCharData.charLength; // record how many bytes we need for the 'character' const incompleteCharIndex = incompleteCharData.index; // this is the index of the multibyte character that is incomplete // copy from index of incomplete character to end of buffer const bytesToCopy = buffer.length - incompleteCharIndex; buffer.copy(this.incomplete, 0, incompleteCharIndex, buffer.length); this.byteCount = bytesToCopy; // record how many bytes we actually copied if (bytesToCopy < buffer.length) { // buffer had bytes before the incomplete character // so smush any character we may have completed with any complete characters in the buffer return char + buffer.toString(this.encoding, 0, incompleteCharIndex); } return char; // any now-completed character that was previously incomplete, possibly empty } }
JavaScript
class Component extends PureComponent { static propTypes = { title: PropTypes.string, emoji: PropTypes.string, } handleClick(emoji) { alert(`You clicked on ${emoji}`); // eslint-disable-line } render() { return ( <div className="list__tab"> <div> <span>When you</span> <button type="button" onClick={() => this.handleClick(this.props.emoji)} > click </button> <span> {this.props.title} </span> </div> <div> <span>You will get a </span> {this.props.emoji} </div> </div> ); } }
JavaScript
class UAL { /** * @param chains A list of chains the dapp supports. * * @param appName The name of the app using the authenticators * * @param authenticators A list of authenticator apps that the dapp supports. */ constructor(chains, appName, authenticators) { this.chains = chains; this.appName = appName; this.authenticators = authenticators; } /** * Returns an object with a list of initialized Authenticators that returned true for shouldRender() * as well as an authenticator that supports autoLogin */ getAuthenticators() { const availableAuthenticators = this.authenticators.filter((authenticator) => { return authenticator.shouldRender(); }); availableAuthenticators.forEach((authenticator) => authenticator.init()); let autoLoginAuthenticator = null; if (availableAuthenticators.length === 1) { if (availableAuthenticators[0].shouldAutoLogin()) { autoLoginAuthenticator = availableAuthenticators[0]; } } return { availableAuthenticators, autoLoginAuthenticator }; } }
JavaScript
class PastePlainText extends Plugin { static get pluginName() { return 'PasteAsPlainText' } static get requires() { return [ PastePlainTextUI, PastePlainTextCommand ] } init() { (new Translation()).translate(); const editor = this.editor; editor.commands.add( 'pastePlainText', new PastePlainTextCommand( editor ) ); // The logic responsible for converting HTML to plain text. const clipboardPlugin = editor.plugins.get( 'ClipboardPipeline' ); const command = editor.commands.get( 'pastePlainText' ); const editingView = editor.editing.view; editingView.document.on( 'clipboardInput', ( evt, data ) => { if ( editor.isReadOnly || !command.value ) { return; } const dataTransfer = data.dataTransfer; let content = plainTextToHtml( dataTransfer.getData( 'text/plain' ) ); data.content = this.editor.data.htmlProcessor.toView( content ); } ); } }
JavaScript
class Zettle { constructor(...args) { this.clientId = args[0].clientId; this.assertionToken = args[0].assertionToken; this.organizationUuid = args[0].organizationUuid || "self"; this.token = null; this.tokenExp = new Date().getTime(); logger.debug("Initialized Zettle API instance."); } /** * Function to see if the token we have is valid. * @returns Always true, grabs a new token if needed. */ async hasValidToken() { if (this.tokenExp < new Date().getTime()) { logger.debug("Token has expired, getting a new one."); await this.getToken(); return true; } else { logger.debug("Auth token still valid , using it."); return true; } } /** * This function grabs token from the Zettle API. * @returns True if token was set successfully. */ async getToken() { let res = await axios({ method: "post", url: "https://oauth.zettle.com/token", data: `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=${this.clientId}&assertion=${this.assertionToken}`, }); this.token = res.data.access_token; this.tokenExp = new Date().getTime() + res.data.expires_in * 1000; logger.debug("Got back a new token from Zettle, saved it down."); return true; } /** * This function grabs the latest orders from the Zettle API. * @param {String} limit The amount of orders to fetch. * @param {Boolean} descending If they should be sorted by desc. * @returns */ async getLatestPurchases(limit, descending) { logger.debug(`Grabbing ${limit} latest purchases, desc: ${descending}.`); await this.hasValidToken(); let res = await axios({ method: "get", url: `https://purchase.izettle.com/purchases/v2?limit=${limit}&descending=${descending}`, headers: { Authorization: `Bearer ${this.token}`, }, }); logger.debug(`Got back the latest purchases.`); return res.data; } }
JavaScript
class Lifecycle { /* * onCreated(), * onAttached(), * onPropsReceived(nextProps), * onUpdated(prevProps), * onDestroyed(), * onDetached() */ static onComponentCreated(component) { if (component.hasOwnMethod('onCreated')) { component.onCreated.call(component.sandbox); } if (component.child) { this.onNodeCreated(component.child); } } static onElementCreated(element) { for (const child of element.children) { this.onNodeCreated(child); } } static onNodeCreated(node) { if (node.isElement()) { return this.onElementCreated(node); } if (!node.isRoot()) { return this.onComponentCreated(node); } } static onRootCreated(root) { if (root.hasOwnMethod('onCreated')) { root.onCreated.call(root.sandbox); } } static onComponentAttached(component) { if (component.child) { this.onNodeAttached(component.child); } if (component.hasOwnMethod('onAttached')) { component.onAttached.call(component.sandbox); } } static onElementAttached(element) { for (const child of element.children) { this.onNodeAttached(child); } } static onNodeAttached(node) { if (node.isElement()) { return this.onElementAttached(node); } if (!node.isRoot()) { return this.onComponentAttached(node); } } static onRootAttached(root) { if (root.hasOwnMethod('onAttached')) { root.onAttached.call(root.sandbox); } } static onComponentReceivedProps(component, nextProps) { if (component.hasOwnMethod('onPropsReceived')) { component.onPropsReceived.call(component.sandbox, nextProps); } } static onComponentUpdated(component, prevProps) { if (component.hasOwnMethod('onUpdated')) { component.onUpdated.call(component.sandbox, prevProps); } } static onComponentDestroyed(component) { for (const cleanUpTask of component.cleanUpTasks) { cleanUpTask(); } if (component.hasOwnMethod('onDestroyed')) { component.onDestroyed.call(component.sandbox); } if (component.child) { this.onNodeDestroyed(component.child); } } static onElementDestroyed(element) { for (const child of element.children) { this.onNodeDestroyed(child); } } static onNodeDestroyed(node) { if (node.isElement()) { return this.onElementDestroyed(node); } if (!node.isRoot()) { return this.onComponentDestroyed(node); } } static onComponentDetached(component) { if (component.child) { this.onNodeDetached(component.child); } if (component.hasOwnMethod('onDetached')) { component.onDetached.call(component.sandbox); } } static onElementDetached(element) { for (const child of element.children) { this.onNodeDetached(child); } } static onNodeDetached(node) { if (node.isElement()) { return this.onElementDetached(node); } if (!node.isRoot()) { return this.onComponentDetached(node); } } static beforePatchApplied(patch) { const Type = opr.Toolkit.Patch.Type; switch (patch.type) { case Type.ADD_COMPONENT: return this.onComponentCreated(patch.component); case Type.ADD_ELEMENT: return this.onElementCreated(patch.element); case Type.INIT_ROOT_COMPONENT: return this.onRootCreated(patch.root); case Type.INSERT_CHILD_NODE: return this.onNodeCreated(patch.node); case Type.REMOVE_CHILD_NODE: return this.onNodeDestroyed(patch.node); case Type.REMOVE_COMPONENT: return this.onComponentDestroyed(patch.component); case Type.REMOVE_ELEMENT: return this.onElementDestroyed(patch.element); case Type.REPLACE_CHILD: this.onNodeDestroyed(patch.child); this.onNodeCreated(patch.node); return; case Type.UPDATE_COMPONENT: return this.onComponentReceivedProps(patch.target, patch.props); } } static beforeUpdate(patches) { for (const patch of patches) { this.beforePatchApplied(patch); } } static afterPatchApplied(patch) { const Type = opr.Toolkit.Patch.Type; switch (patch.type) { case Type.ADD_COMPONENT: return this.onComponentAttached(patch.component); case Type.ADD_ELEMENT: return this.onElementAttached(patch.element); case Type.INIT_ROOT_COMPONENT: return this.onRootAttached(patch.root); case Type.INSERT_CHILD_NODE: return this.onNodeAttached(patch.node); case Type.REMOVE_CHILD_NODE: return this.onNodeDetached(patch.node); case Type.REMOVE_COMPONENT: return this.onComponentDetached(patch.component); case Type.REMOVE_ELEMENT: return this.onElementDetached(patch.element); case Type.REPLACE_CHILD: this.onNodeDetached(patch.child); this.onNodeAttached(patch.node); return; case Type.UPDATE_COMPONENT: return this.onComponentUpdated(patch.target, patch.prevProps); } } static afterUpdate(patches) { patches = [...patches].reverse(); for (const patch of patches) { this.afterPatchApplied(patch); } } }
JavaScript
class OkEventsEmitter { /** * This class contains all you need to made event emitter */ constructor() { /** * @hidden * @private */ this.m_events = {}; // contains all events } /** * this method register an event * @param event * @param listener * @public */ on(event, listener) { if (!this.m_events[event]) { this.m_events[event] = []; } this.m_events[event].push(listener); } /** * this method remove an event registered if this event doesn't exist that throw an error * @param event * @param listenerToRemove * @public */ removeListener(event, listenerToRemove) { if (!this.m_events[event]) { throw new Error(`Can't remove a listener. Event "${event}" doesn't exits.`); } const filterListeners = (listener) => listener !== listenerToRemove; this.m_events[event] = this.m_events[event].filter(filterListeners); } /** * This method is used to emit an event if this event doesn't exist that throw an error * @param event * @param data * @protected */ emit(event, data) { if (!this.m_events[event]) { throw new Error(`Can't emit an event. Event "${event}" doesn't exits.`); } const fireCallbacks = (callback) => { callback(data); }; this.m_events[event].forEach(fireCallbacks); } }
JavaScript
class StoreApiService extends ApiService { constructor(httpClient, loginService, apiEndpoint = 'store') { super(httpClient, loginService, apiEndpoint); this.name = 'storeService'; } ping() { const headers = this.getBasicHeaders(); return this.httpClient .get(`/_action/${this.getApiBasePath()}/ping`, { headers }) .then((response) => { return ApiService.handleResponse(response); }); } login(shopwareId, password) { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .post(`/_action/${this.getApiBasePath()}/login`, { shopwareId, password }, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } checkLogin() { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .post(`/_action/${this.getApiBasePath()}/checklogin`, {}, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } logout() { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .post(`/_action/${this.getApiBasePath()}/logout`, {}, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } getLicenseList() { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .get(`/_action/${this.getApiBasePath()}/licenses`, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } getUpdateList() { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .get(`/_action/${this.getApiBasePath()}/updates`, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } /** * @deprecated tag:v6.5.0 for updating and installing plugins use downloadAndUpdatePlugin * TODO: remove param onlyDownload with removing deprecation and remove the source code after * the if statement "onlyDownload". It should now only download the plugin and do not trigger a update. */ downloadPlugin(pluginName, unauthenticated = false, onlyDownload = false) { const headers = this.getBasicHeaders(); const params = this.getBasicParams({ pluginName: pluginName }); if (unauthenticated) { params.unauthenticated = true; } // TODO: remove if condition but keep content of the block if (onlyDownload) { return this.httpClient .get(`/_action/${this.getApiBasePath()}/download`, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } // TODO: remove this when removing deprecation return this.httpClient .get(`/_action/${this.getApiBasePath()}/download`, { params, headers }) .then(() => { return this.httpClient .post('/_action/plugin/update', null, { params, headers }); }) .then((response) => { return ApiService.handleResponse(response); }); } downloadAndUpdatePlugin(pluginName, unauthenticated = false) { const headers = this.getBasicHeaders(); const params = this.getBasicParams({ pluginName: pluginName }); if (unauthenticated) { params.unauthenticated = true; } return this.httpClient .get(`/_action/${this.getApiBasePath()}/download`, { params, headers }) .then(() => { return this.httpClient .post('/_action/plugin/update', null, { params, headers }); }) .then((response) => { return ApiService.handleResponse(response); }); } getLicenseViolationList() { const headers = this.getBasicHeaders(); const params = this.getBasicParams(); return this.httpClient .post(`/_action/${this.getApiBasePath()}/plugin/search`, null, { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } getBasicParams(additionalParams = {}) { const basicParams = { language: localStorage.getItem('sw-admin-locale') }; return Object.assign({}, basicParams, additionalParams); } }
JavaScript
class HttpStatus { constructor (status, message) { this.http_status = status this.message = message } }
JavaScript
class HttpError extends Error { constructor (status, message) { super(message) this.http_status = status } }
JavaScript
class ImagePitcher extends Pitcher { /** * The pitching method */ pitch() { // Is type (ancestors not relevant) if ( this.selectionContainer.type === "Image" ) { this.state.isImage = true; // If it is, it can this.state.canImage = true; return; } // Is not a node, should be empty or a clean selection to be ok. // If selection is multiblock, cannot be an image, so short circuit if ( !Helpers.isHighestLevelBlock( this.selectionContainer ) ) { return; } // If selection is empty => All is ok if ( Helpers.selectionIsEmpty( this.selection ) ) { this.state.canImage = true; return; } } }
JavaScript
class PermissionsCommand extends DiscordCommand { /** * Creates an instance for an organization from a source and assigns a given language manager to it. * @param {Context} context the Bot's context * @param {string} source the source name (like Discord etc.) * @param {LangManager} commandLangManager the language manager * @param {string} orgId the organization identifier * @return {Command} the created instance */ static createForOrg(context, source, commandLangManager, orgId) { return new PermissionsCommand(context, source, commandLangManager, orgId); } /** * Gets the text id of the command's name from localization resources. * @return {string} the id of the command's name to be localized */ static getCommandInterfaceName() { return 'command_permissions_name'; } /** * Gets the user-friendly name of the command to display to the user (typically used in the Web interface). * @return {string} the user-friendly name */ static get DISPLAY_NAME() { return 'command_permissions_displayname'; } /** * Gets the array of all arguments definitions of the command. * @return {Array<CommandArgDef>} the array of definitions */ static getDefinedArgs() { return PermissionsCommandArgDefs; } /** * Gets the help text for the command (excluding the help text for particular arguments). * The lang manager is basically the manager from the HelpCommand's instance. * @see HelpCommand * @param {Context} context the Bot's context * @param {LangManager} langManager the language manager to localize the help text * @return {string} the localized help text */ static getHelpText(context, langManager) { return langManager.getString('command_permissions_help'); } /** * Gets the array of defined Discord permission filters for the command. * Source-independent permissions (e.g. stored in the Bot's DB) should be defined in another place. * @return {Array<string>} the array of Discord-specific permissions required */ static getRequiredDiscordPermissions() { return [PermissionsManager.DISCORD_PERMISSIONS.ADMINISTRATOR]; } /** * Validates each of the arguments according to validation types set in their definition. * Throws BotPublicError if any of the validations was violated. * @see CommandArgDef * @throws {BotPublicError} * @param {BaseMessage} message the command's message * @return {Promise} nothing */ async validateFromDiscord(message) { await super.validateFromDiscord(message); if (this.permType !== null) { let foundIndex = -1; const permKeys = Object.keys(PermissionsManager.DEFINED_PERMISSIONS); for (const key of permKeys) { if (this.langManager.getString(PermissionsManager.DEFINED_PERMISSIONS[key].textId) === this.permType) { foundIndex = key; break; } } if (foundIndex < 0) { this.context.log.e(this.constructor.name + ' validateFromDiscord: invalid permType ' + this.permType); throw new BotPublicError(this.langManager.getString('command_permissions_error_wrong_type', this.permType)); } else { this.permType = PermissionsManager.DEFINED_PERMISSIONS[foundIndex]; } } } /** * Executes the command instance. The main function of a command, it's essence. * All arguments scanning, validation and permissions check is considered done before entering this function. * So if any exception happens inside the function, it's considered a Bot's internal problem. * @param {BaseMessage} message the Discord message as the source of the command * @return {Promise<string>} the result text to be replied as the response of the execution */ async executeForDiscord(message) { // Inherited function with various possible implementations, some args may be unused. /* eslint no-unused-vars: ["error", { "args": "none" }] */ // Keep "return await" to properly catch exceptions from the inside. /* eslint-disable no-return-await */ return await this.getPermissionsDescription( message, 'command_permissions_no_permissions', 'command_permissions_permission' ); /* eslint-enable no-return-await */ } /** * Gets the filter object for permissions query. * @param {BaseMessage} message the Discord message * @return {Object} the filter */ async getFilter(message) { // Inherited function with various possible implementations, some args may be unused. /* eslint no-unused-vars: ["error", { "args": "none" }] */ let typeFilter = {}; if (this.permType !== null) { typeFilter = { permissionType: this.permType.name }; } return typeFilter; } /** * Gets a summarized list of peermissions description according to the filter. * @param {BaseMessage} message the Discord message with the command * @param {string} emptyTextId the text id to be used in case of no matching permissions found * @param {string} resultTextId the text id to be used in case of matching permissions are found * @return {Promise<string>} the result string to be replier the the caller */ async getPermissionsDescription(message, emptyTextId, resultTextId) { const filter = await this.getFilter(message); const permissions = await this.context.dbManager.getDiscordRows( this.context.dbManager.permissionsTable, this.orgId, filter ); if (permissions.length === 0) { return this.langManager.getString(emptyTextId); } let result = ''; for (const permission of permissions) { const filterDescription = this.makeFilterDescription(permission); let subjectTypeString = ''; let subjectString = ''; if (permission.subjectType === PermissionsManager.SUBJECT_TYPES.user.name) { subjectTypeString = this.langManager.getString(PermissionsManager.SUBJECT_TYPES.user.textId); subjectString = DiscordUtils.makeUserMention(permission.subjectId); } else { subjectTypeString = this.langManager.getString(PermissionsManager.SUBJECT_TYPES.role.textId); subjectString = DiscordUtils.makeRoleMention(permission.subjectId); } let permType = permission.permissionType; const permKeys = Object.keys(PermissionsManager.DEFINED_PERMISSIONS); for (const key of permKeys) { if (PermissionsManager.DEFINED_PERMISSIONS[key].name === permission.permissionType) { permType = this.langManager.getString(PermissionsManager.DEFINED_PERMISSIONS[key].textId); break; } } result = result + this.langManager.getString( resultTextId, permission.id, permType, subjectTypeString, subjectString, filterDescription ) + '\n'; } return result; } /** * Makes the filter description for a granted permission. * @param {OrgPermission} permission the permission * @return {string} the result text */ makeFilterDescription(permission) { if (permission.filter === undefined || permission.filter === null) { return ''; } const filterKeys = Object.keys(permission.filter); let filterDescription = ' { '; for (const filterKey of filterKeys) { let filterFieldValue = ''; let foundInChannelFilters = false; for (let k = 0; k < PermissionsManager.DISCORD_CHANNELS_FILTERS.length; k++) { if (PermissionsManager.DISCORD_CHANNELS_FILTERS[k].name === filterKey) { if (permission.filter[filterKey] === OhUtils.ANY_VALUE) { filterFieldValue = this.langManager.getString(DiscordCommand.ANY_VALUE_TEXT); } else { filterFieldValue = DiscordUtils.makeChannelMention(permission.filter[filterKey]); } foundInChannelFilters = true; } } let foundInMembersFilters = false; for (let k = 0; k < PermissionsManager.DISCORD_MEMBERS_FILTERS.length; k++) { if (PermissionsManager.DISCORD_MEMBERS_FILTERS[k].name === filterKey) { if (permission.filter[filterKey] === OhUtils.ANY_VALUE) { filterFieldValue = this.langManager.getString(DiscordCommand.ANY_VALUE_TEXT); } else { filterFieldValue = DiscordUtils.makeUserMention(permission.filter[filterKey]); } foundInMembersFilters = true; } } let foundInRolesFilters = false; for (let k = 0; k < PermissionsManager.DISCORD_ROLES_FILTERS.length; k++) { if (PermissionsManager.DISCORD_ROLES_FILTERS[k].name === filterKey) { if (permission.filter[filterKey] === OhUtils.ANY_VALUE) { filterFieldValue = this.langManager.getString(DiscordCommand.ANY_VALUE_TEXT); } else { filterFieldValue = DiscordUtils.makeRoleMention(permission.filter[filterKey]); } foundInRolesFilters = true; } } if (!foundInChannelFilters && !foundInMembersFilters && !foundInRolesFilters) { filterFieldValue = permission.filter[filterKey]; } filterDescription = filterDescription + ' ' + this.langManager.getString(PermissionsManager.DEFINED_FILTERS[filterKey].textId) + ' : ' + filterFieldValue + ';'; } filterDescription += ' } '; return this.langManager.getString('command_permissions_filter_condition', filterDescription); } }
JavaScript
class GridRowTreeMouseHandler extends GridMouseHandler { static isInTreeBox(gridPoint, grid) { const { column, row, x, y } = gridPoint; const { metrics } = grid; const { gridX, gridY, firstColumn, visibleColumnXs, visibleColumnWidths, visibleRowHeights, visibleRowYs, visibleRowTreeBoxes, } = metrics; if ( column === firstColumn && row != null && visibleRowTreeBoxes.get(row) != null && x > gridX && y > gridY ) { const columnX = visibleColumnXs.get(column); const width = visibleColumnWidths.get(column); const rowY = visibleRowYs.get(row); const height = visibleRowHeights.get(row); if ( x >= gridX + columnX && x <= gridX + columnX + width && y >= gridY + rowY && y <= gridY + rowY + height ) { return true; } } return false; } onDown(gridPoint, grid) { return GridRowTreeMouseHandler.isInTreeBox(gridPoint, grid); } onClick(gridPoint, grid) { if (GridRowTreeMouseHandler.isInTreeBox(gridPoint, grid)) { const { row } = gridPoint; grid.toggleRowExpanded(row); return true; } return false; } }
JavaScript
class SettingsManager extends Singleton { constructor() { super(game); this.settings = {}; } setSFX(bool, saveToData) { return; this.settings.soundOn = bool; (this.settings.soundOn) ? SoundManager.instance.enableSFX() : SoundManager.instance.disableSFX(); if (saveToData) this._saveSettings(); } setBGM(bool, saveToData) { return; this.settings.musicOn = bool; (this.settings.musicOn) ? SoundManager.instance.enableBGM() : SoundManager.instance.disableBGM(); if (saveToData) this._saveSettings(); } setSettings(settingsObj) { this.settings = settingsObj; return; this.setSFX(this.settings.soundOn, false); this.setBGM(this.settings.musicOn, false); } _saveSettings() { DataManager.instance.playerData.settings = this.settings; DataManager.instance.saveAllDataAsync(); } }
JavaScript
class HandledError { /** * Create a HandledError. * @member {string} [errorId] * @member {date} [timestamp] * @member {string} [deviceName] * @member {string} [osVersion] * @member {string} [osType] * @member {string} [country] * @member {string} [language] * @member {string} [userId] */ constructor() { } /** * Defines the metadata of HandledError * * @returns {object} metadata of HandledError * */ mapper() { return { required: false, serializedName: 'HandledError', type: { name: 'Composite', className: 'HandledError', modelProperties: { errorId: { required: false, serializedName: 'errorId', type: { name: 'String' } }, timestamp: { required: false, serializedName: 'timestamp', type: { name: 'DateTime' } }, deviceName: { required: false, serializedName: 'deviceName', type: { name: 'String' } }, osVersion: { required: false, serializedName: 'osVersion', type: { name: 'String' } }, osType: { required: false, serializedName: 'osType', type: { name: 'String' } }, country: { required: false, serializedName: 'country', type: { name: 'String' } }, language: { required: false, serializedName: 'language', type: { name: 'String' } }, userId: { required: false, serializedName: 'userId', type: { name: 'String' } } } } }; } }
JavaScript
class InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare { /** * Constructs a new <code>InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare</code>. * Per-share figures. * @alias module:model/InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare */ constructor() { InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare} obj Optional instance to populate. * @return {module:model/InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare} The populated <code>InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse2004ReportedKeyFiguresFirstFiscalYearCurrencyDependentKeyFiguresPerShare(); if (data.hasOwnProperty('sales')) { obj['sales'] = ApiClient.convertToType(data['sales'], 'Number'); } if (data.hasOwnProperty('recurringDilutedEarnings')) { obj['recurringDilutedEarnings'] = ApiClient.convertToType(data['recurringDilutedEarnings'], 'Number'); } if (data.hasOwnProperty('dividends')) { obj['dividends'] = ApiClient.convertToType(data['dividends'], 'Number'); } if (data.hasOwnProperty('bookValue')) { obj['bookValue'] = ApiClient.convertToType(data['bookValue'], 'Number'); } if (data.hasOwnProperty('cashFlow')) { obj['cashFlow'] = ApiClient.convertToType(data['cashFlow'], 'Number'); } } return obj; } }
JavaScript
class GuildQueue extends EventEmitter { /** * Initializes a guild queue * @param {object} data - The queue data * @param {GuildPlayer} - The associated player */ constructor (data, player) { super() /** * The associated player * @type {GuildPlayer} */ this.player = player this._d = data this.setMaxListeners(30) } /** * Currently playing item * @type {QueueItem} */ get nowPlaying () { return this._d.nowPlaying ? new QueueItem(this._d.nowPlaying, this) : undefined } /** * Items in the queue * @type {QueueItem[]} */ get items () { return Object.freeze(this._d.items ? this._d.items.map(item => new QueueItem(item, this)) : []) } /** * Is the queue currently frozen? * @type {boolean} */ get frozen () { return this._d.frozen } set frozen (v) { this._d.frozen = v this.emit('updated') } /** * The associated guild * @type {Discordie.IGuild} */ get guild () { return this.player.guild } /** * Add an item to the queue * @param {object} item - Item to add * @param {boolean} silent - If true, no event will be emitted * @param {boolean} noPlayback - If true, playback will not be triggered * @returns {object} */ addItem (item, silent = false, noPlayback = false) { if (!item.path || !item.voiceChannel || !item.requestedBy) return false if (item.duration <= 0) item.filters = [] const itm = { } // Convert the item to a JSON-safe object Object.assign(itm, item, { uid: (new Chance()).guid(), voteSkip: [], status: 'queue', requestedBy: item.requestedBy.id || item.requestedBy, voiceChannel: item.voiceChannel.id || item.voiceChannel }) if (item.textChannel && item.textChannel.id) itm.textChannel = item.textChannel.id // Add the item const index = this._d.items.push(itm) - 1 const i = this.items[index] // Emit events if (!silent) this.emit('newItem', { index, item: i }) if (!silent) this.emit('updated') // Nothing being played right now? Start playback inmediately if ((!this.nowPlaying || !this.player.audioPlayer.encoderStream) && !noPlayback) { this._d.nowPlaying = this._d.items.shift() this.player.play() } return { index, i } } /** * Remove item at index * @param {number} index * @param {Discordie.IGuildMember} user - User that requested the item removal * @returns {object} */ remove (index, user) { if (!isFinite(index) || index >= this._d.items.length) return false const item = new QueueItem(this._d.items.splice(index, 1)[0]) this.emit('removed', { item, user }) this.emit('updated') return { item, user } } /** * Remove last item * @param {Discordie.IGuildMember} user - User that requested the item removal * @returns {object} */ removeLast (user) { return this.remove(this.items.length - 1, user) } /** * Swaps 2 items * @param {number} index1 * @param {number} index2 * @param {Discordie.IGuildMember} user - User that requested the swap * @returns {object} */ swap (index1, index2, user) { if (!this._d.items[index1] || !this._d.items[index2]) return false const _item1 = this._d.items[index1] this._d.items[index1] = this._d.items[index2] this._d.items[index2] = _item1 const items = [ this.items[index1], this.items[index2] ] this.emit('swapped', { index1, index2, items, user }) this.emit('updated') return { index1, index2, items, user } } /** * Moves an item to another position * @param {number} index - Index of the item * @param {number} position - New position * @param {Discordie.IGuildMember} user * @returns {object} */ move (index, position, user) { if (index >= this._d.items.length || position >= this._d.items.length) return false if (index < 0 || position < 0) return false this._d.items.splice(position, 0, this._d.items.splice(index, 1)[0]) const item = this.items[position] this.emit('moved', { index, position, item, user }) this.emit('updated') return { index, position, item, user } } /** * Moves an item to the first position * @param {number} index - Index of the item * @param {Discordie.IGuildMember} user * @returns {object} */ bump (index, user) { return this.move(index, 0) } /** * Shuffles the items in the queue */ shuffle () { this._d.items = new Chance().shuffle(this._d.items) this.emit('shuffled') this.emit('updated') } /** * Clears the queue */ clear () { this._d.items = [] this.emit('cleared') this.emit('updated') } }
JavaScript
class IsVisible extends React.Component { static displayName = 'IsVisible'; state = { visibleClass: '' }; getChildContext = () => { return { visibleClass: this.state.visibleClass }; }; componentDidUpdate(prevProps) { prevProps !== this.props && this.chooseClass(this.props.isOpen); } isVisible = element => { let tempParentArr = []; const elementBoundingRect = element.getBoundingClientRect(); const elementParent = element.parentElement; const windowBottom = window.pageXOffset + window.innerHeight; const elementTop = elementBoundingRect.top - 36 - elementBoundingRect.height; const elementBottom = elementBoundingRect.bottom; const findParents = elem => { return !elem.parentElement ? tempParentArr : findParents(elem.parentElement, tempParentArr.push(elem)); }; const elementParents = findParents(elementParent); const findOverflow = node => { const searchProps = ['overflow', 'overflow-y']; return searchProps.reduce((agg, prop) => { let overflowElement = ReactDOM.findDOMNode(node).style[prop]; return !overflowElement || agg.includes(overflowElement) ? agg : (agg += overflowElement); }, ''); }; const findScrollParent = () => { let overflowElement = null; let idx = 0; while (!overflowElement && elementParents[idx]) { if (/(auto|scroll)/.test(findOverflow(elementParents[idx]))) { return (overflowElement = elementParents[idx]); } idx++; } return overflowElement ? overflowElement : window; }; const scrollParent = findScrollParent(element); const parentBottom = (!!scrollParent.getBoundingClientRect && scrollParent.getBoundingClientRect().bottom) || windowBottom; const parentTop = (!!scrollParent.getBoundingClientRect && scrollParent.getBoundingClientRect().top) || 0; return ( (elementBottom < windowBottom && elementBottom < parentBottom) || (elementTop < 0 && elementTop < parentTop) ); }; chooseClass = (isOpen) => { return isOpen && this.isVisible(ReactDOM.findDOMNode(this.dropdown)) ? this.setState({ visibleClass: 'bottom' }) : this.setState({ visibleClass: 'top' }); }; render() { const { children } = this.props; return React.cloneElement(children, { ref: ref => (this.dropdown = ref) }); } }
JavaScript
class SetupChecks { static validate(rushConfiguration) { // NOTE: The Node.js version is also checked in rush/src/start.ts const errorMessage = SetupChecks._validate(rushConfiguration); if (errorMessage) { console.error(colors.red(Utilities_1.Utilities.wrapWords(errorMessage))); throw new AlreadyReportedError_1.AlreadyReportedError(); } } static _validate(rushConfiguration) { // Check for outdated tools if (rushConfiguration.packageManager === 'pnpm') { if (semver.lt(rushConfiguration.packageManagerToolVersion, MINIMUM_SUPPORTED_PNPM_VERSION)) { return `The rush.json file requests PNPM version ` + rushConfiguration.packageManagerToolVersion + `, but PNPM ${MINIMUM_SUPPORTED_PNPM_VERSION} is the minimum supported by Rush.`; } } else if (rushConfiguration.packageManager === 'npm') { if (semver.lt(rushConfiguration.packageManagerToolVersion, MINIMUM_SUPPORTED_NPM_VERSION)) { return `The rush.json file requests NPM version ` + rushConfiguration.packageManagerToolVersion + `, but NPM ${MINIMUM_SUPPORTED_NPM_VERSION} is the minimum supported by Rush.`; } } SetupChecks._checkForPhantomFolders(rushConfiguration); } static _checkForPhantomFolders(rushConfiguration) { const phantomFolders = []; const seenFolders = new Set(); // Check from the real parent of the common/temp folder const commonTempParent = path.dirname(node_core_library_1.FileSystem.getRealPath(rushConfiguration.commonTempFolder)); SetupChecks._collectPhantomFoldersUpwards(commonTempParent, phantomFolders, seenFolders); // Check from the real folder containing rush.json const realRushJsonFolder = node_core_library_1.FileSystem.getRealPath(rushConfiguration.rushJsonFolder); SetupChecks._collectPhantomFoldersUpwards(realRushJsonFolder, phantomFolders, seenFolders); if (phantomFolders.length > 0) { if (phantomFolders.length === 1) { console.log(colors.yellow(Utilities_1.Utilities.wrapWords('Warning: A phantom "node_modules" folder was found. This defeats Rush\'s protection against' + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' + ' delete this folder:'))); } else { console.log(colors.yellow(Utilities_1.Utilities.wrapWords('Warning: Phantom "node_modules" folders were found. This defeats Rush\'s protection against' + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' + ' delete these folders:'))); } for (const folder of phantomFolders) { console.log(colors.yellow(`"${folder}"`)); } console.log(); // add a newline } } /** * Checks "folder" and each of its parents to see if it contains a node_modules folder. * The bad folders will be added to phantomFolders. * The seenFolders set is used to avoid duplicates. */ static _collectPhantomFoldersUpwards(folder, phantomFolders, seenFolders) { // Stop if we reached a folder that we already analyzed while (!seenFolders.has(folder)) { seenFolders.add(folder); // If there is a node_modules folder under this folder, add it to the list of bad folders const nodeModulesFolder = path.join(folder, RushConstants_1.RushConstants.nodeModulesFolderName); if (node_core_library_1.FileSystem.exists(nodeModulesFolder)) { phantomFolders.push(nodeModulesFolder); } // Walk upwards const parentFolder = path.dirname(folder); if (!parentFolder || parentFolder === folder) { // If path.dirname() returns its own input, then means we reached the root break; } folder = parentFolder; } } }
JavaScript
class Exciter { constructor() { this._filter = new StmLowpassFilter(); this._amp = 0; } set stiffness(value) { // stiffness := timbre const freq = (32 * Math.pow(10, 2.7 * value)) / sampleRate; this._filter.setParams(freq, 0.5); } strike(amp) { this._amp = amp; } process() { const y = this._filter.process(this._amp); this._amp = 0; return y; } }
JavaScript
class DfuOperation { constructor(dfuUpdates, dfuTransport, autoStart = false) { this.updates = dfuUpdates.updates; this.transport = dfuTransport; if (autoStart) { this.start(); } } /** * Starts the DFU operation. Returns a Promise that resolves as soon as * the DFU has been performed (as in "everything has been sent to the * transport, and the CRCs back seem correct"). * * If called with a truthy value for the 'forceful' parameter, then * the DFU procedure will skip the steps that detect whether a previous * DFU procedure has been interrupted and can be continued. In other * words, the DFU procedure will be started from the beginning, regardless. * * Calling start() more than once has no effect, and will only return a * reference to the first Promise that was returned. * * @param {Bool} forceful if should skip the steps * @return {Promise} a Promise that resolves as soon as the DFU has been performed */ start(forceful = false) { if (this.finishPromise) { return this.finishPromise; } this.finishPromise = this.performNextUpdate(0, forceful); return this.finishPromise; } // Takes in an update from this._update, performs it. Returns a Promise // which resolves when all updates are done. // - Tell the transport to send the init packet // - Tell the transport to send the binary blob // - Proceed to the next update performNextUpdate(updateNumber, forceful) { if (this.updates.length <= updateNumber) { return Promise.resolve(); } let start; if (forceful) { start = this.transport.restart(); } else { start = Promise.resolve(); } return start .then(() => this.transport.sendInitPacket(this.updates[updateNumber].initPacket)) .then(() => this.transport.sendFirmwareImage(this.updates[updateNumber].firmwareImage)) .then(() => this.performNextUpdate(updateNumber + 1, forceful)); } }
JavaScript
class SetProcessLinkId extends Action { constructor(settings) { super(); this.title = this.name = 'SetProcessLinkId'; /** * Node parameters. * * @property parameters * @type {Object} * @property {MemoryField} parameters.processLinkId a string that the incoming post must bring in order to link the process * @property {boolean} parameters.remove set to true to remove this channel * **/ this.parameters = _.extend(this.parameters, { 'processLinkId': '', 'remove': false }); this.description = 'Set/unset a link id between processes. data then can be retrieved in other channels/processes using the Link id'; settings = settings || {}; } /** * Tick method. * * @private * @param {Tick} tick A tick instance. * @return {TickStatus} A status constant. **/ tick(tick) { try { var data = this.alldata(tick); var processLinkId = _.template(utils.wrapExpression(this.properties.processLinkId))(data); if (!this.properties.remove) { tick.process.addSearchKey('link_id', processLinkId); tick.process.save(); } else { tick.process.removeSearchKey('link_id'); tick.process.save(); } return b3.SUCCESS(); } catch (err) { dblogger.error("Error at SetProcessLinkId: " + this.summary(tick) + ":" + err.message); return b3.ERROR(); } } /** * defines validation methods to execute at the editor; if one of them fails, a dashed red border is displayed for the node * @return {Array<Validator>} */ validators(node) { function validCompositeField(field) { return field && (!isNaN(field) || (field.indexOf('message.') === 0 || field.indexOf('fsm.') === 0 || field.indexOf('context.') === 0 || field.indexOf('global.') === 0 || field.indexOf('volatile.') === 0)); } return [{ condition: validCompositeField(node.properties.processLinkId), text: "processLinkId should start with message., context., global. fsm. or volatile." }]; } }
JavaScript
class DefaultSettingsHandler extends SettingsHandler { /** * Creates a new default settings handler with the given defaults * @param {object} defaults The default setting values, keyed by setting name. * @param {object} invertedDefaults The default inverted setting values, keyed by setting name. */ constructor(defaults, invertedDefaults) { super(); this._defaults = defaults; this._invertedDefaults = invertedDefaults; } getValue(settingName, roomId) { let value = this._defaults[settingName]; if (value === undefined) { value = this._invertedDefaults[settingName]; } return value; } setValue(settingName, roomId, newValue) { throw new Error("Cannot set values on the default level handler"); } canSetValue(settingName, roomId) { return false; } isSupported() { return true; } }
JavaScript
class Json2Dom { /** ************************************************************************** * @param {Object} ctl Controller which will recive call backs. ****************************************************************************/ constructor(ctl) { this.ctl = ctl; this.elements = {}; } /** ************************************************************************** * build from json object * @param {Object} json json data * @return {DOM} builded dom ****************************************************************************/ build(json) { let elm = null; Object.keys(json).forEach((key) => { const value = json[key]; const re = key.match(/^\$(\w+)/); if (re) { const role = re[1]; elm = this.myParseJson(value, role); return; } }); return elm; } /** ************************************************************************** * load from json url * @param {String} url json url * @return {Promise} possible to wait beacon finished ****************************************************************************/ load(url) { return new Promise((resolve, reject) => { new Promise((load, fail) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener('load', () => { load(xhr); }, false); xhr.addEventListener('error', (error) => { fail(error); }, false); xhr.open('GET', url, true); xhr.send(); }).then((xhr) => { if (xhr.status !== 200) { reject(`could not get json format - ${xhr.status}`); } try { const o = JSON.parse(xhr.responseText); resolve(this.build(o)); } catch (error) { reject(`could not get json format - ${error}`); } }).catch((error) => { reject(error); }); }); } /** ************************************************************************** * parse json * @param {Object} json json data * @param {String} role target role * @return {DOM} builded dom ****************************************************************************/ myParseJson(json, role) { const capRole = Json2Dom.capitalization(role); // create element if (this.ctlFunc(`before${capRole}Create`, { data: json.data, json }) === false) { return null; } let elm; if (json.type === 'dynamic') { elm = this.ctlFunc(`dynamic${capRole}Create`, { data: json.data, json }); } else { elm = document.createElement(json.type); } if (typeof elm === 'undefined') { throw new Error(`${role} can not create any element.`); } // set attributes elm.setAttribute('role', role); elm.addEventListener('click', (e) => { this.ctlFunc(`on${capRole}Click`, { event: e, elm, data: json.data, json }); }, false); // set other attributes and child elements Object.keys(json).forEach((key) => { const value = json[key]; const re = key.match(/^\$(\w+)/); if (re) { const childRole = re[1]; const child = this.myParseJson(value, childRole); elm.appendChild(child); } else if (key === 'style') { elm.style.cssText = value; } else if (key === 'data' || key === 'type') { return; } else { elm.setAttribute(key, value); } }); // after create this.ctlFunc(`after${capRole}Create`, { data: json.data, json }); this.elements[role] = elm; return elm; } /** ************************************************************************** * controller func * @param {String} funcName controller's function name * @param {Object} option parameter option * @return {Something} return function value; ****************************************************************************/ ctlFunc(funcName, option) { if (typeof this.ctl[funcName] === 'function') { return this.ctl[funcName](option); } return null; } /** ************************************************************************** * capitalization * @param {String} str source string * @return {String} capitalized string ****************************************************************************/ static capitalization(str) { return str.charAt(0).toUpperCase() + str.slice(1); } }
JavaScript
class PageElementMap extends _1.PageNode { /** * A PageElementMap manages multiple related "static" PageElements which all have the same type and the same "base" * selector. * * The PageElements managed by PageElementMap are always known in advance and do not change (eg. navigation menu * entries). They can therefore be statically identified when PageElementMap is initially created by constraining * the map's "base" XPath selector using XPath modification functions. * * This initial identification process makes use of a `mappingObject` and a `mappingFunc` which are both defined in * PageElement's `identifier` object: * * - For each property of `mappingObject`, `mappingFunc` is invoked with the map's "base" selector as the first and * the value of the currently processed property as the second parameter. * - `mappingFunc` then constrains the "base" selector by using XPath modification functions which are passed the * values of the currently processed properties as parameters. * - Each resulting constrained selector is used to retrieve a managed PageElement from the map's PageNodeStore. * - These identified PageElements are then mapped to the corresponding key names of `mappingObject`'s properties * * The resulting object of mapped PageElements can be accessed via PageElementMap's `$` accessor. * * All of PageElementMap's state retrieval (getXXX) and state check functions (hasXXX/hasAnyXXX/containsXXX) return * their result values as a result map. This is an object whose key names or taken from PageElementMap's `$` * accessor and whose values are the results of the respective function being executed on the mapped PageElement. * * @example * // baseSelector = "//nav/a[.="Dashboard"]" * // mappingObject = {dashboard: "Dashboard"} * // * // returns '//nav/a[.="Dashboard"]' for this mappingFunc: * ( baseSelector, mappingValue ) => xpath( baseSelector ).text( mappingValue ) * * // returns {dashboard: PageElement("//nav/a[.="Dashboard"]")} * this.$ * * @param selector the "base" XPath selector of PageElementMap which is constrained to identify the map's managed * PageElements * @opts the options used to configure an instance of PageElementMap */ constructor(selector, _a) { var { identifier, elementStoreFunc, elementOpts: elementOptions } = _a, superOpts = __rest(_a, ["identifier", "elementStoreFunc", "elementOpts"]); super(selector, superOpts); this._selector = selector; this._elementOpts = elementOptions; this._elementStoreFunc = elementStoreFunc; this._identifier = identifier; this._$ = Workflo.Object.mapProperties(this._identifier.mappingObject, (value, key) => this._elementStoreFunc.apply(this._store, [ this._identifier.mappingFunc(this._selector, value), this._elementOpts, ])); this.currently = new PageElementMapCurrently(this); this.wait = new PageElementMapWait(this); this.eventually = new PageElementMapEventually(this); } /** * `$` provides access to all mapped PageElements of PageElementMap. */ get $() { return this._$; } /** * This function changes the `mappingObject` used by PageElementMap's `identifier` object to constrain the "base" * XPath selector of PageElementMap using XPath modification functions in order to statically identify a * PageElementMap's managed PageElements. * * This can be useful if, for example, the links of a navigation menu are represented using a PageElementMap and * the GUI is switched to another language: Now the values used to identify the links by text change while the keys * used to access the links via tha map's `$` property stay the same. * * @param mappingObject */ changeMappingObject(mappingObject) { this._$ = Workflo.Object.mapProperties(mappingObject, (value, key) => this._elementStoreFunc.apply(this._store, [ this._identifier.mappingFunc(this._selector, value), this._elementOpts, ])); } // GETTER FUNCTIONS /** * Returns the "base" XPath selector that identifies all PageElements managed by PageElementMap. */ getSelector() { return this._selector; } /** * Returns the texts of all PageElements managed by PageElementMap as a result map after performing the initial * waiting condition of each PageElement. * * @param filterMask can be used to skip the invocation of the `getText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getText(filterMask) { return this.eachGet(this._$, node => node.getText(), filterMask); } /** * Returns the direct texts of all PageElements managed by PageElementMap as a result map after performing the * initial waiting condition of each PageElement. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `getDirectText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getDirectText(filterMask) { return this.eachGet(this._$, node => node.getDirectText(), filterMask); } /** * Returns the 'enabled' status of all PageElements managed by PageElementMap as a result map after performing the * initial waiting condition of each PageElement. * * @param filterMask can be used to skip the invocation of the `getIsEnabled` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getIsEnabled(filterMask) { return this.eachGet(this.$, node => node.getIsEnabled(), filterMask); } /** * Returns the 'hasText' status of all PageElements managed by PageElementMap as a result map after performing the * initial waiting condition of each managed PageElement. * * A PageElement's 'hasText' status is set to true if its actual text equals the expected text. * * @param texts the expected texts used in the comparisons which set the 'hasText' status */ getHasText(texts) { return this.eachCompare(this.$, (element, expected) => element.currently.hasText(expected), texts); } /** * Returns the 'hasAnyText' status of all PageElements managed by PageElementMap as a result map after performing * the initial waiting condition of each managed PageElement. * * A PageElement's 'hasAnyText' status is set to true if the PageElement has any text. * * @param filterMask can be used to skip the invocation of the `getHasAnyText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getHasAnyText(filterMask) { return this.eachCompare(this.$, (element) => element.currently.hasAnyText(), filterMask, true); } /** * Returns the 'containsText' status of all PageElements managed by PageElementMap as a result map after performing * the initial waiting condition of each managed PageElement. * * A PageElement's 'containsText' status is set to true if its actual text contains the expected text. * * @param texts the expected texts used in the comparisons which set the 'containsText' status */ getContainsText(texts) { return this.eachCompare(this.$, (element, expected) => element.currently.containsText(expected), texts); } /** * Returns the 'hasDirectText' status of all PageElements managed by PageElementMap as a result map after performing * the initial waiting condition of each managed PageElement. * * A PageElement's 'hasDirectText' status is set to true if its actual direct text equals the expected direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts used in the comparisons which set the 'hasDirectText' status */ getHasDirectText(directTexts) { return this.eachCompare(this.$, (element, expected) => element.currently.hasDirectText(expected), directTexts); } /** * Returns the 'hasAnyDirectText' status of all PageElements managed by PageElementMap as a result map after * performing the initial waiting condition of each managed PageElement. * * A PageElement's 'hasAnyDirectText' status is set to true if the PageElement has any direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `getHasAnyDirectText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getHasAnyDirectText(filterMask) { return this.eachCompare(this.$, (element) => element.currently.hasAnyDirectText(), filterMask, true); } /** * Returns the 'containsDirectText' status of all PageElements managed by PageElementMap as a result map after * performing the initial waiting condition of each managed PageElement. * * A PageElement's 'containsDirectText' status is set to true if its actual direct text contains the expected direct * text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts used in the comparisons which set the 'containsDirectText' status */ getContainsDirectText(directTexts) { return this.eachCompare(this.$, (element, expected) => element.currently.containsDirectText(expected), directTexts); } // HELPER FUNCTIONS /** * Used to determine if a function of a managed PageElement should be invoked or if its invocation should be skipped * because the PageElement is not included by a filterMask. * * @param filter a filterMask entry that refers to a corresponding managed PageElement */ _includedInFilter(value) { return (typeof value === 'boolean' && value === true); } /** * Invokes a state check function for each PageElement in a passed `context` map and returns a map of state * check function results. * * @template T the type of an expected value * @param context a map containing all PageElements for which `checkFunc` should be executed * @param checkFunc a state check function executed for each PageElement in `context`. It is passed a PageElement as * first parameter and an expected value used by the state check comparison as an optional second parameter. * @param expected a map of expected values used for the state check comparisons * @param isFilterMask if set to true, the `expected` parameter represents a filterMask which can be used to skip the * invocation of the state check function for some or all PageElements. * The results of skipped function invocations are not included in the total results map. * @returns an map of results of a state check function executed for each PageElement in `context` */ eachCompare(context, checkFunc, expected, isFilterMask = false) { const result = {}; for (const key in context) { if (helpers_1.isNullOrUndefined(expected)) { result[key] = checkFunc(context[key]); } else { const expectedValue = expected[key]; if (isFilterMask) { if (this._includedInFilter(expectedValue)) { result[key] = checkFunc(context[key], expectedValue); } } else { if (typeof expectedValue !== 'undefined') { result[key] = checkFunc(context[key], expectedValue); } } } } return result; } /** * Invokes a state check function for each PageElement in a passed `context` map and returns true if the result of * each state check function invocation was true. * * @template T the type of an expected value * @param context a map containing all PageElements for which `checkFunc` should be executed * @param checkFunc a state check function executed for each PageElement in `context`. It is passed a PageElement as * first parameter and an expected value used by the state check comparison as an optional second parameter. * @param expected a map of expected values used for the state check comparisons * @param isFilterMask if set to true, the `expected` parameter represents a filterMask which can be used to skip the * invocation of the state check function for some or all PageElements. * The results of skipped function invocations are not included in the results map. * @returns true if the state check functions of all checked PageElements returned true or if no state check functions * were invoked at all */ eachCheck(context, checkFunc, expected, isFilterMask = false) { const diffs = {}; for (const key in context) { if (helpers_1.isNullOrUndefined(expected)) { if (!checkFunc(context[key])) { diffs[`.${key}`] = context[key].__lastDiff; } } else { if (isFilterMask) { if (this._includedInFilter(expected[key])) { if (!checkFunc(context[key])) { diffs[`.${key}`] = context[key].__lastDiff; } } } else { if (typeof expected[key] !== 'undefined') { if (!checkFunc(context[key], expected[key])) { diffs[`.${key}`] = context[key].__lastDiff; } } } } } this._lastDiff = { tree: diffs, }; return Object.keys(diffs).length === 0; } /** * Invokes a state retrieval function for each PageElement in a passed `context` map and returns a map of state * retrieval function results. * * @template T the type of a value of the results map * @param context a map containing all PageElements for which `getFunc` should be executed * @param getFunc a state retrieval function executed for each PageElement in `context`. It is passed a PageElement * as first parameter. * @param filterMask can be used to skip the invocation of the state retrieval function for some or all PageElements. * The results of skipped function invocations are not included in the total results map. * @returns an map of results of a state retrieval function executed for each PageElement in `context` */ eachGet(context, getFunc, filterMask) { const result = {}; for (const key in context) { if (helpers_1.isNullOrUndefined(filterMask)) { result[key] = getFunc(context[key]); } else { if (this._includedInFilter(filterMask[key])) { result[key] = getFunc(context[key]); } } } return result; } /** * Invokes a wait function for each PageElement in a passed `context` map. * * @template T the type of an expected value * @param context a map containing all PageElements for which `checkFunc` should be executed * @param waitFunc a wait function executed for each PageElement in `context`. It is passed a PageElement as * first parameter and an expected value used by the wait condition as an optional second parameter. * @param expected a map of expected values used for the wait conditions * @param isFilterMask if set to true, the `expected` parameter represents a filterMask which can be used to skip the * invocation of the wait function for some or all PageElements. * @returns this (an instance of PageElementMap) */ eachWait(context, waitFunc, expected, isFilterMask = false) { for (const key in context) { if (helpers_1.isNullOrUndefined(expected)) { waitFunc(context[key]); } else { if (isFilterMask) { if (this._includedInFilter(expected[key])) { waitFunc(context[key]); } } else if (typeof expected[key] !== 'undefined') { waitFunc(context[key], expected[key]); } } } return this; } /** * Invokes an action for each of PageElementMap's managed PageElements. * * @param action an action executed for each of PageElementMap's managed PageElements * @param filterMask can be used to skip the execution of an action for some or all PageElements * @returns this (an instance of PageElementMap) */ eachDo(action, filterMask) { const context = this.$; for (const key in context) { if (helpers_1.isNullOrUndefined(filterMask)) { action(context[key]); } else { if (this._includedInFilter(filterMask[key])) { action(context[key]); } } } return this; } /** * Invokes a setter function for each PageElement in a passed `context` map. * * @template T the type of a single setter value * @param context a map containing all PageElements for which `setFunc` should be executed * @param setFunc a setter function executed for each PageElement in `context`. It is passed a PageElement as * first parameter and the value to be set as second parameter. * @param values a map of setter values * @returns this (an instance of PageElementMap) */ eachSet(context, setFunc, values) { for (const key in context) { if (values) { if (typeof values[key] !== 'undefined') { setFunc(context[key], values[key]); } } else { setFunc(context[key]); } } return this; } }
JavaScript
class PageElementMapCurrently extends _1.PageNodeCurrently { /** * Returns the current texts of all PageElements managed by PageElementMap as a result map. * * @param filterMask can be used to skip the invocation of the `getText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getText(filterMask) { return this._node.eachGet(this._node.$, node => node.currently.getText(), filterMask); } /** * Returns the current direct texts of all PageElements managed by PageElementMap as a result map. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `getDirectText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getDirectText(filterMask) { return this._node.eachGet(this._node.$, node => node.currently.getDirectText(), filterMask); } /** * Returns the current 'exists' status of all PageElements managed by PageElementMap as a result map. * * @param filterMask can be used to skip the invocation of the `getExists` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getExists(filterMask) { return this._node.eachGet(this._node.$, node => node.currently.exists(), filterMask); } /** * Returns the current 'visible' status of all PageElements managed by PageElementMap as a result map. * * @param filterMask can be used to skip the invocation of the `getIsVisible` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getIsVisible(filterMask) { return this._node.eachGet(this._node.$, node => node.currently.isVisible(), filterMask); } /** * Returns the current 'enabled' status of all PageElements managed by PageElementMap as a result map. * * @param filterMask can be used to skip the invocation of the `getIsEnabled` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getIsEnabled(filterMask) { return this._node.eachGet(this._node.$, node => node.currently.isEnabled(), filterMask); } /** * Returns the current 'hasText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'hasText' status is set to true if its actual text equals the expected text. * * @param texts the expected texts used in the comparisons which set the 'hasText' status */ getHasText(texts) { return this._node.eachCompare(this._node.$, (element, expected) => element.currently.hasText(expected), texts); } /** * Returns the current 'hasAnyText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'hasAnyText' status is set to true if the PageElement has any text. * * @param filterMask can be used to skip the invocation of the `getHasAnyText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getHasAnyText(filterMask) { return this._node.eachCompare(this._node.$, (element) => element.currently.hasAnyText(), filterMask, true); } /** * Returns the current 'containsText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'containsText' status is set to true if its actual text contains the expected text. * * @param texts the expected texts used in the comparisons which set the 'containsText' status */ getContainsText(texts) { return this._node.eachCompare(this._node.$, (element, expected) => element.currently.containsText(expected), texts); } /** * Returns the current 'hasDirectText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'hasDirectText' status is set to true if its actual direct text equals the expected direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts used in the comparisons which set the 'hasDirectText' status */ getHasDirectText(directTexts) { return this._node.eachCompare(this._node.$, (element, expected) => element.currently.hasDirectText(expected), directTexts); } /** * Returns the current 'hasAnyDirectText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'hasAnyDirectText' status is set to true if the PageElement has any direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `getHasAnyDirectText` function for some or all managed * PageElements. The results of skipped function invocations are not included in the total results object. */ getHasAnyDirectText(filterMask) { return this._node.eachCompare(this._node.$, (element) => element.currently.hasAnyDirectText(), filterMask, true); } /** * Returns the current 'containsDirectText' status of all PageElements managed by PageElementMap as a result map. * * A PageElement's 'containsDirectText' status is set to true if its actual direct text contains the expected direct * text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts used in the comparisons which set the 'containsDirectText' status */ getContainsDirectText(directTexts) { return this._node.eachCompare(this._node.$, (element, expected) => element.currently.containsDirectText(expected), directTexts); } /** * Returns true if all PageElements managed by PageElementMap currently exist. * * @param filterMask can be used to skip the invocation of the `exists` function for some or all managed * PageElements */ exists(filterMask) { return this._node.eachCheck(this._node.$, element => element.currently.exists(), filterMask, true); } /** * Returns true if all PageElements managed by PageElementMap are currently visible. * * @param filterMask can be used to skip the invocation of the `isVisible` function for some or all managed * PageElements */ isVisible(filterMask) { return this._node.eachCheck(this._node.$, element => element.currently.isVisible(), filterMask, true); } /** * Returns true if all PageElements managed by PageElementMap are currently enabled. * * @param filterMask can be used to skip the invocation of the `isEnabled` function for some or all managed * PageElements */ isEnabled(filterMask) { return this._node.eachCheck(this._node.$, element => element.currently.isEnabled(), filterMask, true); } /** * Returns true if the actual texts of all PageElements managed by PageElementMap currently equal the expected texts. * * @param texts the expected texts supposed to equal the actual texts */ hasText(texts) { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.hasText(expected), texts); } /** * Returns true if all PageElements managed by PageElementMap currently have any text. * * @param filterMask can be used to skip the invocation of the `hasAnyText` function for some or all managed * PageElements */ hasAnyText(filterMask) { return this._node.eachCheck(this._node.$, (element) => element.currently.hasAnyText(), filterMask, true); } /** * Returns true if the actual texts of all PageElements managed by PageElementMap currently contain the expected * texts. * * @param texts the expected texts supposed to be contained in the actual texts */ containsText(texts) { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.containsText(expected), texts); } /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently equal the expected * direct texts. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed to equal the actual direct texts */ hasDirectText(directTexts) { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.hasDirectText(expected), directTexts); } /** * Returns true if all PageElements managed by PageElementMap currently have any direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `hasAnyDirectText` function for some or all managed * PageElements */ hasAnyDirectText(filterMask) { return this._node.eachCheck(this._node.$, (element) => element.currently.hasAnyDirectText(), filterMask, true); } /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently contain the * expected direct texts. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed to be contained in the actual direct texts */ containsDirectText(directTexts) { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.containsDirectText(expected), directTexts); } /** * returns the negated variants of PageElementMapCurrently's state check functions */ get not() { return { /** * Returns true if all PageElements managed by PageElementMap currently do not exist. * * @param filterMask can be used to skip the invocation of the `exists` function for some or all managed * PageElements */ exists: (filterMask) => { return this._node.eachCheck(this._node.$, element => element.currently.not.exists(), filterMask, true); }, /** * Returns true if all PageElements managed by PageElementMap are currently not visible. * * @param filterMask can be used to skip the invocation of the `isVisible` function for some or all managed * PageElements */ isVisible: (filterMask) => { return this._node.eachCheck(this._node.$, element => element.currently.not.isVisible(), filterMask, true); }, /** * Returns true if all PageElements managed by PageElementMap are currently not enabled. * * @param filterMask can be used to skip the invocation of the `isEnabled` function for some or all managed * PageElements */ isEnabled: (filterMask) => { return this._node.eachCheck(this._node.$, element => element.currently.not.isEnabled(), filterMask, true); }, /** * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not equal the * expected texts. * * @param texts the expected texts supposed not to equal the actual texts */ hasText: (text) => { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasText(expected), text); }, /** * Returns true if all PageElements managed by PageElementMap currently do not have any text. * * @param filterMask can be used to skip the invocation of the `hasAnyText` function for some or all managed * PageElements */ hasAnyText: (filterMask) => { return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyText(), filterMask, true); }, /** * Returns true if the actual texts of all PageElements managed by PageElementMap currently do not contain the * expected texts. * * @param texts the expected texts supposed not to be contained in the actual texts */ containsText: (text) => { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsText(expected), text); }, /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not equal * the expected direct texts. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed not to equal the actual direct texts */ hasDirectText: (directText) => { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.hasDirectText(expected), directText); }, /** * Returns true if all PageElements managed by PageElementMap currently do not have any direct text. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param filterMask can be used to skip the invocation of the `hasAnyDirectText` function for some or all managed * PageElements */ hasAnyDirectText: (filterMask) => { return this._node.eachCheck(this._node.$, (element) => element.currently.not.hasAnyDirectText(), filterMask, true); }, /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap currently do not contain * the expected direct texts. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts */ containsDirectText: (directText) => { return this._node.eachCheck(this._node.$, (element, expected) => element.currently.not.containsDirectText(expected), directText); }, }; } }
JavaScript
class PageElementMapWait extends _1.PageNodeWait { /** * Waits for all PageElements managed by PageElementMap to exist. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `exists` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ exists(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.exists(otherOpts), filterMask, true); } /** * Waits for all PageElements managed by PageElementMap to be visible. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isVisible` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ isVisible(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.isVisible(otherOpts), filterMask, true); } /** * Waits for all PageElements managed by PageElementMap to be enabled. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isEnabled` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ isEnabled(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.isEnabled(otherOpts), filterMask, true); } /** * Waits for the actual texts of all PageElements managed by PageElementMap to equal the expected texts. * * Throws an error if the condition is not met within a specific timeout. * * @param texts the expected texts supposed to equal the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasText(texts, opts) { return this._node.eachWait(this._node.$, (element, expected) => element.wait.hasText(expected, opts), texts); } /** * Waits for all PageElements managed by PageElementMap to have any text. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyText` function for some * or all managed PageElements, the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasAnyText(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, (element) => element.wait.hasAnyText(otherOpts), filterMask, true); } /** * Waits for the actual texts of all PageElements managed by PageElementMap to contain the expected texts. * * Throws an error if the condition is not met within a specific timeout. * * @param texts the expected texts supposed to be contained in the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ containsText(texts, opts) { return this._node.eachWait(this._node.$, (element, expected) => element.wait.containsText(expected, opts), texts); } /** * Waits for the actual direct texts of all PageElements managed by PageElementMap to equal the expected direct texts. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed to equal the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasDirectText(directTexts, opts) { return this._node.eachWait(this._node.$, (element, expected) => element.wait.hasDirectText(expected, opts), directTexts); } /** * Waits for all PageElements managed by PageElementMap to have any direct text. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyDirectText` function for * some or all managed PageElements, the `timeout` within which the condition is expected to be met and the `interval` * used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasAnyDirectText(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, (element) => element.wait.hasAnyDirectText(otherOpts), filterMask, true); } /** * Waits for the actual direct texts of all PageElements managed by PageElementMap to contain the expected direct * texts. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed to be contained in the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ containsDirectText(directTexts, opts) { return this._node.eachWait(this._node.$, (element, expected) => element.wait.containsDirectText(expected, opts), directTexts); } /** * returns the negated variants of PageElementMapWait's state check functions */ get not() { return { /** * Waits for all PageElements managed by PageElementMap not to exist. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `exists` function for * some or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ exists: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.not.exists(otherOpts), filterMask, true); }, /** * Waits for all PageElements managed by PageElementMap not to be visible. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isVisible` function for * some or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ isVisible: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.not.isVisible(otherOpts), filterMask, true); }, /** * Waits for all PageElements managed by PageElementMap not to be enabled. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isEnabled` function for * some or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. * * @returns this (an instance of PageElementMap) */ isEnabled: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, element => element.wait.not.isEnabled(otherOpts), filterMask, true); }, /** * Waits for the actual texts of all PageElements managed by PageElementMap not to equal the expected texts. * * Throws an error if the condition is not met within a specific timeout. * * @param texts the expected texts supposed not to equal the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasText: (texts, opts) => { return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.hasText(expected, opts), texts); }, /** * Waits for all PageElements managed by PageElementMap not to have any text. * * Throws an error if the condition is not met within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyText` function for * some or all managed PageElements, the `timeout` within which the condition is expected to be met and the * `interval` used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasAnyText: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, (element) => element.wait.not.hasAnyText(otherOpts), filterMask, true); }, /** * Waits for the actual texts of all PageElements managed by PageElementMap not to contain the expected texts. * * Throws an error if the condition is not met within a specific timeout. * * @param texts the expected texts supposed not to be contained in the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ containsText: (texts, opts) => { return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.containsText(expected, opts), texts); }, /** * Waits for the actual direct texts of all PageElements managed by PageElementMap not to equal the expected * direct texts. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts not supposed to equal the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasDirectText: (directTexts, opts) => { return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.hasDirectText(expected, opts), directTexts); }, /** * Waits for all PageElements managed by PageElementMap not to have any direct text. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyDirectText` function * for some or all managed PageElements, the `timeout` within which the condition is expected to be met and the * `interval` used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ hasAnyDirectText: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachWait(this._node.$, (element) => element.wait.not.hasAnyDirectText(otherOpts), filterMask, true); }, /** * Waits for the actual direct texts of all PageElements managed by PageElementMap not to contain the expected * direct texts. * * Throws an error if the condition is not met within a specific timeout. * * A direct text is a text that resides on the level directly below the selected HTML element. * It does not include any text of the HTML element's nested children HTML elements. * * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. * * @returns this (an instance of PageElementMap) */ containsDirectText: (directTexts, opts) => { return this._node.eachWait(this._node.$, (element, expected) => element.wait.not.containsDirectText(expected, opts), directTexts); }, }; } }
JavaScript
class PageElementMapEventually extends _1.PageNodeEventually { /** * Returns true if all PageElements managed by PageElementMap eventually exist within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `exists` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ exists(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.exists(otherOpts), filterMask, true); } /** * Returns true if all PageElements managed by PageElementMap eventually are visible within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isVisible` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ isVisible(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.isVisible(otherOpts), filterMask, true); } /** * Returns true if all PageElements managed by PageElementMap eventually are enabled within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isEnabled` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ isEnabled(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.isEnabled(otherOpts), filterMask, true); } /** * Returns true if the actual texts of all PageElements managed by PageElementMap eventually equal the expected texts * within a specific timeout. * * @param texts the expected texts supposed to equal the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasText(texts, opts) { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.hasText(expected, opts), texts); } /** * Returns true if all PageElements managed by PageElementMap eventually have any text within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyText` function for some * or all managed PageElements, the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasAnyText(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, (element) => element.eventually.hasAnyText(otherOpts), filterMask, true); } /** * Returns true if the actual texts of all PageElements managed by PageElementMap eventually contain the expected * texts within a specific timeout. * * @param texts the expected texts supposed to be contained in the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ containsText(texts, opts) { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.containsText(expected, opts), texts); } /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap eventually equal the expected * direct texts within a specific timeout. * * @param directTexts the expected direct texts supposed to equal the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasDirectText(directTexts, opts) { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.hasDirectText(expected, opts), directTexts); } /** * Returns true if all PageElements managed by PageElementMap eventually have any direct text within a specific * timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyDirectText` function for * some or all managed PageElements, the `timeout` within which the condition is expected to be met and the `interval` * used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasAnyDirectText(opts = {}) { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, (element) => element.eventually.hasAnyDirectText(otherOpts), filterMask, true); } /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap eventually contain the * expected direct texts within a specific timeout. * * @param directTexts the expected direct texts supposed to be contained in the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ containsDirectText(directTexts, opts) { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.containsDirectText(expected, opts), directTexts); } /** * returns the negated variants of PageElementMapEventually's state check functions */ get not() { return { /** * Returns true if all PageElements managed by PageElementMap eventually do not exist within a specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `exists` function for some * or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ exists: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.not.exists(otherOpts), filterMask, true); }, /** * Returns true if all PageElements managed by PageElementMap eventually are not visible within a specific * timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isVisible` function for * some or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ isVisible: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.not.isVisible(otherOpts), filterMask, true); }, /** * Returns true if all PageElements managed by PageElementMap eventually are not enabled within a specific * timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `isEnabled` function for * some or all managed PageElements and the `timeout` within which the condition is expected to be met * * If no `timeout` is specified, a PageElement's default timeout is used. */ isEnabled: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, element => element.eventually.not.isEnabled(otherOpts), filterMask, true); }, /** * Returns true if the actual texts of all PageElements managed by PageElementMap eventually do not equal the * expected texts within a specific timeout. * * @param texts the expected texts supposed not to equal the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasText: (texts, opts) => { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.not.hasText(expected, opts), texts); }, /** * Returns true if all PageElements managed by PageElementMap eventually do not have any text within a specific * timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyText` function for * some or all managed PageElements, the `timeout` within which the condition is expected to be met and the * `interval` used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasAnyText: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, (element) => element.eventually.not.hasAnyText(otherOpts), filterMask, true); }, /** * Returns true if the actual texts of all PageElements managed by PageElementMap eventually do not contain the * expected texts within a specific timeout. * * @param texts the expected texts supposed not to be contained in the actual texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ containsText: (texts, opts) => { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.not.containsText(expected, opts), texts); }, /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap eventually do not equal * the expected direct texts within a specific timeout. * * @param directTexts the expected direct texts supposed not to equal the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasDirectText: (directTexts, opts) => { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.not.hasDirectText(expected, opts), directTexts); }, /** * Returns true if all PageElements managed by PageElementMap eventually do not have any direct text within a * specific timeout. * * @param opts includes a `filterMask` which can be used to skip the invocation of the `hasAnyDirectText` function * for some or all managed PageElements, the `timeout` within which the condition is expected to be met and the * `interval` used to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ hasAnyDirectText: (opts = {}) => { const { filterMask } = opts, otherOpts = __rest(opts, ["filterMask"]); return this._node.eachCheck(this._node.$, (element) => element.eventually.not.hasAnyDirectText(otherOpts), filterMask, true); }, /** * Returns true if the actual direct texts of all PageElements managed by PageElementMap eventually do not contain * the expected direct texts within a specific timeout. * * @param directTexts the expected direct texts supposed not to be contained in the actual direct texts * @param opts includes the `timeout` within which the condition is expected to be met and the `interval` used * to check it * * If no `timeout` is specified, a PageElement's default timeout is used. * If no `interval` is specified, a PageElement's default interval is used. */ containsDirectText: (directTexts, opts) => { return this._node.eachCheck(this._node.$, (element, expected) => element.eventually.not.containsDirectText(expected, opts), directTexts); }, }; } }
JavaScript
class ColorPicker extends Component { constructor () { super() this.state = {colors: []} this.getSystemColors = _ => JSON.parse(window.localStorage.getItem('oui.colorpicker')) || [] this.setSystemColors = colors => window.localStorage.setItem('oui.colorpicker', JSON.stringify(colors)) this.onColorChange = hsv => { let color = getConverterForColorType(this.props.value).invert(hsv) this.props.onChange(color) } } onAddColorClick (color) { let colors = this.getSystemColors() colors.push(color) this.setSystemColors(colors) this.forceUpdate() } onRemoveColorClick (color, index) { let colors = this.getSystemColors() colors.splice(index, 1) this.setSystemColors(colors) this.forceUpdate() } componentWillMount () { this.setState({ open: this.props.open }) } render () { let { value, label, style, palette } = this.props let { open } = this.state let toHsv = getConverterForColorType(value) let hsvColor = toHsv(value) return <div style={{ ...base, ...style, height: 'auto' }}> <div style={{display: 'flex', alignItems: 'center'}} onClick={v => this.setState({open: !open})}> <label>{label}</label> <span style={{ ...colorDropletStyle, marginLeft: 'auto', backgroundColor: Colr.fromHsvObject(hsvColor).toHex() }}></span> </div> {open ? <div> <HSVColorPicker style={style} value={hsvColor} onChange={this.onColorChange} /> <Palette key={'user-palette'} values={palette.map(toHsv)} onSelect={this.onColorChange} /> <Palette key={'system-palette'} values={this.getSystemColors()} onSelect={this.onColorChange} onDeselect={this.onRemoveColorClick.bind(this)} /> <div onClick={e => this.onAddColorClick(toHsv(value))} /> </div> : null} </div> } }
JavaScript
class PackageJsonLoader { /** * initialize PackageJsonLoader. * @param {String} pkgName : package name * @param {String} version : package version * @param {Boolean} unpkg : use unpkg.com for registry */ constructor(pkgName, version, unpkg=false) { this._pkgName = pkgName; this._version = version; this._unpkg = unpkg; this._packageJson = packageJson; this._unpkgJson = unpkgJson; } /** * load package json. * if pkgName was configured, search package.json at npm registry. * if pkgName was not configured, throws error * @returns {Promise} resolve with package.json */ load() { return new Promise((resolve, reject) => { if (!this._pkgName) { reject(new Error('pkgName is required')); } else { this._fetchPackageJson() .then((result) => { resolve(result); }) .catch((err) => { reject(err); }); } }) } /** * fetch package json from npm registry. * @param {String} pkgName * @returns {Promise} package.json */ _fetchPackageJson() { let name = this._pkgName; if (!this._unpkg) { return this._packageJson(name, { version: this._version || 'latest', fullMetadata: true }) } else { if (this._version) { name = `${this._pkgName}@${this._version}` } return this._unpkgJson(name); } } }
JavaScript
class SnippetSerializer { static isDevelopment = process.env.NODE_ENV === `production`; /** * Serializes a Snippet object into JSON files. * @param {Snippet} snippet - A snippet object. * @throws Will throw an error if `snippet` is not of the appropriate type. */ static serializeSnippet = snippet => { if (!(snippet instanceof Snippet)) { throw new ArgsError( "Invalid arguments. 'snippet' must be an instance of 'Snippet'." ); } const boundLog = Logger.bind('serializers.snippet.serializeSnippet'); const { contentPath: outDirPath } = global.settings.paths; let chunkPairs = [ [ 'index', Chunk.createIndex( snippet.slug, 'SnippetPage', (snippet.ranking * 0.85).toFixed(2), { vscodeUrl: snippet.vscodeUrl, isUnlisted: !snippet.isListed, } ), ], [ 'snippet', { snippet: new SnippetContext(snippet).toObject({ withVscodeUrl: Boolean(this.isDevelopment), }), }, ], [ 'metadata', { cardTemplate: snippet.config.cardTemplate, breadcrumbs: snippet.breadcrumbs, pageDescription: snippet.seoDescription, }, ], ]; // This check here is to make sure we don't serialize data we don't have. if (Object.prototype.hasOwnProperty.call(snippet, 'recommendedSnippets')) chunkPairs.push([ 'recommendations', { recommendedSnippets: snippet.recommendedSnippets.map(s => new SnippetPreview(s).toObject() ), }, ]); try { return JSONSerializer.serializeToDir( `${outDirPath}/${snippet.slug.slice(1)}`, ...chunkPairs ); } catch (err) { boundLog(`Encountered an error while serializing ${snippet.id}`, 'error'); boundLog(`${err}`, 'error'); throw err; } }; }
JavaScript
class InputError extends Error { constructor (...params) { // Pass remaining arguments (including vendor specific ones) to parent constructor super (...params); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) Error.captureStackTrace(this, InputError); this.name = 'InputError'; this.date = new Date(); }; }
JavaScript
class Pacman extends Character { constructor(img, canvas, windowWidth, row, col) { super(img, canvas, windowWidth, row, col); // this.sprite = new PIXI.Sprite(); // let graphic = new PIXI.Graphics(); // this.sprite.addChild(graphic); // this.drawPacman(Math.PI / 6); this.graphic = new PIXI.Graphics(); this.sprite.addChild(this.graphic); this.drunk = false; this.replacePacman(); this.resizePacman(); } /* Do math to define Pac-Man's * mouth based on the heading */ defineMouth(angle, radius) { let mouthCoords = [0, 0, 0, 0, 0, 0]; let x = this.sprite.getChildAt(0).x; let y = this.sprite.getChildAt(0).y; switch (this.heading) { case "up": mouthCoords[0] = x + Math.cos(angle + (Math.PI * 3) / 2) * radius; mouthCoords[1] = y + Math.sin(angle + (Math.PI * 3) / 2) * radius; mouthCoords[2] = x - Math.cos(angle + (Math.PI * 3) / 2) * radius; mouthCoords[3] = mouthCoords[1]; mouthCoords[4] = (Math.PI * 3) / 2 + angle; mouthCoords[5] = (Math.PI * 3) / 2 - angle; break; case "down": mouthCoords[0] = x + Math.cos(angle + (Math.PI * 3) / 2) * radius; mouthCoords[1] = y - Math.sin(angle + (Math.PI * 3) / 2) * radius; mouthCoords[2] = x - Math.cos(angle + (Math.PI * 3) / 2) * radius; mouthCoords[3] = mouthCoords[1]; mouthCoords[4] = Math.PI / 2 + angle; mouthCoords[5] = Math.PI / 2 - angle; break; case "left": mouthCoords[0] = x + Math.cos(angle + Math.PI) * radius; mouthCoords[1] = y + Math.sin(angle + Math.PI) * radius; mouthCoords[2] = mouthCoords[0]; mouthCoords[3] = y - Math.sin(angle + Math.PI) * radius; mouthCoords[4] = Math.PI + angle; mouthCoords[5] = Math.PI - angle; break; case "right": mouthCoords[0] = x + Math.cos(angle) * radius; mouthCoords[1] = y - Math.sin(angle) * radius; mouthCoords[2] = x + Math.cos(angle) * radius; mouthCoords[3] = y + Math.sin(angle) * radius; mouthCoords[4] = angle; mouthCoords[5] = Math.PI * 2 - angle; break; } return mouthCoords; } drawPacman(angle) { let radius = 0.02 * window.innerWidth; let mouthCoords = this.defineMouth(angle, radius); let graphic = this.sprite.getChildAt(0); graphic.lineStyle(1, 0x000000); // Draw body graphic.beginFill(0xf7fd04); graphic.drawCircle(graphic.x, graphic.y, radius); graphic.endFill(); graphic.beginFill(0x000000); // Draw mouth front graphic.arc( graphic.x, graphic.y, radius, mouthCoords[4], mouthCoords[5], true ); // Draw mouth back graphic.drawPolygon([ graphic.x, graphic.y, mouthCoords[0], mouthCoords[1], mouthCoords[2], mouthCoords[3], ]); graphic.endFill(); } animateMouth(delta) { let angle = (Math.PI / 8) * (1 + Math.sin(delta * 2)); // this.sprite.clear(); this.drawPacman(angle); } }
JavaScript
class CompositeErrorInterceptor extends ErrorInterceptor { constructor(a, b) { super(); assert.argumentIsRequired(a, 'a', ErrorInterceptor, 'ErrorInterceptor'); assert.argumentIsRequired(b, 'b', ErrorInterceptor, 'ErrorInterceptor'); this._a = a; this._b = b; } _onProcess(error, endpoint) { return this._a.process(error, endpoint) .catch((adjusted) => { return this._b.process(adjusted, endpoint); }); } toString() { return '[CompositeErrorInterceptor]'; } }
JavaScript
class TreeNode { constructor(val) { this.val = val; this.left_ptr = null; this.right_ptr = null; } }
JavaScript
class NetworkTargetGroup extends base_target_group_1.TargetGroupBase { /** * @stability stable */ constructor(scope, id, props) { const proto = props.protocol || enums_1.Protocol.TCP; util_1.validateNetworkProtocol(proto); super(scope, id, props, { protocol: proto, port: props.port, }); this.listeners = []; if (props.proxyProtocolV2 != null) { this.setAttribute('proxy_protocol_v2.enabled', props.proxyProtocolV2 ? 'true' : 'false'); } if (props.preserveClientIp !== undefined) { this.setAttribute('preserve_client_ip.enabled', props.preserveClientIp ? 'true' : 'false'); } this.addTarget(...(props.targets || [])); } /** * Import an existing target group. * * @stability stable */ static fromTargetGroupAttributes(scope, id, attrs) { return new ImportedNetworkTargetGroup(scope, id, attrs); } /** * (deprecated) Import an existing listener. * * @deprecated Use `fromTargetGroupAttributes` instead */ static import(scope, id, props) { return NetworkTargetGroup.fromTargetGroupAttributes(scope, id, props); } /** * Add a load balancing target to this target group. * * @stability stable */ addTarget(...targets) { for (const target of targets) { const result = target.attachToNetworkTargetGroup(this); this.addLoadBalancerTarget(result); } } /** * Register a listener that is load balancing to this target group. * * Don't call this directly. It will be called by listeners. * * @stability stable */ registerListener(listener) { this.loadBalancerAttachedDependencies.add(listener); this.listeners.push(listener); } /** * The number of targets that are considered healthy. * * @default Average over 5 minutes * @stability stable */ metricHealthyHostCount(props) { return this.metric('HealthyHostCount', { statistic: 'Average', ...props, }); } /** * The number of targets that are considered unhealthy. * * @default Average over 5 minutes * @stability stable */ metricUnHealthyHostCount(props) { return this.metric('UnHealthyHostCount', { statistic: 'Average', ...props, }); } /** * Full name of first load balancer. * * @stability stable */ get firstLoadBalancerFullName() { if (this.listeners.length === 0) { throw new Error('The TargetGroup needs to be attached to a LoadBalancer before you can call this method'); } return base_target_group_1.loadBalancerNameFromListenerArn(this.listeners[0].listenerArn); } /** * Validate the current construct. * * This method can be implemented by derived constructs in order to perform * validation logic. It is called on all constructs before synthesis. * * @stability stable */ validate() { const ret = super.validate(); const healthCheck = this.healthCheck || {}; const allowedIntervals = [10, 30]; if (healthCheck.interval) { const seconds = healthCheck.interval.toSeconds(); if (!cdk.Token.isUnresolved(seconds) && !allowedIntervals.includes(seconds)) { ret.push(`Health check interval '${seconds}' not supported. Must be one of the following values '${allowedIntervals.join(',')}'.`); } } if (healthCheck.healthyThresholdCount) { const thresholdCount = healthCheck.healthyThresholdCount; if (thresholdCount < 2 || thresholdCount > 10) { ret.push(`Healthy Threshold Count '${thresholdCount}' not supported. Must be a number between 2 and 10.`); } } if (healthCheck.unhealthyThresholdCount) { const thresholdCount = healthCheck.unhealthyThresholdCount; if (thresholdCount < 2 || thresholdCount > 10) { ret.push(`Unhealthy Threshold Count '${thresholdCount}' not supported. Must be a number between 2 and 10.`); } } if (healthCheck.healthyThresholdCount && healthCheck.unhealthyThresholdCount && healthCheck.healthyThresholdCount !== healthCheck.unhealthyThresholdCount) { ret.push([ `Healthy and Unhealthy Threshold Counts must be the same: ${healthCheck.healthyThresholdCount}`, `is not equal to ${healthCheck.unhealthyThresholdCount}.`, ].join(' ')); } if (!healthCheck.protocol) { return ret; } if (!NLB_HEALTH_CHECK_PROTOCOLS.includes(healthCheck.protocol)) { ret.push(`Health check protocol '${healthCheck.protocol}' is not supported. Must be one of [${NLB_HEALTH_CHECK_PROTOCOLS.join(', ')}]`); } if (healthCheck.path && !NLB_PATH_HEALTH_CHECK_PROTOCOLS.includes(healthCheck.protocol)) { ret.push([ `'${healthCheck.protocol}' health checks do not support the path property.`, `Must be one of [${NLB_PATH_HEALTH_CHECK_PROTOCOLS.join(', ')}]`, ].join(' ')); } if (healthCheck.timeout && healthCheck.timeout.toSeconds() !== NLB_HEALTH_CHECK_TIMEOUTS[healthCheck.protocol]) { ret.push([ 'Custom health check timeouts are not supported for Network Load Balancer health checks.', `Expected ${NLB_HEALTH_CHECK_TIMEOUTS[healthCheck.protocol]} seconds for ${healthCheck.protocol}, got ${healthCheck.timeout.toSeconds()}`, ].join(' ')); } return ret; } metric(metricName, props) { return new cloudwatch.Metric({ namespace: 'AWS/NetworkELB', metricName, dimensions: { LoadBalancer: this.firstLoadBalancerFullName, TargetGroup: this.targetGroupFullName }, ...props, }).attachTo(this); } }
JavaScript
class ImportedNetworkTargetGroup extends imported_1.ImportedTargetGroupBase { registerListener(_listener) { // Nothing to do, we know nothing of our members } addTarget(...targets) { for (const target of targets) { const result = target.attachToNetworkTargetGroup(this); if (result.targetJson !== undefined) { throw new Error('Cannot add a non-self registering target to an imported TargetGroup. Create a new TargetGroup instead.'); } } } }
JavaScript
class PinVerificationScreen extends React.Component { static propTypes = { // Authorizes assigning points by PIN authorizePointsByPin: func, // place: placeShape, // Reward being stamped or redeemed reward: rewardShape, // True if he user want to redeem a reward, false otherwise redeem: bool, // Redeems a reward redeemReward: func, // Verifies the entered PIN verifyPin: func, }; constructor(props) { super(props); this.handleNext = this.handleNext.bind(this); this.state = {}; } onPinVerified(pin) { const { redeemReward, redeem, reward } = this.props; const authorization = { authorizationType: 'pin', data: { pin } }; // If the user wants to redeem a reward, we do it automatically by substracting the // required number of points from his punch or loyalty card if (redeem) { redeemReward({ points: -reward.pointsRequired }, authorization, reward); return; } this.navigateToNextStep(authorization); } handleNext() { const { verifyPin, place } = this.props; const { pin } = this.state; const locationId = _.get(place, 'id'); verifyPin(pin, locationId) .then(() => { this.onPinVerified(pin); }) .catch(onWrongPin); } navigateToNextStep(authorization) { const { authorizePointsByPin, place, reward } = this.props; authorizePointsByPin(authorization, place, reward); } renderPinComponent() { return ( <TextInput autoFocus placeholder={I18n.t(ext('pinPlaceholder'))} autoCapitalize="none" autoCorrect={false} keyboardAppearance="light" onChangeText={pin => this.setState({ pin })} returnKeyType="done" secureTextEntry /> ); } render() { return ( <Screen> <NavigationBar title={I18n.t(ext('pinVerificationNavBarTitle'))} /> <View styleName="lg-gutter-top vertical"> <Subtitle styleName="h-center md-gutter-bottom">{I18n.t(ext('cashierVerificationMessage'))}</Subtitle> {this.renderPinComponent()} <Button styleName="full-width inflexible lg-gutter-vertical" onPress={this.handleNext} > <Text>{I18n.t(ext('rewardRedemptionContinueButton'))}</Text> </Button> </View> </Screen> ); } }
JavaScript
class ViewContainerRef { /** * @private */ constructor(viewManager, element) { this.viewManager = viewManager; this.element = element; } _getViews() { var vc = internalView(this.element.parentView).viewContainers[this.element.boundElementIndex]; return isPresent(vc) ? vc.views : []; } /** * Remove all {@link ViewRef}s at current location. */ clear() { for (var i = this.length - 1; i >= 0; i--) { this.remove(i); } } /** * Return a {@link ViewRef} at specific index. */ get(index) { return this._getViews()[index].ref; } /** * Returns number of {@link ViewRef}s currently attached at this location. */ get length() { return this._getViews().length; } /** * Create and insert a {@link ViewRef} into the view-container. * * - `protoViewRef` (optional) {@link ProtoViewRef} - The `ProtoView` to use for creating * `View` to be inserted at this location. If `ViewContainer` is created at a location * of inline template, then `protoViewRef` is the `ProtoView` of the template. * - `atIndex` (optional) `number` - location of insertion point. (Or at the end if unspecified.) * - `context` (optional) {@link ElementRef} - Context (for expression evaluation) from the * {@link ElementRef} location. (Or current context if unspecified.) * - `bindings` (optional) Array of {@link ResolvedBinding} - Used for configuring * `ElementInjector`. * * Returns newly created {@link ViewRef}. */ // TODO(rado): profile and decide whether bounds checks should be added // to the methods below. createEmbeddedView(templateRef, atIndex = -1) { if (atIndex == -1) atIndex = this.length; return this.viewManager.createEmbeddedViewInContainer(this.element, atIndex, templateRef); } createHostView(protoViewRef = null, atIndex = -1, dynamicallyCreatedBindings = null) { if (atIndex == -1) atIndex = this.length; return this.viewManager.createHostViewInContainer(this.element, atIndex, protoViewRef, dynamicallyCreatedBindings); } /** * Insert a {@link ViewRef} at specefic index. * * The index is location at which the {@link ViewRef} should be attached. If omitted it is * inserted at the end. * * Returns the inserted {@link ViewRef}. */ insert(viewRef, atIndex = -1) { if (atIndex == -1) atIndex = this.length; return this.viewManager.attachViewInContainer(this.element, atIndex, viewRef); } /** * Return the index of already inserted {@link ViewRef}. */ indexOf(viewRef) { return ListWrapper.indexOf(this._getViews(), internalView(viewRef)); } /** * Remove a {@link ViewRef} at specific index. * * If the index is omitted last {@link ViewRef} is removed. */ remove(atIndex = -1) { if (atIndex == -1) atIndex = this.length - 1; this.viewManager.destroyViewInContainer(this.element, atIndex); // view is intentionally not returned to the client. } /** * The method can be used together with insert to implement a view move, i.e. * moving the dom nodes while the directives in the view stay intact. */ detach(atIndex = -1) { if (atIndex == -1) atIndex = this.length - 1; return this.viewManager.detachViewInContainer(this.element, atIndex); } }
JavaScript
class TroubleshootingParameters { /** * Create a TroubleshootingParameters. * @property {string} targetResourceId The target resource to troubleshoot. * @property {string} storageId The ID for the storage account to save the * troubleshoot result. * @property {string} storagePath The path to the blob to save the * troubleshoot result in. */ constructor() { } /** * Defines the metadata of TroubleshootingParameters * * @returns {object} metadata of TroubleshootingParameters * */ mapper() { return { required: false, serializedName: 'TroubleshootingParameters', type: { name: 'Composite', className: 'TroubleshootingParameters', modelProperties: { targetResourceId: { required: true, serializedName: 'targetResourceId', type: { name: 'String' } }, storageId: { required: true, serializedName: 'properties.storageId', type: { name: 'String' } }, storagePath: { required: true, serializedName: 'properties.storagePath', type: { name: 'String' } } } } }; } }
JavaScript
class TwitchFlag { constructor(startIndex, endIndex, text, category) { this.startIndex = startIndex; this.endIndex = endIndex; this.word = text; this.categories = category; } }
JavaScript
class ConfluenceRenderer { /** * Creates a new instance. The `options` parameter control a few * tweaks that can be applied by the user in order to render better * markup. * * @param {Object} options */ constructor(options) { // Must not save it as `this.options` because marked overwrites // that property. this.renderOptions = options; } /** * Blockquote. * * > This is a blockquote. * * is changed into * * {quote} * This is a blockquote. * {quote} * * @param {string} text * @return {string} */ blockquote(text) { return `{quote}\n${text.trim()}\n{quote}\n\n`; } /** * A line break. Supposedly if you have a line with 2 or more spaces * followed by a line that doesn't have whitespace, then it turns into * this element. I'm failing to reproduce that scenario. * * @return {string} */ br() { return "\n"; } /** * Code block. * * ```js * // JavaScript code * ``` * * is changed into * * {code:language=javascript|borderStyle=solid|theme=RDark|linenumbers=true|collapse=false} * // JavaScript code * {code} * * @param {string} text * @param {string} lang * @return {string} */ code(text, lang) { var stylingOptions; // Simple clone of the options. stylingOptions = JSON.parse(JSON.stringify(this.renderOptions.codeStyling)); lang = lang || ""; lang = lang.toLowerCase(); lang = this.renderOptions.codeLanguageMap[lang] || this.renderOptions.codeLanguageMap[""]; if (lang) { stylingOptions.language = lang; } // If too big, collapse. if (text.split("\n").length > this.renderOptions.codeCollapseAt) { stylingOptions.collapse = true; } // Convert to a string stylingOptions = querystring.stringify(stylingOptions, "|"); if (stylingOptions) { stylingOptions = `:${stylingOptions}`; } return `{code${stylingOptions}}\n${text}\n{code}\n\n`; } /** * Inline code. * * Text that has statements, like `a = true` or similar. * * turns into * * Text that has statements, like {{a = true}} or similar. * * Be wary. This converts wrong: "Look at `~/file1` or `~/file2`" * Confluence thinks it is subscript and converts the markup into * "Look at <code><sub>/file1</code> or <code></sub>/file2</code>". * That's why some characters need to be escaped. * * @param {string} text * @return {string} */ codespan(text) { text = text.split(/(&[^;]*;)/).map((match, index) => { // These are the delimeters. if (index % 2) { return match; } return match.replace(/[^a-zA-Z0-9 ]/g, (badchar) => { return `&#${badchar[0].charCodeAt(0)};`; }); }); return `{{${text.join("")}}}`; } /** * Strikethrough. * * Supported ~~everywhere~~ in GFM only. * * turns into * * Supported -everywhere- in GFM only. * * @param {string} text * @return {string} */ del(text) { return `-${text}-`; } /** * Emphasis. * * Typically this is *italicized* text. * * turns into * * Typically this is _italicized_ text. * * @param {string} text * @return {string} */ em(text) { return `_${text}_`; } /** * Headings 1 through 6. * * Heading 1 * ========= * * # Heading 1 alternate * * ###### Heading 6 * * turns into * * h1. Heading 1 * * h1. Heading 1 alternate * * h6. Heading 6 * * @param {string} text * @param {number} level * @return {string} */ heading(text, level) { return `h${level}. ${text}\n\n`; } /** * Horizontal rule. * * --- * * turns into * * ---- * * @return {string} */ hr() { return "----\n\n"; } /** * Embedded HTML. * * <div></div> * * turns into * * <div></div> * * @param {string} text * @return {string} */ html(text) { return text; } /** * An embedded image. * * ![alt-text](image-url) * * is changed into * * !image-url! * * Markdown supports alt text and titles. Confluence does not. * * @param {string} href * @return {string} */ image(href) { href = this.renderOptions.imageRewrite(href); return `!${href}!`; } /** * Link to another resource. * * [Home](/) * [Home](/ "some title") * * turns into * * [Home|/] * [some title|/] * * @param {string} href * @param {string} title * @param {string} text * @return {string} */ link(href, title, text) { // Sadly, one must choose if the link's title should be displayed // or the linked text should be displayed. We picked the linked text. text = text || title; if (text) { text += "|"; } href = this.renderOptions.linkRewrite(href); return `[${text}${href}]`; } /** * Converts a list. * * # ordered * * unordered * * becomes * * # ordered * #* unordered * * Note: This adds an extra "\r" before the list in order to cope * with nested lists better. When there's a "\r" in a nested list, it * is translated into a "\n". When the "\r" is left in the converted * result then it is removed. * * @param {string} text * @param {boolean} ordered * @return {string} */ list(text, ordered) { text = text.trim(); if (ordered) { text = text.replace(/^\*/gm, "#"); } return `\r${text}\n\n`; } /** * Changes a list item. Always marks it as an unordered list, but * list() will change it back. * * @param {string} text * @return {string} */ listitem(text) { // If a list item has a nested list, it will have a "\r" in the // text. Turn that "\r" into "\n" but trim out other whitespace // from the list. text = text.replace(/\s*$/, "").replace(/\r/g, "\n"); // Convert newlines followed by a # or a * into sub-list items text = text.replace(/\n([*#])/g, "\n*$1"); return `* ${text}\n`; } /** * A paragraph of text. * * @param {string} text * @return {string} */ paragraph(text) { return `${text}\n\n`; } /** * Creates strong text. * * This is typically **bolded**. * * becomes * * This is typically *bolded*. * * @param {string} text * @return {string} */ strong(text) { return `*${text}*`; } /** * Renders a table. Most of the work is done in tablecell. * * @param {string} header * @param {string} body * @return {string} */ table(header, body) { return `${header}${body}\n`; } /** * Converts a table cell. When this is a header, the cell is prefixed * with two bars instead of one. * * @param {string} text * @param {Object} flags * @return {string} */ tablecell(text, flags) { var boundary; if (flags.header) { boundary = "||"; } else { boundary = "|"; } return `${boundary}${text}`; } /** * Converts a table row. Most of the work is done in tablecell, however * that can't tell if the cell is at the end of a row or not. Get the * first cell's leading boundary and remove the double-boundary marks. * * @param {string} text * @return {string} */ tablerow(text) { var boundary; boundary = text.match(/^\|*/); if (boundary) { boundary = boundary[0]; } else { boundary = "|"; } return `${text}${boundary}\n`; } /** * Simple text. * * @param {string} text * @return {string} */ text(text) { return text; } }
JavaScript
class RemoveDialogComponent extends React.Component { constructor(props) { super(props); this.state = { proceed: false, }; } handleRemove() { infetadosService.remove(this.props.infetadoId).then(() => this.props.removed()); } render() { const { show, handleClose } = this.props; const { proceed } = this.state; return ( <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Remover Infetados</Modal.Title> </Modal.Header> <Modal.Body>This element will be completely removed from your system, do you want to proceed?&nbsp; {' '} <FontAwesomeIcon icon={proceed ? faCheckSquare : faSquare} onClick={() => this.setState ({ proceed: !proceed })} /> </Modal.Body> <Modal.Footer> <Button variant="danger" onClick={()=>this.handleRemove()} disabled={!proceed}> Remove </Button> </Modal.Footer> </Modal> ); } }
JavaScript
class ProjectListTemplate extends React.Component { render() { const { data } = this.props const { edges: projects } = data.allMarkdownRemark return ( <Layout> <Helmet> <title>Projects | CMUBTG</title> <meta name="twitter:card" content="summary_large_image"></meta> <meta name="twitter:image" content={BTGCover}></meta> </Helmet> <Container className="mt-md-1 pt-md-4"> <Row className="pt-1 mt-5"> <Col> <h1 className="display-3 text-black font-weight-boldest">Projects</h1> </Col> </Row> <div className="pt-1 mt-3"> {projects.map(({ node: project }, index) => ( <ProjectContainer index={index} title={project.frontmatter.title} description={project.frontmatter.overview} photo={getImage(project.frontmatter.photo)} slug={project.fields.slug} /> ))} </div> </Container> </Layout> ); } }
JavaScript
class DraggableAnnotationAccessor extends DraggableElementAccessor { static isSupported() { return !!Chart.Annotation; } static getElements(chartInstance) { return DraggableElementAccessor.getElements( chartInstance, Object.keys(chartInstance.annotation.elements).map(id => chartInstance.annotation.elements[id]), Object.keys(chartInstance.annotation.elements).map(id => chartInstance.annotation.elements[id].options), (config) => { switch (config.type) { case 'line': return DraggableLineAnnotationElement; // @TODO: implement 'box' support, DraggableBoxAnnotationElement class } } ); } }
JavaScript
class Expression { constructor(expression) { if (!expression) throw new Error('[expression] can not be empty!') if (typeof expression !== 'string'){ throw new Error('[expression] must be a string!') } this._expression = expression // whether the expression is valid or not this._valid = false this._process() } /** * Indicate whether the expression is valid or not */ isValid () { return this._valid } _process () { try { let splitArr = (this._expression).trim().split(/\s+/); if (splitArr.length === 5) { splitArr = ['*'].concat(splitArr) } if (splitArr.length !== 6) throw new Error('[expression] is not correct, pls check!') this._secondExpr = splitArr[0] this._minuteExpr = splitArr[1] this._hourExpr = splitArr[2] this._dayOfMonthExpr = splitArr[3] this._monthExpr = splitArr[4] this._dayOfWeekExpr = splitArr[5] this._second = SecondExpression.process(splitArr[0]) this._minute = MinuteExpression.process(splitArr[1]) this._hour = HourExpression.process(splitArr[2]) this._dayOfMonth = DayOfMonthExpression.process(splitArr[3]) this._month = MonthExpression.process(splitArr[4]) this._dayOfWeek = DayOfWeekExpression.process(splitArr[5]) this._valid = this._second !== '' && this._minute !== '' && this._hour !== '' && this._dayOfMonth !== '' && this._month !== '' && this._dayOfWeek !== '' } catch (e) { console.log(e) this._valid = false } } /** * Indicate whether the specified date does match the expression or not * * Return true if specified date matches the expression, or return false * * @param {LocaleDate} localDate specified date. * * @param {String} part the option value. * M - month * D - day of month * d - day of week * H - hour * m - minute * s - second * * @param preTime the previous excuted time */ match (localDate, part, preTime) { // return false if expression is invalid or check param [date] failed if (!this._valid || !localDate || !(localDate instanceof LocaleDate)) return false part = part || '' preTime = preTime || '' const timer = localDate.getLocaleDate() const month = timer.format('M') const dayOfMonth = timer.format('D') const dayOfWeek = timer.format('d') const hour = timer.format('H') const minute = timer.format('m') const second = timer.format('s') if (!part || part === '') { return matchPart(this._month, month) && matchPart(this._dayOfMonth, dayOfMonth) && matchPart(this._dayOfWeek, dayOfWeek) && matchPart(this._hour, hour) && matchPart(this._minute, minute) && matchPart(this._second, second) } switch (part) { case 'M': return matchPart(this._month, month) case 'D': if (/^\*\|\d+$/.test(this._dayOfMonthExpr) && preTime) { const step = this._dayOfMonthExpr.split(`|`)[1] const du = moment.duration(timer - preTime, 'ms') if (du.get('days') >= parseInt(step, 10)) { return true } else { return false } } return matchPart(this._dayOfMonth, dayOfMonth) case 'd': return matchPart(this._dayOfWeek, dayOfWeek) case 'H': return matchPart(this._hour, hour) case 'm': return matchPart(this._minute, minute) case 's': return matchPart(this._second, second) default: throw new Error(`unsupported value [type]: '${part}'`) } } /** * return the input expression */ getExpression () { return this._expression } }
JavaScript
class InitUserData extends React.PureComponent { constructor(props) { super(props); const userStr = localStorage.getItem(USER_STORE_KEY); const user = userStr ? JSON.parse(userStr) : {}; props.store.dispatch({ type: "user/setUser", payload: user }); } render() { return this.props.children; } }
JavaScript
class Router { /** * Initializes the Friendly Pix controller/router. * @constructor */ constructor(loadApp, auth) { this.auth = auth; // Dom elements. this.pagesElements = $('[id^=page-]'); this.splashLogin = $('#login', '#page-splash'); // Make sure /add is never opened on website load. if (window.location.pathname === '/add') { page('/'); } // Configuring routes. const pipe = Router.pipe; const displayPage = this.displayPage.bind(this); const displaySplashIfSignedOut = () => this.displaySplashIfSignedOut(); const loadUser = (userId) => loadApp().then(({userPage}) => userPage.loadUser(userId)); const searchHashtag = (hashtag) => loadApp().then(({searchPage}) => searchPage.loadHashtag(hashtag)); const showHomeFeed = () => loadApp().then(({feed}) => feed.showHomeFeed()); const showGeneralFeed = () => loadApp().then(({feed}) => feed.showGeneralFeed()); const clearFeed = () => loadApp().then(({feed}) => feed.clear()); const showPost = (postId) => loadApp().then(({post}) => post.loadPost(postId)); page('/', pipe(displaySplashIfSignedOut, {continue: true}), pipe(displayPage, {pageId: 'splash'})); page('/home', pipe(showHomeFeed, {continue: true}), pipe(displayPage, {pageId: 'feed', onlyAuthed: true})); page('/recent', pipe(showGeneralFeed, {continue: true}), pipe(displayPage, {pageId: 'feed'})); page('/post/:postId', pipe(showPost, {continue: true}), pipe(displayPage, {pageId: 'post'})); page('/user/:userId', pipe(loadUser, {continue: true}), pipe(displayPage, {pageId: 'user-info'})); page('/search/:hashtag', pipe(searchHashtag, {continue: true}), pipe(displayPage, {pageId: 'search'})); page('/about', pipe(clearFeed, {continue: true}), pipe(displayPage, {pageId: 'about'})); page('/terms', pipe(clearFeed, {continue: true}), pipe(displayPage, {pageId: 'terms'})); page('/add', pipe(displayPage, {pageId: 'add', onlyAuthed: true})); page('*', () => page('/')); // Start routing. page(); } /** * Returns a function that displays the given page and hides the other ones. * if `onlyAuthed` is set to true then the splash page will be displayed instead of the page if * the user is not signed-in. */ displayPage(attributes, context) { const onlyAuthed = attributes.onlyAuthed; if (onlyAuthed) { // If the page can only be displayed if the user is authenticated then we wait or the auth state. this.auth.waitForAuth.then(() => { this._displayPage(attributes, context); }); } else { this._displayPage(attributes, context); } } _displayPage(attributes, context) { const onlyAuthed = attributes.onlyAuthed; let pageId = attributes.pageId; // If the page is restricted to signed-in users and the user is not signedin, redirect to the Splasbh page. if (onlyAuthed && !firebase.auth().currentUser) { return page('/'); } // Displaying the current link as active. Router.setLinkAsActive(context.canonicalPath); // Display the right page and hide the other ones. this.pagesElements.each(function(index, element) { if (element.id === 'page-' + pageId) { $(element).show(); } else if (element.id === 'page-splash' && onlyAuthed) { $(element).fadeOut(1000); } else { $(element).hide(); } }); // Force close the Drawer if opened. MaterialUtils.closeDrawer(); // Scroll to top. Router.scrollToTop(); } /** * Display the Splash-page if the user is signed-out. * Otherwise redirect to the home feed. */ displaySplashIfSignedOut() { if (!firebase.auth().currentUser) { this.splashLogin.show(); } else { page('/home'); } } /** * Reloads the current page. */ static reloadPage() { let path = window.location.pathname; if (path === '') { path = '/'; } page(path); } /** * Scrolls the page to top. */ static scrollToTop() { $('html,body').animate({scrollTop: 0}, 0); } /** * Pipes the given function and passes the given attribute and Page.js context. * A special attribute 'continue' can be set to true if there are further functions to call. */ static pipe(funct, attribute) { const optContinue = attribute ? attribute.continue : false; return (context, next) => { if (funct) { const params = Object.keys(context.params); if (!attribute && params.length > 0) { funct(context.params[params[0]], context); } else { funct(attribute, context); } } if (optContinue) { next(); } }; } /** * Highlights the correct menu item/link. */ static setLinkAsActive(canonicalPath) { if (canonicalPath === '') { canonicalPath = '/'; } $('.is-active').removeClass('is-active'); $(`[href="${canonicalPath}"]`).addClass('is-active'); } }
JavaScript
class S3Folder extends pulumi.ComponentResource { constructor(bucketName, path, opts) { super("pulumi:examples:S3Folder", bucketName, {}, opts); // Register this component with name pulumi:examples:S3Folder // Create a bucket and expose a website index document let siteBucket = new aws.s3.Bucket(bucketName, { website: { indexDocument: "index.html", }, }, { parent: this }); // specify resource parent // For each file in the directory, create an S3 object stored in `siteBucket` for (let item of require("fs").readdirSync(path)) { let filePath = require("path").join(path, item); let object = new aws.s3.BucketObject(item, { bucket: siteBucket, // reference the s3.Bucket object source: new pulumi.asset.FileAsset(filePath), // use FileAsset to point to a file contentType: mime.getType(filePath) || undefined, // set the MIME type of the file }, { parent: this }); // specify resource parent } // Set the access policy for the bucket so all objects are readable let bucketPolicy = new aws.s3.BucketPolicy("bucketPolicy", { bucket: siteBucket.bucket, policy: siteBucket.bucket.apply(this.publicReadPolicyForBucket), }, { parent: this }); // specify resource parent this.bucketName = siteBucket.bucket; this.websiteUrl = siteBucket.websiteEndpoint; // Register output properties for this component this.registerOutputs({ bucketName: this.bucketName, websiteUrl: this.websiteUrl, }); } publicReadPolicyForBucket(bucketName) { return JSON.stringify({ Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: "*", Action: [ "s3:GetObject" ], Resource: [ `arn:aws:s3:::${bucketName}/*` // policy refers to bucket name explicitly ] }] }); } }