language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class SectionConfig { /** * @param {?=} options */ constructor(options) { this.sections = {}; // console.log('SectionConfig', options); if (options) { Object.assign(this, options); this.sections = options.sections || {}; } } }
JavaScript
class SectionModuleComponent { constructor() { this.version = '0.0.12'; } /** * @return {?} */ ngOnInit() { } }
JavaScript
class Section extends PageIndex { /** * @param {?=} options */ constructor(options) { super(options); } }
JavaScript
class SectionService { /** * @param {?} options */ constructor(options) { // console.log('SectionService', options); options = options || {}; this.options = new SectionConfig(options); } /** * @param {?} section * @return {?} */ resolve(section) { /** @type {?} */ let component; if (section) { component = this.options.sections[section.component] || SectionComponent; } else { component = SectionComponent; // component = this.pageService.options.notFoundPage || SectionComponent; } return component; } }
JavaScript
class SectionOutletComponent extends DisposableComponent { /** * @param {?} componentFactoryResolver * @param {?} sectionService */ constructor(componentFactoryResolver, sectionService) { super(); this.componentFactoryResolver = componentFactoryResolver; this.sectionService = sectionService; } /** * @return {?} */ ngOnInit() { /** @type {?} */ const component = this.sectionService.resolve(this.section); /** @type {?} */ const factory = this.componentFactoryResolver.resolveComponentFactory(component); this.viewContainerRef.clear(); /** @type {?} */ const componentRef = this.viewContainerRef.createComponent(factory); /** @type {?} */ const instance = componentRef.instance; instance.section = this.section; if (typeof instance['SectionInit'] === 'function') { instance['SectionInit'](); } this.componentRef = componentRef; } /** * @return {?} */ ngOnDestroy() { this.componentRef.destroy(); } }
JavaScript
class WizardSwitcher extends React.Component { constructor(props) { super(props); this.state = { page: undefined, pageIds: undefined, progress: 0, disableSubmit: false, isLastPage: false, isFirstPage: true, apiError: undefined, apiMessage: undefined, slideIn: true, slideDirection: 'left', values: this.props.initialValues || {}, errors: {}, visitedPages: [] } this.pageIds = []; } componentDidMount() { this.setState({ page: this.pageIds[0], pageIds: this.pageIds, isLastPage: (this.pageIds.length === 1) ? true : false }) } recordWizardPageIds = (id) => { if (this.pageIds.includes(id)) { return; } else { this.pageIds.push(id) } } nextPage = () => { let stateUpdates = { isFirstPage: false }; let values = this.state.values; const currentPageIndex = this.state.pageIds.indexOf(this.state.page) + 1; Object.keys(values).map(k => { if (Array.isArray(values[k])) { return values[k] } else { if (values[k]) { values[k] = values[k].trim() } return values[k] } }); this.setState({ values }) // For paper sliding animation this.setState({ slideIn: true, slideDirection: 'left' }) // Handles page skipping let nextPage = this.state.pageIds[Math.min(currentPageIndex, this.state.pageIds.length)]; if (this.props.skips) { let skipTo = this.props.skips(this.state.values, this.state.page, this.props); if (skipTo !== undefined) { nextPage = skipTo; } } stateUpdates.page = nextPage; let nextPageIndex = this.state.pageIds.indexOf(nextPage); // Adds current page to the page history let tempVisitedPages = this.state.visitedPages; tempVisitedPages.push(this.state.page); stateUpdates.visitedPages = tempVisitedPages; // Determines value for progress bar. let progress = Math.floor((100 / this.state.pageIds.length) * nextPageIndex); stateUpdates.progress = progress; let secondToLastPageId = this.state.pageIds[this.state.pageIds.length - 2] if (this.state.page === secondToLastPageId) { stateUpdates.progress = 100; stateUpdates.isLastPage = true; } this.setState(stateUpdates); } previousPage = () => { let stateUpdates = { isLastPage: false }; // For paper sliding animation this.setState({ slideIn: true, slideDirection: 'right' }) // Removes most recent page from history and sets current page to that. // Allows page skipping to work. let tempVisitedPages = this.state.visitedPages; let previousPage = tempVisitedPages.pop(); let previousPageIndex = this.state.pageIds.indexOf(previousPage) stateUpdates.page = previousPage; // Determines value for progress bar let progress = Math.floor((100 / this.state.pageIds.length) * previousPageIndex); stateUpdates.progress = progress; let secondToFirstPage = this.state.pageIds[1] if (this.state.page === secondToFirstPage) { stateUpdates.isFirstPage = true; stateUpdates.progress = 0; } this.setState(stateUpdates); } // Handles how checkboxes are recorded. We add all values to an array, and add/remove values as needed. recordCheckboxValues = (name, value) => { let stateValue = (this.state.values[name] === undefined) ? [] : this.state.values[name]; if (stateValue.includes(value)) { // Remove existing value from array let index = stateValue.indexOf(value); if (index > -1) { stateValue.splice(index, 1); } } else { stateValue = [...stateValue, ...Array(value)]; } return stateValue; } // Handles recording text fields, and radio buttons. recordValues = (event) => { let value = event.target.value; let name = event.target.name; if (event.target.type === 'checkbox') { value = this.recordCheckboxValues(name, value); } let fieldValue = { [name]: value }; let stateValues = {...this.state.values, ...fieldValue} this.setState({ values: stateValues }); } // If the validate prop is specified, run it and add all errors. // Returns true if there are errors, false if not. runValidation = () => { if (Boolean(this.props.validate)) { const returnedErrors = this.props.validate(this.state.values, this.state.page, this.props) if (Object.keys(returnedErrors).length > 0) { const stateErrors = {...this.state.errors, ...returnedErrors} this.setState({ errors: stateErrors }); return true; } else { this.setState({ errors: {}}) return false; } } } // Handles closing the snackbar component. handleClose = (event, reason) => { if (reason === 'clickaway') { return; } this.setState({ apiError: undefined, apiMessage: undefined }) } // Method that is called on submission of the form. // API calls can be made here. onSubmit = (e) => { e.preventDefault() // Prevents form from automatically redirecting if (!this.runValidation()) { this.setState({ disableSubmit: true }) if (this.props.submit) { this.props.submit(this.props, this.state, { updateState: this.updateState }) } } } // Method that is called when a user presses a key on the form. onKeyPress = (e) => { if (e.key === 'Enter') { e.preventDefault(); // Prevents calling onSubmit with the enter key // Enter key now calls the next page if (!this.state.isLastPage) { if (!this.runValidation()) { this.nextPage() } } } } collectBulkValues = (valuesObject) => { const combinedValues = {...this.state.values, ...valuesObject}; this.setState({ values: combinedValues }); } render() { return ( <WizardProvider value={{ pathCode: this.props.pathCode, nextPage: this.nextPage, previousPage: this.previousPage, page: this.state.page, progress: this.state.progress, submitDisabled: this.state.disableSubmit, isLastPage: this.state.isLastPage, isFirstPage: this.state.isFirstPage, recordValues: this.recordValues, values: this.state.values, errors: this.state.errors, runValidation: this.runValidation, apiError: this.state.apiError, apiMessage: this.state.apiMessage, handleSnackbarClose: this.handleClose, slideIn: this.state.slideIn, slideDirection: this.state.slideDirection, collectBulkValues: this.collectBulkValues, recordWizardPageIds: this.recordWizardPageIds }}> <form onSubmit={this.onSubmit} onKeyPress={this.onKeyPress}> {this.props.children} </form> </WizardProvider> ) } }
JavaScript
class HttpStatusCodeError extends common_1.CustomError { /** @private */ constructor(_statusCode, statusText, _body, isJson) { super(`Encountered HTTP status code ${_statusCode}: ${statusText}\n\nBody:\n${!isJson && _body.length > 150 ? `${_body.substr(0, 147)}...` : _body}`); this._statusCode = _statusCode; this._body = _body; } get statusCode() { return this._statusCode; } get body() { return this._body; } }
JavaScript
class Couchbase extends NoSQL { /** * ID type. */ getDefaultIdType(prop) { return String; } constructor(name, settings, Accessor) { super(name, settings, Accessor); this._viewStale = couchbase.ViewQuery.Update.NONE; } /** * Connect to Couchbase */ _connect(settings, database) { // Cluster. if (settings.cluster == null) { settings.cluster = {}; } if (settings.cluster.url == null) { debug('Cluster URL settings missing; trying default'); settings.cluster.url = 'couchbase://localhost'; } if (settings.cluster.options == null) { settings.cluster.options = {}; } // Bucket. if (settings.bucket == null) { settings.bucket = {}; } if (settings.bucket.name == null) { debug('Bucket name settings missing; trying default'); settings.bucket.name = 'default'; } if (settings.bucket.password == null) { settings.bucket.password = ''; } settings.version = settings.version || 5; // View. if (settings.stale != null) { this._viewStale = settings.stale; } // Cluster. const cluster = new couchbase.Cluster( settings.cluster.url, settings.cluster.options ); // Authentication https://docs.couchbase.com/java-sdk/current/sdk-authentication-overview.html if (parseInt(settings.version, 10) >= 5) { cluster.authenticate( settings.cluster.username, settings.cluster.password ); } this._cluster = Promise.resolve(cluster).then( utils.promisifyAllResolveWithReturn ); // A connection is established when a bucket is open. // @see http://developer.couchbase.com/documentation/server/4.0/sdks/node-2.5/performance-tuning.html return this._cluster .call('openBucketAsync', settings.bucket.name, settings.bucket.password) .then((bucket) => { if (settings.bucket.operationTimeout) { bucket.operationTimeout = settings.bucket.operationTimeout; } return bucket; }) .then(Promise.promisifyAll); } /** * Disconnect from Couchbase */ _disconnect(bucket) { // Cleanup. this._cluster = null; this._manager = null; // Disconnect. return bucket.disconnect(); } /** * Ping db server. */ ping(callback) { let promise; if (this._cluster == null) { promise = Promise.reject(new Error('not connected')); } else { promise = this.connect() .call('getAsync', '1') .return(true) .catch(function(err) { if (err.message === 'The key does not exist on the server') { return true; } return Promise.reject(err); }); } return promise.asCallback(callback); } /** * ViewQuery APIs. */ /** * Shortcut. */ view(designDoc, viewName, options) { return this.runViewQuery(this.newViewQuery(designDoc, viewName, options)); } /** * Shortcut. */ runViewQuery(query, params) { return this.connect().call('queryAsync', query, params); } /** * Build a new view query. * * @see http://docs.couchbase.com/sdk-api/couchbase-node-client-2.1.2/ViewQuery.html * @param {String} designDoc * @param {String} viewName * @param {Object} options * @return {Object} */ newViewQuery(designDoc, viewName, options) { const ViewQuery = couchbase.ViewQuery; // With some defaults. // See https://docs.couchbase.com/sdk-api/couchbase-node-client-2.1.4/ViewQuery.html#.ErrorMode let query = ViewQuery.from(designDoc, viewName) .on_error(ViewQuery.ErrorMode.STOP) .order(ViewQuery.Order.ASCENDING) .stale(this._viewStale); if (options == null) { return query; } // The SDK made it easier for some options formats. // Call. let opts = Object.assign({}, options); [ 'stale', 'order', 'group', 'group_level', 'key', 'keys', 'include_docs', 'full_set', 'on_error', 'limit' ].forEach((key) => { if (opts[key] != null) { query = query[key].call(query, opts[key]); delete opts[key]; } }); // Apply. ['range', 'id_range'].forEach((key) => { if (opts[key] != null) { query = query[key].apply(query, opts[key]); delete opts[key]; } }); query = query.custom(opts); return query; } /** * Bucket Manager APIs. */ /** * You don't need to use this directly usually. Use the APIs below. * * @private */ manager() { // Only one manager is needed. if (this._manager == null) { this._manager = this.connect().call('manager').then(Promise.promisifyAll); } return this._manager; } /** * Shortcut. */ getDesignDocument(name) { return this.manager().call('getDesignDocumentAsync', name); } /** * Shortcut. */ getDesignDocuments() { return this.manager().call('getDesignDocumentsAsync'); } /** * Shortcut. */ insertDesignDocument(name, data) { return this.manager().call('insertDesignDocumentAsync', name, data); } /** * Shortcut. */ removeDesignDocument(name) { return this.manager().call('removeDesignDocumentAsync', name); } /** * Shortcut. */ upsertDesignDocument(name, data) { return this.manager().call('upsertDesignDocumentAsync', name, data); } /** * Cluster Manager APIs. */ clusterManager(username, password) { // Only one manager is needed. if (this._clusterManager == null) { this._clusterManager = this._cluster .call('manager', username, password) .then(Promise.promisifyAll); } return this._clusterManager; } /** * Operation hooks. */ /** * Implement `autoupdate()`. * * @see `DataSource.prototype.autoupdate()` */ autoupdate(models, callback) { debug('autoupdate', this.settings); // Create views. let designDocs = defaultDesignDocs; if (this.settings.designDocs) { designDocs = Object.assign({}, designDocs, this.settings.designDocs); } let promise = Promise.resolve(true); for (let name in designDocs) { promise = promise.then(() => { return this.upsertDesignDocument(name, designDocs[name]).then((res) => { debug('created design document', name, designDocs[name], res); return res; }); }); } return promise.asCallback(callback); } /** * Implement `automigrate()`. * * @see `DataSource.prototype.automigrate()` * * Not really useful. Usually we manage databases in other ways. */ // automigrate(models, callback) { // debug('automigrate', this.settings.database); // } }
JavaScript
class BaseDao { /** * @constructor * @param {Object<mongo:Object<dbName: string, >>} config * @param {MongoClient} dbClient instance of MongoDB Client * @param {string} collectionName */ constructor(config, dbClient) { this.id = null; this.query = null; this.dbClient = dbClient; this.config = config; this.collection = config.collection ? config.collection : ""; //paginate data this.head = {}; this.data = []; this.error = []; //aggregations this.sort = config.sort ? config.sort : { _id: -1 }; this.pageSize = config.pageSize ? config.pageSize : 20; this.page = 1; this.match = {}; } /** * the page to view * @param {Number} page */ set page(page) { if (!isNaN(page) && +page > 0) { this._page = +page; } } /** * @param {Number} pageSize */ set pageSize(pageSize) { if (!isNaN(pageSize) && +pageSize > 0) { this._pageSize = +pageSize; } } get page() { return this._page; } get pageSize() { return this._pageSize; } /** * query params from call * @param {Object<field: value>} query */ set query(query) { this._query = query; } get query() { return this._query; } /** * @param {String} collectionName */ set collection(collectionName) { this._collection = collectionName; } get collection() { return this._collection; } // get offset(){ // } /** * @return {Object} database connection to collection */ get dbRef() { return this.dbClient.db(this.dbName).collection(this.collection); } /** * sets the id of the document you want to query, also sets the _idString value for raw id string * @param {string} id of the document you want to query */ set id(idString) { if (idString) { if (idString.length >= 24) { this._id = (0, _mongodb.ObjectId)(idString); } else { this._id = { _id: "invalid id, must be at least 24 characters long,curr length " + idString.length }; throw this._id; } } else { this._id = null; } } /** * @return {ObjectId} mongo database id in BSON Object */ get id() { return this._id; } /** * @return the output base object */ get output() { return { head: { page: this.page, pageSize: this.pageSize, length: this.data.length, dataset: this.collection }, data: this.data, error: this.error }; } /** * reset the output parts */ resetOutput() { this.head = {}; this.data = []; this.error = []; } /** * @return output object data */ find() { var _this = this; return _asyncToGenerator(function* () { _this.resetOutput(); try { //id declared, just get one if (_this.id) { var obj = yield _this.dbRef.findOne(_this.id); if (obj) { _this.data = [obj]; } } else { // this.data = await this.dbRef.find().toArray(); var aggregationArr = [{ $match: _this.match }, { $skip: (_this.page - 1) * _this.pageSize }, { $limit: _this.pageSize }]; if (_this.query) { aggregationArr.push(_this.query); } _this.data = yield _this.dbRef.aggregate(aggregationArr).sort(_this.sort).toArray(); //change _id to id // this.data.map(cleanMongoId); } } catch (ex) { _this.resetOutput(); _this.error.push(ex.message); } return _this.data; })(); } /** * inserts data into the collection, overwrite this with your own implemntation for validation * @param {Object} data for insert */ create(data) { var _this2 = this; return _asyncToGenerator(function* () { _this2.resetOutput(); if (data) { try { var insertedData = yield _this2.dbRef.insertOne(data); _this2.data = [_objectSpread({ _id: insertedData.insertedId }, data)]; } catch (ex) { _this2.resetOutput(); _this2.error.push(ex.message); } } return _this2.data; })(); } /** * Updates the document with the id set in the class attribute * @param {Object} data for update */ update(data) { var _this3 = this; return _asyncToGenerator(function* () { _this3.resetOutput(); if (!_this3.id) { throw "id is required"; } if (!data) { throw "missing data"; } if (data) { try { var origDataRes = yield _this3.dbRef.findOneAndUpdate({ _id: _this3.id }, { $set: data }); _this3.data = [_objectSpread(_objectSpread({}, origDataRes.value), data)]; } catch (ex) { _this3.resetOutput(); _this3.error.push(ex.message); } } return _this3.data; })(); } /** * handles delete operations */ delete() { var _this4 = this; return _asyncToGenerator(function* () { _this4.resetOutput(); try { //id declared, just get one if (_this4.id) { var obj = yield _this4.dbRef.deleteOne({ _id: _this4.id }); if (obj.deletedCount) { _this4.data = [{ id: _this4.id.toHexString() }]; } else { //failed delete for some reason _this4.error = [{ fail: _this4.id.toHexString() }]; } } else { _this4.error = [{ id: "required" }]; throw "id is required"; } } catch (ex) { _this4.resetOutput(); _this4.error.push(ex.message); } return _this4.data; })(); } }
JavaScript
class DemoFuroCard extends FBP(LitElement) { /** * Themable Styles * @private * @return {CSSResult} */ static get styles() { // language=CSS return Theme.getThemeForComponent(this.name) || css` :host { display: block; height: 100%; padding-right: var(--spacing); } :host([hidden]) { display: none; } furo-demo-snippet{ height: 800px; } ` } /** * @private * @returns {TemplateResult} */ render() { // language=HTML return html` <furo-vertical-flex> <h2>Demo demo-furo-card</h2> <p>description</p> <furo-demo-snippet flex> <template> <style>furo-card { margin: 20px; width: 320px; float: left; }</style> <furo-vertical-scroller> <furo-card header-text="With media" secondary-text="Secondary text goes here"> <img slot="media" src="/_page/images/hamburg.png" alt=""> <div ƒ-.inner-text="--fromTextarea" style="margin-bottom: 30px">Do not forget to give the card <br> a height</div> <furo-horizontal-flex space slot="action"> <furo-button primary label="primary"></furo-button> <furo-button accent label="accent"></furo-button> <furo-empty-spacer></furo-empty-spacer> <furo-button danger label="Danger"></furo-button> </furo-horizontal-flex> </furo-card> <furo-card> <img slot="media" src="/_page/images/hamburg.png" alt=""> <h1>Title in content</h1> <div ƒ-.inner-text="--fromTextarea" style="margin-bottom: 30px">Do not forget to give the card <br> a height</div> <furo-horizontal-flex space slot="action"> <furo-button primary label="primary"></furo-button> <furo-button accent label="accent"></furo-button> <furo-empty-spacer></furo-empty-spacer> <furo-button danger label="Danger"></furo-button> </furo-horizontal-flex> </furo-card> <furo-card header-text="Title goes here" secondary-text="Secondary text goes hereSecondary text goes hereSecondary text goes hereSecondary text goes here"> <div>Text in default slot</div> <div slot="action"> <furo-horizontal-flex space slot="action"> <furo-button primary label="primary"></furo-button> <furo-empty-spacer></furo-empty-spacer> <furo-button label="Danger"></furo-button> </furo-horizontal-flex> </div> </furo-card> <furo-card header-text="Title goes here" secondary-text="Secondary text goes here"> <div> Content text blah </div> <div slot="action"> <furo-horizontal-flex space slot="action"> <furo-button primary label="primary"></furo-button> <furo-empty-spacer></furo-empty-spacer> <furo-button label="Danger"></furo-button> </furo-horizontal-flex> </div> </furo-card> </furo-vertical-scroller> </template> </furo-demo-snippet> </furo-vertical-flex> `; } }
JavaScript
class ColorContrastCalc { /** * Returns an instance of Color. * * As colorValue, you can pass a predefined color name, or an RGB * value represented as an array of Integers or a hex code such as * [255, 255, 255] or "#ffff00". name is assigned to the returned * instance if it does not have a name already assigned. * @param {string|Array<number, number, number>} colorValue - name * of a predefined color or RGB value * @param {string} name - Unless the instance has predefined name, * the name passed to the method is set to self.name * @returns {Color} Instance of Color */ static colorFrom(colorValue, name = null) { const errMessage = "A color should be given as an array or string."; if (! (Utils.isString(colorValue)) && ! (colorValue instanceof Array)) { throw new Error(errMessage); } if (colorValue instanceof Array) { return this.colorFromRgb(colorValue, name); } return this.colorFromStr(colorValue, name); } /** * @private */ static colorFromRgb(colorValue, name = null) { const errMessage = "An RGB value should be given in form of [r, g, b]."; if (! Utils.isValidRgb(colorValue)) { throw new Error(errMessage); } const hexCode = Utils.rgbToHexCode(colorValue); return Color.List.HEX_TO_COLOR.get(hexCode) || new Color(hexCode, name); } /** * @private */ static colorFromStr(colorValue, name = null) { const errMessage = "A hex code is in form of '#xxxxxx' where 0 <= x <= f."; const namedColor = Color.getByName(colorValue); if (namedColor) { return namedColor; } if (! Utils.isValidHexCode(colorValue)) { throw new Error(errMessage); } const hexCode = Utils.normalizeHexCode(colorValue); return Color.List.HEX_TO_COLOR.get(hexCode) || new Color(hexCode, name); } /** * Returns an array of named colors that satisfy a given level of * contrast ratio * @param {Color} color - base color to which other colors are compared * @param {string} [level="AA"] - A, AA or AAA * @returns {Color[]} */ static colorsWithSufficientContrast(color, level = "AA") { const ratio = Checker.levelToRatio(level); return this.NAMED_COLORS.filter(combinedColor => { return color.contrastRatioAgainst(combinedColor) >= ratio; }); } /** * Returns an array of colors which share the same saturation and lightness. * By default, so-called pure colors are returned. * @param {number} [s=100] - Ratio of saturation in percentage. * @param {number} [l=50] - Ratio of lightness in percentage. * @param {number} [h_interval=1] - Interval of hues given in degrees. * By default, it returns 360 hues beginning from red. * (Red is included twice, because it corresponds to 0 and 360 degrees.) * @returns {Color[]} */ static hslColors(s = 100, l = 50, h_interval = 1) { return Color.List.hslColors(s, l, h_interval); } /** * Returns a function to be used as a parameter of Array.prototype.sort() * @param {string} [colorOrder="rgb"] - A left side primary color has a higher * sorting precedence * @param {string} [keyType="color"] - Type of keys used for sorting: * "color", "hex" or "rgb" * @param {function} [keyMapper=null] - A function used to retrive key values * from elements to be sorted * @returns {function} Function that compares given two colors */ static compareFunction(colorOrder = "rgb", keyType = "color", keyMapper = null) { return this.Sorter.compareFunction(colorOrder, keyType, keyMapper); } /** * Sorts colors in an array and returns the result as a new array * @param {Color[]|String[]} colors - List of colors * @param {string} [colorOrder="rgb"] - A left side primary color has a higher * sorting precedence, and an uppercase letter means descending order * @param {function} [keyMapper=null] - A function used to retrive key values * from elements to be sorted * @param {string} [mode="auto"] - If set to "hex", key values are handled as * hex code strings * @returns {Color[]} An array of sorted colors */ static sort(colors, colorOrder = "rgb", keyMapper = null, mode = "auto") { return this.Sorter.sort(colors, colorOrder, keyMapper, mode); } /** * @private */ static setup() { /** * Array of named colors defined at * https://www.w3.org/TR/SVG/types.html#ColorKeywords * @property {Color[]} NAMED_COLORS */ this.NAMED_COLORS = Color.List.NAMED_COLORS; /** @private */ this.NAME_TO_COLOR = Color.List.NAME_TO_COLOR; /** @private */ this.HEX_TO_COLOR = Color.List.HEX_TO_COLOR; /** * Array of web safe colors * @property {Color[]} WEB_SAFE_COLORS */ this.WEB_SAFE_COLORS = Color.List.WEB_SAFE_COLORS; Object.freeze(this); } }
JavaScript
class Inspector extends Component { constructor( props ) { super( ...arguments ); } render() { // Setup the attributes const { attributes: { borderWidth, borderColor, borderRadius, backgroundColor, padding, }, setAttributes, } = this.props; const onChangeBorderColor = ( value ) => setAttributes( { borderColor: value } ); const onChangeBackgroundColor = ( value ) => setAttributes( { backgroundColor: value } ); return ( <InspectorControls key="inspector"> <PanelBody> <RenderSettingControl id="ab_pricing_inner_padding"> <RangeControl label={ __( 'Pricing Column Padding', 'atomic-blocks' ) } value={ padding } onChange={ ( value ) => this.props.setAttributes( { padding: value } ) } min={ 0 } max={ 20 } step={ 1 } /> </RenderSettingControl> <RenderSettingControl id="ab_pricing_inner_borderWidth"> <RangeControl label={ __( 'Pricing Column Border', 'atomic-blocks' ) } value={ borderWidth } onChange={ ( value ) => this.props.setAttributes( { borderWidth: value, } ) } min={ 0 } max={ 10 } step={ 1 } /> </RenderSettingControl> <RenderSettingControl id="ab_pricing_inner_borderRadius"> <RangeControl label={ __( 'Pricing Column Border Radius', 'atomic-blocks' ) } value={ borderRadius } onChange={ ( value ) => this.props.setAttributes( { borderRadius: value, } ) } min={ 0 } max={ 20 } step={ 1 } /> </RenderSettingControl> </PanelBody> { 0 < borderWidth && ( <RenderSettingControl id="ab_pricing_inner_borderColor"> <PanelColorSettings title={ __( 'Pricing Column Border Color', 'atomic-blocks' ) } initialOpen={ false } colorSettings={ [ { value: borderColor, onChange: onChangeBorderColor, label: __( 'Border Color', 'atomic-blocks' ), }, ] } ></PanelColorSettings> </RenderSettingControl> ) } <RenderSettingControl id="ab_pricing_inner_colorSettings"> <PanelColorSettings title={ __( 'Pricing Column Background Color', 'atomic-blocks' ) } initialOpen={ false } colorSettings={ [ { value: backgroundColor, onChange: onChangeBackgroundColor, label: __( 'Background Color', 'atomic-blocks' ), }, ] } ></PanelColorSettings> </RenderSettingControl> </InspectorControls> ); } }
JavaScript
class WPSearch extends BaseSearch { /** * @param {!InternalOpenGateAPI} ogapi - this is configuration about Opengate North API. * @param {!string} url - this define a specific resource to make the search * @param {object} filter - this is the filter * @param {object} limit - this is the pagination about the search * @param {object} sort - this defined parameters to order the result of search * @param {object} group * @param {object} select * @param {nubmer} timeout */ constructor(ogapi, url, filter, limit = { limit: {} }, sort, group, select, timeout, urlParams) { super(ogapi, url, timeout); this._setUrlParameters(urlParams); this._postObj = merge(filter, limit, group, select); if (typeof sort === 'object') { this._postObj = merge(this._postObj, sort); } } _filter() { return this._postObj; } _loadData(resource) { let _this = this; let defered = q.defer(); let filter = _this._asyncPagingFilter(); let paging = false; //Funcion que realizara la llamada al search paginado y, de forma recursiva, llamara a todas las paginas function loadAll() { console.log(JSON.stringify(filter)); if (_this.cancel || typeof _this.cancel === 'string') { var message = typeof _this.cancel === 'string' ? _this.cancel : 'Cancel process'; defered.reject({ data: message, statusCode: 403 }); } else { _this._ogapi.Napi .post(_this._resource, filter, _this._timeout, _this._getExtraHeaders(), _this._getUrlParameters()) .then((response) => { let statusCode = response.statusCode; let body = response.body; if (!body && response.text) { try { let parsedResult = JSON.parse(response.text); if (parsedResult) { body = parsedResult; } } catch (ignoreError) { console.error("Impossible to parse text from response"); } } if (statusCode === 200) { paging = true; defered.notify(body); //Se permite devolver un boolean o un string que reemplazará el mensaje por defecto if (body.data.length === filter.limit.size) { filter.limit.start += 1; loadAll(); } else { defered.resolve({ data: 'DONE', statusCode: 200 }); } } else { if (paging) { defered.resolve({ data: 'DONE', statusCode: 200 }); } else defered.reject({ data: body, statusCode: statusCode }); } }) .catch((error) => { defered.reject(error); }); } } loadAll(); return defered.promise; } }
JavaScript
class Engine { /** * @method constructor * @return {Engine} * * @description Initializes the Engine as not running and containing * Utilities. */ constructor() { this.context = new Context(); this.startLoop(); this.running = false; } /** * @method start * @return {VOID} * * @description Engages the engine to the animation loop, if it has been started. */ start() { this.running = true; } /** * @method stop * @return {VOID} * * @description Disengages the engine to the animation loop, if it has been started. */ stop() { this.running = false; this.destroy(); } /** * @method startLoop * @return {VOID} * * @description Begins the animation loop. */ startLoop() { let engine = this; let clock = new THREE.Clock(); let lastFrame = new Date(); let raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; function loop( now ) { raf(loop); let delta = clock.getDelta(); if(engine.running !== false) { engine.update( delta ); if ( delta < 160 ) { engine.render( delta ); } } lastFrame = now; } loop(lastFrame); } destroy() {} }
JavaScript
class JishoDictionaryEntry { constructor(dictionaryEntry) { this.node = dictionaryEntry; this.word = this.readWord(); this.reading = this.readReading(); this.readingHiragana = katakanaToHiragana(this.reading); this.meaningsWrapper = this.readMeaningsWrapper(); } /** * Read out the reading from the dictionary entry. */ readReading() { let jishoKana = ''; let furigana = this.node.getElementsByClassName('furigana')[0]; if (typeof furigana === 'undefined' || furigana === null) { return ''; } if (furigana.innerText == '') { return this.readWord(); } [...furigana.children].forEach(element => { if (element.tagName == 'SPAN' && element.innerText == '') { jishoKana += '*'; } else if (element.classList.contains('kanji')) { jishoKana += element.innerText; } }); /* rb rt tags */ if (jishoKana == '' || jishoKana == '*') { // ヨーロッパ --- 欧羅巴 jishoKana = furigana.innerText + jishoKana; } let okurigana = this.node.getElementsByClassName('text')[0]; [...okurigana.children].forEach(element => { if (element.tagName == 'SPAN' && element.className == '') { jishoKana = jishoKana.replace('*', element.innerText); } }) return jishoKana.replace(/[\*]/g, ''); // replacing any asteriks left: addresses bug with 小火 } /** * Read out the Japanese word from the dictionary entry. */ readWord() { return this.node .getElementsByClassName('concept_light-representation')[0] .getElementsByClassName('text')[0] .innerText.replace(/\([^()]*\)/g, ''); } /** * Read out the meanings-wrapper from the dictionary entry. */ readMeaningsWrapper() { return this.node.getElementsByClassName('meanings-wrapper')[0]; } /** * Get ordinal number of for a meaning/translation in this dictionary entry * * @param {HTMLElement} [meaning] Element of class 'meaning-wrapper' * @returns {Number} Ordinal number of current meaning/translation */ readMeaningOrdinal(meaning) { return parseInt(meaning.innerText.split('.')[0], 10); } /** * Get ordinal number of the last meaning/translation of this dictionary entry * * @returns {Number} Ordinal number of last meaning/translation in a dictionary entry */ lastOrdinalInMeaningsWrapper() { let lastOrdinal = 1; let children = [...this.meaningsWrapper.childNodes] for (let i = children.length - 1; i >= 0; i--) { let tmp = this.readMeaningOrdinal(children[i]); if (!isNaN(tmp)) { lastOrdinal = tmp; break; } } return lastOrdinal; } /** * Test if the dictionary entry has a pitch accent diagram attached. */ hasPitchAccentDiagram() { return this.node.getElementsByClassName('pitchDiagram').length > 0 ? true : false; } /** * Test if the dictionary entry has an audio file attached. */ hasAudio() { let audioElement = this.node.getElementsByClassName('concept_audio'); if (typeof audioElement !== 'undefined' && audioElement.length !== 0) { return true; } return false; } }
JavaScript
class JSONConverter { importDocument (doc, json) { doc.fromJson(json) return doc } exportDocument (doc) { var schema = doc.getSchema() var json = { schema: { name: schema.name }, nodes: [] } const visited = {} function _export (node) { if (!node) return if (visited[node.id]) return visited[node.id] = true const nodeSchema = node.getSchema() const childProps = nodeSchema.getChildProperties() for (const prop of childProps) { const val = node.get(prop.name) if (isArray(val)) { val.forEach(id => { _export(doc.get(id)) }) } else { _export(doc.get(val)) } } json.nodes.push(node.toJSON()) } for (const node of doc.getNodes().values()) { _export(node) } return json } }
JavaScript
class ThemeManager { // WARNING // DO NOT ADD MORE COLORS HERE // ThemeManager is going to be deprecated static colors = { pink: { primary: { text: '#355ed3', accent: '#ef7ede', support: '#fbafef', background: '#fadaf5', }, secondary: secondaryColorSet, base: baseColorSet, toc: { text: '#9c9c9c', accent: '#ef7ede', support: '#fbafef', background: '#fadaf5', }, }, default: { primary: { text: '#a67a44', accent: '#a67a44', support: '#d0a67d', background: '#f1f1f1', }, secondary: secondaryColorSet, base: { ...baseColorSet, background: '#f1f1f1', }, toc: { text: '#afafaf', accent: '#a67a44', support: '#d0a67d', background: '#fefefe', }, }, photo: { primary: { text: '#a67a44', accent: '#a67a44', support: '#d0a67d', background: '#08192d', }, secondary: secondaryColorSet, base: { text: 'rgba(255, 255, 255, 0.8)', lightText: 'rgba(255, 255, 255, 0.5)', button: { text: { color: '#808080', }, border: { color: '#808080', }, background: { color: 'initial', }, hover: { text: { color: '#fff', }, border: { color: '#fff', }, background: { color: 'initial', }, }, }, line: 'rgba(216, 216, 216, 0.2)', background: '#08192d', }, toc: { text: '#afafaf', accent: '#a67a44', support: '#d0a67d', background: '#fefefe', }, }, } /** * @param {string} [theme=article:v2:default] - Theme name * @returns {undefined} */ constructor(theme) { this.theme = theme } /** * @param {string} [theme=article:v2:default] - Theme name * @returns {ThemeColors} */ getColors(theme = '') { const _theme = theme || this.theme switch (_theme) { case themeConst.article.v2.pink: { return ThemeManager.colors.pink } case themeConst.article.v2.photo: { return ThemeManager.colors.photo } case themeConst.article.v2.default: default: { return ThemeManager.colors.default } } } }
JavaScript
class App extends React.Component { render() { return ( <div> <Switch history={history}> <PrivateRoute exact path="/" component={HomePage} /> <PrivateRoute exact path="/:portfolioname/:portfolioid/estates/" component={EstatesPage} /> <PrivateRoute exact path="/searchresultredirect" component={SearchResultRedirectPage} /> <PrivateRoute exact path="/:portfolioname/:portfolioid/:estatename/:estateid/estate" component={EstatePage} /> <PrivateRoute exact path="/:portfolioname/:portfolioid/:estatename/:estateid/:datacategoryname/:datacategoryid/datacategory" component={DataCategoryPage} /> <PrivateRoute exact path="/:portfolioname/:portfolioid/:estatename/:estateid/:datacategoryname/:datacategoryid/:filecategoryname/:filecategoryid/filecategory" component={FileCategoryPage} /> <Route path="/login" component={LoginPage} /> <Route path="/about" component={AboutPage} /> <Route component={NotFoundPage} /> </Switch> </div> ); } }
JavaScript
class GoogleSearchList extends Component { init() { /** * Whether or not google search results are loading. * * @type {Boolean} */ this.loading = true; /** * Whether or not there are more results that can be loaded. * * @type {Boolean} */ this.moreResults = false; /** * the google search list. * * @type {Array} */ this.googleresults = []; this.refresh(); } view() { const params = this.props.params; let loading; if (this.loading) { loading = LoadingIndicator.component(); } else if (this.moreResults) { loading = Button.component({ children: app.translator.trans( "core.forum.discussion_list.load_more_button" ), className: "Button", onclick: this.loadMore.bind(this) }); } if (this.googleresults.length === 0 && !this.loading) { const text = app.translator.trans( "irony-google-search.forum.page.empty_text" ); return ( <div className="DiscussionList">{Placeholder.component({ text })}</div> ); } return ( <div className={ "DiscussionList" + (this.props.params.q ? " DiscussionList--searchResults" : "") } > <ul className="DiscussionList-discussions"> {this.googleresults.map(info => { return <li>{GoogleSearchListItem.component({ info, params })}</li>; })} </ul> <div className="DiscussionList-loadMore">{loading}</div> </div> ); } /** * Get the parameters that should be passed in the API request to get * google search results. * * @return {Object} * @api */ requestParams() { return this.props.params; } /** * Clear and reload the google search list. * * @public */ refresh(clear = true) { if (clear) { this.loading = true; this.googleresults = []; } return this.loadResults().then( results => { this.googleresults = []; this.parseResults(results); }, () => { this.loading = false; m.redraw(); } ); } /** * Load a new page of google search results. * 请求api获取数据 * * @param {Integer} offset The index to start the page at. * @return {Promise} */ loadResults(offset) { const preloadedLists = app.preloadedApiDocument(); if (preloadedLists) { return m.deferred().resolve(preloadedLists).promise; } return app .request({ method: "GET", url: app.forum.attribute("apiUrl") + "/google/search", data: this.requestParams() }) .then(function(data) { return data; }); //return app.store.find("google/search", this.requestParams()); } /** * Load the next page of google search results. * * @public */ loadMore() { this.loading = true; this.loadResults(this.googleresults.length).then( this.parseResults.bind(this) ); } /** * Parse results and append them to the google search list. * * @param {Array} results * @return {Array} */ parseResults(results) { [].push.apply(this.googleresults, results); this.loading = false; this.moreResults = false; m.lazyRedraw(); return results; } /** * Remove a google search from the list if it is present. * * @param {Array} list * @public */ removeList(list) { const index = this.googleresults.indexOf(list); if (index !== -1) { this.googleresults.splice(index, 1); } } /** * Add a google search to the top of the list. * * @param {Array} list * @public */ addList(list) { this.googleresults.unshift(list); } }
JavaScript
class Home extends React.PureComponent { strings = getStrings().Home; constructor(props) { super(props); this.state = { clicked: false }; updateNavigation('Home', props.navigation.state.routeName); } /** * Sets the user information */ setUser = (userInfo) => { this.props.logonUser(userInfo); } /** * Creates the Kalend calendar in the user's Google Account */ setCalendar() { getCalendarID2().then(data => { if (data.calendarID === undefined) { createCalendar().then(data => { this.props.setCalendarID(data.calendarID); this.props.setCalendarColor(data.calendarColor); this.props.navigation.navigate(DashboardNavigator); }); } else { this.props.setCalendarID(data.calendarID); this.props.setCalendarColor(data.calendarColor); this.props.navigation.navigate(DashboardNavigator); } }); } /** * Log In the user with their Google Account */ signIn = () => { let params = { dashboardTitle: getStrings().Dashboard.name, chatbotTitle: getStrings().Chatbot.name, compareTitle: getStrings().CompareSchedule.name, settingsTitle: getStrings().Settings.name }; this.props.setBottomString(params); if (!this.state.clicked) { this.state.clicked = true; googleIsSignedIn().then((signedIn) => { if (!signedIn || !this.props.HomeReducer || this.props.HomeReducer.profile === null) { googleGetCurrentUserInfo().then((userInfo) => { if (userInfo !== undefined) { this.setUser(userInfo); this.setCalendar(); } googleSignIn().then((userInfo) => { if (userInfo !== null) { this.setUser(userInfo); this.setCalendar(); } this.state.clicked = false; }); }); } else { this.setCalendar(); } }); } } showWebsite = (url) => { if (Platform.OS === 'ios') { this.openSafari(url); } else { this.openChrome(url); } } openSafari = (url) => { SafariView.isAvailable() .then(SafariView.show({url, tintColor: dark_blue, barTintColor: white, fromBottom: true })) .catch(() => this.openChrome(url)); } openChrome = (url) => { CustomTabs.openURL(url, { toolbarColor: dark_blue, enableUrlBarHiding: true, showPageTitle: true, enableDefaultShare: true, forceCloseOnRedirection: true, }); } render() { let source = Platform.OS === 'ios' ? require('../../assets/img/loginScreen/backPattern_ios.png') : require('../../assets/img/loginScreen/backPattern_android.png'); return ( <LinearGradient style={styles.container} colors={gradientColors}> <ImageBackground style={styles.container} source={source} resizeMode="repeat"> <StatusBar translucent={true} barStyle={Platform.OS === 'ios' ? 'dark-content' : 'default'} backgroundColor={'#00000050'} /> <View style={styles.content}> <View style={styles.topSection}> <Image style={styles.logo} source={require('../../assets/img/kalendLogo.png')} resizeMode="contain" /> </View> <View style={styles.bottomSection}> <View style={styles.signInSection}> <GoogleSigninButton style={styles.signInButton} size={GoogleSigninButton.Size.Wide} color={GoogleSigninButton.Color.Light} onPress={this.signIn} /> </View> <TouchableOpacity style={styles.cdhSection} onPress={ ()=>{ this.props.language === 'en' ? this.showWebsite('https://cdhstudio.ca/') : this.showWebsite('https://cdhstudio.ca/fr'); }}> <Text style={styles.cdhSectionText}> <Text style={styles.cdhText}>{this.strings.createdBy}</Text> <Text style={styles.cdhLink}>{this.strings.cdhStudio}</Text> </Text> </TouchableOpacity> </View> </View> </ImageBackground> </LinearGradient> ); } }
JavaScript
class DependencyListPlugin { /** * Creates a new DependencyListPlugin configured with the given options. * The options given must conform to the options schema. * * @see PLUGIN_OPTIONS_SCHEMA * * @param {*} options * The configuration options to apply to the plugin. */ constructor(options = {}) { validateOptions(PLUGIN_OPTIONS_SCHEMA, options, 'DependencyListPlugin'); this.options = options; } /** * Entrypoint for all Webpack plugins. This function will be invoked when * the plugin is being associated with the compile process. * * @param {Compiler} compiler * A reference to the Webpack compiler. */ apply(compiler) { /** * Logger for this plugin. * * @type {Logger} */ const logger = compiler.getInfrastructureLogger(PLUGIN_NAME); /** * The full path to the output file that should contain the list of * discovered NPM module dependencies. * * @type {string} */ const outputFile = path.join( this.options.path || compiler.options.output.path, this.options.filename || 'npm-dependencies.txt' ); // Wait for compilation to fully complete compiler.hooks.done.tap(PLUGIN_NAME, (stats) => { const moduleCoords = {}; // Map each file used within any bundle built by the compiler to // its corresponding NPM package, ignoring files that have no such // package stats.compilation.fileDependencies.forEach(file => { // Locate NPM package corresponding to file dependency (there // may not be one) const moduleFinder = finder(file); const npmPackage = moduleFinder.next().value; // Translate absolute path into more readable path relative to // root of compilation process const relativePath = path.relative(compiler.options.context, file); if (npmPackage.name) { moduleCoords[npmPackage.name + ':' + npmPackage.version] = true; logger.info('File dependency "%s" mapped to NPM package "%s" (v%s)', relativePath, npmPackage.name, npmPackage.version); } else logger.info('Skipping file dependency "%s" (no NPM package)', relativePath); }); // Write all discovered NPM packages to configured output file const sortedCoords = Object.keys(moduleCoords).sort(); fs.writeFileSync(outputFile, sortedCoords.join('\n') + '\n'); }); } }
JavaScript
class ChallengeController { /* ================================ GETS ================================ */ // Get challenge by id async getChallengeById(req, res) { try { const id_challenge_req = req.params.id; const challenge = await Challenge.findById(id_challenge_req); res.send(challenge); } catch (error) { console.log(error); } } // Get challenge by username async getChallengeByUsername(req, res) { try { const username = req.params.username; const user = await User.findOne({username: username}).populate('task_challenges.task'); var active = []; // Search tasks inactives by user for (const task of user.task_challenges){ if (task.tier !== 0 && task.status){ const challenge = await Challenge.findOne({category: task.task.category, tier: task.tier}); active.push(challenge._id); } } const challenges = await Challenge.find({ _id: active }); res.send(challenges) } catch (error) { console.log(error); } } //Get all challenges async getChallenges(req, res) { try { const challenges = await Challenge.find(); res.send(challenges); } catch (error) { console.log(error); } } /*async insertChallenges(){ try{ await challenges.forEach(challenge => { var new_challenge = new Challenge(challenge); new_challenge.save(function (err){if (err) return console.error(err)}) }); }catch(error){ console.log(error); } }*/ /* ================================ PUTS ================================ */ async updateChallenge(req, res) { try { const id_challenge_req = req.params.id; const challenge_req = req.body; const challenge = await Challenge.findByIdAndUpdate(id_challenge_req, challenge_req); res.send(challenge) } catch (error) { console.log(error); } } /* ================================ POSTS ================================ */ async postChallenge(req, res) { try { const { category, description, tier, duration, value } = req.body; const challenge = new Challenge({ category, description, tier, duration, value }); await challenge.save(function (err) { if (err) return res.status(400).json({ error: 'Ha ocurrido un error' }); res.status(200).json({ message: `Challenge ${description} creada correctamente` }); }); } catch (error) { console.log(error); } } /* ================================ DELETE ================================ */ async deleteChallenge(req, res) { try{ const id_tc = req.params.id await Challenge.findByIdAndDelete(id_tc); res.status(200).json({ message: 'Challenge/Challenge eliminado correctamente'}) } catch (error){ console.log(error) } } }
JavaScript
class SetMultimap extends Map { set(key, value) { if (this.has(key)) { const set = this.get(key); set.add(value); super.set(key, set); } else { const set = new Set; set.add(value); super.set(key, set); } return this; } get count() { return [...this.values()].reduce((sum, set) => sum += set.size, 0); } toJSON() { const serializeMembers = (set) => { return [...set.values()].reduce((acc, value) => { acc.push(value); return acc; }, []); }; return [...this.keys()].reduce((acc, key) => { const set = this.get(key); acc[key] = serializeMembers(set); return acc; }, {}); } get [Symbol.toStringTag]() { return 'SetMultimap'; } }
JavaScript
class TimeSeries { constructor(arg) { this._collection = null; // Collection this._data = null; // Meta data if (arg instanceof TimeSeries) { // // Copy another TimeSeries // var other = arg; this._data = other._data; this._collection = other._collection; } else if (_underscore.default.isObject(arg)) { // // TimeSeries(object data) where data may be: // { "events": [event-1, event-2, ..., event-n]} // or // { "columns": [time|timerange|index, column-1, ..., column-n] // "points": [ // [t1, v1, v2, ..., v2], // [t2, v1, v2, ..., vn], // ... // ] // } var obj = arg; if (_underscore.default.has(obj, "events")) { // // Initialized from an event list // var { events } = obj, meta1 = (0, _objectWithoutProperties2.default)(obj, ["events"]); //eslint-disable-line this._collection = new _collection.default(events); this._data = buildMetaData(meta1); } else if (_underscore.default.has(obj, "collection")) { // // Initialized from a Collection // var { collection } = obj, meta3 = (0, _objectWithoutProperties2.default)(obj, ["collection"]); //eslint-disable-line this._collection = collection; this._data = buildMetaData(meta3); } else if (_underscore.default.has(obj, "columns") && _underscore.default.has(obj, "points")) { // // Initialized from the wire format // var { columns, points, utc = true } = obj, meta2 = (0, _objectWithoutProperties2.default)(obj, ["columns", "points", "utc"]); //eslint-disable-line var [eventKey, ...eventFields] = columns; var _events = points.map(point => { var [t, ...eventValues] = point; var d = _underscore.default.object(eventFields, eventValues); var options = utc; switch (eventKey) { case "time": return new _timeevent.default(t, d, options); case "index": return new _indexedevent.default(t, d, options); case "timerange": return new _timerangeevent.default(t, d, options); default: throw new Error("Unknown event type"); } }); this._collection = new _collection.default(_events); this._data = buildMetaData(meta2); } if (!this._collection.isChronological()) { throw new Error("TimeSeries was passed non-chronological events"); } } } // // Serialize // /** * Turn the TimeSeries into regular javascript objects */ toJSON() { var e = this.atFirst(); if (!e) { return; } var columnList = this.columns(); var columns; if (e instanceof _timeevent.default) { columns = ["time", ...columnList]; } else if (e instanceof _timerangeevent.default) { columns = ["timerange", ...columnList]; } else if (e instanceof _indexedevent.default) { columns = ["index", ...columnList]; } var points = []; for (var _e of this._collection.events()) { points.push(_e.toPoint(columnList)); } return _underscore.default.extend(this._data.toJSON(), { columns, points }); } /** * Represent the TimeSeries as a string */ toString() { return JSON.stringify(this.toJSON()); } /** * Returns the extents of the TimeSeries as a TimeRange. */ timerange() { return this._collection.range(); } /** * Alias for `timerange()` */ range() { return this.timerange(); } /** * Gets the earliest time represented in the TimeSeries. * * @return {Date} Begin time */ begin() { return this.range().begin(); } /** * Gets the latest time represented in the TimeSeries. * * @return {Date} End time */ end() { return this.range().end(); } /** * Access a specific TimeSeries event via its position * * @param {number} pos The event position */ at(pos) { return this._collection.at(pos); } /** * Returns an event in the series by its time. This is the same * as calling `bisect` first and then using `at` with the index. * * @param {Date} time The time of the event. * @return {TimeEvent|IndexedEvent|TimeRangeEvent} */ atTime(time) { var pos = this.bisect(time); if (pos >= 0 && pos < this.size()) { return this.at(pos); } } /** * Returns the first event in the series. * * @return {TimeEvent|IndexedEvent|TimeRangeEvent} */ atFirst() { return this._collection.atFirst(); } /** * Returns the last event in the series. * * @return {TimeEvent|IndexedEvent|TimeRangeEvent} */ atLast() { return this._collection.atLast(); } /** * Generator to return all the events in the series * * @example * ``` * for (let event of series.events()) { * console.log(event.toString()); * } * ``` */ *events() { for (var i = 0; i < this.size(); i++) { yield this.at(i); } } /** * Sets a new underlying collection for this TimeSeries. * * @param {Collection} collection The new collection * @param {boolean} isChronological Causes the chronological * order of the events to * not be checked * * @return {TimeSeries} A new TimeSeries */ setCollection(collection) { var isChronological = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!isChronological && !collection.isChronological()) { throw new Error("Collection supplied is not chronological"); } var result = new TimeSeries(this); if (collection) { result._collection = collection; } else { result._collection = new _collection.default(); } return result; } /** * Returns the index that bisects the TimeSeries at the time specified. * * @param {Date} t The time to bisect the TimeSeries with * @param {number} b The position to begin searching at * * @return {number} The row number that is the greatest, but still below t. */ bisect(t, b) { var tms = t.getTime(); var size = this.size(); var i = b || 0; if (!size) { return undefined; } for (; i < size; i++) { var ts = this.at(i).timestamp().getTime(); if (ts > tms) { return i - 1 >= 0 ? i - 1 : 0; } else if (ts === tms) { return i; } } return i - 1; } /** * Perform a slice of events within the TimeSeries, returns a new * TimeSeries representing a portion of this TimeSeries from * begin up to but not including end. * * @param {Number} begin The position to begin slicing * @param {Number} end The position to end slicing * * @return {TimeSeries} The new, sliced, TimeSeries. */ slice(begin, end) { var sliced = this._collection.slice(begin, end); return this.setCollection(sliced, true); } /** * Crop the TimeSeries to the specified TimeRange and * return a new TimeSeries. * * @param {TimeRange} timerange The bounds of the new TimeSeries * * @return {TimeSeries} The new, cropped, TimeSeries. */ crop(timerange) { var timerangeBegin = timerange.begin(); var beginPos = this.bisect(timerangeBegin); var bisectedEventOutsideRange = this.at(beginPos).timestamp() < timerangeBegin; beginPos = bisectedEventOutsideRange ? beginPos + 1 : beginPos; var endPos = this.bisect(timerange.end(), beginPos); return this.slice(beginPos, endPos + 1); } /** * Returns a new TimeSeries by testing the fieldPath * values for being valid (not NaN, null or undefined). * * The resulting TimeSeries will be clean (for that fieldPath). * * @param {string} fieldPath Name of value to look up. If not supplied, * defaults to ['value']. "Deep" syntax is * ['deep', 'value'] or 'deep.value' * * @return {TimeSeries} A new, modified, TimeSeries. */ clean(fieldSpec) { var cleaned = this._collection.clean(fieldSpec); return this.setCollection(cleaned, true); } /** * Generator to return all the events in the collection. * * @example * ``` * for (let event of timeseries.events()) { * console.log(event.toString()); * } * ``` */ *events() { for (var i = 0; i < this.size(); i++) { yield this.at(i); } } // // Access meta data about the series // /** * Fetch the timeseries name * * @return {string} The name given to this TimeSeries */ name() { return this._data.get("name"); } /** * Rename the timeseries */ setName(name) { return this.setMeta("name", name); } /** * Fetch the timeseries Index, if it has one. * * @return {Index} The Index given to this TimeSeries */ index() { return this._data.get("index"); } /** * Fetch the timeseries Index, as a string, if it has one. * * @return {string} The Index, as a string, given to this TimeSeries */ indexAsString() { return this.index() ? this.index().asString() : undefined; } /** * Fetch the timeseries `Index`, as a `TimeRange`, if it has one. * * @return {TimeRange} The `Index`, as a `TimeRange`, given to this `TimeSeries` */ indexAsRange() { return this.index() ? this.index().asTimerange() : undefined; } /** * Fetch the UTC flag, i.e. are the events in this `TimeSeries` in * UTC or local time (if they are `IndexedEvent`s an event might be * "2014-08-31". The actual time range of that representation * depends on where you are. Pond supports thinking about that in * either as a UTC day, or a local day). * * @return {TimeRange} The Index, as a TimeRange, given to this TimeSeries */ isUTC() { return this._data.get("utc"); } /** * Fetch the list of column names. This is determined by * traversing though the events and collecting the set. * * Note: the order is not defined * * @return {array} List of columns */ columns() { var c = {}; for (var e of this._collection.events()) { var d = e.toJSON().data; _underscore.default.each(d, (val, key) => { c[key] = true; }); } return _underscore.default.keys(c); } /** * Returns the internal `Collection` of events for this `TimeSeries` * * @return {Collection} The collection backing this `TimeSeries` */ collection() { return this._collection; } /** * Returns the meta data about this TimeSeries as a JSON object. * Any extra data supplied to the TimeSeries constructor will be * placed in the meta data object. This returns either all of that * data as a JSON object, or a specific key if `key` is supplied. * * @param {string} key Optional specific part of the meta data * @return {object} The meta data */ meta(key) { if (!key) { return this._data.toJSON(); } else { return this._data.get(key); } } /** * Set new meta data for the TimeSeries. The result will * be a new TimeSeries. */ setMeta(key, value) { var newTimeSeries = new TimeSeries(this); var d = newTimeSeries._data; var dd = d.set(key, value); newTimeSeries._data = dd; return newTimeSeries; } // // Access the series itself // /** * Returns the number of events in this TimeSeries * * @return {number} Count of events */ size() { return this._collection ? this._collection.size() : 0; } /** * Returns the number of valid items in this TimeSeries. * * Uses the fieldSpec to look up values in all events. * It then counts the number that are considered valid, which * specifically are not NaN, undefined or null. * * @return {number} Count of valid events */ sizeValid(fieldSpec) { return this._collection.sizeValid(fieldSpec); } /** * Returns the number of events in this TimeSeries. Alias * for size(). * * @return {number} Count of events */ count() { return this.size(); } /** * Returns the sum for the fieldspec * * @param {string} fieldPath Column to find the stdev of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The sum */ sum(fieldPath, filter) { return this._collection.sum(fieldPath, filter); } /** * Aggregates the events down to their maximum value * * @param {string} fieldPath Column to find the max of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * * @return {number} The max value for the field */ max(fieldPath, filter) { return this._collection.max(fieldPath, filter); } /** * Aggregates the events down to their minimum value * * @param {string} fieldPath Column to find the min of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The min value for the field */ min(fieldPath, filter) { return this._collection.min(fieldPath, filter); } /** * Aggregates the events in the TimeSeries down to their average * * @param {string} fieldPath Column to find the avg of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The average */ avg(fieldPath, filter) { return this._collection.avg(fieldPath, filter); } /** * Aggregates the events in the TimeSeries down to their mean (same as avg) * * @param {string} fieldPath Column to find the mean of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The mean */ mean(fieldPath, filter) { return this._collection.mean(fieldPath, filter); } /** * Aggregates the events down to their medium value * * @param {string} fieldPath Column to find the median of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The resulting median value */ median(fieldPath, filter) { return this._collection.median(fieldPath, filter); } /** * Aggregates the events down to their stdev * * @param {string} fieldPath Column to find the stdev of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The resulting stdev value */ stdev(fieldPath, filter) { return this._collection.stdev(fieldPath, filter); } /** * Gets percentile q within the TimeSeries. This works the same way as numpy. * * @param {integer} q The percentile (should be between 0 and 100) * * @param {string} fieldPath Column to find the qth percentile of. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * * @param {string} interp Specifies the interpolation method * to use when the desired quantile lies between * two data points. Options are: "linear", "lower", "higher", * "nearest", "midpoint" * @param {function} filter Optional filter function used to clean data before aggregating * * @return {number} The percentile */ percentile(q, fieldPath) { var interp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "linear"; var filter = arguments.length > 3 ? arguments[3] : undefined; return this._collection.percentile(q, fieldPath, interp, filter); } /** * Aggregates the events down using a user defined function to * do the reduction. * * @param {function} func User defined reduction function. Will be * passed a list of values. Should return a * singe value. * @param {string} fieldPath Column to aggregate over. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * * @return {number} The resulting value */ aggregate(func, fieldPath) { return this._collection.aggregate(func, fieldPath); } /** * Gets n quantiles within the TimeSeries. This works the same way as numpy's percentile(). * For example `timeseries.quantile(4)` would be the same as using percentile with q = 0.25, 0.5 and 0.75. * * @param {integer} n The number of quantiles to divide the * TimeSeries into. * @param {string} fieldPath Column to calculate over. A deep value can * be referenced with a string.like.this. If not supplied * the `value` column will be aggregated. * @param {string} interp Specifies the interpolation method * to use when the desired quantile lies between * two data points. Options are: "linear", "lower", "higher", * "nearest", "midpoint". * @return {array} An array of n quantiles */ quantile(quantity) { var fieldPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "value"; var interp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "linear"; return this._collection.quantile(quantity, fieldPath, interp); } /** * Returns a new Pipeline with input source being initialized to * this TimeSeries collection. This allows pipeline operations * to be chained directly onto the TimeSeries to produce a new * TimeSeries or event result. * * @example * * ``` * timeseries.pipeline() * .offsetBy(1) * .offsetBy(2) * .to(CollectionOut, c => out = c); * ``` * * @return {Pipeline} The Pipeline. */ pipeline() { return new _pipeline.Pipeline().from(this._collection); } /** * Takes an operator that is used to remap events from this TimeSeries to * a new set of events. * * @param {function} operator An operator which will be passed each * event and which should return a new event. * @return {TimeSeries} A TimeSeries containing the remapped events */ map(op) { var collections = this.pipeline().map(op).toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Takes a fieldSpec (list of column names) and outputs to the callback just those * columns in a new TimeSeries. * * @example * * ``` * const ts = timeseries.select({fieldSpec: ["uptime", "notes"]}); * ``` * * @param options An object containing options for the command * @param {string|array} options.fieldSpec Column or columns to select into the new TimeSeries. * If you need to retrieve multiple deep nested values * that ['can.be', 'done.with', 'this.notation']. * A single deep value with a string.like.this. * * @return {TimeSeries} The resulting TimeSeries with renamed columns */ select(options) { var { fieldSpec } = options; var collections = this.pipeline().select(fieldSpec).toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Takes a `fieldSpecList` (list of column names) and collapses * them to a new column named `name` which is the reduction (using * the `reducer` function) of the matched columns in the `fieldSpecList`. * * The column may be appended to the existing columns, or replace them, * based on the `append` boolean. * * @example * * ``` * const sums = ts.collapse({ * name: "sum_series", * fieldSpecList: ["in", "out"], * reducer: sum(), * append: false * }); * ``` * * @param options An object containing options: * @param {array} options.fieldSpecList The list of columns to collapse. (required) * @param {string} options.name The resulting collapsed column name (required) * @param {function} options.reducer The reducer function (required) * @param {bool} options.append Append the collapsed column, rather * than replace * * @return {TimeSeries} The resulting collapsed TimeSeries */ collapse(options) { var { fieldSpecList, name, reducer, append } = options; var collections = this.pipeline().collapse(fieldSpecList, name, reducer, append).toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Rename columns in the underlying events. * * Takes a object of columns to rename. Returns a new `TimeSeries` containing * new events. Columns not in the dict will be retained and not renamed. * * @example * ``` * new_ts = ts.renameColumns({ * renameMap: {in: "new_in", out: "new_out"} * }); * ``` * * @note As the name implies, this will only rename the main * "top level" (ie: non-deep) columns. If you need more * extravagant renaming, roll your own using `TimeSeries.map()`. * * @param options An object containing options: * @param {Object} options.renameMap Columns to rename. * * @return {TimeSeries} The resulting TimeSeries with renamed columns */ renameColumns(options) { var { renameMap } = options; return this.map(event => { var eventType = event.type(); var d = event.data().mapKeys(key => renameMap[key] || key); return new eventType(event.key(), d); }); } /** * Take the data in this TimeSeries and "fill" any missing or invalid * values. This could be setting `null` values to zero so mathematical * operations will succeed, interpolate a new value, or pad with the * previously given value. * * The `fill()` method takes a single `options` arg. * * @example * ``` * const filled = timeseries.fill({ * fieldSpec: ["direction.in", "direction.out"], * method: "zero", * limit: 3 * }); * ``` * * @param options An object containing options: * @param {string|array} options.fieldSpec Column or columns to fill. If you need to * retrieve multiple deep nested values * that ['can.be', 'done.with', 'this.notation']. * A single deep value with a string.like.this. * @param {string} options.method "linear" or "pad" or "zero" style interpolation * @param {number} options.limit The maximum number of points which should be * interpolated onto missing points. You might set this to * 2 if you are willing to fill 2 new points, * and then beyond that leave data with missing values. * * @return {TimeSeries} The resulting filled TimeSeries */ fill(options) { var { fieldSpec = null, method = "zero", limit = null } = options; var pipeline = this.pipeline(); if (method === "zero" || method === "pad") { pipeline = pipeline.fill({ fieldSpec, method, limit }); } else if (method === "linear" && _underscore.default.isArray(fieldSpec)) { fieldSpec.forEach(fieldPath => { pipeline = pipeline.fill({ fieldSpec: fieldPath, method, limit }); }); } else { throw new Error("Invalid fill method:", method); } var collections = pipeline.toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Align event values to regular time boundaries. The value at * the boundary is interpolated. Only the new interpolated * points are returned. If limit is reached nulls will be * returned at each boundary position. * * One use case for this is to modify irregular data (i.e. data * that falls at slightly irregular times) so that it falls into a * sequence of evenly spaced values. We use this to take data we * get from the network which is approximately every 30 second * (:32, 1:02, 1:34, ...) and output data on exact 30 second * boundaries (:30, 1:00, 1:30, ...). * * Another use case is data that might be already aligned to * some regular interval, but that contains missing points. * While `fill()` can be used to replace `null` values, `align()` * can be used to add in missing points completely. Those points * can have an interpolated value, or by setting limit to 0, * can be filled with nulls. This is really useful when downstream * processing depends on complete sequences. * * @example * ``` * const aligned = ts.align({ * fieldSpec: "value", * period: "1m", * method: "linear" * }); * ``` * * @param options An object containing options: * @param {string|array} options.fieldSpec Column or columns to align. If you need to * retrieve multiple deep nested values * that ['can.be', 'done.with', 'this.notation']. * A single deep value with a string.like.this. * @param {string} options.period Spacing of aligned values. e.g. "6h" or "5m" * @param {string} options.method "linear" or "pad" style interpolation to boundaries. * @param {number} options.limit The maximum number of points which should be * interpolated onto boundaries. You might set this to * 2 if you are willing to interpolate 2 new points, * and then beyond that just emit nulls on the boundaries. * * @return {TimeSeries} The resulting aligned TimeSeries */ align(options) { var { fieldSpec = "value", period = "5m", method = "linear", limit = null } = options; var collection = this.pipeline().align(fieldSpec, period, method, limit).toKeyedCollections(); return this.setCollection(collection["all"], true); } /** * Returns the derivative of the TimeSeries for the given columns. The result will * be per second. Optionally you can substitute in `null` values if the rate * is negative. This is useful when a negative rate would be considered invalid. * * @param options An object containing options: * @param {string|array} options.fieldSpec Column or columns to get the rate of. If you * need to retrieve multiple deep nested values * that ['can.be', 'done.with', 'this.notation']. * @param {bool} options.allowNegative Will output null values for negative rates. * This is useful if you are getting the rate * of a counter that always goes up, except * when perhaps it rolls around or resets. * * @return {TimeSeries} The resulting `TimeSeries` containing calculated rates. */ rate() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var { fieldSpec = "value", allowNegative = true } = options; var collection = this.pipeline().rate(fieldSpec, allowNegative).toKeyedCollections(); return this.setCollection(collection["all"], true); } /** * Builds a new TimeSeries by dividing events within the TimeSeries * across multiple fixed windows of size `windowSize`. * * Note that these are windows defined relative to Jan 1st, 1970, * and are UTC, so this is best suited to smaller window sizes * (hourly, 5m, 30s, 1s etc), or in situations where you don't care * about the specific window, just that the data is smaller. * * Each window then has an aggregation specification applied as * `aggregation`. This specification describes a mapping of output * fieldNames to aggregation functions and their fieldPath. For example: * ``` * { in_avg: { in: avg() }, out_avg: { out: avg() } } * ``` * will aggregate both "in" and "out" using the average aggregation * function and return the result as in_avg and out_avg. * * Note that each aggregation function, such as `avg()` also can take a * filter function to apply before the aggregation. A set of filter functions * exists to do common data cleanup such as removing bad values. For example: * ``` * { value_avg: { value: avg(filter.ignoreMissing) } } * ``` * * @example * ``` * const timeseries = new TimeSeries(data); * const dailyAvg = timeseries.fixedWindowRollup({ * windowSize: "1d", * aggregation: {value: {value: avg()}} * }); * ``` * * @param options An object containing options: * @param {string} options.windowSize The size of the window. e.g. "6h" or "5m" * @param {object} options.aggregation The aggregation specification (see description above) * @param {bool} options.toTimeEvents Output as `TimeEvent`s, rather than `IndexedEvent`s * @return {TimeSeries} The resulting rolled up `TimeSeries` */ fixedWindowRollup(options) { var { windowSize, aggregation, toTimeEvents = false } = options; if (!windowSize) { throw new Error("windowSize must be supplied, for example '5m' for five minute rollups"); } if (!aggregation || !_underscore.default.isObject(aggregation)) { throw new Error("aggregation object must be supplied, for example: {value: {value: avg()}}"); } var aggregatorPipeline = this.pipeline().windowBy(windowSize).emitOn("discard").aggregate(aggregation); var eventTypePipeline = toTimeEvents ? aggregatorPipeline.asTimeEvents() : aggregatorPipeline; var collections = eventTypePipeline.clearWindow().toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Builds a new TimeSeries by dividing events into hours. * * Each window then has an aggregation specification `aggregation` * applied. This specification describes a mapping of output * fieldNames to aggregation functions and their fieldPath. For example: * ``` * {in_avg: {in: avg()}, out_avg: {out: avg()}} * ``` * * @param options An object containing options: * @param {bool} options.toTimeEvents Convert the rollup events to `TimeEvent`s, otherwise it * will be returned as a `TimeSeries` of `IndexedEvent`s. * @param {object} options.aggregation The aggregation specification (see description above) * * @return {TimeSeries} The resulting rolled up TimeSeries */ hourlyRollup(options) { var { aggregation, toTimeEvents = false } = options; if (!aggregation || !_underscore.default.isObject(aggregation)) { throw new Error("aggregation object must be supplied, for example: {value: {value: avg()}}"); } return this.fixedWindowRollup("1h", aggregation, toTimeEvents); } /** * Builds a new TimeSeries by dividing events into days. * * Each window then has an aggregation specification `aggregation` * applied. This specification describes a mapping of output * fieldNames to aggregation functions and their fieldPath. For example: * ``` * {in_avg: {in: avg()}, out_avg: {out: avg()}} * ``` * * @param options An object containing options: * @param {bool} options.toTimeEvents Convert the rollup events to `TimeEvent`s, otherwise it * will be returned as a `TimeSeries` of `IndexedEvent`s. * @param {object} options.aggregation The aggregation specification (see description above) * * @return {TimeSeries} The resulting rolled up TimeSeries */ dailyRollup(options) { var { aggregation, toTimeEvents = false } = options; if (!aggregation || !_underscore.default.isObject(aggregation)) { throw new Error("aggregation object must be supplied, for example: {value: {value: avg()}}"); } return this._rollup("daily", aggregation, toTimeEvents); } /** * Builds a new TimeSeries by dividing events into months. * * Each window then has an aggregation specification `aggregation` * applied. This specification describes a mapping of output * fieldNames to aggregation functions and their fieldPath. For example: * ``` * {in_avg: {in: avg()}, out_avg: {out: avg()}} * ``` * * @param options An object containing options: * @param {bool} options.toTimeEvents Convert the rollup events to `TimeEvent`s, otherwise it * will be returned as a `TimeSeries` of `IndexedEvent`s. * @param {object} options.aggregation The aggregation specification (see description above) * * @return {TimeSeries} The resulting rolled up `TimeSeries` */ monthlyRollup(options) { var { aggregation, toTimeEvents = false } = options; if (!aggregation || !_underscore.default.isObject(aggregation)) { throw new Error("aggregation object must be supplied, for example: {value: {value: avg()}}"); } return this._rollup("monthly", aggregation, toTimeEvents); } /** * Builds a new TimeSeries by dividing events into years. * * Each window then has an aggregation specification `aggregation` * applied. This specification describes a mapping of output * fieldNames to aggregation functions and their fieldPath. For example: * * ``` * {in_avg: {in: avg()}, out_avg: {out: avg()}} * ``` * * @param options An object containing options: * @param {bool} options.toTimeEvents Convert the rollup events to `TimeEvent`s, otherwise it * will be returned as a `TimeSeries` of `IndexedEvent`s. * @param {object} options.aggregation The aggregation specification (see description above) * * @return {TimeSeries} The resulting rolled up `TimeSeries` */ yearlyRollup(options) { var { aggregation, toTimeEvents = false } = options; if (!aggregation || !_underscore.default.isObject(aggregation)) { throw new Error("aggregation object must be supplied, for example: {value: {value: avg()}}"); } return this._rollup("yearly", aggregation, toTimeEvents); } /** * @private * * Internal function to build the TimeSeries rollup functions using * an aggregator Pipeline. */ _rollup(type, aggregation) { var toTimeEvents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var aggregatorPipeline = this.pipeline().windowBy(type).emitOn("discard").aggregate(aggregation); var eventTypePipeline = toTimeEvents ? aggregatorPipeline.asTimeEvents() : aggregatorPipeline; var collections = eventTypePipeline.clearWindow().toKeyedCollections(); return this.setCollection(collections["all"], true); } /** * Builds multiple `Collection`s, each collects together * events within a window of size `windowSize`. Note that these * are windows defined relative to Jan 1st, 1970, and are UTC. * * @example * ``` * const timeseries = new TimeSeries(data); * const collections = timeseries.collectByFixedWindow({windowSize: "1d"}); * console.log(collections); // {1d-16314: Collection, 1d-16315: Collection, ...} * ``` * * @param options An object containing options: * @param {bool} options.windowSize The size of the window. e.g. "6h" or "5m" * * @return {map} The result is a mapping from window index to a Collection. */ collectByFixedWindow(_ref) { var { windowSize } = _ref; return this.pipeline().windowBy(windowSize).emitOn("discard").toKeyedCollections(); } /* * STATIC */ /** * Defines the event type contained in this TimeSeries. The default here * is to use the supplied type (time, timerange or index) to build either * a TimeEvent, TimeRangeEvent or IndexedEvent. However, you can also * subclass the TimeSeries and reimplement this to return another event * type. */ static event(eventKey) { switch (eventKey) { case "time": return _timeevent.default; case "timerange": return _timerangeevent.default; case "index": return _indexedevent.default; default: throw new Error("Unknown event type: ".concat(eventKey)); } } /** * Static function to compare two TimeSeries to each other. If the TimeSeries * are of the same instance as each other then equals will return true. * @param {TimeSeries} series1 * @param {TimeSeries} series2 * @return {bool} result */ static equal(series1, series2) { return series1._data === series2._data && series1._collection === series2._collection; } /** * Static function to compare two TimeSeries to each other. If the TimeSeries * are of the same value as each other then equals will return true. * @param {TimeSeries} series1 * @param {TimeSeries} series2 * @return {bool} result */ static is(series1, series2) { return _immutable.default.is(series1._data, series2._data) && _collection.default.is(series1._collection, series2._collection); } /** * Reduces a list of TimeSeries objects using a reducer function. This works * by taking each event in each TimeSeries and collecting them together * based on timestamp. All events for a given time are then merged together * using the reducer function to produce a new event. The reducer function is * applied to all columns in the fieldSpec. Those new events are then * collected together to form a new TimeSeries. * * @example * * For example you might have three TimeSeries with columns "in" and "out" which * corresponds to two measurements per timestamp. You could use this function to * obtain a new TimeSeries which was the sum of the the three measurements using * the `sum()` reducer function and an ["in", "out"] fieldSpec. * * ``` * const totalSeries = TimeSeries.timeSeriesListReduce({ * name: "totals", * seriesList: [inTraffic, outTraffic], * reducer: sum(), * fieldSpec: [ "in", "out" ] * }); * ``` * * @param options An object containing options. Additional key * values in the options will be added as meta data * to the resulting TimeSeries. * @param {array} options.seriesList A list of `TimeSeries` (required) * @param {function} options.reducer The reducer function e.g. `max()` (required) * @param {array | string} options.fieldSpec Column or columns to reduce. If you * need to retrieve multiple deep * nested values that ['can.be', 'done.with', * 'this.notation']. A single deep value with a * string.like.this. * * @return {TimeSeries} The reduced TimeSeries */ static timeSeriesListReduce(options) { var { fieldSpec, reducer } = options, data = (0, _objectWithoutProperties2.default)(options, ["fieldSpec", "reducer"]); var combiner = _event.default.combiner(fieldSpec, reducer); return TimeSeries.timeSeriesListEventReduce(_objectSpread({ fieldSpec, reducer: combiner }, data)); } /** * Takes a list of TimeSeries and merges them together to form a new * Timeseries. * * Merging will produce a new Event; only when events are conflict free, so * it is useful in the following cases: * * to combine multiple TimeSeries which have different time ranges, essentially * concatenating them together * * combine TimeSeries which have different columns, for example inTraffic has * a column "in" and outTraffic has a column "out" and you want to produce a merged * trafficSeries with columns "in" and "out". * * @example * ``` * const inTraffic = new TimeSeries(trafficDataIn); * const outTraffic = new TimeSeries(trafficDataOut); * const trafficSeries = TimeSeries.timeSeriesListMerge({ * name: "traffic", * seriesList: [inTraffic, outTraffic] * }); * ``` * * @param options An object containing options. Additional key * values in the options will be added as meta data * to the resulting TimeSeries. * @param {array} options.seriesList A list of `TimeSeries` (required) * @param {array | string} options.fieldSpec Column or columns to merge. If you * need to retrieve multiple deep * nested values that ['can.be', 'done.with', * 'this.notation']. A single deep value with a * string.like.this. * * @return {TimeSeries} The merged TimeSeries */ static timeSeriesListMerge(options) { var { fieldSpec } = options, data = (0, _objectWithoutProperties2.default)(options, ["fieldSpec"]); var merger = _event.default.merger(fieldSpec); return TimeSeries.timeSeriesListEventReduce(_objectSpread({ fieldSpec, reducer: merger }, data)); } /** * @private */ static timeSeriesListEventReduce(options) { var { seriesList, fieldSpec, reducer } = options, data = (0, _objectWithoutProperties2.default)(options, ["seriesList", "fieldSpec", "reducer"]); if (!seriesList || !_underscore.default.isArray(seriesList)) { throw new Error("A list of TimeSeries must be supplied to reduce"); } if (!reducer || !_underscore.default.isFunction(reducer)) { throw new Error("reducer function must be supplied, for example avg()"); } // for each series, make a map from timestamp to the // list of events with that timestamp var eventList = []; seriesList.forEach(series => { for (var event of series.events()) { eventList.push(event); } }); var events = reducer(eventList, fieldSpec); // Make a collection. If the events are out of order, sort them. // It's always possible that events are out of order here, depending // on the start times of the series, along with it the series // have missing data, so I think we don't have a choice here. var collection = new _collection.default(events); if (!collection.isChronological()) { collection = collection.sortByTime(); } var timeseries = new TimeSeries(_objectSpread({}, data, { collection })); return timeseries; } }
JavaScript
class Notifier extends EventEmitter { /** * Create an instance of Notifier class * @param {config} config - the global config options */ constructor(config) { super(); this.subscribers = {}; } /** * create a subscriber * @param {string} name - the key name of the subscribers * @return {object} ins - the instance of event emitter */ subscribe(name) { this.subscribers[name] = new EventEmitter(); return this.subscribers[name]; } /** * Notify all the subscribers */ notifyAll(...args) { this.emit(...args); } /** * Notify a subscribers * @param {string} name - whom to notify */ notify(name, ...args) { if (this.subscribers[name] instanceof EventEmitter) { this.subscribers[name].emit(...args); } } }
JavaScript
class GetTransactionsList extends GetTransactionBase { /** * Constructor for execute transaction * * @param {Object} params * @param {Integer} params.limit - limit * @param {Array} params.statuses - statuses * @param {Array} params.meta_properties - meta_properties * @param {Integer} [params.start_time] - Start time * @param {Integer} [params.end_time] - End time * */ constructor(params) { super(params); const oThis = this; oThis.status = params.statuses; oThis.limit = params.limit; oThis.metaProperty = params.meta_properties; oThis.startTime = params.start_time || null; oThis.endTime = params.end_time || null; oThis.paginationIdentifier = params[pagination.paginationIdentifierKey]; oThis.auxChainId = null; oThis.transactionDetails = {}; oThis.integerStatuses = []; oThis.responseMetaData = { [pagination.nextPagePayloadKey]: {} }; } /** * Validate and sanitize parameters. * * @returns {*} * * @private */ async _validateAndSanitizeParams() { const oThis = this; // Parameters in paginationIdentifier take higher precedence. if (oThis.paginationIdentifier) { let parsedPaginationParams = oThis._parsePaginationParams(oThis.paginationIdentifier); logger.log('======= Parsed Pagination Params =======', JSON.stringify(parsedPaginationParams)); oThis.status = parsedPaginationParams.status; // Override status oThis.metaProperty = parsedPaginationParams.meta_property; // Override meta_property oThis.limit = parsedPaginationParams.limit; // Override limit oThis.from = parsedPaginationParams.from; // Override from oThis.startTime = parsedPaginationParams.start_time; // Override startTime oThis.endTime = parsedPaginationParams.end_time; // Override endTime } else { oThis.status = oThis.status || []; if (oThis.metaProperty) { oThis.metaProperty = await basicHelper.sanitizeMetaPropertyData(oThis.metaProperty); if (!CommonValidators.validateMetaPropertyArray(oThis.metaProperty)) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'a_s_t_g_bu_1', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['invalid_meta_properties'], debug_options: {} }) ); } } else { oThis.metaProperty = []; } oThis.limit = oThis.limit || oThis._defaultPageLimit(); oThis.from = 0; } if (oThis.from + oThis.limit >= 10000) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'a_s_t_g_bu_3', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['query_not_supported'], debug_options: {} }) ); } // Validate status await oThis._validateAndSanitizeStatus(); // Validate limit return oThis._validatePageSize(); } /** * * @private */ _validateSearchResults() { // Nothing to do. } /** * Set meta property. * * @private */ _setMeta() { const oThis = this, esResponseData = oThis.esSearchResponse.data; if (esResponseData.meta[pagination.hasNextPage]) { let esNextPagePayload = esResponseData.meta[pagination.nextPagePayloadKey] || {}; oThis.responseMetaData[pagination.nextPagePayloadKey] = { [pagination.paginationIdentifierKey]: { from: esNextPagePayload.from, limit: oThis.limit, meta_property: oThis.metaProperty, status: oThis.status, start_time: oThis.startTime || null, end_time: oThis.endTime || null } }; } oThis.responseMetaData[pagination.totalNoKey] = esResponseData.meta[pagination.getEsTotalRecordKey]; } /** * Format API response * * @return {*} * * @private */ _formatApiResponse() { const oThis = this; return responseHelper.successWithData({ [resultType.transactions]: oThis.txDetails, [resultType.meta]: oThis.responseMetaData }); } /** * Get elastic search query. * * @return Object <Service config> * * Eg finalConfig = { * query: { * query_string: { * default_field : "user_addresses_status" OR fields: ['user_addresses_status', 'meta'] if meta present, * query: '( f-0x4e13fc4e514ea40cb3783cfaa4d876d49034aa18 OR t-0x33533531C09EC51D6505EAeA4A17D7810aF1DcF5924A99 ) AND ( n=transaction_name AND t=user_to_user ) AND ( 0 OR 1 )' * } * } * } * * @private **/ _getEsQueryObject() { const oThis = this, addressQueryString = oThis._getUserAddressQueryString(), statusQueryString = oThis._getStatusQueryString(), metaQueryString = oThis._getMetaQueryString(), queryFieldKey = metaQueryString ? 'fields' : 'default_field'; let queryObject = oThis._getQueryObject(), queryBody = queryObject['query']['query_string'], esQueryVals = [addressQueryString], esQuery; if (queryFieldKey === 'fields') { queryBody[queryFieldKey] = [ESConstants.userAddressesOutKey, ESConstants.metaOutKey]; } else { queryBody[queryFieldKey] = ESConstants.userAddressesOutKey; } if (statusQueryString) { esQueryVals.push(statusQueryString); } if (metaQueryString) { esQueryVals.push(metaQueryString); } if (oThis.startTime || oThis.endTime) { const startEndTimeQueryString = oThis._getStartTimeEndTimeQueryString(oThis.startTime, oThis.endTime); esQueryVals.push(startEndTimeQueryString); } esQuery = esQueryFormatter.getAndQuery(esQueryVals); queryBody.query = esQuery; logger.debug('ES query for getting user transaction', oThis.tokenHolderAddress, queryObject); queryObject.size = oThis.limit; queryObject.from = oThis.from; return queryObject; } /** * Get query object. * * @returns {{query: {query_string: {}}}} * * @private */ _getQueryObject() { return { query: { query_string: {} }, sort: [ { created_at: 'desc' } ] }; } /** * Get user address string. * * Eg ( f-0x4e13fc4e514ea40cb3783cfaa4d876d49034aa18 OR t-0x33533531C09EC51D6505EAeA4A17D7810aF1DcF5924A99 ) * * @returns {String} * * @private */ _getUserAddressQueryString() { const oThis = this; const address = [ ESConstants.formAddressPrefix + oThis.tokenHolderAddress, ESConstants.toAddressPrefix + oThis.tokenHolderAddress ], query = esQueryFormatter.getORQuery(address); return esQueryFormatter.getQuerySubString(query); } /** * Get start time and end time query string. * * @param {Integer} startTime * @param {Integer} endTime * @returns {string} * @private */ _getStartTimeEndTimeQueryString(startTime, endTime) { if (startTime && endTime) { return `created_at:(>=${startTime} AND <=${endTime}) `; } else if (startTime) { return `created_at:(>=${startTime}) `; } else if (endTime) { return `created_at:(<=${endTime}) `; } } /** * Get status query string. * * @returns {*} * * @private */ _getStatusQueryString() { const oThis = this; if (oThis.integerStatuses.length === 0) return null; let query = esQueryFormatter.getORQuery(oThis.integerStatuses); return esQueryFormatter.getQuerySubString(query); } /** * Get meta query string. * * @returns {*} * Eg ( ( n=transaction_name1 AND t=user_to_user1 AND d=details1) OR ( n=transaction_name2 AND t=user_to_user2 )) * * @private */ _getMetaQueryString() { const oThis = this; if (!oThis.metaProperty || oThis.metaProperty.length === 0) return null; let metaQueries = []; for (let cnt = 0; cnt < oThis.metaProperty.length; cnt++) { let currMeta = oThis.metaProperty[cnt], currMetaValues = oThis._getMetaVals(currMeta); if (currMetaValues) { let currMetaQuery = esQueryFormatter.getAndQuery(currMetaValues); currMetaQuery = esQueryFormatter.getQuerySubString(currMetaQuery); metaQueries.push(currMetaQuery); } } if (metaQueries.length === 0) return null; let metaQueriesString = esQueryFormatter.getORQuery(metaQueries); return esQueryFormatter.getQuerySubString(metaQueriesString); } /** * Get meta values. * * @param meta * Eg [ {n:name1 , t:type1, d:details1} , {n:name2 , t:type2, d:details2}] * * @returns {*} */ _getMetaVals(meta) { if (!meta) return null; const nameKey = ESConstants.metaNameKey, typeKey = ESConstants.metaTypeKey, detailsKey = ESConstants.metaDetailsKey; let name = meta['name'], type = meta['type'], details = meta['details'], separator = '=', vals = []; if (name) { name = esQueryFormatter.getEscapedQuery(name); let nameVal = nameKey + separator + name; vals.push(nameVal); } if (type) { type = esQueryFormatter.getEscapedQuery(type); let typeVal = typeKey + separator + type; vals.push(typeVal); } if (details) { details = esQueryFormatter.getEscapedQuery(details); let detailsVal = detailsKey + separator + details; vals.push(detailsVal); } if (vals.length == 0) return null; return vals; } /** * Default page limit. * * @private */ _defaultPageLimit() { return pagination.defaultTransactionPageSize; } /** * Minimum page limit. * * @private */ _minPageLimit() { return pagination.minTransactionPageSize; } /** * Maximum page limit. * * @private */ _maxPageLimit() { return pagination.maxTransactionPageSize; } /** * Current page limit. * * @private */ _currentPageLimit() { const oThis = this; return oThis.limit; } /** * Status validations * * @returns {Promise<void>} * * @private */ async _validateAndSanitizeStatus() { const oThis = this; if (!oThis.status.length) return; const validStatuses = pendingTransactionConstants.invertedStatuses; for (let i = 0; i < oThis.status.length; i++) { let currStatusInt = validStatuses[oThis.status[i]]; if (!currStatusInt) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'a_s_t_g_bu_2', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['invalid_statuses'], debug_options: {} }) ); } else { oThis.integerStatuses.push(currStatusInt); } } } }
JavaScript
class LoginActions { constructor() { this.generateActions( 'loginSuccess', 'loginFail', 'noEmail', 'noPassword', 'getUserId' ); } // Making Get call to DB to get user info loginUser(email, password) { $.ajax({ type: 'POST', url: '/api/user/login', data: { userEmail: email, userPassword: password } }) .done((data) => { this.actions.loginSuccess(data); }) .fail((err) => { this.actions.loginFail(err); }); } }
JavaScript
class PubSub extends events.EventEmitter { /** *Creates an instance of PubSub. * @param {object} { host, port } - parameters for initiating the message queue. * @memberof PubSub */ constructor({ host, port }) { super(); this._host = host; this._port = port; this._messageQueue = null; } /** * @description - set the required message queue for pub/sub. * @param {object} messageQueue - message queue object. * @memberof PubSub */ set messageQueue(messageQueue) { let _this = this; _this._messageQueue = messageQueue; _this._messageQueue.init({ host: _this._host, port: _this._port }); _this._messageQueue.on('message', (channel, message) => { _this.emit('message', channel, message); }); } /** * @description - get the message queue which is being used. * @memberof PubSub */ get messageQueue() { return this._messageQueue; } /** * @description - publish a given payload to a specific channel. * @param {string} channel - the channel to be published. * @param {string} payload - payload to be sent. * @memberof PubSub */ publish(channel, payload) { this._messageQueue.publish(channel, payload); } /** * @description - subscribe to a specific channel. * @param {*} channel - the channel to be subscribed. * @memberof PubSub */ subscribe(channel) { let _this = this; _this._messageQueue.subscribe(channel); } }
JavaScript
class FieldBadge extends AbstractField { _getClassFromDecoration(decoration) { return `bg-${decoration.split('-')[1]}-light`; } }
JavaScript
class ContentSearchService { /** * @returns {object} Bounds object for the window. */ get searchBarBounds() { return { width: 400, height: 56 }; } /** * @param {WindowsManager} windowsManager */ constructor(windowsManager) { this.windowsManager = windowsManager; /** * The map of find in page request IDs and the corresponding windows. * * @type {{[key: number]: Electron.WebContents}} */ this.requests = {}; /** * The list of WebContents being currently processed by this content search service. * @type {Electron.WebContents[]} */ this.contents = []; /** * @type {{ barWindow: BrowserWindow, targetWindow: BrowserWindow }[]} */ this.map = []; this[resizeHandler] = this[resizeHandler].bind(this); this[moveHandler] = this[moveHandler].bind(this); this[targetCloseHandler] = this[targetCloseHandler].bind(this); this[barCloseHandler] = this[barCloseHandler].bind(this); this[targetReloadHandler] = this[targetReloadHandler].bind(this); } listen() { ipcMain.on('search-bar-command', this[searchBarCommandHandler].bind(this)); } /** * Starts a search for a content window or focuses on the search button if the search bar is already opened. * @param {Electron.BrowserWindow} win */ start(win) { const item = this.map.find((entry) => entry.targetWindow === win); if (item) { this[focusBarInput](item.barWindow); } else { this[initializeSearchBar](win); } } /** * Creates a new search bar and attaches it to the given windows * @param {Electron.BrowserWindow} targetWindow */ [initializeSearchBar](targetWindow) { const options = { ...this.windowsManager.createBaseWindowOptions('search-bar.js'), frame: false, movable: false, parent: targetWindow, transparent: true, // backgroundColor: '#00ffffff', // hasShadow: false, }; delete options.backgroundColor; const barWindow = new BrowserWindow(options); this.map.push({ barWindow, targetWindow, }); this[positionWindow](barWindow, targetWindow); this.windowsManager.loadPage(barWindow, 'search-bar.html'); this[listenTargetEvents](targetWindow); this[listenBarEvents](barWindow); barWindow.webContents.once('did-finish-load', () => this[focusBarInput](barWindow)); if (process.argv.includes('--dev')) { barWindow.webContents.openDevTools(); } } /** * Positions the search bar window according to main window position. * * @param {Electron.BrowserWindow} barWindow * @param {Electron.BrowserWindow} targetWindow */ [positionWindow](barWindow, targetWindow) { const rect = targetWindow.getBounds(); const winBounds = this.searchBarBounds; const maxRight = rect.width + rect.x; const x = maxRight - winBounds.width - 12; // padding const maxTop = rect.y + 26; winBounds.x = x; winBounds.y = maxTop; barWindow.setBounds(winBounds); } /** * Listens to the target window's move and resize events to reposition the corresponding search bar. * * @param {Electron.BrowserWindow} targetWindow */ [listenTargetEvents](targetWindow) { targetWindow.on('resize', this[resizeHandler]); targetWindow.on('move', this[moveHandler]); targetWindow.on('close', this[targetCloseHandler]); targetWindow.webContents.on('did-start-loading', this[targetReloadHandler]); } /** * Removes previously registered events. * * @param {Electron.BrowserWindow} targetWindow */ [unlistenTargetEvents](targetWindow) { targetWindow.removeListener('resize', this[resizeHandler]); targetWindow.removeListener('move', this[moveHandler]); targetWindow.removeListener('close', this[targetCloseHandler]); targetWindow.webContents.removeListener('did-start-loading', this[targetReloadHandler]); } /** * Listens to the search bar window events * * @param {Electron.BrowserWindow} barWindow */ [listenBarEvents](barWindow) { barWindow.on('close', this[barCloseHandler]); } /** * Removes previously registered search events/ * * @param {Electron.BrowserWindow} barWindow */ [unlistenBarEvents](barWindow) { barWindow.removeListener('close', this[barCloseHandler]); } /** * A handler for `resize` event from the app window. Repositions the search bar window. * @param {any} e Event sent from the app window. */ [resizeHandler](e) { const win = /** @type BrowserWindow */ (e.sender); const item = this.map.find((entry) => entry.targetWindow === win); if (!item) { return; } this[positionWindow](item.barWindow, item.targetWindow); } /** * A handler for `move` event from the app window. Repositions the search bar window. * @param {any} e Event sent from the app window. */ [moveHandler](e) { const win = /** @type BrowserWindow */ (e.sender); const item = this.map.find((entry) => entry.targetWindow === win); if (!item) { return; } this[positionWindow](item.barWindow, item.targetWindow); } /** * Event handler for the application window close handler. Removes this service from cache, * closes search bar (if any) amd removes window listeners. * @param {any} e Event sent from the app window. */ [targetCloseHandler](e) { const win = /** @type BrowserWindow */ (e.sender); const index = this.map.findIndex((entry) => entry.targetWindow === win); if (index === -1) { return } const item = this.map[index]; this.map.splice(index, 1); if (!item.barWindow.isDestroyed()) { item.barWindow.close(); } } [barCloseHandler](e) { const win = /** @type BrowserWindow */ (e.sender); const index = this.map.findIndex((entry) => entry.barWindow === win); if (index === -1) { return } const item = this.map[index]; this.map.splice(index, 1); const { barWindow, targetWindow } = item; if (!this.contents.includes(targetWindow.webContents)) { const contentsIndex = this.contents.indexOf(targetWindow.webContents); this.contents.splice(contentsIndex, 1); } targetWindow.webContents.stopFindInPage('clearSelection'); this[unlistenBarEvents](barWindow); this[unlistenTargetEvents](targetWindow); } /** * Focuses on the input element of the search bar * * @param {Electron.BrowserWindow} barWindow */ [focusBarInput](barWindow) { if (barWindow.isDestroyed()) { return; } if (!barWindow.isVisible()) { barWindow.show(); } barWindow.webContents.send('command', 'focus-input'); } /** * @param {BrowserWindow} targetWindow * @param {BrowserWindow} barWindow * @param {string} query * @param {Electron.FindInPageOptions=} opts */ [findHandler](targetWindow, barWindow, query, opts) { if (!this.contents.includes(targetWindow.webContents)) { this.contents.push(targetWindow.webContents); targetWindow.webContents.on('found-in-page', this[foundInPageHandler].bind(this)); } const request = targetWindow.webContents.findInPage(query, opts); this.requests[request] = barWindow.webContents; } /** * @param {Electron.WebContents} targetContents */ [clearHandler](targetContents) { const index = this.contents.findIndex((item) => item === targetContents); targetContents.stopFindInPage('clearSelection'); targetContents.removeAllListeners('found-in-page'); this.contents.splice(index, 1); } /** * @param {Electron.Event} event * @param {Electron.Result} detail */ [foundInPageHandler](event, detail) { const { requestId, matches, activeMatchOrdinal } = detail; const barContents = this.requests[requestId]; if (!barContents) { return; } delete this.requests[requestId]; barContents.send('search-bar-found-in-page', matches, activeMatchOrdinal); } /** * @param {any} e * @param {...any} args */ [searchBarCommandHandler](e, ...args) { const contents = /** @type Electron.WebContents */ (e.sender); const item = this.map.find((entry) => entry.barWindow.webContents === contents); if (!item) { return } const [command, ...rest] = args; switch (command) { case 'find': this[findHandler](item.targetWindow, item.barWindow, rest[0], rest[1]); break; case 'clear': this[clearHandler](item.targetWindow.webContents); break; case 'close': item.barWindow.close(); break; default: } } [targetReloadHandler](e) { const contents = /** @type Electron.WebContents */ (e.sender); const item = this.map.find((entry) => entry.targetWindow.webContents === contents); if (!item) { return; } item.barWindow.close(); } }
JavaScript
class Controller { static setupEventListeners() { Controller.DOMstrings = UIController.getDOMstrings(); document .querySelector(Controller.DOMstrings.logoutBtn) .addEventListener("click", AuthController.logout); document .querySelector(Controller.DOMstrings.codingProgressLinkSelector) .addEventListener("click", Controller.navigateToCodingProgress); document .querySelector(Controller.DOMstrings.projectMenu) .addEventListener("click", Controller.navigateToSelectedProject); document .querySelector(Controller.DOMstrings.systemsMenu) .addEventListener("click", Controller.navigateToSelectedSystem); } static clearAllTimers() { import("./traffic_graphs_controller.js").then(module => { module.TrafficGraphsController.clearTimers(); }); import("./systems_graphs_controller.js").then(module => { module.SystemsGraphsController.clearTimers(); }); } static resetActiveLink() { let elements = document.querySelectorAll(Controller.DOMstrings.activeLinks); elements.forEach((element) => { element.classList.remove(Controller.DOMstrings.activeLinkClassName); }); } static displayCodingProgress() { // Add the coding progress section to the UI UIController.addCodingProgressSection(); DataController.watchActiveProjects(UIController.addkeywordOptions); Controller.resetActiveLink(); document .querySelector(Controller.DOMstrings.codingProgressLinkSelector) .classList.add(Controller.DOMstrings.activeLinkClassName); // Get data for coding progress table import("./coding_progress_table_controller.js").then((module) => { let unsubscribeFunc = DataController.watchCodingProgress( module.CodingProgressTableController.updateCodingProgressTable ); DataController.registerSnapshotListener(unsubscribeFunc); }); } static displayProject(project) { // Add the graphs container to the UI UIController.addGraphs(project); Controller.resetActiveLink(); document .querySelector(Controller.DOMstrings.trafficsLinkSelector) .classList.add(Controller.DOMstrings.activeLinkClassName); // Update and show the Graphs import("./traffic_graphs_controller.js").then((module) => { let unsubscribeFunc = DataController.watchProjectTrafficData( project, module.TrafficGraphsController.updateGraphs ); DataController.registerSnapshotListener(unsubscribeFunc); }); const { updateTotals, displayATCredits } = TrafficMetricsController; // Update and show the Metrics DataController.projectTrafficDataMetrics(project, updateTotals); // Update Africa's Talking balance let unsubscribeWatchATCredits = DataController.watchATCredits(project, displayATCredits); DataController.registerSnapshotListener(unsubscribeWatchATCredits); } static displayMirandaMetrics() { UIController.addSystemsGraphs(); // Update and show the Graphs import("./systems_graphs_controller.js").then((module) => { let unsubscribeFunc = DataController.watchMirandaMetrics( module.SystemsGraphsController.updateGraphs ); DataController.registerSnapshotListener(unsubscribeFunc); }); } static displayPipelines() { UIController.addPipelinesGraphs(); // Update and show the Graphs import("./pipelines_controller.js").then((module) => { let unsubscribeFunc = DataController.watchPipelinesMetrics( module.PipelinesController.updatePipelinePage ); DataController.registerSnapshotListener(unsubscribeFunc); }); } static navigateToCodingProgress(e) { if (e.target && e.target.nodeName == "A") { Controller.clearAllTimers(); DataController.detachSnapshotListener(); window.location.hash = "coding_progress"; Controller.displayCodingProgress(); } } static navigateToSelectedProject(e) { if (e.target && e.target.nodeName == "A") { Controller.clearAllTimers(); DataController.detachSnapshotListener(); console.log(e.target.innerText); let project = e.target.innerText; window.location.hash = `traffic-${project}`; Controller.displayProject(project); } } static navigateToSelectedSystem(e) { if (e.target && e.target.nodeName == "A") { Controller.resetActiveLink(); document .querySelector(Controller.DOMstrings.systemsLinkSelector) .classList.add(Controller.DOMstrings.activeLinkClassName); Controller.clearAllTimers(); DataController.detachSnapshotListener(); let system = e.target.innerText; if (system.toLowerCase() === "miranda") { Controller.displayMirandaMetrics(); } if (system.toLowerCase() === "pipelines") { Controller.displayPipelines(); } } } static displayDeepLinkedTrafficPage(activeProjectsData) { let activeProjects = [], page_route = window.location.hash.substring(1); activeProjectsData.forEach((project) => { activeProjects.push(project.project_name); }); let project = page_route.split("traffic-")[1]; if (activeProjects.includes(project)) { Controller.displayProject(project); } else { // update the URL and replace the item in the browser history // without reloading the page history.replaceState(null, null, " "); Controller.displayCodingProgress(); } } static init() { console.log("Application has started."); // Authorize user AuthController.getUser(); // set up event listeners Controller.setupEventListeners(); // Add the dropdown menu to the UI DataController.watchActiveProjects(UIController.addDropdownMenu); // Get hash value let page_route = window.location.hash.substring(1); // Navigate appropriately according to the hash value if (page_route) { if (page_route == "coding_progress") { Controller.displayCodingProgress(); } else if (page_route == "systems") { Controller.displaySystems(); } else if (page_route == "pipelines") { Controller.displayPipelines(); } else if (page_route.startsWith("traffic-")) { DataController.watchActiveProjects(Controller.displayDeepLinkedTrafficPage); } else { // update the URL and replace the item in the browser history // without reloading the page history.replaceState(null, null, " "); Controller.displayCodingProgress(); } } else { Controller.displayCodingProgress(); } } }
JavaScript
class TimeAxis extends AbstractModule { constructor(options = {}) { super(parameters, options); } // for use in zoom for example get layer() { return this._layer; } install() { const { timeline, track } = this.block.ui; // dummy axis waiting for track config this._layer = new ui.axis.AxisLayer(ui.axis.timeAxisGenerator(1, '4/4'), { top: 0, height: 12, zIndex: this.zIndex, }); this._layer.setTimeContext(timeline.timeContext); this._layer.configureShape(ui.shapes.Ticks, {}, { color: 'steelblue' }); track.add(this._layer); } uninstall() { const { track } = this.block.ui; track.remove(this._layer); } setTrack(data, metadata) { this._layer.render(); this._layer.update(); } }
JavaScript
class Extension { constructor (location, metadata) { this._location = location } }
JavaScript
class MyLSPlant extends MyLSystem { constructor(scene) { super(scene); this.axiom = "X"; this.ruleF = "FF"; this.angle = 45.0* Math.PI / 180; this.iterations = 4; this.scaleFactor = 0.5; this.ruleII ="F[-X][X]F[-X]+X"; this.ruleIII ="F[-X][X]+X"; this.ruleIV = "F[+X]-X"; this.ruleV = "F[/X][X]F[\\\\X]+X"; this.ruleVI = "F[\\X][X]/X"; this.ruleVII = "F[/X]\\X"; this.ruleVIII = "F[^X][X]F[&X]^X"; this.ruleIX = "F[^X]&X"; this.ruleX = "F[&X]^X"; this.productions = { "F": [ this.ruleF ], "X": [ this.ruleII,this.ruleIII,this.ruleIV,this.ruleV,this.ruleVI,this.ruleVII,this.ruleVIII,this.ruleIX,this.ruleX], }; this.scale = Math.pow(this.scaleFactor, this.iterations-1); this.iterate(); } // cria o lexico da gramática initGrammar(){ this.grammar = { "F": new MyTreeTrunk(this.scene), "X": new MyLeaf(this.scene) }; } }
JavaScript
class App extends Component { render() { return ( <div className="App" style={{height: "100%"}}> <Toolbar/> <Routes /> </div> ) } }
JavaScript
class TriggersSeeder extends Seeder { /** * * @return {boolean} if collection is empty */ async shouldRun() { return Trigger.countDocuments() .exec() .then((count) => count === 0); } /** * * @return {object} trigger objects */ async run() { return Trigger.create(data); } }
JavaScript
class CopyToClipboardController { constructor(el) { this._el = el; this._data = el.dataset['toCopy'] ?? ''; el.addEventListener('click', e => this.handleCopyClick(e)); } handleCopyClick(e) { e.preventDefault(); const TOOLTIP_SHOW_DURATION_MS = 1000; if (!navigator.clipboard) { this.showTooltipText('Unable to copy', TOOLTIP_SHOW_DURATION_MS); return; } navigator.clipboard .writeText(this._data) .then(() => { this.showTooltipText('Copied!', TOOLTIP_SHOW_DURATION_MS); }) .catch(() => { this.showTooltipText('Unable to copy', TOOLTIP_SHOW_DURATION_MS); }); } showTooltipText(text, durationMs) { this._el.setAttribute('data-tooltip', text); setTimeout(() => this._el.setAttribute('data-tooltip', ''), durationMs); } }
JavaScript
class MainScene extends Phaser.Scene { constructor() { super({ key: 'MainScene' }) } create() { const map = this.make.tilemap({ key: 'map' }); const layer = map.createLayer('0', 'tileset', 0, 0); const layer2 = map.createLayer('1', 'tileset', 0, 0); this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels); } update() { } }
JavaScript
class UnitprotRDFService { BASE_URL = null; constructor(base_url = 'https://www.uniprot.org/uniprot') { this.BASE_URL = base_url; } /** * Downloads data for the given protein from Uniprot * @param {string} accession The unique ID of the protein to query for * @returns {Promise<Document>} */ query = async (accession) => { const url = `${ this.BASE_URL }/${ accession }.xml`; const result = await fetch(url); const text = await result.text(); const parser = new DOMParser() const doc = parser.parseFromString(text, "text/xml"); return doc; } }
JavaScript
class Servelet { constructor (options = {}) { this.options = Object.assign({}, defaults, options); this.options.staticExt = this.options.staticExt.split(';'); this.options.dynamicExt = this.options.dynamicExt.split(';'); this.root = this.options.root || path.dirname(require.main.filename); this.emitter = new events.EventEmitter(); this.error = null; this.warning = null; this.ready = false; // These objects contain page name and functions to retrieve page contents this.views = {}; this.partials = {}; // Initiate all valid pages for view and partial folders and handle any errors this.initAllPages((err) => { if (err) { return this.error = err; } this.ready = true; }); } get error () { return this._error; } set error (err) { if (err !== null) { this.emitter.emit('error', err); } this._error = err; } get warning () { return this._warning; } set warning (warn) { if (warn !== null) { this.emitter.emit('warning', warn); } this._warning = warn; } get ready () { return this._ready; } set ready (status) { if (status === true) { this.emitter.emit('ready'); } this._ready = status; } /** * Get a directory string * @param {string} folder The folder name * @return {string} */ getDirectory (folder) { return path.join(this.root, folder, '/'); } /** * Get the page name for the views or partials object * @param {string} page The page name * @return {string} */ getPages (page) { const opts = this.options; return [ (opts.views + page).replace(/\//g, ''), (opts.views + opts.partials + page).replace(/\//g, ''), ]; } /** * Locates and stores all dynamic and/or static pages in the view and partial folders * @param {string=} type The type of file to locate * @param {function(Error)} cb The callback function for error or completion * @return void */ initAllPages (type, cb) { // type is optional / check for callback if (typeof type === 'function') { cb = type; type = 'all'; } let completed = 0, total = 2; // The total amount of scan calls to make /** * Scan for pages within a directory and initialize them * @param {string} dir The directory to search in * @return void */ const scan = (dir) => { let fullDir = this.getDirectory(dir); try { fs.readdir(fullDir, (err, files) => { if (err) { // Callback on initAllPages completion will never fire // because files in this readdir call are never initiated return cb(err); } const totalFiles = files.length; let completedFiles = 0; /** * Check if all async calls are complete * @return void */ const checkCompletion = () => { if (completedFiles === totalFiles) { // All files in directory have been scanned if (++completed === total) { // All readdir calls are complete cb(null); } } }; /** * Complete the current file scan * @param {Error|null} err The error from file init or null * @return void */ const fileComplete = (err) => { if (err) { return cb(err); } completedFiles += 1; checkCompletion(); }; if (totalFiles === 0) { // Empty directory checkCompletion(); } else { files.forEach((file) => { let page = path.parse(file), ext = page.ext.replace('.', ''); if ((type === 'static' || type === 'all') && this.options.staticExt.indexOf(ext) >= 0) { this.initPage(dir, page, fileComplete, true); } else if ((type === 'dynamic' || type === 'all') && this.options.dynamicExt.indexOf(ext) >= 0) { this.initPage(dir, page, fileComplete); } else if (page.ext === '' && page.base !== this.options.partials) { // Check for non-partial directory const newDir = `${dir}/${page.base}`, newFullDir = this.getDirectory(dir); if (fs.existsSync(newFullDir)) { // Add to amount of total scans and scan subdirectory total += 1; fileComplete(null); scan(newDir); } else { fileComplete(null); } } else { // Skip the file for wrong extension type fileComplete(null); } }); } }); } catch (err) { total = -1; this.error = err; cb(`Failed to read from the ${dir} folder.`); } }; scan(this.options.views); scan(`${this.options.views}/${this.options.partials}`); } /** * Initialize a static page to the views or partials object * @param {string} dir The directory of the page * @param {Object} page The path.parse object for the page * @param {Function} cb The callback function for error or completion * @param {bool} isStatic If the page is a static page * @return void */ initPage (dir, page, cb, isStatic) { const opts = this.options, displayType = (dir.indexOf(`${opts.views}/${opts.partials}`) >= 0) ? 'partials' : 'views', loc = this[displayType], name = dir.replace(/\//g, '') + page.name, fullDir = this.getDirectory(dir); if (isStatic) { // Cache the file content for the static page // and use a helper function to retrieve the content this.getStaticFile(fullDir + page.base, (err, content) => { if (err) { return cb(err); } loc[name] = () => content; loc[name]['type'] = 'static'; loc[name]['ext'] = page.ext; loc[name]['page'] = page.name; loc[name]['dir'] = dir; cb(null); }); } else { // Get the dynamic page content by requiring the file try { loc[name] = require(fullDir + page.base); if (typeof loc[name] !== 'function') { this.warning = `The ${name} dynamic page did not export a module to build the page content.`; loc[name] = () => {}; } loc[name]['type'] = 'dynamic'; loc[name]['ext'] = page.ext; cb(null); } catch (e) { // Reset page to return empty string for its content loc[name] = () => ''; loc[name]['type'] = 'dynamic'; loc[name]['ext'] = page.ext; return cb(e); } } } /** * Get the content of a static page file * @param {string} fname The absolute file name to load from the views folder * @param {function(Error, string)} cb The callback to handle an error and the file content * @return void */ getStaticFile (fname, cb) { fs.readFile(fname, 'utf8', (err, data) => { if (err) { return cb(err); } cb(null, data); }); } /** * Load a page based on static or dynamic extension * @param {string=} page The page name to load. Defaults to 'index' * @param {Object=} data The data object to send to the dynamic page * @param {bool} layout If the page is a layout * @return {string} The compiled content from the loaded page */ loadPage (page = 'index', data = {}, layout = false) { const fullPage = this.getPages(page)[0]; let res = ''; if (this.views.hasOwnProperty(fullPage)) { // All pages in the views object will have either static or dynamic extensions // and have a function (unless an error occurred) that returns a string of the content try { // If using a layout, the data object has already been created let allData = (layout) ? data : this.createDataObject(data); // A static page will just ignore the object sent to it res = this.views[fullPage](allData); } catch (err) { // Catch any errors that happen within the dynamic page this.error = err; return `An error has occurred within the dynamic ${page} page.`; } return res; } else { res = `The ${page} page could not be found.`; this.error = new Error(res); return res; } } /** * Include one or more partial files into a dynamic page * @param {string|string[]} page A page name or array of page names to include from the partials * @param {Object=} data An object of data to send to the partial page * @return void */ includePartial (page, data = {}) { const fullPage = this.getPages(page)[1]; if (Array.isArray(page)) { page.forEach((p) => { this.includePartial(p, data); }); } else { if (this.partials.hasOwnProperty(fullPage)) { try { let content = this.partials[fullPage](data); return content; } catch (e) { this.error = e; return ''; } } else { this.error = new Error(`Could not find the ${page} include file.`); return ''; } } } /** * Create the dynamic page data object * @param {Object} data The initial data object * @return {Object} */ createDataObject (data) { let dataObj = Object.assign({}, data); dataObj.global = this.options.globalData; dataObj.include = (page, newData) => { return this.include(dataObj, page, newData); }; dataObj.layout = (page, ...html) => { return this.layout(dataObj, page, html); }; return dataObj; } /****************/ /** API Methods */ /****************/ /** * Include a partial file * @param {Object} data The original data object * @param {string} page The page name to include * @param {Object=} newData Any new data to pass through * @return {string} The html string from the include */ include (data, page, newData) { return this.includePartial( page, Object.assign({}, data, newData) ); } /** * Include a layout view * @param {Object} data The original data object * @param {string} page The layout name with optional view names that bind to the data object * (e.g. 'layout:body' or 'layout:section1:section2) * @param {string[]} html The array of html string(s) to bind to the data object sent to the layout * @return {string} The html string from the layout */ layout (data, page, html) { let pages = page.split(':'), htmlData = {}; if (pages && page[0]) { // Assign the html to the layout variable and add the original data for (let i = 1; i < pages.length; i += 1) { htmlData[pages[i]] = html[i - 1] || ''; } Object.assign(data, htmlData); // Load the layout page with the new data return this.loadPage(pages[0], data, true); } else { return html; } } }
JavaScript
class API { constructor (options) { this[serveletKey] = new Servelet(options); } /** * The error that occurred or null * @return {Error|null} */ get error () { return this[serveletKey].error; } /** * If the servelet instance is ready to serve * @return {boolean} */ get ready () { return this[serveletKey].ready; } /** * Update the global data object that is passed to all dynamic pages * @param {Object} data The object to update the dynamic data with * @return {Object} The servelet instance */ updateGlobalData (data) { Object.assign(this[serveletKey].options.globalData, data); return this; } /** * Serves dynamic or static pages in the views folder as compiled text * Use the on('error', callback) method to catch errors. * @param {string} page The page name to serve from the views folder * @param {Object=} data The object to pass into a dynamic page * @param {function(Error, string)=} callback The optional callback for completion * @return {Object} The servelet instance */ /** * Serves dynamic or static pages in the views folder as compiled text * Use the on('error', callback) method to catch errors. * @param {string} page The page name to serve from the views folder * @param {function(Error, string)=} callback The optional callback for completion * @return {Object} The servelet instance */ serve (page, data = {}, callback) { // Overload if (typeof data === 'function') { callback = data; data = {}; } callback(this[serveletKey].loadPage(page, data)); } /** * Add an event listener for one of these events: 'error', 'warning', 'ready' * @param {string} event The event to listen for * @param {Function} callback The callback function * @return {Object} The servelet instance */ on (event, callback) { this[serveletKey].emitter.addListener(event, callback); return this; } /** * Remove an event listener for one of these events: 'error', 'warning', 'ready' * @param {string} event The event to listen for * @param {Function} callback The callback that was used in the 'on' method call * @return {Object} The servelet instance */ off (event, callback) { this[serveletKey].emitter.removeListener(event, callback); return this; } /** * Reload one or more static pages in the servelet Cache * Omit page argument to reload all static pages. * @param {(string|string[])=} page An optional page name or array of page names * @param {Function(Error|null)=} callback The callback function for error or completion * @return {Object} The servelet instance */ reloadStaticPage (page, callback = () => {}) { // page is optional / check for callback if (typeof page === 'function') { callback = page; page = null; } const serve = this[serveletKey], opts = serve.options; let complete = (err) => { if (err) { return callback(err); } callback(null); }; if (Array.isArray(page)) { page.forEach(this.reloadStaticPage.bind(this)); } else if (typeof page === 'string') { const fullPage = serve.getPages(page); let dir = '', file = '', ext = serve.options.staticExt, view = (serve.views.hasOwnProperty(fullPage[0])) ? serve.views[fullPage[0]] : null, partial = (serve.partials.hasOwnProperty(fullPage[1])) ? serve.partials[fullPage[1]] : null; if (view && ext.indexOf(view.ext.replace('.', '')) >= 0) { dir = view.dir; file = view.page + view.ext; } else if (partial && ext.indexOf(partial.ext.replace('.', '')) >= 0) { dir = partial.dir; file = partial.page + partial.ext; } else { callback(new Error(`Could not reload the static ${page} page, since it was never initialized.`)); return this; } // Re-initialize a single static page serve.initPage(dir, path.parse(file), complete, true); } else { // Re-initialize all static pages serve.initAllPages('static', complete); } return this; } }
JavaScript
class LeftMenu extends HTMLElement { constructor() { super(); this.render = this.render.bind(this); this.addView = this.addView.bind(this); this.toGrid = this.toGrid.bind(this); this.toTabbed = this.toTabbed.bind(this); this.toRows = this.toRows.bind(this); this.cloneWindow = this.cloneWindow.bind(this); this.nonLayoutWindow = this.nonLayoutWindow.bind(this); this.replaceLayoutFromTemplate = this.replaceLayoutFromTemplate.bind(this); this.applySnapshotFromTemplate = this.applySnapshotFromTemplate.bind(this); this.onclick = this.clickHandler.bind(this); //List of apps available in the menu. this.appList = [ { url: CHART_URL, printName: 'OF Chart', processAffinity: 'ps_1' }, { url: 'https://www.tradingview.com/chart/?symbol=NASDAQ:AAPL', printName: 'TradeView', processAffinity: 'tv_1' }, { url: 'https://www.google.com/search?q=INDEXDJX:+.DJI&stick=H4sIAAAAAAAAAONgecRozC3w8sc9YSmtSWtOXmNU4eIKzsgvd80rySypFBLjYoOyeKS4uDj0c_UNkgsry3kWsfJ5-rm4Rrh4RVgp6Ll4eQIAqJT5uUkAAAA&source=lnms&sa=X&ved=0ahUKEwii_NWT9fzoAhU3mHIEHWy3AWIQ_AUIDSgA&biw=1280&bih=1366&dpr=1', printName: 'News', processAffinity: 'mw_1' } ]; this.snapshotMenu = document.querySelector('snapshot-menu'); this.layoutMenu = document.querySelector('layout-menu'); this.layoutContainer = document.querySelector('#layout-container'); this.render(); //Whenever the store updates we will want to render any new elements. onStoreUpdate(() => { this.render(); }); } clickHandler(e) { const target = e.target; if (target.className === 'snapshot-button' || target.className === 'layout-button') { if (!this.layoutContainer.classList.contains('hidden')) { this.layoutContainer.classList.toggle('hidden'); } } if (target.className === 'snapshot-button') { this.snapshotMenu.showElement(); this.layoutMenu.hideElement(); } else if (target.className === 'layout-button') { this.layoutMenu.showElement(); this.snapshotMenu.hideElement(); } else { this.layoutMenu.hideElement(); this.snapshotMenu.hideElement(); if (this.layoutContainer.classList.contains('hidden')) { this.layoutContainer.classList.toggle('hidden'); } } } async render() { const layoutTemplates = getTemplates(LAYOUT_STORE_KEY); const snapshotTemplates = getTemplates(SNAPSHOT_STORE_KEY); const menuItems = html` <span>Applications</span> <ul> ${this.appList.map((item) => html`<li> <button @click=${() => this.addView(item.printName)}>${item.printName}</button> </li>`)} <li><button @click=${() => this.nonLayoutWindow().catch(console.error)}>OF Window</button></li> </ul> <span>Layouts</span> <ul> <li><button @click=${() => this.toGrid().catch(console.error)}>Grid</button></li> <li><button @click=${() => this.toTabbed().catch(console.error)}>Tab</button></li> ${layoutTemplates.map((item) => html`<li> <button @click=${() => this.replaceLayoutFromTemplate(item.name)}>${item.name}</button> </li>`)} <li><button @click=${() => this.cloneWindow().catch(console.error)}>Clone</button></li> <li><button class="layout-button">Save Layout</button></li> </ul> <span>Snapshots</span> <ul> ${snapshotTemplates.map((item) => html`<li><button @click=${() => this.applySnapshotFromTemplate(item.name)}>${item.name}</button></li>`)} <li><button class="snapshot-button">Save Snapshot</button></li> </ul>`; return render(menuItems, this); } async applySnapshotFromTemplate(templateName) { const template = getTemplateByName(SNAPSHOT_STORE_KEY, templateName); return fin.Platform.getCurrentSync().applySnapshot(template.snapshot, { closeExistingWindows: template.close }); } async replaceLayoutFromTemplate(templateName) { const templates = getTemplates(LAYOUT_STORE_KEY); const templateToUse = templates.find(i => i.name === templateName); fin.Platform.Layout.getCurrentSync().replace(templateToUse.layout); } async addView(printName) { const viewOptions = this.appList.find(i => i.printName === printName); return fin.Platform.getCurrentSync().createView(viewOptions, fin.me.identity); } async toGrid() { await fin.Platform.Layout.getCurrentSync().applyPreset({ presetType: 'grid' }); } async toTabbed() { await fin.Platform.Layout.getCurrentSync().applyPreset({ presetType: 'tabs' }); } async toRows() { await fin.Platform.Layout.getCurrentSync().applyPreset({ presetType: 'rows' }); } async cloneWindow() { const bounds = await fin.me.getBounds(); const layout = await fin.Platform.Layout.getCurrentSync().getConfig(); const snapshot = { windows: [ { defaultWidth: bounds.width, defaultHeight: bounds.height, layout } ] }; return fin.Platform.getCurrentSync().applySnapshot(snapshot); } async nonLayoutWindow() { return fin.Platform.getCurrentSync().applySnapshot({ windows: [{ defaultWidth: 600, defaultHeight: 600, defaultLeft: 200, defaultTop: 200, saveWindowState: false, url: CHART_URL, contextMenu: true }] }); } }
JavaScript
class TitleBar extends HTMLElement { constructor() { super(); this.render = this.render.bind(this); this.maxOrRestore = this.maxOrRestore.bind(this); this.toggleTheme = this.toggleTheme.bind(this); this.toggleMenu = this.toggleMenu.bind(this); this.render(); } async render() { const titleBar = html` <div class="title-bar-draggable"> <div id="title"></div> </div> <div id="buttons-wrapper"> <div class="button" title="Toggle Theme" id="theme-button" @click=${this.toggleTheme}></div> <div class="button" title="Toggle Sidebar" id="menu-button" @click=${this.toggleMenu}></div> <div class="button" title="Toggle Layout Lock" id="lock-button" @click=${this.toggleLockedLayout}></div> <div class="button" title="Minimize Window" id="minimize-button" @click=${() => fin.me.minimize().catch(console.error)}></div> <div class="button" title="Maximize Window" id="expand-button" @click=${() => this.maxOrRestore().catch(console.error)}></div> <div class="button" title="Close Window" id="close-button" @click=${() => fin.me.close().catch(console.error)}></div> </div>`; return render(titleBar, this); } async maxOrRestore() { if (await fin.me.getState() === "normal") { return await fin.me.maximize(); } return fin.me.restore(); } async toggleLockedLayout () { const oldLayout = await fin.Platform.Layout.getCurrentSync().getConfig(); const { settings, dimensions } = oldLayout; if(settings.hasHeaders && settings.reorderEnabled) { fin.Platform.Layout.getCurrentSync().replace({ ...oldLayout, settings: { ...settings, hasHeaders: false, reorderEnabled: false } }); } else { fin.Platform.Layout.getCurrentSync().replace({ ...oldLayout, settings: { ...settings, hasHeaders: true, reorderEnabled: true }, dimensions: { ...dimensions, headerHeight: 25 } }); } }; toggleTheme () { const root = document.documentElement; root.classList.toggle('light-theme'); } toggleMenu () { document.querySelector('left-menu').classList.toggle('hidden'); } }
JavaScript
class CourseDetail { constructor(input) { this.assignment_name = input.assignment_name this.assignment_grade = input.assignment_grade this.lastname = input.student.lastname this.firstname = input.student.firstname } //end constructor } // end class CourseDetails
JavaScript
class GetBatchDataResponseWrapper { /** * @param {number} statusCode * @param {*} response */ constructor(statusCode, response) { /** * @type {number} */ this.statusCode = statusCode; /** * @type {*} */ this.response = response; } /** * @returns { BatchDataResponse } */ getResponse200() { if (this.statusCode !== 200) { throw new Error("Invalid response getter called. getResponse200 can't return a " + this.statusCode + " response"); } return this.response; } /** * @returns { BatchStatusResponse } */ getResponse202() { if (this.statusCode !== 202) { throw new Error("Invalid response getter called. getResponse202 can't return a " + this.statusCode + " response"); } return this.response; } }
JavaScript
class GetBatchDataWithPostResponseWrapper { /** * @param {number} statusCode * @param {*} response */ constructor(statusCode, response) { /** * @type {number} */ this.statusCode = statusCode; /** * @type {*} */ this.response = response; } /** * @returns { BatchDataResponse } */ getResponse200() { if (this.statusCode !== 200) { throw new Error("Invalid response getter called. getResponse200 can't return a " + this.statusCode + " response"); } return this.response; } /** * @returns { BatchStatusResponse } */ getResponse202() { if (this.statusCode !== 202) { throw new Error("Invalid response getter called. getResponse202 can't return a " + this.statusCode + " response"); } return this.response; } }
JavaScript
class NotImplementedException extends Exception { /** * @constructor * @summary Constructs a new not implemented exception */ constructor(message) { super(message || "Not Implemented", ErrorCodes.NOT_IMPLEMENTED); } }
JavaScript
class ArgumentException extends Exception { constructor(argName) { super("Improper argument value for " + argName, ErrorCodes.ARGUMENT_EXCEPTION); } }
JavaScript
class RuleViolation { /** * @constructor * @summary Creates a new instance of the rule violation * @param {string} message The message to be shown * @param {string} code A codified reason for the violation * @param {string} severity The severity of the rule violation */ constructor(message, code, severity) { this._message = message; this._code = code; this._severity = severity; } /** * @method * @summary Represent as JSON */ toJSON() { return { message: this._message, code: this._code, severity: this._severity } } }
JavaScript
class BusinessRuleViolationException extends Exception { /** * @constructor * @param {*} violations The business rules that were violated either as a hash map or list of strings */ constructor(violations) { // Transcribe and call super if(Array.isArray(violations)) { var causedBy = []; for(var i in violations) { if(violations[i] instanceof String) causedBy.push(new RuleViolation(violations[i], ErrorCodes.UNKNOWN, RuleSeverity.ERROR)); else if(violations[i] instanceof RuleViolation) causedBy.push(violations[i]); } super("Business constraint failed", ErrorCodes.RULES_VIOLATION, causedBy); } else if(violations) super(violations, ErrorCodes.RULES_VIOLATION); else super("Business constraint failed", ErrorCodes.RULES_VIOLATION); this._violations = violations; } }
JavaScript
class NotFoundException extends Exception { /** * @constructor * @summary Creates a new instance of the NotFoundException * @param {string} objectType The type of object that was not found * @param {string} objectId The identifier of the object */ constructor(objectType, objectId) { super(`${objectType} with id ${objectId} was not found`, ErrorCodes.NOT_FOUND); } }
JavaScript
class NotSupportedException extends Exception { /** * @constructor * @summary Creates a new instance of the NotSupportedException */ constructor(message) { super(message || "Operation not supported", ErrorCodes.NOT_SUPPORTED); } }
JavaScript
class Title { /** * @param {Object|DefaultConfig} parserConfig */ constructor(parserConfig) { if(parserConfig instanceof DefaultConfig) this.parserConfig = parserConfig; else this.parserConfig = new DefaultConfig(parserConfig); this.contentLanguage = this.parserConfig.contentLanguage; this.namespacesWithSubpages = [ Title.NS_TALK, Title.NS_USER, Title.NS_USER_TALK, Title.NS_PROJECT, Title.NS_PROJECT_TALK, Title.NS_FILE_TALK, Title.NS_MEDIAWIKI, Title.NS_MEDIAWIKI_TALK, Title.NS_TEMPLATE, Title.NS_TEMPLATE_TALK, Title.NS_HELP, Title.NS_HELP_TALK, Title.NS_CATEGORY_TALK ]; this.mNamespace = Title.NS_MAIN; this.mDbkeyform = null; this.mInterwiki = ''; this.mFragment = ''; this.mUrlform = ''; this.mTextform = ''; } /** * Create a new Title from text, such as what one would find in a link. * Decodes any HTML entities in the text. * * @param {String} text title text * @param {Object|DefaultConfig} parserConfig parser configuration * @param {Number} [namespace=Title.NS_MAIN] title namespace * @return {Title} * @static */ static newFromText(text, parserConfig, namespace=Title.NS_MAIN) { // DWIM: Integers can be passed in here when page titles are used as array keys. if(typeof text != 'string' && typeof text != 'number') throw new Error('Text must be a string.'); if(!text) return null; // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text const filteredText = Sanitizer.decodeCharReferencesAndNormalize(text); const t = new Title(parserConfig); t.mDbkeyform = filteredText.replace(/ /g, '_'); t.mNamespace = Title.NS_MAIN; t.secureAndSplit(); if(namespace != Title.NS_MAIN) t.mNamespace = namespace; return t; } /** * Secure and split - main initialisation function for this object * * Assumes that mDbkeyform has been set, and is urldecoded * and uses underscores, but not otherwise munged. This function * removes illegal characters, splits off the interwiki and * namespace prefixes, sets the other forms, and canonicalizes * everything. * * @return {Boolean} True on success * @private */ secureAndSplit() { // MediaWikiTitleCodec.splitTitleString short reimplementation // Strip Unicode bidi override characters. this.mDbkeyform = this.mDbkeyform.replace(/[\u200E\u200F\u202A-\u202E]+/gu, ''); // Clean up whitespace this.mDbkeyform = this.mDbkeyform.replace(/[ _\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/gu, '_'); this.mDbkeyform = this.mDbkeyform.replace(/(^_*)|(_*$)/g, ''); const UTF8_REPLACEMENT = '\xef\xbf\xbd'; if(this.mDbkeyform.indexOf(UTF8_REPLACEMENT) != -1) // Contained illegal UTF-8 sequences or forbidden Unicode chars. throw new Error('The requested page title contains an invalid UTF-8 sequence.'); // Initial colon indicates main namespace rather than specified default // but should not create invalid {ns,title} pairs such as {0,Project:Foo} if(this.mDbkeyform != '' && this.mDbkeyform[0] == ':') { this.mNamespace = Title.NS_MAIN; this.mDbkeyform = this.mDbkeyform.substr(1); // remove the colon but continue processing this.mDbkeyform = this.mDbkeyform.replace(/^_*/, ''); // remove any subsequent whitespace } // Namespace or interwiki prefix let m = null; if((m = /^(.+?)_*:_*(.*)$/g.exec(this.mDbkeyform))) { let ns = this.getNsIndex(m[1]); if(ns !== false) { // Ordinary namespace this.mDbkeyform = m[2]; this.mNamespace = ns; // Talk:X pages - skipped } else if(this.isValidInterwiki(m[1])) { // Interwiki link this.mDbkeyform = m[2]; this.mInterwiki = m[1]; // If there's an initial colon after the interwiki, that also // resets the default namespace if(this.mDbkeyform != '' && this.mDbkeyform[0] == ':') { this.mNamespace = Title.NS_MAIN; this.mDbkeyform = this.mDbkeyform.substr(1); this.mDbkeyform = this.mDbkeyform.replace(/^_*/, ''); } } // If there's no recognized interwiki or namespace, // then let the colon expression be part of the title. } // non empty title only if(this.mDbkeyform == '') throw new Error('The requested page title is empty or contains only the name of a namespace.') // fragment const fragment = this.mDbkeyform.indexOf('#'); if(fragment != -1) { this.mFragment = this.mDbkeyform.substr(fragment + 1); this.mDbkeyform = this.mDbkeyform.substr(0, fragment); // remove whitespace again: prevents "Foo_bar_#" // becoming "Foo_bar_" this.mDbkeyform = this.mDbkeyform.replace(/_*$/g, ''); } // Reject illegal characters. if((m = Title.getTitleInvalidRegex().exec(this.mDbkeyform))) throw new Error(`The requested page title contains invalid characters: "${ m[0] }".`); // Pages with "/./" or "/../" appearing in the URLs will often be un- // reachable due to the way web browsers deal with 'relative' URLs. // Also, they conflict with subpage syntax. Forbid them explicitly. if(this.mDbkeyform.indexOf('.') != -1 && ( this.mDbkeyform == '.' || this.mDbkeyform == '..' || this.mDbkeyform.indexOf('./') == 0 || this.mDbkeyform.indexOf('../') == 0 || this.mDbkeyform.indexOf('/./') != -1 || this.mDbkeyform.indexOf(/../) != -1 || /\/\.$/.test(this.mDbkeyform) || /\/\.\.$/.test(this.mDbkeyform))) throw new Error('Title has relative path. Relative page titles (./, ../) are invalid, because they will often be unreachable when handled by user\'s browser.'); // Magic tilde sequences? Nu-uh! if(this.mDbkeyform.indexOf('~~~') != -1) throw new Error('The requested page title contains invalid magic tilde sequence (<nowiki>~~~</nowiki>).') // Limit the size of titles to 255 bytes. This is typically the size of the // underlying database field. We make an exception for special pages, which // don't need to be stored in the database, and may edge over 255 bytes due // to subpage syntax for long titles, e.g. [[Special:Block/Long name]] const maxLength = this.mNamespace != Title.NS_SPECIAL ? 255 : 512; if(this.mDbkeyform.length > maxLength) throw new Error(`The requested page title is too long. It must be no longer than ${ maxLength } bytes in UTF-8 encoding.`) // Normally, all wiki links are forced to have an initial capital letter so [[foo]] // and [[Foo]] point to the same place. Don't force it for interwikis, since the // other site might be case-sensitive. this.mDbkeyform = this.mDbkeyform[0].toUpperCase() + this.mDbkeyform.substr(1); // Can't make a link to a namespace alone... "empty" local links can only be // self-links with a fragment identifier. if(this.mDbkeyform == '' && this.mInterwiki == '' && this.mNamespace != Title.NS_MAIN) throw new Error('The requested page title is empty or contains only the name of a namespace.') // IPv6 usernames - skipped // Any remaining initial :s are illegal. if(this.mDbkeyform != '' && this.mDbkeyform[0] == ':') throw new Error('The requested page title contains an invalid colon at the beginning.'); this.mUrlform = encodeURIComponent(this.mDbkeyform); this.mTextform = this.mDbkeyform.replace(/_/g, ' '); return true; } /** * Check namespace number by its name (return false if namespace not found) * * @param {String} ns namespace name * @return {Number|Boolean} False when namespace unknown */ getNsIndex(ns) { return this.contentLanguage.getNamespaceIndex(ns); } /** * Get the namespace text * * @param {Number|Boolean} [ns=false] optional. If not set - this.mNamespace is used * @return {String|Boolean} return false when unknown namespace id */ getNsText(ns=false) { ns = ns === false ? this.mNamespace : ns; let a = this.contentLanguage.getNamespaceName(ns); return a ? a : false; } /** * Get a regex character class describing the legal characters in a link * * @return {String} * @private * @static */ static legalChars() { return " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+"; } /** * Returns a simple regex that will match on characters and sequences invalid in titles. * Note that this doesn't pick up many things that could be wrong with titles, but that * replacing this regex with something valid will make many titles valid. * Previously Title::getTitleInvalidRegex() * * @return {RegExp} RegExp object * @private * @static */ static getTitleInvalidRegex() { return new RegExp( // Any character not allowed is forbidden... '[^' + Title.legalChars() + ']' + // URL percent encoding sequences interfere with the ability // to round-trip titles -- you can't link to them consistently. '|%[0-9A-Fa-f]{2}' + // XML/HTML character references produce similar issues. '|&[A-Za-z0-9\x80-\xff]+;' + '|&#[0-9]+;' + '|&#x[0-9A-Fa-f]+;', 'g'); } /** * Get the main part with underscores * * @return {String} */ getDBkey() { return this.mDbkeyform; } /** * Get the namespace index, i.e. one of the Title.NS_xxxx constants. * * @return {Number} */ getNamespace() { return this.mNamespace; } /** * Get the interwiki prefix * * @return {String} Interwiki prefix */ getInterwiki() { return this.mInterwiki; } /** * Is this Title interwiki? * * @return {Boolean} */ isExternal() { return this.mInterwiki != ''; } /** * Check if namespace is valid interwiki name * * @param {String} ns namespace text * @return {Boolean} */ isValidInterwiki(ns) { return this.parserConfig.validInterwikiNames.includes(ns); } /** * Get the Title fragment (i.e. the bit after the #) in text form * * @return {String} */ getFragment() { return this.mFragment; } /** * Check if a Title fragment is set * * @return {Boolean} */ hasFragment() { return this.mFragment != ''; } /** * Compare with another title. * * @param {Title} title * @return {Boolean} */ equals(title) { // Note: === is necessary for proper matching of number-like titles. return this.mInterwiki == title.getInterwiki() && this.mNamespace == title.getNamespace() && this.mDbkeyform === title.getDBkey(); } /** * Get the prefixed title with spaces. * This is the form usually used for display * * @param {Boolean} [skipInterwiki=false] * @param {Boolean} [forUrl=false] encode result for URL * @return {String} The prefixed title, with spaces */ getPrefixedText(skipInterwiki=false, forUrl=false) { let t = ''; if(!skipInterwiki && this.isExternal()) t = this.mInterwiki + ':'; if(this.mNamespace != 0) { let nsText = this.getNsText(); if(nsText === false) // See T165149. Awkward, but better than erroneously linking to the main namespace. nsText = this.getNsText(Title.NS_SPECIAL) + `:Badtitle/NS${ this.mNamespace }`; t += nsText + ':'; } if(forUrl) t += this.mDbkeyform; else t += this.mDbkeyform.replace(/_/g, ' '); return t; } /** * Get the text form (spaces not underscores) of the main part * * @return {String} */ getText() { return this.mTextform; } /** * Get the prefixed database key form * * @return {String} */ getPrefixedDBkey() { return this.getPrefixedText().replace(/ /g, '_'); } /** * Get the URL-encoded form of the main part * * @return {String} */ getPartialURL() { return this.mUrlform; } /** * Check if page exists * * @return {Boolean} */ exists() { if(this.mDbkeyform == '' && this.hasFragment()) return true; return this.parserConfig.titleExists(this) } /** * Should links to this title be shown as potentially viewable (i.e. as * "bluelinks"), even if there's no record by this title in the page * table? * * @return {Boolean} */ isAlwaysKnown() { if(this.mInterwiki != '') return true; // any interwiki link might be viewable, for all we know switch(this.mNamespace) { case Title.NS_MEDIA: case Title.NS_FILE: case Title.NS_SPECIAL: case Title.NS_MEDIAWIKI: return true; case Title.NS_MAIN: // selflink, possibly with fragment return this.mDbkeyform == ''; default: return false; } } /** * Does this title refer to a page that can (or might) be meaningfully * viewed? * * @return {Boolean} */ isKnown() { return this.isAlwaysKnown() || this.exists(); } /** * Get a real URL referring to this title, with interwiki link query and * fragment * * @param {URLSearchParams|Object|Array|String} [query] * @param {String} [proto='//'] Protocol type to use in URL ('//' - relative, 'http://', 'https://') * @param {Boolean} [skipFragment=false] * @return {String} The URL */ getFullURL(query=null, proto='//', skipFragment=false) { let url = this.parserConfig.getFullURL(this, query, proto); if(url) return url; // redirect to fragment only if(this.mFragment != '' && this.mDbkeyform == '' && !query) return '#' + this.mFragment; // reduce query to string if(!(query instanceof URLSearchParams)) query = new URLSearchParams(query ? query : ''); query.set('title', this.getPrefixedText(true, true)); query = new URLSearchParams([['title', query.get('title')], ...Array.from(query.entries()).filter(([k,]) => k != 'title')]); // title should be first query param const longQuery = Array.from(query.values()).length > 1 || !query.has('title'); query = query.toString(); // interwiki url = this.parserConfig.baseUrlForTitle; if(longQuery) url = this.parserConfig.baseUrlForQuery; if(this.isExternal()) url = this.parserConfig.interwikiUrl.replace(/\$LANGUAGE/g, this.mInterwiki); // generate url url = url.replace(/\$PROTOCOL/g, proto) .replace(/\$TITLE/g, this.getPrefixedText(true, true)) .replace(/\$QUERY/g, query); if(!skipFragment && this.mFragment != '') url += '#' + this.mFragment; return url; } /** * Get the edit URL for this Title (if not interwiki) * * @return {String} */ getEditURL() { if(this.isExternal()) return ''; return this.getFullURL({action: 'edit'}); } /** * Get url for image (ie. /images/a/af/LoremIpsum.png) * * @return {String} */ getImageURL() { let a = this.parserConfig.getImageURL(this); if(a) return a; a = md5_lib(this.mUrlform); return `/images/${ a[0] }/${ a[0] + a[1] }/${ this.mUrlform }`; } /** * Get url for image thumb (ie. /images/thumb/a/af/LoremIpsum.png/150px-LoremIpsum.png) * * @param {Number} width thumb width * @return {String} */ getThumbURL(width) { let a = this.parserConfig.getThumbURL(this); if(a) return a; a = md5_lib(this.mUrlform); return `/images/thumb/${ a[0] }/${ a[0] + a[1] }/${ this.mUrlform }/${ width }px-${ this.mUrlform }`; } /** * Get upload link for image file * * @return {String} */ getImageUploadURL(proto='//') { let t = this.parserConfig.contentLanguage.getSpecialPageTitle('upload', this.parserConfig); return t.getFullURL({ wpDestFile: this.getPartialURL() }, proto); } /** * Get the lowest-level subpage name, i.e. the rightmost part after any slashes * * ```javascript * Title.newFromText('User:Foo/Bar/Baz').getSubpageText(); * // returns: "Baz" * ``` * * @return {String} Subpage name */ getSubpageText() { if(this.namespacesWithSubpages.indexOf(this.mNamespace) == -1) return this.mTextform; let parts = this.mTextform.split('/'); return parts.pop(); } /** * Get the title for a subpage of the current page * * ```javascript * Title.newFromText('User:Foo/Bar/Baz').getSubpage('Asdf'); * // returns: Title('User:Foo/Bar/Baz/Asdf') * ``` * * @param {String} text The subpage name to add to the title * @return {Title|null} Subpage title, or null on an error */ getSubpage(text) { return Title.newFromText(this.getPrefixedText() + '/' + text, this.parserConfig); } /** * Get all subpages of this page. * * @return {Title[]} Title array, or empty array if this page's namespace * doesn't allow subpages */ getSubpages() { if(this.namespacesWithSubpages.indexOf(this.mNamespace) == -1) return []; let parts = this.getPrefixedText().split('/'); let lastTitle = Title.newFromText(parts.shift(), this.parserConfig); return parts.map(part => { lastTitle = lastTitle.getSubpage(part); return lastTitle; }); } /** * Does this have subpages? * * @return {Boolean} */ hasSubpages() { return this.getSubpages().length > 0; } /** * Get the base page name without a namespace, i.e. the part before the subpage name * * ```javascript * Title.newFromText('User:Foo/Bar/Baz').getBaseText(); * // returns: 'Foo/Bar' * ``` * * @return {String} Base name */ getBaseText() { if(this.namespacesWithSubpages.indexOf(this.mNamespace) == -1) return this.mTextform; let parts = this.mTextform.split('/'); if(parts.length == 1) return this.mTextform; parts.pop(); return parts.reduce((txt, part) => txt + (txt != '' ? '/' : '') + part, ''); } }
JavaScript
class InsetTextComponent extends LitElement { static get styles() { return [componentStyles]; } constructor() { super(); } connectedCallback() { super.connectedCallback(); } render() { return html`<div class="govuk-inset-text"> <slot></slot> </div>`; } }
JavaScript
class Calculator extends Component{ /*componentDidMount() { const { calculator,action }= this.props; }*/ render(){ const { calculator,action }= this.props; return ( <div> <p>{calculator}</p> <button onClick={action}>plus</button> <button onClick={action}>minus</button> </div> ) } }
JavaScript
class App extends React.Component { render() { return ( <div> <Header /> <div className="mainContent"> {this.props.children} </div> <Footer /> </div> ); } }
JavaScript
class Search extends Component { static displayName = Search.name; render() { return ( <div> <DefaultNavMenu /> <Container> <SideNav> <SideDrop name="Domain"> <SideItem>Geophysics</SideItem> <SideItem>Business</SideItem> <SideItem>Analysis</SideItem> <SideItem>Drilling</SideItem> <SideItem>Software</SideItem> </SideDrop> <SideDrop name="Rating"> <SideItem>2+ Stars</SideItem> <SideItem>3+ Stars</SideItem> <SideItem>4+ Stars</SideItem> <SideItem>5 Stars</SideItem> </SideDrop> <SideDrop name="Duration"> <SideItem>0-3 Hours</SideItem> <SideItem>4-9 Hours</SideItem> <SideItem>10-15 Hours</SideItem> <SideItem>16+ Hours</SideItem> </SideDrop> <SideDrop name="Difficulty"> <SideItem>Beginner</SideItem> <SideItem>Intermediate</SideItem> <SideItem>Expert</SideItem> </SideDrop> </SideNav> </Container> <Footer/> </div> ); } }
JavaScript
class ModelView extends TexturedModelView { /** * @param {Scene} scene * @return {Object} */ createSceneData(scene) { let model = this.model; let data = super.createSceneData(scene); let particleEmitters = []; let particleEmitters2 = []; let ribbonEmitters = []; let eventObjectEmitters = []; for (let emitter of model.particleEmitters) { particleEmitters.push(new ParticleEmitter(emitter)); } for (let emitter of model.particleEmitters2) { particleEmitters2.push(new ParticleEmitter2(emitter)); } for (let emitter of model.ribbonEmitters) { ribbonEmitters.push(new RibbonEmitter(emitter)); } for (let emitter of model.eventObjects) { let type = emitter.type; if (type === 'SPN') { eventObjectEmitters.push(new EventObjectSpnEmitter(emitter)); } else if (type === 'SPL') { eventObjectEmitters.push(new EventObjectSplEmitter(emitter)); } else if (type === 'UBR') { eventObjectEmitters.push(new EventObjectUbrEmitter(emitter)); } else if (type === 'SND') { eventObjectEmitters.push(new EventObjectSndEmitter(emitter)); } } return { ...data, particleEmitters, particleEmitters2, ribbonEmitters, eventObjectEmitters, }; } /** * @param {Scene} scene */ update(scene) { let data = super.update(scene); if (data) { let batchCount = this.model.batches.length; let buckets = data.buckets; let renderedInstances = 0; let renderedParticles = 0; let renderedBuckets = 0; let renderCalls = 0; for (let i = 0, l = data.usedBuckets; i < l; i++) { renderedInstances += buckets[i].count; renderedBuckets += 1; renderCalls += batchCount; } for (let emitter of data.particleEmitters) { emitter.update(); let particles = emitter.alive; if (particles) { renderedParticles += particles; renderCalls += 1; } } for (let emitter of data.particleEmitters2) { emitter.update(); let particles = emitter.alive; if (particles) { renderedParticles += particles; renderCalls += 1; } } for (let emitter of data.ribbonEmitters) { emitter.update(); let particles = emitter.alive; if (particles) { renderedParticles += particles; renderCalls += 1; } } for (let emitter of data.eventObjectEmitters) { emitter.update(); // Sounds are not particles. if (emitter.type !== 'SND') { let particles = emitter.alive; if (particles) { renderedParticles += particles; renderCalls += 1; } } } this.renderedInstances = renderedInstances; this.renderedParticles = renderedParticles; this.renderedBuckets = renderedBuckets; this.renderCalls = renderCalls; } } }
JavaScript
class OpenPlantNgComponent { constructor() { } /** * @return {?} */ ngOnInit() { } }
JavaScript
class MsgBoxComponent { constructor() { this.msgBoxObj = new MsgBoxObj(); this.btnPassDisable = true; this.msgBoxReady = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"](); } /** * @return {?} */ inputFocus() { if (this.inputTextEl != null) this.inputTextEl.nativeElement.focus(); return true; } /** * @param {?} event * @return {?} */ onInputKeyDown(event) { if (event.key == "Enter") this.onInputTextOKClick(); if (event.key == "Escape") this.onInputTextCancelClick(); } /** * @return {?} */ ngOnInit() { this.msgBoxReady.emit(this.msgBoxObj); } /** * @return {?} */ yesClick() { this.msgBoxObj.selectedDel(Selected.Yes); this.msgBoxObj.hide(); } /** * @return {?} */ noClick() { this.msgBoxObj.selectedDel(Selected.No); this.msgBoxObj.hide(); } /** * @return {?} */ okPassClick() { this.msgBoxObj.passChangeDel(Selected.Ok, this.tbPass2); this.msgBoxObj.hide(); } /** * @return {?} */ cancelPassClick() { this.msgBoxObj.passChangeDel(Selected.Cancel, null); this.msgBoxObj.hide(); } /** * @param {?} param * @return {?} */ onTextChangeP1(param) { this.tbPass1 = param; if (this.tbPass1.length < 5) this.btnPassDisable = true; else { this.btnPassDisable = (this.tbPass1 != this.tbPass2); } } /** * @param {?} param * @return {?} */ onTextChangeP2(param) { this.tbPass2 = param; if (this.tbPass2.length < 5) this.btnPassDisable = true; else { this.btnPassDisable = (this.tbPass1 != this.tbPass2); } } /** * @param {?} param * @return {?} */ onInputTextChange(param) { this.tbInput = param; } /** * @return {?} */ onInputTextOKClick() { this.msgBoxObj.textInputDel(Selected.Ok, this.tbInput); this.msgBoxObj.hide(); } /** * @return {?} */ onInputTextCancelClick() { this.msgBoxObj.textInputDel(Selected.Cancel, this.tbInput); this.msgBoxObj.hide(); } }
JavaScript
class CentreMsgComponent { constructor() { this.centreMsgReady = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"](); this.CMObj = new CentreMsgObject(); } /** * @return {?} */ ngOnInit() { this.centreMsgReady.emit(this.CMObj); } }
JavaScript
class OpchartComponent { constructor() { } /** * @return {?} */ ngOnInit() { } }
JavaScript
class CtrlrConf { //constructor(id: string, ctrlrTagName: string, description: string, ctrlrTempl: CtrlrTempl, mainParams: CtrlrConfRowCol[], ctrlrConfTabs: CtrlrConfTab[]) { constructor(id, ctrlrTagName, description, ctrlrTempl, mainParams) { if (id == null) this.id = _global__WEBPACK_IMPORTED_MODULE_1__["Global"].newGuid(); else this.id = id; this.description = description; this.ctrlrTagName = ctrlrTagName; this.ctrlrTempl = ctrlrTempl; this.mainParams = mainParams; //Get CV, MV, DV, INF Parameters this.ctrlrConfTabs = []; for (var t = 1; t <= 4; t++) { //Go through the Tabs (CV, MV, DV, INF) in the Controller Template this.ctrlrConfTabs = this.ctrlrConfTabs.concat(new CtrlrConfTab(_global__WEBPACK_IMPORTED_MODULE_1__["Global"].ctrlrConfTabNames[t], t, this.ctrlrTempl, [])); } this.ctrlrMatrixPairs = []; } findCtrlrMatrixValue(cVNum, mVNum) { let mp = this.ctrlrMatrixPairs.find(mp => mp.cVNum == cVNum && mp.mVNum == mVNum); if (mp == null) return null; return mp.value; } getMainTab() { return this.ctrlrConfTabs[0]; } getCtrlrRowCol(paramName) { let ctrlrConfRowCol = this.mainParams.find(p => p.ctrlrTemplParam.name == paramName); return ctrlrConfRowCol; } getCtrlrTopStripVw() { let ctrlrTopStripVw = new _model_ctrlr__WEBPACK_IMPORTED_MODULE_2__["CtrlrTopStripVw"](); let fetchItems = []; let topStripRC = this.getCtrlrRowCol("Status"); if (topStripRC.isOPTag) { fetchItems = fetchItems.concat(new _global__WEBPACK_IMPORTED_MODULE_1__["FetchItem"](topStripRC.value, topStripRC.ctrlrTemplParam.name, false)); ctrlrTopStripVw.statusMapping = topStripRC.ctrlrTemplParam.mapping; } else { if (topStripRC.ctrlrTemplParam.mapping != null) { ctrlrTopStripVw.status = topStripRC.ctrlrTemplParam.mapping.getValueText(topStripRC.value); ctrlrTopStripVw.statusColor = topStripRC.ctrlrTemplParam.mapping.getValueColor(ctrlrTopStripVw.status); } else ctrlrTopStripVw.status = topStripRC.value; } topStripRC = this.getCtrlrRowCol("Mode"); if (topStripRC.isOPTag) { fetchItems = fetchItems.concat(new _global__WEBPACK_IMPORTED_MODULE_1__["FetchItem"](topStripRC.value, topStripRC.ctrlrTemplParam.name, false)); ctrlrTopStripVw.modeMapping = topStripRC.ctrlrTemplParam.mapping; } else { if (topStripRC.ctrlrTemplParam.mapping != null) { ctrlrTopStripVw.mode = topStripRC.ctrlrTemplParam.mapping.getValueText(topStripRC.value); ctrlrTopStripVw.modeColor = topStripRC.ctrlrTemplParam.mapping.getValueColor(ctrlrTopStripVw.mode); } else ctrlrTopStripVw.mode = topStripRC.value; } topStripRC = this.getCtrlrRowCol("Benefit"); if (topStripRC.isOPTag) { fetchItems = fetchItems.concat(new _global__WEBPACK_IMPORTED_MODULE_1__["FetchItem"](topStripRC.value, topStripRC.ctrlrTemplParam.name, false)); } else ctrlrTopStripVw.benefitN = topStripRC.value; ctrlrTopStripVw.fetchItems = fetchItems; return ctrlrTopStripVw; } getCtrlrMatrixVw() { let ctrlrMatrixVw = new CtrlrMatrixVw(this.ctrlrMatrixPairs); //Build First Row View (MVs) let mVRow = new CtrlrMatrixRowVw(); mVRow.cells = mVRow.cells.concat(new CtrlrMatrixCellVw(_enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrMatrixCellType"].TopLeftMost)); this.ctrlrConfTabs.find(t => t.tabId == _enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrVarType"].MV).rows.forEach((r, i) => { let mVCell = new CtrlrMatrixCellVw(_enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrMatrixCellType"].XVCell, false, "MV" + this.padLeft(i.toString(), '0', 2), i, r.getBasicInfo(), r.cols); mVRow.cells = mVRow.cells.concat(mVCell); }); ctrlrMatrixVw.rows = ctrlrMatrixVw.rows.concat(mVRow); //Build Other Rows this.ctrlrConfTabs.find(t => t.tabId == _enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrVarType"].CV).rows.forEach(cv => { let cVInfo = cv.getBasicInfo(); let row = new CtrlrMatrixRowVw(); mVRow.cells.forEach(mv => { if (mv.ctrlrMatrixCellType == _enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrMatrixCellType"].TopLeftMost) { //This indicates the top left most cell, which entire column holds cvs let cVHeader = new CtrlrMatrixCellVw(_enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrMatrixCellType"].XVCell, false, "CV" + this.padLeft(cVInfo.number.toString(), '0', 2), cVInfo.number, cVInfo, cv.cols); row.cells = row.cells.concat(cVHeader); } else { let cell = new CtrlrMatrixCellVw(_enums__WEBPACK_IMPORTED_MODULE_3__["CtrlrMatrixCellType"].Cell, false, this.findCtrlrMatrixValue(cVInfo.number, mv.xVBasicInfoVw.number)); row.cells = row.cells.concat(cell); } }); ctrlrMatrixVw.rows = ctrlrMatrixVw.rows.concat(row); }); console.log(ctrlrMatrixVw); return ctrlrMatrixVw; } padLeft(text, padChar, size) { return (String(padChar).repeat(size) + text).substr((size * -1), size); } }
JavaScript
class XVBasicInfoVw { constructor(num, desc) { this.description = desc; this.number = num; } }
JavaScript
class CtrlrTemplVw { constructor(id, name, ctrlrTemplTabVws, mappings) { if (id == null) this.id = _global__WEBPACK_IMPORTED_MODULE_1__["Global"].newGuid(); else this.id = id; this.name = name; this.tabs = ctrlrTemplTabVws; this.mappings = mappings; } toCtrlrTempl() { let params = []; this.tabs.forEach(t => params = params.concat(t.params)); let ret = new CtrlrTempl(this.id, this.name, params, this.mappings); return ret; } }
JavaScript
class HeaderCell { constructor(rowSpan, colSpan, header) { this.rowSpan = rowSpan; this.colSpan = colSpan; this.header = header; } }
JavaScript
class DataRow { constructor(dataCells) { this.dataCells = dataCells; } }
JavaScript
class DataCell { constructor(value, tagId, color, ctrlrTemplParam) { this.value = value; this.tagId = tagId; this.color = color; this.ctrlrTemplParam = ctrlrTemplParam; this.setValue(value); } setValue(valueIn) { this.value = valueIn; if (this.ctrlrTemplParam.dType == _enums__WEBPACK_IMPORTED_MODULE_1__["DType"].string) { this.valueStr = this.value; } else { switch (this.ctrlrTemplParam.numberFormat) { case _enums__WEBPACK_IMPORTED_MODULE_1__["NumberFormat"].TwoDecimals: this.valueStr = (Math.round(this.value * 100) / 100).toFixed(2).toString(); break; case _enums__WEBPACK_IMPORTED_MODULE_1__["NumberFormat"].Percentage: this.valueStr = (Math.round(this.value * 10) / 10).toFixed(1).toString() + '%'; break; case _enums__WEBPACK_IMPORTED_MODULE_1__["NumberFormat"].None: if (this.ctrlrTemplParam.mapping == null) this.valueStr = valueIn; else { let mp = this.ctrlrTemplParam.mapping.mapPairs.find(mp => mp.val == valueIn); if (mp != null) { this.valueStr = mp.text; this.color = mp.colorHex; } else this.valueStr = valueIn; } break; } } } }
JavaScript
class PagerManager extends Collection { /** * PagerManager constructor * @param {Dyno} dyno Dyno core instance */ constructor(dyno) { super(); this.dyno = dyno; } /** * Create a pager * @param {Object} options Pager options * @param {String|GuildChannel} options.channel The channel this pager will be created in * @param {User|Member} options.user The user this pager is created for * @param {Object} options.embed The embed object to be sent without fields * @param {Object[]} options.fields All embed fields that will be paged * @param {Number} [options.pageLimit=10] The number of items per page, max 25, default 10 */ create(options) { if (!options || !options.channel || !options.user) return; let id = `${options.channel.id}.${options.user.id}`; let pager = new Pager(this, id, options); this.set(id, pager); return pager; } }
JavaScript
class Vec2 { constructor(x, y) { this.x = x; this.y = y; } norm() { return Math.hypot(this.x, this.y); } dot(other) { return this.x * other.x + this.y * other.y; } cross(other) { return this.x * other.y - this.y * other.x; } }
JavaScript
class Card extends Block { constructor(dataset, mobile_compact) { super(dataset); this._type = dataset.blockContent && dataset.blockContent.length > 0 ? dataset.blockContent : ''; this._header = new Header( this._type, 'h3', dataset.headline, dataset.headlineUrl, dataset.headlineColor, dataset.leader, dataset.leaderListItems, dataset.leaderListClass, dataset.leaderListTag, dataset.linkUrls, dataset.linkTitles ); this._mobileCompact = mobile_compact; //console.log(this._layout); } render(){ let html = ''; let img = ''; // Generate the HTML for the image if included. if(this._type === 'Image_card' && this._img){ img += this._img.render(); } // Add the mobile-swipe class if requested. let mobile = this._mobileCompact === 'true' ? 'mobile-swipe' : ''; html = ` <article class="card ${this._type} ${this._layout} ${ mobile }"> ${ img } ${ this._header.render() } </article> `; return html; } }
JavaScript
class EventController { /** * Constructor * * @param {object} query initial query * @param {boolean} upcomingSkipRegistrationOpen if `true`, skip all events with open registration in upcoming event list */ constructor(query = {}, upcomingSkipRegistrationOpen = false) { this.query = query; // Because past events do not need some advertising tweaks anymore, // enforce sorting for past events to ensure the correct sort in time. const pastQuery = JSON.parse(JSON.stringify(query)); pastQuery.sort = ['-time_start', '-time_advertising_start']; this._pastEvents = new EventListController(pastQuery, () => { const date = `${new Date().toISOString().split('.')[0]}Z`; return { where: { show_website: true, time_advertising_start: { $lt: date }, $or: [{ time_start: null }, { time_start: { $lt: date } }], }, }; }); let upcomingAdditionalQuery; if (upcomingSkipRegistrationOpen) { upcomingAdditionalQuery = () => { const date = `${new Date().toISOString().split('.')[0]}Z`; return { where: { show_website: true, time_start: { $gt: date }, time_advertising_start: { $lt: date }, $or: [ { time_register_start: null }, { time_register_end: null }, { time_register_end: { $lt: date } }, { time_register_start: { $gt: date } }, ], }, }; }; } else { upcomingAdditionalQuery = () => { const date = `${new Date().toISOString().split('.')[0]}Z`; return { where: { show_website: true, time_start: { $gt: date }, time_advertising_start: { $lt: date }, }, }; }; } this._upcomingEvents = new EventListController(query, upcomingAdditionalQuery); this._openRegistrationEvents = new EventListController(query, () => { const date = `${new Date().toISOString().split('.')[0]}Z`; return { where: { show_website: true, time_advertising_start: { $lt: date }, time_register_start: { $lt: date }, time_register_end: { $gt: date }, }, }; }); } /** Set a new query used by all EventListController to load events */ async setQuery(query) { if (Query.isEqual(this.query, query)) return false; this.query = Query.copy(query); this.openRegistrationEvents.setQuery(this.query); this.upcomingEvents.setQuery(this.query); this.pastEvents.setQuery(this.query); const jobs = [ this.openRegistrationEvents.loadAll(), this.upcomingEvents.loadAll(), this.pastEvents.loadPageData(1), ]; await Promise.all(jobs); return true; } /** Reload all event data */ async reload() { const jobs = [ this.openRegistrationEvents.loadAll(), this.upcomingEvents.loadAll(), this.pastEvents.reload(), ]; await Promise.all(jobs); } /** Get EventListController for all events with open registration window */ get openRegistrationEvents() { return this._openRegistrationEvents; } /** Get EventListController for all upcoming events */ get upcomingEvents() { return this._upcomingEvents; } /** Get EventListController for all past events */ get pastEvents() { return this._pastEvents; } /** Check if the event is already loaded */ isEventLoaded(eventId) { const test = item => item._id === eventId; return ( this.openRegistrationEvents.some(test) || this.upcomingEvents.some(test) || this.pastEvents.some(test) ); } /** * Load a specific event * @param {String} eventId */ // eslint-disable-next-line class-methods-use-this async loadEvent(eventId) { const event = await m.request({ method: 'GET', url: `${apiUrl}/events/${eventId}`, headers: { Authorization: getToken(), }, }); if (!event.show_website) { throw new Error('Event not found'); } return new Event(event); } }
JavaScript
class TicketForm extends Lists { state = { newItem: true, form: { title: formConfig( "Title", "Title ...", "text", "", "input", { isRequired: true }, false, false ), description: formConfig( "Ticket Description", "Description ...", "text", "", "textArea", { isRequired: true }, false, false ), assigned: formConfig( "Assigned", "email ...", "email", "", "input", { isRequired: true, isArrayPresent: true }, false, false ), ticketPriority: { elementConfig: [ { value: "None" }, { value: "Low" }, { value: "Medium" }, { value: "High" }, ], value: "High", name: "Ticket Priority", isValid: true, fieldType: "select", }, ticketType: { elementConfig: [ { value: "Bugs/Errors" }, { value: "Feature Requests" }, ], value: "Bugs/Errors", name: "Ticket Type", isValid: true, fieldType: "select", }, ticketStatus: { elementConfig: [ { value: "Open" }, { value: "In Progress" }, { value: "Resolved" }, { value: "Additional Info Required" }, ], value: "Open", name: "Ticket Status", isValid: true, fieldType: "select", }, }, }; componentDidMount() { const { id: projectID, key: ticketKey } = this.props.match.params; //Developers are not allowed to add new tickets if ( ticketKey === "new" && (this.props.role === "developer" || this.props.role === "N/A") ) this.props.history.goBack(); if (!this.props.allProjUsers[projectID]) this.props.fetchProjUsers(projectID); if (ticketKey === "new") return null; this.populateForm(); } mapResponseToState(name) { return obj[name]; } populateForm() { // populate form with existing ticket input field values const { id: projectID, key: ticketKey } = this.props.match.params; const formCopy = { ...this.state.form }; const tickets = this.props.allProjTickets[projectID] || this.props.userTickets; const ticket = tickets.find((curr) => curr.key === ticketKey); Object.keys(formCopy).map( (name) => (formCopy[name] = { ...formCopy[name], value: ticket[this.mapResponseToState(name)], isValid: true, }) ); this.setState({ form: formCopy, ticket }); } formSubmitHandler = () => { const ticketObj = this.createResponseTicket(); const history = this.createTicketHistory(ticketObj); this.props.submitTicket( this.props.match.params.id, { ...ticketObj, history }, this.props.match.params.key, this.props.role ); this.props.history.goBack(); }; createResponseTicket() { //This function craetes the response object to be stored in the API const users = this.props.allProjUsers[this.props.match.params.id] || []; const devIndex = users.findIndex( (curr) => curr.email === this.state.form.assigned.value ); if (devIndex === -1) return null; const { title, description, ticketPriority, ticketType, assigned, ticketStatus, } = this.state.form; const ticketObj = { title: title.value, description: description.value, ticketPriority: ticketPriority.value, ticketType: ticketType.value, assigned: users[devIndex].name, projName: this.props.match.params.name, assignedEmail: assigned.value.trim().toLowerCase(), submitter: this.state.ticket ? this.state.ticket.submitter : this.props.name, submitterEmail: this.state.ticket ? this.state.ticket.submitterEmail : this.props.email.trim().toLowerCase(), status: ticketStatus.value, created: this.state.ticket ? this.state.ticket.created : createDateString(new Date()), projid: this.props.match.params.id, comments: this.state.ticket ? this.state.ticket.comments : [], }; return ticketObj; } createTicketHistory(ticketObj) { //this function keeps track of all changes made on existing tickets let history = []; if (this.state.ticket) { history = [...this.state.ticket.history]; Object.keys(this.state.form).forEach((curr) => { const current = this.mapResponseToState(curr); if ( ticketObj[current] !== this.state.ticket[current] && current !== "description" ) history.unshift({ property: mapResponseToName(current), oldVal: this.state.ticket[current], newVal: ticketObj[current], date: createDateString(new Date()), }); }); } return history; } render() { return ( <div> <Modal header={<p>Create new Ticket</p>} modalStyle={{ width: "80%" }}> <form onSubmit={(e) => e.preventDefault()}> <div className={classes.InputContainer}> <div className={classes.InputChilds}> {this.props.role !== "Developer" ? ( Object.keys(this.state.form) .slice(0, 3) .map((curr) => ( <Input {...this.state.form[curr]} key={curr} inputStyle={{ padding: "5px", borderRadius: "0px" }} labelStyle={{ color: "#555", fontSize: "80%" }} containerStyle={{ width: "80%", margin: "auto" }} inputHandler={(e) => this.inputHandler( e, curr, this.props.allProjUsers[ this.props.match.params.id ] || [] ) } /> )) ) : ( <Input {...this.state.form["ticketStatus"]} inputStyle={{ padding: "5px", borderRadius: "0px" }} labelStyle={{ color: "#555", fontSize: "80%" }} containerStyle={{ width: "80%", margin: "auto" }} inputHandler={(e) => this.inputHandler( e, "ticketStatus", this.props.allProjUsers[this.props.match.params.id] || [] ) } /> )} </div> {this.props.role !== "Developer" ? ( <div className={classes.InputChilds}> {Object.keys(this.state.form) .slice(3) .map((curr) => ( <Input {...this.state.form[curr]} key={curr} inputStyle={{ padding: "5px", borderRadius: "0px" }} labelStyle={{ color: "#555", fontSize: "80%" }} containerStyle={{ width: "80%", margin: "auto" }} inputHandler={(e) => this.inputHandler( e, curr, this.props.allProjUsers[ this.props.match.params.id ] || [] ) } /> ))} </div> ) : null} </div> <div className={classes.ButtonDiv}> <Button clicked={this.formSubmitHandler} disabled={!this.checkFormValidity(this.state.form)} > Submit Ticket </Button> </div> </form> </Modal> </div> ); } }
JavaScript
class Header extends Component { static propTypes = { playerStatus: PropTypes.string, queue: PropTypes.array, queueCursor: PropTypes.number, shuffle: PropTypes.bool, repeat: PropTypes.string, useNativeFrame: PropTypes.bool, } constructor(props) { super(props); this.onKey = this.onKey.bind(this); } search(e) { AppActions.library.filterSearch(e.target.value); } getCover() { var queue = this.props.queue; var queueCursor = this.props.queueCursor; var trackPlaying = queue[queueCursor]; if (!trackPlaying) { return null } else { console.log(trackPlaying.artist + " " + trackPlaying.title); return <Cover artist={trackPlaying.artist.join(', ')} title={trackPlaying.title} /> } } onKey(e) { switch (e.keyCode) { case 70: { // "F" if(e.ctrlKey) { this.refs.search.refs.input.select(); } } } } render() { return ( <header> <div className='main-header'> { this.getCover() } <div className="col-search-controls"> <h2>My Music <span className='sorting-method'>A-Z by Title</span></h2> <Input selectOnClick placeholder='Enter keywords...' className='form-control input-sm search' changeTimeout={250} clearButton ref='search' onChange={this.search} /> </div> <div className='col-player-infos'> <PlayingBar queue={this.props.queue} queueCursor={this.props.queueCursor} shuffle={this.props.shuffle} repeat={this.props.repeat} /> </div> <div className='col-main-controls'> <PlayerControls playerStatus={this.props.playerStatus} /> </div> </div> <KeyBinding onKey={this.onKey} preventInputConflict /> </header> ); } }
JavaScript
class PruningTable { constructor(moveTables, moves) { this.computePruningTable(moveTables, moves); } setPruningValue(index, value) { this.table[index >> 3] ^= (0xf ^ value) << ((index & 7) << 2); } getPruningValue(index) { return (this.table[index >> 3] >> ((index & 7) << 2)) & 0xf; } computePruningTable(moveTables, moves) { const size = moveTables.reduce((acc, obj) => acc * obj.size, 1); this.table = []; for (let i = 0; i < (size + 7) >> 3; i += 1) { this.table.push(-1); } let depth = 0; let done = 0; const powers = [1]; for (let i = 1; i < moveTables.length; i += 1) { powers.push(moveTables[i - 1].size * powers[i - 1]); } const permutations = cartesian(moveTables.map((data) => data.solvedIndexes)); for (let i = 0; i < permutations.length; i += 1) { let index = 0; for (let j = 0; j < permutations[i].length; j += 1) { index += powers[j] * permutations[i][j]; } this.setPruningValue(index, 0); done += 1; } // We generate the table using a BFS. Depth 0 contains all positions which // are solved, and we loop through the correct indexes and apply all 18 moves // to the correct states. Then we visit all positions at depth 2, and apply // the 18 moves, and so on. while (done !== size) { // When half the table is generated, we switch to a backward search // where we apply the 18 moves to all empty entries. If the result // is a position which corresponds to the previous depth, we set the // index to the current depth. const inverse = done > size / 2; const find = inverse ? 0xf : depth; const check = inverse ? depth : 0xf; depth += 1; for (let index = 0; index < size; index += 1) { if (this.getPruningValue(index) === find) { for (let moveIndex = 0; moveIndex < moves.length; moveIndex += 1) { const move = moves[moveIndex]; let currentIndex = index; let position = 0; for (let i = powers.length - 1; i >= 0; i -= 1) { position += powers[i] * moveTables[i].doMove(Math.floor(currentIndex / powers[i]), move); currentIndex %= powers[i]; } if (this.getPruningValue(position) === check) { done += 1; if (inverse) { this.setPruningValue(index, depth); break; } this.setPruningValue(position, depth); } } } } } } }
JavaScript
class Menu extends React.PureComponent { constructor(props) { super(props); this.menuContentRef = React.createRef(); this.toggleRef = React.createRef(); this.state = { alignment: this.parseAlignment(), open: false, openInProcess: false, position: null }; } clickMenu = (event) => { // Hide the menu if the click originates from the menu scrim or a standard navigational element if (event.target.classList.contains('ias-menu')) { this.hideMenu(); } else { let currentElement = event.target; while (currentElement && currentElement.tagName) { // Navigational elements sometimes have children const tagName = currentElement.tagName.toLowerCase(); if (STANDARD_NAVIGATIONAL_TAGS.indexOf(tagName) !== -1) { this.hideMenu(); break; } currentElement = currentElement.parentNode; } } }; hideMenu() { this.setState({ open: false, position: null }); } parseAlignment() { const {iasAlign} = this.props; const tokens = (iasAlign) ? iasAlign.split(' ') : []; return { horizontal: H_ALIGN[tokens[0]] || H_ALIGN.start, vertical: V_ALIGN[tokens[1]] || V_ALIGN.bottom }; } render() { const {open, openInProcess, position} = this.state; // Dynamically add toggle menu handler const toggleElement = React.cloneElement(this.props.toggleElement, { key: 'menu-toggle', onClick: this.showMenu, ref: this.toggleRef }); let menuClass = 'ias-menu'; if (open) { menuClass += ' ias-open'; } const menuStyle = openInProcess ? {visibility: 'hidden'} : null; const menuContentStyle = position ? { bottom: Menu.numberToPixels(position.bottom), left: Menu.numberToPixels(position.left), right: Menu.numberToPixels(position.right), top: Menu.numberToPixels(position.top) } : null; // Use a Portal to insert the menu inside the document body // This stops some CSS styles from appearing on top of the menu (for example, button outlines) const menu = ReactDOM.createPortal(( <div className={menuClass} key="menu" onClick={this.clickMenu} style={menuStyle}> <div className="ias-menu-content" ref={this.menuContentRef} style={menuContentStyle}> {this.props.children} </div> </div> ), document.body); return [menu, toggleElement]; } showMenu = () => { // When showing the menu, first open the menu so the size can be calculated but keep it invisible. this.setState({ open: true, openInProcess: true }, () => { // Once this update has been rendered, set the menuContent position and make the menu visible. const position = calculateMenuPosition(this.menuContentRef.current, this.toggleRef.current, this.state.alignment); this.setState({ openInProcess: false, position }); }); }; static numberToPixels(num) { return (num === null) ? null : num + 'px'; } }
JavaScript
class RemiCart extends connect(store)(PageViewElement) { static get template() { return html([ template ]); } _delete(e){ let product = e.target.data; if (product){ store.dispatch(removeFromCart(product, this.user != null)) } //handle it } /** * Instance of the element is created/upgraded. Use: initializing state, * set up event listeners, create shadow dom. * @constructor */ constructor() { super(); } connectedCallback(){ super.connectedCallback(); } _checkout(){ window.scrollTo(0, 0); this.$.checkoutComponent.open(); } /** * Use for one-time configuration of your component after local DOM is initialized. */ ready() { super.ready(); const buttonRipple = new MDCRipple(this.querySelector('.mdc-button')); } _stateChanged(state){ this.total = state.shop.cart.total; this.numitems = state.shop.cart.numitems; this.items = state.shop.cart.items; this.user = state.app.user; } }
JavaScript
class ConsoleWriter extends AbstractLogWriter { /** * @private * * Creates a new Console Writer. Never called directly, but AwesomeLog * will call this when `AwesomeLog.start()` is issued. * * @param {Object} options */ constructor(options) { options = AwesomeUtils.Object.extend({ colorize: true, colorStyle: "level", // "line" or "level" colors: { ACCESS: "green", ERROR: "red", WARN: "yellow", INFO: "magenta", DEBUG: "cyan", } },options); super(options); if (this.options.colorize) { let theme = {}; Object.keys(this.options.colors||{}).forEach((level)=>{ theme[level] = this.options.colors[level]; }); this[$THEME] = theme; } this[$CLOSED] = false; } /** * @private * * Write a log message to STDOUT. * * @param {*} message * @param {Object} logentry * @return {void} */ write(message,logentry) { message = ""+message; try { // sometimes the stdout stream closes (usualy during program termination) and we cant do anything about it. if (!this[$CLOSED] && process.stdout.writable) { if (this.options.colorize) { if (this.options.colorStyle==="level") process.stdout.write(message.replace(logentry.level,AwesomeUtils.ANSI.stylize(this[$THEME][logentry.level],(logentry.level)))+"\n"); else process.stdout.write(AwesomeUtils.ANSI.stylize(this[$THEME][logentry.level],message)+"\n"); } else process.stdout.write(message+"\n"); } } catch (ex) { // if stdout throws an error, not much we can do other than stop writing. this.close(); } } /** * @private * * Flush the pending writes. This has not effect in this case. * * @return {void} */ flush() { // intentionally blank } /** * @private * * Close the writer. This has not effect in this case. * * @return {void} */ close() { this[$CLOSED] = true; } }
JavaScript
class Checkbox extends Component { /** * Constructor * @param {HTMLElement} parent - The element to add this checkbox to. * @param {number} x - The x position of the checkbox. * @param {number} y - The y position of the checkbox. * @param {string} label - The label label of the checkbox. * @param {boolean} checked - The initial checked state of the checkbox. * @param {function} defaultHandler - A function that will handle the "click" event. */ constructor(parent, x, y, label, checked, defaultHandler) { super(parent, x, y); this._label = label; this._createChildren(); this._createStyle(); this._createListeners(); this.setSize(100, 10); this.setChecked(checked); this.addEventListener("click", defaultHandler); this._addToParent(); this._updateWidth(); } ////////////////////////////////// // Core ////////////////////////////////// _createChildren() { this._setWrapperClass("MinimalCheckbox"); this._wrapper.tabIndex = 0; this._check = this._createDiv(this._wrapper, "MinimalCheckboxCheck"); this._textLabel = new Label(this._wrapper, 15, 0, this._label); } _createStyle() { const style = document.createElement("style"); style.textContent = Style.checkbox; this.shadowRoot.append(style); } _createListeners() { this._onClick = this._onClick.bind(this); this._onKeyPress = this._onKeyPress.bind(this); this._wrapper.addEventListener("click", this._onClick); this._wrapper.addEventListener("keypress", this._onKeyPress); } ////////////////////////////////// // Handlers ////////////////////////////////// _onClick(event) { event.stopPropagation(); if (this._enabled) { this.toggle(); this.dispatchEvent(new CustomEvent("click", { detail: this._checked })); } } _onKeyPress(event) { if (event.keyCode === 13 && this._enabled) { this._wrapper.click(); } } ////////////////////////////////// // Private ////////////////////////////////// _updateCheckStyle() { let className = this._checked ? "MinimalCheckboxCheckChecked " : "MinimalCheckboxCheck "; if (!this._enabled) { className += "MinimalCheckboxCheckDisabled"; } this._check.setAttribute("class", className); if (this._enabled) { this._setWrapperClass("MinimalCheckbox"); } else { this._setWrapperClass("MinimalCheckboxDisabled"); } } _updateWidth() { this.style.width = this._textLabel.x + this._textLabel.width + "px"; } ////////////////////////////////// // Public ////////////////////////////////// /** * Adds a handler function for the "click" event on this checkbox. * @param {function} handler - A function that will handle the "click" event. * @returns This instance, suitable for chaining. */ addHandler(handler) { this.addEventListener("click", handler); return this; } /** * Automatically changes the value of a property on a target object with the main value of this component changes. * @param {object} target - The target object to change. * @param {string} prop - The string name of a property on the target object. * @return This instance, suitable for chaining. */ bind(target, prop) { this.addEventListener("click", event => { target[prop] = event.detail; }); return this; } /** * Gets whether or not this checkbox is checked. * @returns Whether or not this checkbox is checked. */ getChecked() { return this._checked; } /** Gets the label on this checkbox. * @returns The text of the label of this checkbox. */ getLabel() { return this._label; } getWidth() { return this._textLabel.x + this._textLabel.width; } /** * Sets the checked state of this checkbox. * @params {boolean} checked - Whether or not this checkbox will be checked. * @returns This instance, suitable for chaining. */ setChecked(checked) { this._checked = checked; this._updateCheckStyle(); return this; } setEnabled(enabled) { if (this._enabled === enabled) { return this; } super.setEnabled(enabled); this._updateCheckStyle(); this._textLabel.enabled = enabled; if (this._enabled) { this._wrapper.tabIndex = 0; } else { this._wrapper.tabIndex = -1; } return this; } setHeight(height) { super.setHeight(height); this._textLabel.height = height; this._check.style.top = Math.round((this._height - 10) / 2) + "px"; return this; } /** * Sets the label of this checkbox. * @param {string} label - The label to set on this checkbox. * @returns this instance, suitable for chaining. */ setLabel(label) { this._label = label; this._textLabel.text = label; this._updateWidth(); return this; } /** * Sets the width of this checkbox. In fact, setting the width does nothing because it is automatically determined by the width of the label. */ setWidth() { return this; } /** * Toggles the state of the checkbox between checked and not checked. * @returns This instance, suitable for chaining. */ toggle() { this.setChecked(!this._checked); return this; } ////////////////////////////////// // Getters/Setters // alphabetical. getter first. ////////////////////////////////// /** * Sets and gets the checked state of the checkbox. */ get checked() { return this.getChecked(); } set checked(checked) { this.setChecked(checked); } /** * Sets and gets the label shown in the button's label. */ get label() { return this.getLabel(); } set label(label) { this.setLabel(label); } }
JavaScript
class NoteInfoGenerator { /* PROPERTIES: noteArray = array of notes constructed using SJT.js iterator = iterator for the number of notes traversed generation = number of permutation to return generationIndex = index within the permutation we are referencing note = note we are referenceing (noteArray[generation][generationIndex]) scaleSize = number of entries in a scale, used to work out generation maxIndex = maximum index of the array. At present this is calculated dumbly, just by mutiplying the length of the two levels of the array. TODO: This could be done by using a flattening function later */ constructor(noteArray, iterator = 0, generation = 0, generationIndex = 0, scaleSize = 0) { this.noteArray = noteArray; this.iterator = iterator; this.generation = generation; this.generationIndex = generationIndex; this.note = this.noteArray[this.generation][this.generationIndex]; this.scaleSize = noteArray[0].length; this.maxIndex = this.noteArray.length * this.noteArray[0].length } //returns all relevant information as an object getInfo() { return { iteration: this.iterator, generation: this.generation, generationIndex: this.generationIndex, note: this.note, scaleSize: this.scaleSize } } //increments ONLY, does not return information, also checks to make sure the iteration isn't over the maximum. The maximum is only calculated once in the constructor so that it's not calculated multiple times to save on power increment() { this.iterator++; if (this.iterator >= this.maxIndex) { this.iterator = 0; } } //returns an object of information about the current note, then moves onto the next generation getNoteInfo() { //get size of scale and use it to work out how many generations have elapsed this.generation = parseInt(this.iterator/this.scaleSize, 10); this.generationIndex = this.iterator%this.scaleSize; this.note = this.noteArray[this.generation][this.generationIndex] //return all of the relevant information to be used later on by the visuals side. return { iteration: this.iterator, generation: this.generation, generationIndex: this.generationIndex, note: this.note } } getInformation() { return { iteration: this.iterator } } //return note values as an object AND increment the iterator. playNote() { const noteInfo = this.getNoteInfo(); this.increment() return noteInfo } }
JavaScript
class Search extends Core { constructor(options) { super(options); this._render(Template, options); } _componentDidMount() { this._setIcons(); } hideClearIcon() { this._findDOMEl( '.hig__global-nav__side-nav__search__clear', this.el ).classList.remove('hig__global-nav__side-nav__search__clear--show'); } onClearIconClick(fn) { return this._attachListener( 'click', '.hig__global-nav__side-nav__search__clear', this.el, fn ); } onFocusIn(fn) { return this._attachListener( 'focusin', '.hig__global-nav__side-nav__search__inputholder__input', this.el, fn ); } onFocusOut(fn) { return this._attachListener( 'focusout', '.hig__global-nav__side-nav__search__inputholder__input', this.el, fn ); } onInput(fn) { return this._attachListener( 'input', '.hig__global-nav__side-nav__search__inputholder__input', this.el, fn ); } setPlaceholder(placeholder) { this._findDOMEl( '.hig__global-nav__side-nav__search__inputholder__input', this.el ).setAttribute('placeholder', placeholder); } setValue(value) { this._findDOMEl( '.hig__global-nav__side-nav__search__inputholder__input', this.el ).value = value; } showClearIcon() { this._findDOMEl( '.hig__global-nav__side-nav__search__clear', this.el ).classList.add('hig__global-nav__side-nav__search__clear--show'); } _setIcons() { const mountSearchIcon = this._findDOMEl( '.hig__global-nav__side-nav__search__icon', this.el ); this._findOrCreateIconComponent(mountSearchIcon, 'search').setNameOrSVG( 'search', '16' ); const mountClearIcon = this._findDOMEl( '.hig__global-nav__side-nav__search__clear', this.el ); this._findOrCreateIconComponent(mountClearIcon, 'clear').setNameOrSVG( 'close-small' ); } _findOrCreateIconComponent(mountElOrSelector, name = 'icon') { if (this[name]) { return this[name]; } this[name] = new Icon({}); this[name].mount(mountElOrSelector); return this[name]; } }
JavaScript
class PageNotFound extends Component { render() { return ( <div> <h1><strong>Página não Encontrada</strong></h1> </div> ); } }
JavaScript
class CanvasDrawingSystem extends System { constructor() { super(...arguments); this.types = ['transform', 'canvas']; this.systemType = SystemType.Draw; this.priority = -1; } initialize(scene) { this._ctx = scene.engine.ctx; this._engine = scene.engine; this._camera = scene.camera; } sort(a, b) { return a.components.transform.z - b.components.transform.z; } update(entities, delta) { this._clearScreen(); let transform; let canvasdraw; const length = entities.length; for (let i = 0; i < length; i++) { if (entities[i].visible && !entities[i].isOffScreen) { transform = entities[i].components.transform; canvasdraw = entities[i].components.canvas; this._ctx.save(); this._pushCameraTransform(transform); this._ctx.save(); this._applyTransform(entities[i]); canvasdraw.draw(this._ctx, delta); this._ctx.restore(); this._popCameraTransform(transform); this._ctx.restore(); } if (this._engine.isDebug) { this._ctx.save(); this._pushCameraTransform(transform); this._ctx.strokeStyle = 'yellow'; entities[i].debugDraw(this._ctx); this._popCameraTransform(transform); this._ctx.restore(); } } if (this._engine.isDebug) { this._ctx.save(); this._camera.draw(this._ctx); this._camera.debugDraw(this._ctx); this._ctx.restore(); } } _applyTransform(actor) { let parent = actor.parent; while (parent) { this._ctx.translate(parent.pos.x, parent.pos.y); this._ctx.rotate(parent.rotation); this._ctx.scale(parent.scale.x, parent.scale.y); parent = parent.parent; } this._ctx.translate(actor.pos.x, actor.pos.y); this._ctx.rotate(actor.rotation); this._ctx.scale(actor.scale.x, actor.scale.y); } _clearScreen() { this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height); this._ctx.fillStyle = this._engine.backgroundColor.toString(); this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height); } _pushCameraTransform(transform) { if (transform.coordPlane === CoordPlane.World) { // Apply camera transform to place entity in world space this._ctx.save(); if (this._camera) { this._camera.draw(this._ctx); } } } _popCameraTransform(transform) { if (transform.coordPlane === CoordPlane.World) { // Restore back to screen space from world space if we were drawing an entity there this._ctx.restore(); } } }
JavaScript
class AsyncReaderWriterLock { constructor(options) { this.writeCounter = 0; this.currentReads = []; this.pendingReadCount = 0; this.pendingWrites = []; options = { writeInProgress: false, ...options }; if (options.writeInProgress === true) { this.tryWriteBegin(); } } toJson() { return { currentWrite: this.currentWrite != null ? this.currentWrite.tags : null, pendingWrites: this.pendingWrites.length, currentReads: this.currentReads.length, pendingReads: this.pendingReadCount, value: this._value != null ? "yes" : "no", }; } // /** if no writes are waiting, will quickly return. otherwise will do a normal blocking wait // * // * returns the // */ // public pulseRead() { // if ( this.currentWrite != null ) { // throw new Error( "AsyncReaderWriterLock: you are attempting to read the value while a write is occuring. call .readBegin() first" ); // } // return this._value;// as Readonly<TValue>; // } /** returns true if a write is pending (in progress or queued). if false, you can read without being blocked. */ isWritePending() { return this.pendingWrites.length > 0; } /** begin a read lock. the returned promise resolves once the lock is aquired * * many simulatanious read locks are allowed, and be sure to call [[readEnd]] for each call of [[readBegin]] */ async readBegin() { //let readToken = if (this.pendingWrites.length > 0) { //this.pendingReads.push(promise.CreateExposedPromise()); this.pendingReadCount++; while (this.pendingWrites.length > 0) { await Promise.all(this.pendingWrites); } this.pendingReadCount--; } log.assert(this.pendingWrites.length === 0, "expect writeQueue to be zero length"); log.assert(this.currentWrite == null, "race, current write should not be possible while start reading"); this.currentReads.push(promise.CreateExposedPromise()); return this._value; } /** release your read lock */ readEnd() { log.assert(this.currentReads.length > 0, "out of current reads, over decremented?"); log.assert(this.currentWrite == null, "race, current write should not be possible while reading"); let readToken = this.currentReads.pop(); if (readToken != null) { readToken.fulfill(); } } /** returns true, if able to instantly obtain a write lock, false if any reads or writes are in progress */ tryWriteBegin() { if (this.pendingWrites.length > 0 || this.currentReads.length > 0) { return false; } //do sync writeBegin log.assert(this.currentWrite == null, "race, current write should not be possible while start writing (tryWriteBegin)"); const writeId = this.writeCounter++; let thisWrite = promise.CreateExposedPromise({ writeId }); this.pendingWrites.push(thisWrite); this.currentWrite = thisWrite; log.assert(this.currentWrite === this.pendingWrites[0], "current write should be at head of queue. (tryWriteBegin)"); return true; } /** take a write lock. returned promise resolves once your lock is aquired. */ async writeBegin() { const writeId = this.writeCounter++; let thisWrite = promise.CreateExposedPromise({ writeId }); this.pendingWrites.push(thisWrite); //wait until it's this write's turn while (this.pendingWrites[0].tags.writeId !== writeId) { await this.pendingWrites[0]; } //wait while there are still active reads while (this.currentReads.length > 0) { await bluebird_1.default.all(this.currentReads); } //now on the item log.assert(this.currentWrite == null, "race, current write should not be possible while start writing"); this.currentWrite = thisWrite; log.assert(this.currentWrite === this.pendingWrites[0], "current write should be at head of queue. (writeBegin)"); } /** finish the write lock, allowing writing of the stored [[value]] when doing so */ async writeEnd( /**write the data [[value]], or if a promise is passed, an exclusive write lock will be held until it exits*/ valueOrWritePromise) { try { //log.assertIf( thisWrite._tags.writeId === writeId, "writeId mismatch" ); // tslint:disable-next-line: no-unbound-method if (valueOrWritePromise instanceof bluebird_1.default || (_.isObject(valueOrWritePromise) && _.isFunction(valueOrWritePromise.then))) { this._value = await bluebird_1.default.resolve(valueOrWritePromise); } else { this._value = valueOrWritePromise; } } finally { log.assert(this.currentWrite != null, "race, current write should be set"); log.assert(this.currentWrite === this.pendingWrites[0], "current write should be at head of queue. (writeEnd)"); let thisWrite = this.pendingWrites.shift(); this.currentWrite = null; thisWrite.fulfill(); } } /** hold a non-exclusive read lock for the duration of the promise. */ async read(/** until this promise returns, a non-exclusive read lock will be held*/ readFcn) { if (readFcn == null && this.currentWrite == null) { //high performance scenario where we just return the value without doing awaits return this._value; } await this.readBegin(); try { if (readFcn != null) { await bluebird_1.default.resolve(this._value).then(readFcn); } return this._value; } finally { this.readEnd(); } } /** hold an exclusive write lock for the duration of the promise. */ async write(/**write the data, or if a promise is passed, an exclusive write lock will be held until it exits*/ valueOrWritePromise) { let toWrite; await this.writeBegin(); return this.writeEnd(valueOrWritePromise); } }
JavaScript
class MySqlPool { /** * Create a new MySqlPool with the provided configuration. * * Configuration options are the same as the ones that mysqljs accepts: * + https://github.com/mysqljs/mysql#pool-options * * Generally speaking, you will get a MySql pool by calling either: * + `mySqlEasier.configure(config)` -- to create a global pool for the app * + `const myPool = mySqlEasier.createPool(config)` -- to create a new pool */ constructor(config) { this.config = config; this.pool = new mysql.createPool(config); } /** * End this pool. After the end operation is complete, connections * that were retrieved from this pool will no longer function. */ end() { if (!this.pool) return Promise.resolve(); return new Promise((resolve, reject) => { this.pool.end(err => { this.pool = null; if (err) { reject(err); } else { resolve(); } }); }); } /** * Retrieve a MySqlConnection from this pool. * * When you are done with the connection, call `myConnection.done()` * to release it back to the pool. */ getConnection() { return new Promise((resolve, reject) => { if (!this.pool) { reject('Pool has ended. Connections are not available.'); } else { this.pool.getConnection((err, connection) => { if (err) { reject(err); } else { resolve(new MySqlConnection(connection, this.config)); } }); } }); } }
JavaScript
class AudioPlayerImpl extends events_1.EventEmitter { /** * @internal */ constructor() { super(); /** * @internal */ this.manager = null; /** * @internal */ this._playResourceOnEnd = false; /** * @internal */ this._disconnected = false; /** * @internal */ this._aborting = false; /** * @internal */ this._stopping = false; /** * @internal */ this._playing = false; /** * @internal */ this._looping = false; /** * @internal */ this._volume = 1; /** * @internal */ this._player = new voice_1.AudioPlayer(); this._player.on("stateChange", this._onAudioChange.bind(this)); } /** * @internal */ get guildID() { return this._connection?.joinConfig.guildId; } /** * @internal */ get status() { return this._player.state.status; } /** * @internal */ get playing() { return this._playing; } /** * @internal */ get playbackDuration() { return !this.playing ? 0 : this._resource.player === this ? Math.floor(this._resource.cachedSecond * 1000) : this._audio instanceof prism_media_1.default.opus.Decoder ? this._resource.cache.getReader(this._audio)?.packetRead ?? 0 : 0; } /** * @internal */ setManager(manager) { validation_1.AudioPlayerValidation.validateManager(manager); this.manager = manager; } /** * @internal */ link(connection) { validation_1.AudioPlayerValidation.validateConnection(connection); this._checkNotLinked(); connection.subscribe(this._player); this._connection = connection; // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; function onConnectionChange(oldState, newState) { if (oldState.status !== voice_1.VoiceConnectionStatus.Destroyed && newState.status === voice_1.VoiceConnectionStatus.Destroyed) { connection.off("stateChange", onConnectionChange); self.manager._deletePlayerIfExist(self.guildID); const subscription = self._connection.state.subscription; subscription?.unsubscribe(); if (self._playing) { if (self._resource.player === self && self.manager.cache && !self._resource.isLive) self._resource.cacheWriter.unpipe(); self._disconnected = true; self._player.stop(); } self.emit("unlink"); self._connection = null; self._cleanup(); } else if (oldState.subscription && !newState.subscription) { connection.off("stateChange", onConnectionChange); } } connection.on("stateChange", onConnectionChange); } /** * @internal */ unlink() { this._checkLinked(); const subscription = this._connection.state.subscription; subscription?.unsubscribe(); if (this._playing) { if (this._resource.player === this && this.manager.cache && !this._resource.isLive) this._resource.cacheWriter.unpipe(); this._disconnected = true; this._player.stop(); } this.emit("unlink"); this._connection = null; this._cleanup(); } /** * @internal */ setFilter(filter) { validation_1.AudioPlayerValidation.validateFilters(filter); if (!filter || !Object.keys(filter).length) this._filters = null; else this._filters = filter; } /** * @internal */ setVolume(volume) { validation_1.AudioPlayerValidation.validateVolume(volume); this._checkPlaying(); this._volume = volume; const audioResource = this._player.state.resource; if (audioResource) audioResource.volume.setVolume(this._volume); } /** * @internal */ stop() { this._checkPlaying(); if (this._resource.player === this && this.manager.cache && !this._resource.isLive) this._resource.cacheWriter.unpipe(); this._stopping = true; const stopped = this._player.stop(); this._stopping = false; if (!stopped) { if (this._resource.player === this) this._resource.player = null; this._cleanup(); } return stopped; } /** * @internal */ loop() { this._checkPlaying(); this._looping = !this._looping; return this._looping; } /** * @internal */ pause(pauseOrUnpause) { this._checkPlaying(); if ((typeof pauseOrUnpause === "boolean" && pauseOrUnpause === false) || ([voice_1.AudioPlayerStatus.Paused].includes(this.status) && pauseOrUnpause !== true)) { this._player.unpause(); return false; } return this._player.pause(); } /** * @internal */ filter() { this._checkPlaying(); const player = this._resource.player; this._audio.unpipe(); const audioResource = this._createAudioResource(); if (player !== this && !this._resource.allCached) this._playResourceOnEnd = true; if (player === this) this._resource.player = this; this._player.play(audioResource); this._audio.pipe(audioResource.metadata); } /** * @internal */ async seek(seconds) { validation_1.AudioPlayerValidation.validateSeconds(seconds); this._checkPlaying(); if (this._resource.isLive) throw new Error("Livestream cannot be seekened"); if (seconds > this._resource.cachedSecond && this._resource.allCached) { this.stop(); return; } if (seconds === this._resource.cachedSecond) { if (this._resource.player === this) return; this._playResourceOnEnd = true; this._player.stop(); return; } const player = this._resource.player; this._abort(); if (seconds < this._resource.cachedSecond && !this.manager.cache) await this._getResource(this._urlOrLocation, this._sourceType); if (seconds > this._resource.cachedSecond) { const skipper = new Skipper_1.Skipper(seconds - this._resource.cachedSecond, this._resource.cacheWriter); if (player && player !== this) { this._audio.destroy(); player._switchCache(); } this._resource.cacheWriter.pipe(skipper); await new Promise((res) => skipper.once("close", res)); this._playResource(); } else this._playCache(seconds); } /** * @internal */ async play(urlOrLocation, sourceType) { validation_1.AudioPlayerValidation.validateUrlOrLocation(urlOrLocation); validation_1.AudioPlayerValidation.validateSourceType(sourceType); this._checkNotPlaying(); await this._getResource(urlOrLocation, sourceType); if (!this._resource) { this.emit("end"); return; } this._playing = true; this._sourceType = sourceType; this._urlOrLocation = urlOrLocation; if (this._resource.player === this) this._playResource(); else this._playCache(); this.manager.emit("audioStart", this.guildID, urlOrLocation); } /** * @internal */ _playResource() { const audioResource = this._createAudioResource(); this._resource.player = this; this._audio = this._resource.cacheWriter; this._player.play(audioResource); this._audio.pipe(audioResource.metadata); } /** * @internal */ _playCache(startOnSeconds = 0) { const audioResource = this._createAudioResource(); const cacheStream = this._resource.cache.read(this._resource.identifier, startOnSeconds); this._audio = cacheStream; this._player.play(audioResource); this._audio.pipe(audioResource.metadata); if (!this._resource.allCached) this._playResourceOnEnd = true; } /** * @internal */ _createAudioResource() { const streams = [new prism_media_1.default.VolumeTransformer({ type: "s16le", volume: this._volume }), new prism_media_1.default.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 })]; if (this._filters) { const filters = []; Object.entries(this._filters).forEach((filter) => { if (!filter[1].length) { filters.push(filter[0]); return; } filters.push(filter.join("=")); }); streams.unshift(new prism_media_1.default.FFmpeg({ args: [...FILTER_FFMPEG_ARGS, filters.join(",")] })); } //Avoid null on _readableState.awaitDrainWriters streams.unshift(new stream_1.PassThrough()); return new voice_1.AudioResource([], streams, streams[0], 0); } /** * @internal */ _abort() { this._audio.unpipe(); this._aborting = true; this._player.stop(); this._aborting = false; } /** * @internal */ _checkNotLinked() { if (this._connection) throw new validation_1.PlayerError(validation_1.ErrorMessages.PlayerAlreadyLinked); } /** * @internal */ _checkLinked() { if (!this._connection) throw new validation_1.PlayerError(validation_1.ErrorMessages.PlayerNotLinked); } /** * @internal */ _checkNotPlaying() { this._checkLinked(); if (this._playing) throw new validation_1.PlayerError(validation_1.ErrorMessages.PlayerAlreadyPlaying); } /** * @internal */ _checkPlaying() { this._checkLinked(); if (!this._playing) throw new validation_1.PlayerError(validation_1.ErrorMessages.PlayerNotPlaying); } /** * @internal */ async _getResource(urlOrLocation, sourceType) { switch (sourceType) { case 0: await this._getYoutubeResource(urlOrLocation); break; case 1: await this._getSoundcloudResource(urlOrLocation); break; case 2: await this._getLocalResource(urlOrLocation); break; default: throw new validation_1.PlayerError(validation_1.ErrorMessages.NotValidSourceType(sourceType)); } } /** * @internal */ async _getYoutubeResource(url) { const identifier = ytdl_core_1.getVideoID(url); if (this.manager.cache?.youtube.hasCache(identifier)) { this._resource = await this.manager.cache.youtube.getResource(identifier); return; } function getOpusFormat(format) { return format.codecs === "opus" && format.container === "webm" && format.audioSampleRate === "48000"; } function getOtherFormat(sourceFormats, isLive) { function noVideo(format) { return !format.hasVideo; } let getFormat = (format) => format.hasAudio; if (isLive) getFormat = (format) => format.hasAudio && format.isHLS; const formats = sourceFormats.filter(getFormat); const filteredFormat = formats.find(noVideo); return filteredFormat || formats[0]; } const options = { highWaterMark: 1 << 22, ...this.manager.youtube }; let info = this._info; if (!info) info = await ytdl_core_1.getInfo(url, options); const playability = info.player_response?.playabilityStatus; if (!playability) { this.manager.emit("audioError", this.guildID, url, ErrorCode_1.ErrorCode.youtubeNoPlayerResponse); return; } else if (["UNPLAYABLE", "LOGIN_REQUIRED"].includes(playability.status)) { let errCode; switch (playability.status) { case "UNPLAYABLE": errCode = ErrorCode_1.ErrorCode.youtubeUnplayable; break; case "LOGIN_REQUIRED": errCode = ErrorCode_1.ErrorCode.youtubeLoginRequired; } this.manager.emit("audioError", this.guildID, url, errCode); return; } if (!this.manager.cache && !info.videoDetails.isLiveContent) this._info = info; async function onPipeAndUnpipe(resource) { const commander = new events_1.EventEmitter(); let contentLength = 0, downloaded = 0; await new Promise((resolve) => resource.source.once("pipe", resolve)); resource.source.on("progress", (_, audioDownloaded, audioLength) => { downloaded = audioDownloaded; contentLength = audioLength; }); resource.source.on("unpipe", async () => { if (downloaded >= contentLength) return; resource.autoPaused = true; setImmediate(commander.emit.bind(commander, "unpipe")); }); resource.source.on("pipe", async () => { await new Promise((resolve) => commander.once("unpipe", resolve)); if (!resource.source.readable || !resource.source.readableFlowing) await new Promise((resolve) => resource.source.once("readable", resolve)); resource.autoPaused = false; }); } let format = info.formats.find(getOpusFormat); const canDemux = format && !info.videoDetails.isLiveContent; if (canDemux) { options.format = format; const resource = this._resource = new Resource_1.Resource({ identifier, player: this, source: ytdl_core_1.downloadFromInfo(info, options), demuxer: new prism_media_1.default.opus.WebmDemuxer(), decoder: new prism_media_1.default.opus.Decoder({ rate: 48000, channels: 2, frameSize: 960 }), cacheWriter: new CacheWriter_1.CacheWriter(), cache: this.manager.cache?.youtube }); stream_1.pipeline(resource.source, resource.demuxer, resource.decoder, resource.cacheWriter, noop_1.noop); onPipeAndUnpipe(resource); resource.cacheWriter.once("close", () => { resource.source.destroy(); resource.demuxer.destroy(); resource.decoder.destroy(); }); return; } format = getOtherFormat(info.formats, info.videoDetails.isLiveContent); if (!format) { this.manager.emit("audioError", this.guildID, url, ErrorCode_1.ErrorCode.noFormatOrMedia); return; } options.format = format; const resource = this._resource = new Resource_1.Resource({ identifier, player: this, source: ytdl_core_1.downloadFromInfo(info, options), decoder: new prism_media_1.default.FFmpeg({ args: FFMPEG_ARGS }), cacheWriter: new CacheWriter_1.CacheWriter(), cache: info.videoDetails.isLiveContent ? null : this.manager.cache?.youtube, isLive: info.videoDetails.isLiveContent }); stream_1.pipeline(resource.source, resource.decoder, resource.cacheWriter, noop_1.noop); onPipeAndUnpipe(resource); resource.cacheWriter.once("close", () => { resource.source.destroy(); resource.decoder.destroy(); }); } /** * @internal */ async _getSoundcloudResource(url) { function getOpusMedia(media) { return media.find(({ format }) => { return format.mime_type === "audio/ogg; codecs=\"opus\""; }); } let info = this._info; if (!info) info = await this.manager.soundcloud.getInfo(url); if (!info.media) { this.manager.emit("audioError", this.guildID, url, ErrorCode_1.ErrorCode.noFormatOrMedia); return; } if (!this.manager.cache) this._info = info; const identifier = String(info.id); if (this.manager.cache?.soundcloud.hasCache(identifier)) { this._resource = await this.manager.cache.soundcloud.getResource(identifier); return; } let transcoding = getOpusMedia(info.media.transcodings); if (transcoding) { const resource = this._resource = new Resource_1.Resource({ identifier, player: this, source: await downloadMedia_1.downloadMedia(transcoding, await this.manager.soundcloud.getClientID(), this.manager.soundcloud.axios), demuxer: new prism_media_1.default.opus.OggDemuxer(), decoder: new prism_media_1.default.opus.Decoder({ rate: 48000, channels: 2, frameSize: 960 }), cacheWriter: new CacheWriter_1.CacheWriter(), cache: this.manager.cache?.soundcloud }); stream_1.pipeline(resource.source, resource.demuxer, resource.decoder, resource.cacheWriter, noop_1.noop); resource.cacheWriter.once("close", () => { resource.source.destroy(); resource.demuxer.destroy(); resource.decoder.destroy(); }); return; } transcoding = info.media.transcodings[0]; if (!transcoding) { this.manager.emit("audioError", this.guildID, url, ErrorCode_1.ErrorCode.noFormatOrMedia); return; } const resource = this._resource = new Resource_1.Resource({ identifier, player: this, source: await downloadMedia_1.downloadMedia(transcoding, await this.manager.soundcloud.getClientID(), this.manager.soundcloud.axios), decoder: new prism_media_1.default.FFmpeg({ args: FFMPEG_ARGS }), cacheWriter: new CacheWriter_1.CacheWriter(), cache: this.manager.cache?.soundcloud }); stream_1.pipeline(resource.source, resource.decoder, resource.cacheWriter, noop_1.noop); resource.cacheWriter.once("close", () => { resource.source.destroy(); resource.decoder.destroy(); }); } /** * @internal */ async _getLocalResource(location) { let fileHandle; try { fileHandle = await promises_1.open(location, "r"); } catch { this.manager.emit("audioError", this.guildID, location, ErrorCode_1.ErrorCode.cannotOpenFile); return; } const identifier = await fileHandle.stat({ bigint: true }).then((stat) => String(stat.ino)); await fileHandle.close(); if (this.manager.cache?.local.hasCache(identifier)) { this._resource = await this.manager.cache.local.getResource(identifier); return; } const { stream, type } = await voice_1.demuxProbe(fs_1.createReadStream(location)); const resource = this._resource = new Resource_1.Resource({ identifier, player: this, source: stream, demuxer: type === voice_1.StreamType.WebmOpus ? new prism_media_1.default.opus.WebmDemuxer() : type === voice_1.StreamType.OggOpus ? new prism_media_1.default.opus.OggDemuxer() : undefined, decoder: [voice_1.StreamType.WebmOpus, voice_1.StreamType.OggOpus].includes(type) ? new prism_media_1.default.opus.Decoder({ rate: 48000, channels: 2, frameSize: 960 }) : new prism_media_1.default.FFmpeg({ args: FFMPEG_ARGS }), cacheWriter: new CacheWriter_1.CacheWriter(), cache: this.manager.cache?.local }); if ([voice_1.StreamType.WebmOpus, voice_1.StreamType.OggOpus].includes(type)) stream_1.pipeline(resource.source, resource.demuxer, resource.decoder, resource.cacheWriter, noop_1.noop); else stream_1.pipeline(resource.source, resource.decoder, resource.cacheWriter, noop_1.noop); resource.cacheWriter.once("close", () => { resource.source.destroy(); resource.decoder.destroy(); }); } /** * @internal */ async _onAudioChange(oldState, newState) { const paused = [voice_1.AudioPlayerStatus.Paused, voice_1.AudioPlayerStatus.AutoPaused]; if (!paused.includes(oldState.status) && paused.includes(newState.status)) this.emit("pause"); else if (paused.includes(oldState.status) && !paused.includes(newState.status)) this.emit("unpause"); if (oldState.status === voice_1.AudioPlayerStatus.Paused && newState.status === voice_1.AudioPlayerStatus.Playing && this._switchToCache) { this._playCache(this._switchToCache); this._switchToCache = 0; } else if (oldState.status !== voice_1.AudioPlayerStatus.Idle && !newState.resource) { if (!(this._aborting || this._stopping) && this._playResourceOnEnd && !this._resource.allCached) { this._playResourceOnEnd = false; if (this._resource.player && this._resource.player !== this) this._resource.player._switchCache(); this._playResource(); return; } if (this._resource.player === this) { if (!this.manager.cache && !this._resource.cacheWriter.destroyed) this._resource.cacheWriter.read(); this._resource.player = null; } else this._audio.destroy(); if (!this._aborting) { this._playing = false; this._playResourceOnEnd = false; if (!this.manager.cache || this._resource.isLive) this._resource.cacheWriter.destroy(); if (!this._disconnected) { if (this._resource.isLive) { const stopping = this._stopping; const cachedSeconds = this._resource.cachedSecond; await this._getYoutubeResource(this._urlOrLocation); if (this._looping || (this._resource.isLive && !stopping)) { if (this._looping && !(this._resource.isLive && !stopping)) { this.emit("end"); this.manager.emit("audioStart", this.guildID, this._urlOrLocation); this.manager.emit("audioEnd", this.guildID, this._urlOrLocation); } else this._resource.cachedSecond = cachedSeconds; this._playing = true; this._playResource(); return; } } else if (this._looping) { this.emit("end"); this.manager.emit("audioEnd", this.guildID, this._urlOrLocation); if (this.manager.cache) { if (this._resource.cacheWriter.destroyed && !this._resource.allCached) { this.manager.emit("audioError", this.guildID, this._urlOrLocation, ErrorCode_1.ErrorCode.noResource); this._cleanup(); this.emit("end"); return; } this._playCache(); } else { await this._getResource(this._urlOrLocation, this._sourceType); if (!this._resource) { this._cleanup(); return; } this._playResource(); } this._playing = true; this.manager.emit("audioStart", this.guildID, this._urlOrLocation); return; } } this.emit("end"); this.manager.emit("audioEnd", this.guildID, this._urlOrLocation); this._cleanup(); } else this._playResourceOnEnd = false; } } /** * @internal */ _cleanup() { this._info = null; this._audio = null; this._resource = null; this._sourceType = null; this._urlOrLocation = null; this._looping = false; this._disconnected = false; this._playResourceOnEnd = false; } /** * @internal */ _switchCache() { const isPaused = this.status === voice_1.AudioPlayerStatus.Paused; this._audio.unpipe(); const seconds = this._resource.cachedSecond; setImmediate(() => { if (!isPaused) this._playCache(seconds); else this._switchToCache = seconds; }); } }
JavaScript
class DataItem { constructor(builder) { if (arguments.length < 1 || !(String(builder.constructor) === String(DataItem.builder.constructor))) { throw new NoBuilderError(); } if (arguments.length > 1) { throw new TooManyParamsError(); } const name = builder.name(); // Gets data item's name Object.defineProperty(this, "name", { get: function () { return name; }, enumerable: true, configurable: false, }); const format = builder.format(); // Gets data item's format Object.defineProperty(this, "format", { get: function () { return format; }, enumerable: true, configurable: false, }); // Gets data item's size only if supports size (e.g. string) if (ItemFormat.isSizeable(format)) { const size = builder.size(); Object.defineProperty(this, "size", { get: function () { return size; }, enumerable: true, configurable: false, }); } const value = builder.value(); Object.defineProperty(this, "value", { get: function () { return value; }, enumerable: true, configurable: false, }); } /** * Returns a string that represents the current message. */ toString( indent = "" ) { const key = Object.keys(ItemFormat).find(k => ItemFormat[k] === this.format); const len = ItemFormat.isSizeable(this.format) ? this.size : ''; if ( !( validator.isString( indent ) ) ){ indent = ""; } switch (this.format) { case ItemFormat.A: let base = `${indent}${key}<${len}> ${this.name}`; return + ( !this.value) ? base : `${base} [${this.value}]`; case ItemFormat.List: let str = `${key} ${this.name}`; this.value.forEach( x => str += '\n' + indent + x.toString( indent + " " ) ) return indent + str } if (!ItemFormat.isSizeable(this.format)) { return ( this.value instanceof Array ) ? `${indent}${key}<${this.value.length}> ${this.name} [${this.value}]`: `${indent}${key} ${this.name} [${this.value}]`; } } /** * Determines whether the specified item is equal to the current object. * @param {*} dm * The item to compare with the current object. */ equals( dm ){ if (!(dm instanceof DataItem)) { return false; } if( this.format != dm.format ){ return false; } if( this.size != dm.size ){ return false; } if( this.format == ItemFormat.List ){ if( this.value.length != dm.value.length ){ return false; } for( let i = 0; i < this.value.length; ++i ){ if( !this.value[ i ].equals( dm.value[ i ] ) ){ return false; } } } else { const isMyArray = this.value instanceof Array; const isHisArray = dm.value instanceof Array; if( isMyArray !== isHisArray ){ return false; } if( isMyArray ){ const eq = ( this.value.length === dm.value.length ) && ( this.value.every((value, index) => value === dm.value[index])) if( !eq ){ return false; } } else { if( this.value != dm.value ){ return false; } } } return true; } /** * Creates numeric data item. * @param {ItemFormat} f Item format. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric values or numeric arrays can be passed. */ static numeric(f = ItemFormat.I2, name = "", ...values ) { return DataItem .builder .format(f) .value(( 0 == values.length ) ? 0 : /*values.flat()*/ validator.flatten( values ) ) .name(name) .build(); } /** * Creates I1 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static i1(name = "", ...values) { return DataItem.numeric(ItemFormat.I1, name, ...values); } /** * Creates U1 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static u1(name = "", ...values) { return DataItem.numeric(ItemFormat.U1, name, ...values); } /** * Creates I2 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static i2(name = "", ...values) { return DataItem.numeric(ItemFormat.I2, name, ...values); } /** * Creates U2 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static u2(name = "", ...values) { return DataItem.numeric(ItemFormat.U2, name, ...values); } /** * Creates I4 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static i4(name = "", ...values) { return DataItem.numeric(ItemFormat.I4, name, ...values); } /** * Creates U4 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static u4(name = "", ...values) { return DataItem.numeric(ItemFormat.U4, name, ...values); } /** * Creates I8 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static i8(name = "", ...values) { return DataItem.numeric(ItemFormat.I8, name, ...values); } /** * Creates U8 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static u8(name = "", ...values) { return DataItem.numeric(ItemFormat.U8, name, ...values); } /** * Creates F4 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static f4(name = "", ...values) { return DataItem.numeric(ItemFormat.F4, name, ...values); } /** * Creates F8 data item. * @param {String} name Item name. * @param {...any} values Item value(s) for initialization. Single numeric value or numeric array can be passed. */ static f8(name = "", ...values) { return DataItem.numeric(ItemFormat.F8, name, ...values); } /** * Creates string data item. * @param {String} name Item name. * @param {numeric} size Item size. * @param {...any} values Item value for initialization. Single string only can be passed. */ static a(name = "", v, size = 0) { return DataItem .builder .format(ItemFormat.A) .size(size) .value(v) .name(name) .build(); } /** * Creates list data item. * @param {*} name Item name. * @param {...any} items List children items. */ static list(name = "", ...items) { let arr = items.filter( x => x instanceof DataItem ); return DataItem .builder .name(name) .format(ItemFormat.List) .value(arr) .build(); } /** * Returns builder's instance. */ static get builder() { return new Builder(); } }
JavaScript
class Builder { constructor() { props.set(this, { name: '', format: ItemFormat.I2, size: 0, value: undefined, children: [] }); } /** * Gets or sets data item's name. */ name(n) { if (validator.isUndefined( n )) { return props.get(this).name; } if (!validator.isString(n)) { throw new TypeError(constants.getErrMustBeString('name')); } props.get(this).name = n; return this; } /** * Gets or sets data item's format. */ format(f) { if ( validator.isUndefined( f ) /** Format allows 0, cannot use !f */) { return props.get(this).format; } props.get(this).format = validator.getEnumValue(ItemFormat, f); if (!ItemFormat.isSizeable(props.get(this).format)) { props.get(this).size = /*undefined*/0; } if ( !validator.isUndefined( props.get(this).value ) ) { this.value( props.get(this).value ); } return this; } /** * Gets or sets data item's size * Applicable only for items which support size. */ size(s) { if (validator.isUndefined( s )) { return props.get(this).size; } const size = validator.getUShortInRange( s, "Size" ); props.get(this).size = (ItemFormat.isSizeable(props.get(this).format)) ? size : undefined; const shoudSetValueAgain = ( ItemFormat.isSizeable(props.get(this).format) ) && ( !validator.isUndefined( props.get(this).value ) ); if( shoudSetValueAgain ){ this.value( props.get(this).value ); } return this; } /** * Gets or sets data item's value. */ value( v ){ if (validator.isUndefined( v )) { return props.get(this).value; } let value; let format = props.get(this).format; let size = props.get(this).size; const isArray = v instanceof Array; if( format == ItemFormat.List ){ value = ( ( isArray ) ? v : [ v ] ).filter( x => x instanceof DataItem ); } else { if( isArray && ( 1 == v.length || ItemFormat.isString( format ) ) ){ value = validator.getItemValue( v[ 0 ], format, size ); } else if( isArray && 1 < v.length ){ value = []; for( let i = 0; i < v.length; ++i ){ value.push( validator.getItemValue( v[ i ], format, size )); } } else if( !isArray ) { value = validator.getItemValue( v, format, size ); } } props.get(this).value = value; return this; } /** * Creates a new data item and initializes it with set parameters. */ build() { if (!props.get(this).name) { props.get(this).name = ''; } const size = props.get(this).size; const value = props.get(this).value; const format = props.get(this).format; // if( validator.isUndefined( size ) && ItemFormat.isSizeable( format ) ) { // props.get(this).size = 0; // } if( validator.isUndefined( value ) ) { props.get(this).value = ItemFormat.default( format, size ); } return new DataItem(this); } }
JavaScript
class BinarySearchTree { constructor() { this.base = null; } root() { return this.base; } add(data) { const newNode = new Node(data); if (this.base === null) this.base = newNode; else this.insertNode(this.base, newNode); } insertNode(node, newNode) { if (newNode.data < node.data) { if (node.left === null) { node.left = newNode; } else { this.insertNode(node.left, newNode); } } else { if (node.right === null) { node.right = newNode; } else { this.insertNode(node.right, newNode); } } } search(node, data) { if (node === null) { return null; } if (data < node.data) return this.search(node.left, data); else if (data > node.data) return this.search(node.right, data); else return node; } has(data) { return this.search(this.base, data) === null ? false : true; } find(data) { return this.search(this.base, data); } findMin(node) { if (node.left === null) return node; return this.findMin(node.left); } remove(data) { this.removeNode(this.base, data); } removeNode(node, data) { if (node === null) return null; if (data < node.data) { node.left = this.removeNode(node.left, data); return node; } if (data > node.data) { node.right = this.removeNode(node.right, data); return node; } if (data === node.data) { if (node.left === null && node.right === null) { node = null; return node; } if (node.left === null) { node = node.right; return node; } if (node.right === null) { node = node.left; return node; } const newNode = this.findMin(node.right); node.data = newNode.data; node.right = this.removeNode(node.right, newNode.data); return node; } } min() { return this.findMin(this.base).data; } max() { return findMax(this.base).data; function findMax(node) { if (node.right === null) return node; return findMax(node.right); } } }
JavaScript
class JSONDecoder extends Decoder { constructor() { super(); this.setMetadata("targetType", Signal1D.name); this.addInputValidator(0, ArrayBuffer); this.setMetadata("debug", false); this.setMetadata("concatenateRecords", true); } _run(){ var inputBuffer = this._getInput(0); if(!inputBuffer){ console.warn("JSONDecoder requires an JSON string as input \"0\". Unable to continue."); return; } var out = null; try{ out = JSON.parse( inputBuffer ) }catch( e ){ console.log("ERR: " + e.message); return; } this._output[0] = out; } } /* END of class EdfDecoder */
JavaScript
class SearchBar extends Component{ // this is how we initialize state in a class based component // constructor is used for initializing state // component has a constructor function and we are calling the parent constructor constructor(props) { super(props); // we initialize state by defining a new object and passing it to this.state // we want to update term to be whatever this.state is // this is the only time state looks like this.state = { term : ''}; } render(){ // we will be changing state in the render function // always manipulate state with this.setState return ( <div> <input value = {this.state.term} onChange = {event => this.setState({term : event.target.value})} /> </div> //Value of input : {this.state.term} //always wrap a variable around {} ); } // every class must have a render function // this is how we put values into our search bar!! }
JavaScript
class PageLoadMediaPlugin extends Plugin { /** * @memberof Vevet.PageLoadMediaPlugin * @typedef {object} Properties * @augments Vevet.Plugin.Properties * * @property {boolean} [images=true] - *** Defines if all images inside the page will be loaded before showing the page. Even if you call {@linkcode Vevet.PageModule#show}, the page will be shown only when images will be loaded. * @property {boolean} [videos=true] - *** The same thing but about videos. * @property {boolean} [bg=true] - *** The same thing but about background images. * @property {boolean} [bgSelector=.bg] - *** Background images selector. */ /** * @alias Vevet.PageLoadMediaPlugin * @description Construct the class. * * @param {Vevet.PageLoadMediaPlugin.Properties} [data] - Object of data to construct the class. */ constructor(data) { super(data, false); } /** * @readonly * @type {Vevet.PageLoadMediaPlugin.Properties} */ get defaultProp() { return merge(super.defaultProp, { images: true, videos: true, bg: true, bgSelector: '.bg' }); } /** * @member Vevet.PageLoadMediaPlugin#prop * @memberof Vevet.PageLoadMediaPlugin * @readonly * @type {Vevet.PageLoadMediaPlugin.Properties} */ /** * @member Vevet.PageLoadMediaPlugin#_prop * @memberof Vevet.PageLoadMediaPlugin * @protected * @type {Vevet.PageLoadMediaPlugin.Properties} */ /** * @function Vevet.PageLoadMediaPlugin#changeProp * @memberof Vevet.PageLoadMediaPlugin * @param {object} [prop] */ /** * @member Vevet.PageLoadMediaPlugin#_m * @memberof Vevet.PageLoadMediaPlugin * @protected * @type {Vevet.PageModule} */ // Extra for Constructor _extra() { super._extra(); // init vars this._m.on("create", this._initVars.bind(this)); // load media this._m.on("create", this._load.bind(this)); // override show let showCheckMethod = this._m.showCheck.bind(this._m); this._m.showCheck = () => { // native check if (!showCheckMethod()) { return false; } // check resources if ((this._prop.images || this._prop.videos || this._prop.bg) & (this._mediaLoaded < this._mediaTotal)) { this._showAfterMedia = true; return false; } return true; }; } _initVars() { /** * @description Total Media Count * @protected * @member {number} */ this._mediaTotal = 0; /** * @description Total Loaded Media Count * @protected * @member {number} */ this._mediaLoaded = 0; /** * @description If the page is to be shown, but the media has not been loaded yet. * @protected * @member {boolean} */ this._showAfterMedia = false; } /** * @description Load resources. * @protected */ _load() { // images if (this._prop.images) { this._loadImages(); } // videos if (this._prop.videos) { this._loadVideos(); } // backgrounds if (this._prop.bg) { this._loadBg(); } } /** * @description Load all images * @protected */ _loadImages() { // get & load images let images = document.querySelectorAll("img"); this._mediaTotal += images.length; // create pseudo images and load them for (let i = 0; i < images.length; i++) { let image = new Image(); image.onload = this._mediaOnLoad.bind(this); image.onerror = this._mediaOnLoad.bind(this); image.src = images[i].src; } } /** * @description Load all videos * @protected */ _loadVideos() { // get & load videos let videos = document.querySelectorAll("videos"); this._mediaTotal += videos.length; // load videos videos.forEach(video => { video.addEventListener("loadeddata", this._mediaOnLoad.bind(this)); video.load(); }); } /** * @description Load background images * @protected */ _loadBg() { // get & load images let bgs = document.querySelectorAll(this.prop.bgSelector), srcs = []; bgs.forEach(bg => { let style = bg.currentStyle || window.getComputedStyle(bg, false), image = style.backgroundImage; if (image != 'none') { image = image.slice(4, -1).replace(/"/g, ""); srcs.push(image); } }); this._mediaTotal += srcs.length; // // create pseudo images and load them for (let i = 0; i < srcs.length; i++) { let image = new Image(); image.onload = this._mediaOnLoad.bind(this); image.onerror = this._mediaOnLoad.bind(this); image.src = srcs[i]; } } /** * @description When all media is loaded, we show the page. * @protected */ _mediaOnLoad() { this._mediaLoaded++; if (this._mediaLoaded >= this._mediaTotal){ if (this._showAfterMedia) { this._m.show(); } } } }
JavaScript
class Api { constructor(httpClient, authManager = {}) { this.httpClient = httpClient; this.authManager = authManager; } /** * Check if any response has status code >= 300 * @param responseData * @returns {boolean} */ _hasError(responseData) { return responseData.some( (response) => response.code >= 300 ); } /** * Execute the API call and return a nomadoResponse * @param endpoint * @param data * @returns {Promise<nomadoResponse>} * @private */ async _call(endpoint, data = {}) { try { // Wait for http response return await this.httpClient.call(endpoint, data); } catch (e) { // Http client error occured return HttpError.buildResponse(e); } } }
JavaScript
class ShpToPbfTiles extends PbfTiles { constructor(outDir) { super(outDir); }; toLatLon(projection, pair) { if (!projection) return pair; const id = pair.join('_'); if (!this.memoize[id]) { this.memoize[id] = proj4(projection).inverse(pair); } return this.memoize[id]; } processGeoJson(zip, tileZoom, callback) { this.shapeFileLoader = new ShapeFileLoader(); const tileGroups = []; this.shapeFileLoader.load(zip, (shape) => { return this.convertGeometry(this.shapeFileLoader.projection, shape); }, (bbox) => { const bigTile = tilebelt.bboxToTile(bbox); const bigTileBounds = this.bboxToBounds(bbox); let zoomTiles; if (bigTile[2] === tileZoom) { zoomTiles = [bigTile]; } else if (bigTile[2] > tileZoom) { zoomTiles = [this.getOuterTile(bigTile, tileZoom)]; } else { zoomTiles = this.getInnerTiles(bigTile, tileZoom); zoomTiles = zoomTiles.filter((tile) => { const bounds = this.bboxToBounds(tilebelt.tileToBBOX(tile)); return this.intersectsBounds(bounds, bigTileBounds); }); } console.log(`# zoom tiles : ${zoomTiles.length}`); zoomTiles.forEach((tile, i) => { let tileBounds = this.bboxToBounds(tilebelt.tileToBBOX(tile)); tileGroups.push({ tile: tile, bounds: tileBounds, boundsTest: (shapeBounds) => { return this.intersectsBounds(shapeBounds, tileBounds); } }); }); }, tileGroups, () => { const calls = []; tileGroups.forEach((tileGroup, i) => { calls.push((done) => { if (!tileGroup.geoJson) { done(); return; } if (tileGroup.geoJson.features.length > 0) { var buffer = geobuf.encode(tileGroup.geoJson, new Pbf()); const filePath = `${this.outDir}/${tileGroup.tile.join('_')}.proto`; // console.log(buffer.length); fs.writeFile(filePath, buffer, () => { console.log(`SAVED ${filePath}`); done(); }); } }); }); async.parallelLimit(calls, 4, function () { console.log('ALL SAVED'); callback(); }); }); } }
JavaScript
class Product { constructor(name,img,price){ this.name = name; this.img = img; this.price = price; } }
JavaScript
class DoubleClickSearch { constructor() { const authClient = new AuthClient(SEARCH_ADS_SCOPES); /** @const {!Promise<!doubleclick_v2.Doubleclicksearch>} */ this.instance = authClient.getDefaultAuth().then( (auth) => google.doubleclicksearch({version: 'v2', auth})); /** * Logger object from 'log4js' package where this type is not exported. */ this.logger = getLogger('API.DS'); } /** * Updates the availabilities of a batch of floodlight activities in * DoubleClick Search. * See * https://developers.google.com/search-ads/v2/reference/conversion/updateAvailability * @param {!Array<!AvailabilityConfig>} availabilities Floodlight * availabilities array. * @return {!Promise<boolean>} Update result. */ updateAvailability(availabilities) { const availabilityTimestamp = new Date().getTime(); for (const availability of availabilities) { availability.availabilityTimestamp = availabilityTimestamp; } return this.instance .then((searchAds) => { this.logger.debug('Sending out availabilities', availabilities); return searchAds.conversion.updateAvailability( {requestBody: {availabilities}}); }) .then((response) => { this.logger.debug('Get response: ', response); return response.status === 200; }) .catch((error) => { console.error(error); return false; }); } /** * Returns the function to sends out a request to Search Ads 360 with a batch * of conversions. * @see https://developers.google.com/search-ads/v2/reference/conversion/insert * @param {!InsertConversionsConfig} config Campaign Manager configuration. * @return {function(!Array<string>, string): !Promise<boolean>} Function * which can send a batch of hits to Search Ads 360. */ getInsertConversionFn(config) { /** * Sends a batch of hits to Search Ads 360. * @param {!Array<string>} lines Data for single request. It should be * guaranteed that it doesn't exceed quota limitation. * @param {string} batchId The tag for log. * @return {!Promise<boolean>} */ const sendRequest = (lines, batchId) => { const conversionTimestamp = new Date().getTime(); const conversions = lines.map((line, index) => { const record = JSON.parse(line); return Object.assign( { // Default value, can be overwritten by the exported data. conversionTimestamp: conversionTimestamp, // Default conversion Id should be unique in a single request. // See error code 0x0000011F at here: // https://developers.google.com/search-ads/v2/troubleshooting#conversion-upload-errors conversionId: conversionTimestamp + index, }, config, record); }); this.logger.debug('Configuration: ', config); return this.instance.then((searchAds) => { return searchAds.conversion .insert({requestBody: {conversion: conversions}}) .then((response) => { this.logger.debug('Response: ', response); console.log(`SA[${batchId}] Insert ${ response.data.conversion.length} conversions`); return true; }) .catch((error) => { if (error.code === 400 && error.errors) {//requestValidation error const messages = error.errors.map((singleError) => { return singleError.message.replace( 'The request was not valid. Details: ', ''); }); console.log(`SA[${batchId}] partially failed.\n`, messages.join(',\n')); return false; } console.error( `SA insert conversions [${batchId}] failed.`, error.message); this.logger.debug( 'Errors in response:', error.response.data.error); return false; }); }); }; return sendRequest; } }
JavaScript
class ActorPlan { /** * Constructs a new <code>ActorPlan</code>. * @alias module:model/ActorPlan */ constructor() { ActorPlan.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>ActorPlan</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/ActorPlan} obj Optional instance to populate. * @return {module:model/ActorPlan} The populated <code>ActorPlan</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ActorPlan(); if (data.hasOwnProperty('collaborators')) { obj['collaborators'] = ApiClient.convertToType(data['collaborators'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('private_repos')) { obj['private_repos'] = ApiClient.convertToType(data['private_repos'], 'Number'); } if (data.hasOwnProperty('space')) { obj['space'] = ApiClient.convertToType(data['space'], 'Number'); } } return obj; } }
JavaScript
class HTML { getBudget(amount) { totalBudget.innerHTML = `${amount}`; budgetLeft.innerHTML = `${amount}`; } printMessage(message, className) { const messageWrapper = document.createElement('div'); messageWrapper.classList.add('text-center', 'alert', className); messageWrapper.appendChild(document.createTextNode(message)); document.querySelector('.primary').insertBefore(messageWrapper, expenseForm); setTimeout(() => { document.querySelector('.primary .alert').remove(); expenseForm.reset(); }, 2000); } displayExpense(name, amount) { const list = document.querySelector('#expenses .list-group') const li = document.createElement('li'); li.className = 'list-group-item d-flex justify-content-between align-items-center'; li.innerHTML = ` ${name} <span class="badge badge-primary badge-pill">$ ${amount}</span> `; list.appendChild(li); } trackExpense(amount) { const amountLeft = budget.getBudgetLeft(amount); console.log(amount); budgetLeft.innerHTML = `${amountLeft}`; // Change color of the "amount left" area according to the % if((budget.budget/4) > amountLeft) { budgetLeft.parentElement.parentElement.classList.remove('alert-success', 'alert-warning'); budgetLeft.parentElement.parentElement.classList.add('alert-danger'); } else if((budget.budget/2) > amountLeft){ budgetLeft.parentElement.parentElement.classList.remove('alert-success'); budgetLeft.parentElement.parentElement.classList.add('alert-warning'); } } }
JavaScript
class InputTextArea extends Component { static defaultProps = { value: '', className: '', id: false, onChange: () => {}, placeholder: '', style: false, } static propTypes = { /** The value supplied to the field. */ value: PropTypes.string, /** Option class names applied to the input */ className: PropTypes.string, /** An ID to use with a label. Doesn't render if boolean. */ id: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), /** * Gets called whenever the user types. * * @param {string} value The new value */ onChange: PropTypes.func, /** Placeholder value before any input exists */ placeholder: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** Styles to apply to the input. Boolean will not render default. */ style: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), } constructor(props) { super(props); this.state = {}; this.handleChange = this.handleChange.bind(this); } handleChange(event) { const newValue = event.target.value; return this.props.onChange(newValue); } render() { return ( <textarea className={`input v2 ${this.props.className}`} value={this.props.value} id={this.props.id ? this.props.id : ''} onChange={this.handleChange} placeholder={this.props.placeholder} style={this.props.style ? this.props.style : {}} /> ); } }
JavaScript
class User { /* flow-include name: string; id: string; socket: Socket; ip: string; authenticated: bool; lastMessage: string; lastMessageTime: number; activeRooms: Array<string>; */ constructor(name/*: string */, socket/*: Socket */, authenticated/*: bool */) { this.name = name; this.id = toId(name); this.socket = socket; this.ip = this.getIP(socket); this.authenticated = authenticated; this.lastMessage = ''; this.lastMessageTime = Date.now(); } getIP(socket/*: Socket */) /*: string */ { const forwarded = socket.request.headers['x-forwarded-for']; if (forwarded) { return forwarded; } else { return socket.request.connection.remoteAddress; } } setName(name/*: string */) { this.name = name; this.id = toId(name); } }