language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ResponseHelper { /** * Returns a default response object for use in controller handlers * * @param {string} key The object key to use for response data * Default: 'data' * * @return {object} Default response object */ static defaultErrorResponse(err) { // Set default return value const ret = { message: err }; return ret; } /** * internalError Helper method for sending a Internal Server Error response code and default JSON output * @param {Request} req - Express request object * @param {Response} res - Express response object * @param {Error} error - Error object for runtime and internal error */ static internalError(req, res, error) { // Log error is present if (error) { logger.error('internal server error', error); } return res .status(500) .json(ResponseHelper.defaultErrorResponse(error)); } /** * methodNotAllowed Helper method for sending a Method Not Allowed response code and default JSON output * @param {Request} req - Express request object * @param {Response} res - Express response object * @return {json} */ static methodNotAllowed(req, res) { return res .status(405) .json(ResponseHelper.defaultErrorResponse("Method not allowed")); } /** * methodNotImplemented Helper method for sending a Method Not Implemented response code and default JSON output * @param {Request} req - Express request object * @param {Response} res - Express response object * @return {json} */ static methodNotImplemented(req, res) { return res .status(501) .json(ResponseHelper.defaultErrorResponse("Method not implemented")); } /** * notFound Helper method for sending a Not Found response code and default JSON output * @param {Request} req - Express request object * @param {Response} res - Express response object * @return {json} */ static notFound(req, res) { return res .status(404) .json(ResponseHelper.defaultErrorResponse("NOT FOUND")); } }
JavaScript
class RemoteGatewayHomebridgePlatform { constructor(log, config, api) { this.log = log; this.config = config; this.api = api; this.Service = this.api.hap.Service; this.Characteristic = this.api.hap.Characteristic; // this is used to track restored cached accessories this.accessories = []; this.log.debug('Finished initializing platform:', this.config.name); // When this event is fired it means Homebridge has restored all cached accessories from disk. // Dynamic Platform plugins should only register new accessories after this event was fired, // in order to ensure they weren't added to homebridge already. This event can also be used // to start discovery of new accessories. this.api.on('didFinishLaunching', () => { log.debug('Executed didFinishLaunching callback'); // run the method to discover / register your devices as accessories this.discoverDevices(); }); } cmdPublish(url, reqType, message) { if (reqType === 'POST') { axios_1.default.post(url, message).then(res => { console.info(res.data); }).catch(e => { console.error(e); }); } else { axios_1.default.get(url).then(res => { console.info(res.data); }).catch(e => { console.error(e); }); } return true; } /** * This function is invoked when homebridge restores cached accessories from disk at startup. * It should be used to setup event handlers for characteristics and update respective values. */ configureAccessory(accessory) { this.log.info('Loading accessory from cache:', accessory.displayName); // add the restored accessory to the accessories cache so we can track if it has already been registered this.accessories.push(accessory); } /** * This is an example method showing how to register discovered accessories. * Accessories must only be registered once, previously created accessories * must not be registered again to prevent "duplicate UUID" errors. */ discoverDevices() { const devices = this.config.devices || []; const uuids = devices.map(d => this.api.hap.uuid.generate(d.key)); // remove old other for (const accessory of this.accessories) { if (uuids.indexOf(accessory.UUID) === -1) { this.api.unregisterPlatformAccessories(settings_1.PLUGIN_NAME, settings_1.PLATFORM_NAME, [accessory]); } } // loop over the discovered devices and register each one if it has not already been registered let devIndex = 0; for (const device of devices) { devIndex++; // generate a unique id for the accessory this should be generated from // something globally unique, but constant, for example, the device serial // number or MAC address const uuid = this.api.hap.uuid.generate(device.key); // see if an accessory with the same uuid has already been registered and restored from // the cached devices we stored in the `configureAccessory` method above const existingAccessory = this.accessories.find(accessory => accessory.UUID === uuid); if (existingAccessory) { // the accessory already exists this.log.info('Restoring existing accessory from cache:', existingAccessory.displayName); // if you need to update the accessory.context then you should run `api.updatePlatformAccessories`. eg.: // existingAccessory.context.device = device; // this.api.updatePlatformAccessories([existingAccessory]); // create the accessory handler for the restored accessory // this is imported from `platformAccessory.ts` this.initAccessory(device, existingAccessory); } else { // the accessory does not yet exist, so we need to create it this.log.info('Adding new accessory:', device.displayName); // create a new accessory const accessory = new this.api.platformAccessory(device.displayName, uuid); // store a copy of the device object in the `accessory.context` // the `context` property can be used to store any data about the accessory you may need accessory.context.device = device; // create the accessory handler for the newly create accessory // this is imported from `platformAccessory.ts` this.initAccessory(device, accessory); // link the accessory to your platform this.api.registerPlatformAccessories(settings_1.PLUGIN_NAME, settings_1.PLATFORM_NAME, [accessory]); } // it is possible to remove platform accessories at any time using `api.unregisterPlatformAccessories`, eg.: // this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]); } } initAccessory(device, accessory) { switch (device.type) { case 'gate': new GateServiceAccessory_1.GateServiceAccessory(this, this.log, this.config, this.api, accessory); break; case 'switch': new SwitchServiceAccessory_1.SwitchServiceAccessory(this, this.log, this.config, this.api, accessory); break; } } }
JavaScript
class DepthFirstSearchRecursive { static search(graph, start) { let investigated = {}; return this.getNext(graph, start, investigated); } static getNext(graph, vertex, investigated) { investigated[vertex] = vertex; graph[vertex].forEach(item => { if(!investigated[item]) { this.getNext(graph, item, investigated); } }); return Object.keys(investigated); } }
JavaScript
class CryptoWatch { /** * @constructor */ constructor(url = "https://api.cryptowat.ch") { this.url = url; this._allowance = CW_STARTING_ALLOWANCE; } /** * Request helper function * @private */ request(endpoint, params) { return new Promise((resolve, reject) => { const url = `${this.url}/${endpoint}`; http .get(url) .query(params) .end((err, res) => { if (err) { reject({ message: "Request failed", error: String(err), url }); } else { this._allowance = res.body.allowance.remaining; resolve(res.body.result); } }); }); } /** * Gets remaining api allowance. */ allowance() { return this._allowance; } /** * Gets all assets (crypto or fiat currency). */ assets() { return this.request("assets"); } /** * Gets an asset's information. * * @param {String} name */ asset(name) { return this.request(`assets/${name}`); } /** * Gets currency pairs info. */ pairs() { return this.request("pairs"); } /** * Gets info for a currency pair. * * @param {String} name */ pair(name) { return this.request(`pairs/${name}`); } /** * Gets info for all the exchanges. * * @param {Boolean} [active] If true, only return active exchanges */ exchanges(active = true) { return new Promise((resolve, reject) => { this.request("exchanges") .then(exchanges => { if (active) { exchanges = exchanges.filter(e => e.active); } resolve(exchanges); }) .catch(reject); }); } /** * Gets info for an exchange. * * @param {String} name */ exchange(name) { return this.request(`exchanges/${name}`); } /** * Gets info for markets. Optionally specify a single exchange. * * @param {String} [exchange] Optional. Supply a specific exchange to get * markets for */ markets(exchange = "") { let endpoint = "markets"; if (exchange.length > 0) { endpoint = `${endpoint}/${exchange}`; } return this.request(endpoint); } /** * Gets info for a market given an exchange and pair. * * @param {String} exchange * @param {String} pair */ market(exchange, pair) { return this.request(`markets/${exchange}/${pair}`); } /** * Returns price for a given market and currency pair. * * @param {String} market * @param {String} pair */ price(market, pair) { return this.request(`markets/${market}/${pair}/price`); } /** * Aggregate endpoint that returns the current price for all supported * markets. Somes values may be out of date by a few seconds as results * are cached. */ prices() { return this.request("markets/prices"); } /** * Returns summary for a given market and currency pair. * * @param {String} market * @param {String} pair */ summary(market, pair) { return this.request(`markets/${market}/${pair}/summary`); } /** * Aggregate endpoint that returns the market summary for all supported * markets. Some values may be out of date by a few seconds as results are * cached. */ summaries() { return this.request("markets/summaries"); } /** * Returns trades for a given market and currency pair. * * @param {String} market * @param {String} pair * @param {Object} [params] */ trades(market, pair, params) { return this.request(`markets/${market}/${pair}/trades`, params); } /** * Returns the orderbook for a given market and currency pair. * * @param {String} market * @param {String} pair */ orderbook(market, pair) { return this.request(`markets/${market}/${pair}/orderbook`); } /** * Returns a market’s OHLC candlestick data. Returns data as lists of lists * of numbers for each time period integer. * * @param {String} market * @param {String} pair * @param {Object} [params] */ OHLC(market, pair, params) { return this.request(`markets/${market}/${pair}/ohlc`, params); } }
JavaScript
class ReservationResponse extends models['BaseResource'] { /** * Create a ReservationResponse. * @property {string} [location] The Azure Region where the reserved resource * lives. * @property {number} [etag] * @property {string} [id] Identifier of the reservation * @property {string} [name] Name of the reservation * @property {object} [sku] * @property {string} [sku.name] * @property {object} [properties] * @property {string} [properties.reservedResourceType] Possible values * include: 'VirtualMachines', 'SqlDatabases', 'SuseLinux', 'CosmosDb' * @property {string} [properties.instanceFlexibility] Possible values * include: 'On', 'Off' * @property {string} [properties.displayName] Friendly name for user to * easily identify the reservation * @property {array} [properties.appliedScopes] * @property {string} [properties.appliedScopeType] Possible values include: * 'Single', 'Shared' * @property {number} [properties.quantity] * @property {string} [properties.provisioningState] Current state of the * reservation. * @property {date} [properties.effectiveDateTime] DateTime of the * Reservation starting when this version is effective from. * @property {date} [properties.lastUpdatedDateTime] DateTime of the last * time the Reservation was updated. * @property {date} [properties.expiryDate] This is the date when the * Reservation will expire. * @property {string} [properties.skuDescription] Description of the SKU in * english. * @property {object} [properties.extendedStatusInfo] * @property {string} [properties.extendedStatusInfo.statusCode] Possible * values include: 'None', 'Pending', 'Active', 'PurchaseError', * 'PaymentInstrumentError', 'Split', 'Merged', 'Expired', 'Succeeded' * @property {string} [properties.extendedStatusInfo.message] The message * giving detailed information about the status code. * @property {object} [properties.splitProperties] * @property {array} [properties.splitProperties.splitDestinations] List of * destination Resource Id that are created due to split. Format of the * resource Id is * /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId} * @property {string} [properties.splitProperties.splitSource] Resource Id of * the Reservation from which this is split. Format of the resource Id is * /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId} * @property {object} [properties.mergeProperties] * @property {string} [properties.mergeProperties.mergeDestination] * Reservation Resource Id Created due to the merge. Format of the resource * Id is * /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId} * @property {array} [properties.mergeProperties.mergeSources] Resource Ids * of the Source Reservation's merged to form this Reservation. Format of the * resource Id is * /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId} * @property {string} [type] Type of resource. * "Microsoft.Capacity/reservationOrders/reservations" */ constructor() { super(); } /** * Defines the metadata of ReservationResponse * * @returns {object} metadata of ReservationResponse * */ mapper() { return { required: false, serializedName: 'ReservationResponse', type: { name: 'Composite', className: 'ReservationResponse', modelProperties: { location: { required: false, readOnly: true, serializedName: 'location', type: { name: 'String' } }, etag: { required: false, serializedName: 'etag', type: { name: 'Number' } }, id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, sku: { required: false, serializedName: 'sku', type: { name: 'Composite', className: 'SkuName' } }, properties: { required: false, serializedName: 'properties', type: { name: 'Composite', className: 'ReservationProperties' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } } } } }; } }
JavaScript
class EventsLoader { constructor() { this.dir = "./events"; this.markdowns = this.getMarkdownsFromDir(); this.events = this.getYAMLFromDir(); } getCalendar() { const calendars = this.events.map(event => { return event.content.calendar; }) //merge into a single calendar array return [].concat.apply([], calendars); } //loads all .yml (YAML) files from a given directory getYAMLFromDir() { // const dir = this.dir; const requireContext = require.context('./events', true, /(.*)\.yml/); return requireContext.keys().map((fileName) => { const file = fileName.split(".")[1].replace("/", ""); const yamlContent = require(`./events/${file}.yml`); const parsedContent = this.parseEvent(yamlContent); return { file, content: parsedContent, }; }); } //loads all .md (markdown) files from a given directory getMarkdownsFromDir() { const requireContext = require.context("./events/", true, /(.*)\.md/); return requireContext.keys().map((fileName) => { const file = fileName.split(".")[1].replace("/", ""); const mdContent = require(`./events/${file}.md`).default; return { file, content: mdContent, }; }); } //maps the descrition filename with the content from the actual markdown file parseEvent(event) { event.calendar = event.calendar.map(item => { //has a description and it ends with a .md extension if (item.description && item.description.split(".")[2] == "md") { try { const file = item.description.split(".")[1].replace('/', ''); //tries to get the content from the file named at the description const descriptionContent = this.markdowns.find(markdown => { return markdown.file == file }); item.description = descriptionContent; } catch (error) { item.description = "ERROR" console.log("couldn't load markdown", error); } } return item; }) return event; } }
JavaScript
class UrlHelper { /** * Create short url given long url. * * @param {string} longUrl eg. //https://s3.amazonaws.com/uassets.stagingpepo.com/pepo-staging1000/ua/rsku/images/1-b0fb183f452e288c42a6d2b18788551f-original.jpeg * * @returns {string} */ longToShortUrl(longUrl) { const oThis = this; const urlTemplate = longUrl.replace(oThis.redemptionUrlPrefix, oThis.shortRedemptionUrlPrefix); const splitElementsArray = urlTemplate.split('-'), sizeExtension = splitElementsArray[splitElementsArray.length - 1], sizeExtensionArray = sizeExtension.split('.'), fileExtension = sizeExtensionArray[sizeExtensionArray.length - 1]; splitElementsArray[splitElementsArray.length - 1] = oThis.fileNameShortSizeSuffix + '.' + fileExtension; return splitElementsArray.join('-'); } /** * Create long url given short url. * * @param {string} shortUrl * @param {string} size * * @returns {string} */ shortToLongUrl(shortUrl, size) { const oThis = this; shortUrl = shortUrl.replace(oThis.shortRedemptionUrlPrefix, oThis.redemptionUrlPrefix); return shortUrl.replace(oThis.fileNameShortSizeSuffix, size); } /** * Create short resolutions. * * @param {object} imageMap * eg. imageMap * { * '144w': {url: '', size: , width: height:}, * '288w': {url: '', size:, width: height:} * } * @returns {object} */ createShortResolutions(imageMap) { const oThis = this, shortResolutionsMap = {}; for (const imageSize in imageMap) { const shortImageSize = oThis.imageSizesLongNameToShortNameMap[imageSize]; if (!shortImageSize) { throw new Error('Image size is not available.'); } shortResolutionsMap[shortImageSize] = { [oThis.sizeShortName]: imageMap[imageSize].size, [oThis.widthShortName]: imageMap[imageSize].width, [oThis.heightShortName]: imageMap[imageSize].height }; } return shortResolutionsMap; } /** * Create long resolutions. * * @param {object} imageMap * eg. imageMap * { * '144w': {url: '', size: , width: height:}, * '288w': {url: '', size:, width: height:} * } * @returns {object} */ createLongResolutions(imageMap) { const oThis = this, longResolutionsMap = {}; for (const purpose in imageMap) { longResolutionsMap[purpose] = {}; const imageMapForPurpose = imageMap[purpose], resolutions = imageMapForPurpose[oThis.resolutionsShortName], urlTemplate = imageMapForPurpose[oThis.urlTemplateShortName]; for (const resolution in resolutions) { const resolutionLongName = oThis.imageSizesShortNameToLongNameMap[resolution]; longResolutionsMap[purpose][resolutionLongName] = { url: oThis.shortToLongUrl(urlTemplate, resolutionLongName), size: imageMapForPurpose[oThis.resolutionsShortName][resolution][oThis.sizeShortName], width: imageMapForPurpose[oThis.resolutionsShortName][resolution][oThis.widthShortName], height: imageMapForPurpose[oThis.resolutionsShortName][resolution][oThis.heightShortName] }; } } return longResolutionsMap; } // TODO: This needs to be changed according to given s3 url. get redemptionUrlPrefix() { return 'https://dxwfxs8b4lg24.cloudfront.net/ost-platform/rskus/'; } get shortRedemptionUrlPrefix() { return '{{s3_ru}}'; } get fileNameShortSizeSuffix() { return '{{s}}'; } get imageSizesLongNameToShortNameMap() { return { original: 'o', '144w': '144w' }; } /** * Mapping of long column names to their short names. * * @returns {object|*} */ get imageSizesShortNameToLongNameMap() { const oThis = this; return util.invert(oThis.imageSizesLongNameToShortNameMap); } get availablePurposeForImages() { const oThis = this; return { [oThis.coverPurposeForImage]: 1, [oThis.detailPagePurposeForImage]: 1 }; } // Square image. get coverPurposeForImage() { return 'cover'; } // Details page rectangular image. get detailPagePurposeForImage() { return 'detail'; } get sizeShortName() { return 's'; } get widthShortName() { return 'w'; } get heightShortName() { return 'h'; } get urlTemplateShortName() { return 'ut'; } get resolutionsShortName() { return 'rs'; } }
JavaScript
class Task extends Model { /** * @method getById * @author Ernesto Rojas <[email protected]> * @description This method get model name. * @returns {string} Model name. */ getName() { return 'Task'; } /** * @method build * @author Ernesto Rojas <[email protected]> * @description This method build the model. * @returns {mongoose.Model} Mongoose model. */ getSchema() { const opts = { timestamps: true, }; return new Schema( { name: { type: String, required: true, }, done: { type: Boolean, default: false, }, project: { type: Number, required: Types.ObjectId, ref: 'Project', required: true, }, }, opts, ); } }
JavaScript
class HeapItem { /** * The sound object. * @type {Sound} */ sound = null; /** * The group id. * @type {number|null} */ groupId = null; /** * Set the group id and sound. * @param {number} groupId The group id. * @param {Sound} sound The sound instance. */ constructor(groupId, sound) { this.groupId = groupId; this.sound = sound; } }
JavaScript
class HeapItemCollection { /** * The audio source url. * @type {string|null} */ url = null; /** * The collection of sound objects. * @type {object} */ items = {}; /** * Adds a new sound item to the collection. * @param {number} groupId The group id. * @param {Sound} sound The sound instance. */ add(groupId, sound) { const soundId = sound.id().toString(); if (this.items.hasOwnProperty(soundId)) { return; } this.items[soundId] = new HeapItem(groupId, sound); } /** * Removes the sounds. * @param {boolean} [idle = true] True to destroy only the idle sounds. * @param {number} [groupId] The group id. */ free(idle = true, groupId) { Object.values(this.items).forEach(item => { const { sound, soundGroupId } = item; if(idle && (sound.isPlaying() || sound.isPaused())) { return; } if (!Boolean(groupId) || soundGroupId === groupId) { sound.destroy(); delete this.items[sound.id()]; } }); } /** * Returns the sounds belong to the group or all the sounds in the collection. * @param {number} [groupId] The group id. * @return {Array<HeapItem>} */ sounds(groupId) { const itemsArray = Object.values(this.items); const items = groupId ? itemsArray.filter(item => item.groupId === groupId) : itemsArray; return items.map(item => item.sound); } /** * Destroys all the sounds. */ destroy() { Object.values(this.items).forEach(item => item.sound.destroy()); this.items = {}; } }
JavaScript
class Heap { /** * The sound collections. * @type {object} * @private */ _collections = {}; /** * Initialize stuff. */ constructor() { this.free = this.free.bind(this); } /** * Adds a new sound to the respective collection. * @param {string} url The audio source url or base64 string. * @param {number} groupId The group id. * @param {Sound} sound The sound instance. */ add(url, groupId, sound) { if (!this._collections.hasOwnProperty(url)) { this._collections[url] = new HeapItemCollection(); } this._collections[url].add(groupId, sound); } /** * Returns the sound based on the id. * @param {number} id The sound id. */ sound(id) { return this.sounds().find(sound => sound.id() === id); } /** * Returns the sounds belongs to a particular group or all of them. * @param {number} [groupId] The group id. * @return {Array} */ sounds(groupId) { const sounds = []; Object.values(this._collections).forEach(col => sounds.push(...col.sounds(groupId))); return sounds; } /** * Removes sounds from the collections. * @param {boolean} [idle = true] True to destroy only the idle sounds. * @param {number} [groupId] The group id. */ free(idle = true, groupId) { Object.values(this._collections).forEach(col => col.free(idle, groupId)); } /** * Destroys all the sounds. */ destroy() { Object.values(this._collections).forEach(col => col.destroy()); this._collections = {}; } }
JavaScript
class AllProducts extends React.Component { constructor(props) { super(props); this.state = { page: +this.props.location.search.slice(1).split("=")[1] || 1, }; } async componentDidMount() { try { await this.props.fetchProducts(); } catch (err) { console.error(err); } } componentDidUpdate() { /* I check whether the page has changed and load the appropriate data */ if ( +this.props.location.search.slice(1).split("=")[1] && this.state.page !== +this.props.location.search.slice(1).split("=")[1] ) { this.setState( { page: +this.props.location.search.slice(1).split("=")[1] }, () => this.props.fetchProducts() ); /* immediatly after updating state call callback */ } } render() { if (this.props.products.length) { let products = this.props.products; const pages = []; for (let i = 0; i < products.length / 10; ++i) { pages.push(i); } products = products.slice( (this.state.page - 1) * 10, this.state.page * 10 ); return ( <div> <div className="d-flex justify-content-center"> <ul className="pagination pages pagination-lg"> {pages.map((page, index) => { const pageItem = index + 1 === this.state.page ? "page-item active" : "page-item"; return ( <li key={page} className={pageItem}> <ProductPages index={index} /> </li> ); })} </ul> </div> {this.props.isAdmin ? <NewProduct /> : null} <div id="product-list"> {products.map((product) => ( <div id="card" key={product.id}> <img id="product-image-card" className="rounded img-thumbnail" src={product.imageUrl} /> <Link className="product-title-card" to={`/products/${product.id}`} > {product.name} <br />{" "} </Link> <div className="content-wrapper"> <div className="product-content-card"> {product.description} </div> </div> <div className="product-price-card"> Price: ${product.price} </div> {this.props.isAdmin ? ( <span onClick={() => this.props.deleteProduct(product.id)}> x </span> ) : null} </div> ))} </div> </div> ); } else { return ( <ClipLoader color="aqua" size={150} loading={true} speedMultiplier={1.5} /> ); } } }
JavaScript
class Task extends BaseNode { /** * Creates an instance of Task. * @param {Object} [params] * @param {String} [params.type='Action'] Node type. * @param {String} [params.name] * @param {Object} [params.properties] */ constructor({type = 'Task', name, run, description ,properties} = {}) { super({ category: TASK, type: type, name, description, properties }); /** @type {function(Context)} */ this.run = run; } }
JavaScript
class VeloxI18n{ /** * @typedef VeloxI18nColumnOptions * @type {object} * @property {string} name Column name * @property {string} [table] Table name (for example, if the column belong to a view, put the source table name) */ /** * @typedef VeloxI18nTableOptions * @type {object} * @property {string} name Table name * @property {VeloxI18nColumnOptions[]} columns Translated columns */ /** * @typedef VeloxI18nOptions * @type {object} * * @example * { * tables : [ * {name : "foo", columns : [ * {name : "bar"} * ]} * ] * } * * @property {VeloxI18nTableOptions[]} tables the translated tables */ /** * Create the VeloxI18n extension * * @param {VeloxI18n} [options] options */ constructor(options){ this.name = "VeloxI18n"; if(!options){ options = {} ; } this.options = options ; var self = this; this.extendsClient = { getTranslations : function(callback){ //this is the VeloxDatabaseClient object self.getTranslations(this, callback) ; }, getI18nOptions : function(){ //this is the VeloxDatabaseClient object return self.options; }, translateRecords: function(lang, table, records, callback){ //this is the VeloxDatabaseClient object self.translateRecords(this, lang, table, records, callback); }, translateSave : function(lang, table, record, callback){ self.translateSave(this, lang, table, record, callback); }, getLang: function(){ return self.getLang(this) ; } }; this.interceptClientQueries = []; this.interceptClientQueries.push({name : "insert", table: "velox_translation", before : this.beforeSaveTranslation }); this.interceptClientQueries.push({name : "update", table: "velox_translation", before : this.beforeSaveTranslation }); let beforeSearchHook = function(table, search, joinFetch, callback){ let client = this; //let callback = arguments[arguments.length-1] ; self.beforeSearchHook(client, table, joinFetch, callback) ; } ; this.translatedTables = {} ; for(let table of options.tables){ this.translatedTables[table.name] = true ; this.interceptClientQueries.push({name : "getByPk", table: table.name, before : beforeSearchHook, after : this.translateOne }); this.interceptClientQueries.push({name : "searchFirst", table: table.name, before : beforeSearchHook, after : this.translateOne }); this.interceptClientQueries.push({name : "search", table: table.name, before : beforeSearchHook, after : this.translateMany }); this.interceptClientQueries.push({name : "insert", table: table.name, after : this.translateSaveHook }); this.interceptClientQueries.push({name : "update", table: table.name, after : this.translateSaveHook }); } } beforeSearchHook(client, tableP, joinFetch, callback){ var tables = [] ; tables.push(tableP) ; getJoinTables(tables, joinFetch) ; if(tables.every((table)=>{ return !this.translatedTables[table] || !!client["initI18n"+table] ; })){ return callback() ; } let lang = client.getLang() ; if(lang === "base"){ return callback() ;} client.getSchema((err, schema)=>{ if(err){ return callback(err) ;} for(let table of tables){ if(!this.translatedTables[table] || client["initI18n"+table]){ continue ;} client["initI18n"+table] = true ; let tableSql = client.getTable(table) ; let translatedColumns = [] ; this.options.tables.some(function(t){ if(t.name === table){ translatedColumns = t.columns.map(function(c){ return c.name ;}); return true; } }) ; let notTranslatedColumns = schema[table].columns.filter(function(c){ return translatedColumns.indexOf(c.name) === -1; }).map(function(c){ return c.name ;}) ; let from = tableSql+" m " ; let columns = notTranslatedColumns ; let pk = schema[table].pk[0] ; for(let col of translatedColumns){ let alias = "t_"+col ; from += ` LEFT JOIN ( SELECT uid, value FROM velox_translation WHERE lang='${lang}' AND table_name='${table}' and col='${col}' ) ${alias} ON ${alias}.uid = m.${pk} ` ; columns.push('COALESCE('+alias+'.value, m.'+col+') AS "'+col+'"') ; } let cols = columns.join(",") ; let sql = `(SELECT ${cols} FROM ${from})` ; client["getTable_"+table] = function(){ return sql ; } ; } callback() ; }) ; } /** * Clear cache * * @private * @param {string} table table name * @param {object} record record to insert or update * @param {function(Error)} callback called on finish */ beforeSaveTranslation(table, record, callback){ cacheTranslations = null; callback() ; } /** * Get translations (handle cache) * * @param {VeloxDatabaseClient} db database client * @param {function(Error)} callback called on finish */ getTranslations(db, callback){ if(cacheTranslations){ return callback(null, cacheTranslations) ; } db.search("velox_lang", {}, [{name : "trs", otherTable: "velox_translation", type: "2many"}], "lang", function(err, langs){ if(err){ return callback(err) ;} cacheTranslations = {} ; for(let lang of langs){ if(!cacheTranslations[lang.lang]){ cacheTranslations[lang.lang] = {} ; } for(let tr of lang.trs){ if(!cacheTranslations[lang.lang][tr.table_name]){ cacheTranslations[lang.lang][tr.table_name] = {} ; } if(!cacheTranslations[lang.lang][tr.table_name][tr.col]){ cacheTranslations[lang.lang][tr.table_name][tr.col] = {} ; } if(!cacheTranslations[lang.lang][tr.table_name][tr.col][tr.uid]){ cacheTranslations[lang.lang][tr.table_name][tr.col][tr.uid] = tr.value ; } } } callback(null, cacheTranslations) ; }) ; } /** * Translate records * * @param {VeloxDatabaseClient} db database client * @param {function(Error)} callback called on finish */ translateRecords(db, lang, table, records, callback){ db.getTranslations((err, trs)=>{ if(err){ return callback(err) ;} db.getPrimaryKey(table, (err, pkColumns)=>{ if(err){ return callback(err); } let allLangs = Object.keys(trs) ; for(let record of records){ let uid = pkColumns.map((pk)=>{ return record[pk] ;}).join("_") ; let tableDef = db.getI18nOptions().tables.find((t)=>{ return t.name === table ;}) ; let velox_translations = {} ; for(let l of allLangs){ velox_translations[l] = {} ; } if(tableDef){ for(let col of tableDef.columns){ var colTable = col.table||table; for(let l of allLangs){ if(trs[l] && trs[l][colTable] && trs[l][colTable][col.name] && trs[l][colTable][col.name][uid]){ velox_translations[l][col.name] = trs[l][colTable][col.name][uid]; } } if(trs[lang] && trs[lang][colTable] && trs[lang][colTable][col.name] && trs[lang][colTable][col.name][uid]){ record[col.name] = trs[lang][colTable][col.name][uid]; } else if(trs["base"] && trs["base"][colTable] && trs["base"][colTable][col.name] && trs["base"][colTable][col.name][uid]){ record[col.name] = trs["base"][colTable][col.name][uid]; } } } } callback(null, records) ; }); }); } /** * Save translations * * @param {VeloxDatabaseClient} db database client * @param {string} lang lang code * @param {string} table table name * @param {object} record record saved * @param {function(Error)} callback called on finish */ translateSave(db, lang, table, record, callback){ db.getPrimaryKey(table, (err, pkColumns)=>{ if(err){ return callback(err); } let uid = pkColumns.map((pk)=>{ return record[pk] ;}).join("_") ; db.searchFirst("velox_lang", {lang: lang}, (err, langRecord)=>{ if(err){ return callback(err) ; } let changes = [] ; if(!langRecord){ changes.push({table: "velox_lang", record: {lang: lang}}) ; } let tableDef = db.getI18nOptions().tables.find((t)=>{ return t.name === table ;}) ; for(let colDef of tableDef.columns){ changes.push({table: "velox_translation", record: {lang: lang, table_name: colDef.table||table, col: colDef.name, uid: uid, value: record[colDef.name]}}) ; } db.changes(changes, callback) ; }) ; }); } getLang(client){ var lang = "base" ; if(client.context && client.context && client.context.req){ if(client.context.req.lang){ lang = client.context.req.lang ; } else if(client.context.req.headers["x-velox-lang"]){ lang = client.context.req.headers["x-velox-lang"].trim() ; } else if(client.context.req.user && client.context.req.user.lang){ lang = client.context.req.user.lang ; } else if (client.context.req.headers["accept-language"]){ let [acceptedLang] = client.context.req.headers["accept-language"].split(",") ; if(acceptedLang){ lang = acceptedLang.trim() ; } } } return lang; } /** * Update records with translations * * @param {table} table the records tables * @param {object[]} records list of records * @param {function} callback */ translateSaveHook(table, record, callback){ var lang = this.getLang() ; if(lang !== "base"){ this.translateSave(lang, table, record, callback); }else{ callback() ; } } /** * Update records with translations * * @param {table} table the records tables * @param {object[]} records list of records * @param {function} callback */ translateMany(table, records, callback){ var lang = this.getLang() ; if(lang !== "base"){ this.translateRecords(lang, table, records, (err)=>{ if(err){ return callback(err) ; } callback(null, records) ; }); }else{ callback(null, records) ; } } /** * Update record with translations * * @param {table} table the records tables * @param {object} records record * @param {function} callback */ translateOne(table, record, callback){ var lang = this.getLang() ; if(record && lang !== "base"){ this.translateRecords(lang, table, [record], (err)=>{ if(err){ return callback(err) ; } callback(null, record) ; }); }else{ callback(null, record) ; } }; /** * Add needed schema changes on schema updates * * @param {string} backend */ prependSchemaChanges(backend){ if(["pg"].indexOf(backend) === -1){ throw "Backend "+backend+" not handled by this extension" ; } let changes = [] ; changes.push({ sql: this.getCreateTableLang(backend) }) ; changes.push({ sql: this.getCreateTableTranslation(backend) }) ; return changes; } /** * Create the table velox_lang if not exists * @param {string} backend */ getCreateTableLang(backend){ let lines = [ "lang VARCHAR(10) PRIMARY KEY", "description VARCHAR(75)" ] ; if(backend === "pg"){ return ` CREATE TABLE IF NOT EXISTS velox_lang ( ${lines.join(",")} ) ` ; } throw "not implemented for backend "+backend ; } /** * Create the table velox_translation if not exists * @param {string} backend */ getCreateTableTranslation(backend){ let lines = [ "lang VARCHAR(10) REFERENCES velox_lang(lang)", "table_name VARCHAR(128)", "col VARCHAR(128)", "uid VARCHAR(128)", "value TEXT", "PRIMARY KEY(lang, table_name, col, uid)", ]; if(backend === "pg"){ return ` CREATE TABLE IF NOT EXISTS velox_translation ( ${lines.join(",")} ) ` ; } throw "not implemented for backend "+backend ; } }
JavaScript
class Loader { /** * Holds plugin validation rules * * @returns {{name: (function(String): Boolean), isPlugin: (function(Object): boolean)}} */ static get rules () { return { /** * Checks whether the module name matches a journeyman plugin * * @param {String} module * @returns {Boolean} */ name: module => !!module.match( /^journeyman-plugin-(.+)/ ), /** * Checks whether the module is an instance of the plugin base class * * @param {Object} plugin * @returns {Boolean} */ isPlugin: plugin => Plugin.isPrototypeOf( plugin ), /** * Checks whether the module is an instance of the core plugin base class * * @param {Object} plugin * @returns {Boolean} */ isCorePlugin: plugin => CorePlugin.isPrototypeOf( plugin ) }; } /** * Creates a new loader * * @param {Object} npm */ constructor ( npm ) { this.plugins = []; this.paths = [ npm.dir, npm.globalDir ]; this._loadPlugin( path.join( __dirname, '..', 'Core', 'Plugins', 'MakePlugin' ) ); } /** * Discovers plugins in one or more specific search paths * * @param {Array|String} searchPaths * @returns {Promise<Array>} */ async discover ( searchPaths = [] ) { if ( typeof searchPaths === 'string' ) { return this._discoverPath( searchPaths ); } if ( Array.isArray( searchPaths ) ) { await Promise.all( searchPaths // remove invalid paths .filter( path => typeof path !== 'undefined' ) // discover each path .map( searchPath => this._discoverPath( searchPath ) ) ); // merge all plugin sources return Array.prototype.concat( ...this.plugins ); } } /** * Discovers plugins in a specific search path * * @param {String} searchPath * @returns {Promise<Plugin[]>} * @private */ async _discoverPath ( searchPath ) { let modules = []; const loadedModules = []; // try to read the search path try { if ( await exists( searchPath ) ) { modules = await readDir( searchPath ); } } catch ( error ) { throw new PluginDiscoveryError( this, searchPath, error ); } // iterate all module directories found for ( let moduleName of modules ) { // check if the module name matches if ( this.constructor.rules.name( moduleName ) ) { // resolve the plugin path const modulePath = path.resolve( path.join( searchPath, moduleName ) ); loadedModules.push( this._loadPlugin( modulePath ) ); } } return loadedModules; } _loadPlugin ( modulePath ) { let plugin; // try to require the plugin try { plugin = require( modulePath ); } catch ( error ) { throw new PluginLoadError( this, modulePath, error ); } // check if it's a valid plugin if ( !this.constructor.rules.isPlugin( plugin ) && !this.constructor.rules.isCorePlugin( plugin ) ) { throw new InvalidPluginError( this, plugin ); } this.plugins.push( plugin ); return plugin; } }
JavaScript
class CustomRegistryCredentials { /** * Create a CustomRegistryCredentials. * @property {object} [userName] The username for logging into the custom * registry. * @property {string} [userName.value] The value of the secret. The format of * this value will be determined * based on the type of the secret object. If the type is Opaque, the value * will be * used as is without any modification. * @property {string} [userName.type] The type of the secret object which * determines how the value of the secret object has to be * interpreted. Possible values include: 'Opaque', 'Vaultsecret' * @property {object} [password] The password for logging into the custom * registry. The password is a secret * object that allows multiple ways of providing the value for it. * @property {string} [password.value] The value of the secret. The format of * this value will be determined * based on the type of the secret object. If the type is Opaque, the value * will be * used as is without any modification. * @property {string} [password.type] The type of the secret object which * determines how the value of the secret object has to be * interpreted. Possible values include: 'Opaque', 'Vaultsecret' * @property {string} [identity] Indicates the managed identity assigned to * the custom credential. If a user-assigned identity * this value is the Client ID. If a system-assigned identity, the value will * be `system`. In * the case of a system-assigned identity, the Client ID will be determined * by the runner. This * identity may be used to authenticate to key vault to retrieve credentials * or it may be the only * source of authentication used for accessing the registry. */ constructor() { } /** * Defines the metadata of CustomRegistryCredentials * * @returns {object} metadata of CustomRegistryCredentials * */ mapper() { return { required: false, serializedName: 'CustomRegistryCredentials', type: { name: 'Composite', className: 'CustomRegistryCredentials', modelProperties: { userName: { required: false, serializedName: 'userName', type: { name: 'Composite', className: 'SecretObject' } }, password: { required: false, serializedName: 'password', type: { name: 'Composite', className: 'SecretObject' } }, identity: { required: false, serializedName: 'identity', type: { name: 'String' } } } } }; } }
JavaScript
class Preview { constructor(url, $form, options = {}) { this.url = url; this.$form = $form; this.validateErrorTitle = options['validateErrorTitle']; this.validateErrorText = options['validateErrorText']; this.validateSubmitEvent = options['validateSubmitEvent']; } static AddEvent() { } static AddEventOnce() { $(document).on('click.exment_preview', '[data-preview]', {}, Preview.appendPreviewEvent); $(document).on('pjax:complete', function (event) { Preview.AddEvent(); }); } /** * Showing preview */ openPreview() { if (this.validateSubmitEvent !== undefined && !this.validateSubmitEvent()) { Exment.CommonEvent.ShowSwal(null, { type: 'error', title: this.validateErrorTitle, text: this.validateErrorText, showCancelButton: false, }); return; } window.open('', 'exment_preview'); const form = this.$form; const action = form.attr('action'); const method = form.attr('method'); // update form info form.attr('action', this.url) .attr('method', 'post') .attr('target', 'exment_preview') .removeAttr('pjax-container') .data('preview', 1); form.submit(); form.attr('action', action).attr('method', method).attr('target', '').attr('pjax-container', ''); } }
JavaScript
class Queue { constructor () { this.items = {} this.emptyKeys = [] } addItem (key, item) { if (!(key in this.items)) { this.items[key] = [] } this.items[key].push(item) const i = this.emptyKeys.indexOf(key) if (i !== -1) { this.emptyKeys.splice(i, 1) } } getItem (key) { if (!this.getItemsCount(key)) { return } return this.items[key].shift() } getItemsCount (key) { if (!(key in this.items)) { return 0 } return this.items[key].length } flushEmptyKeys () { const keys = Object.keys(this.items) for (let i = 0; i < keys.length; i++) { const key = keys[i] if (this.getItemsCount(key) < 1) { this.emptyKeys.push(key) delete this.items[key] } } } getKeys () { this.flushEmptyKeys() return Object.keys(this.items) } getKeysCount () { return this.getKeys().length } getNextKey (offset) { const keys = this.getKeys() if (keys.length) { for (let i = 0; i < keys.length; i++) { if (offset && i < offset) { continue } if (this.getItemsCount(keys[i])) { return keys[i] } } } } }
JavaScript
class RecipeDetails extends Component { /** * Initilizes ingredients & recipe to empty sets in state */ constructor() { super(); this.state = { ingredients: new Set(), recipe: new Set() }; } /** * Adds the instructions index to the indices of items being edited * @param {Number} instructionIndex * @param {String} itemType - "recipe", "ingredients", or "meta" */ openEditItem(instructionIndex, itemType) { const t = new Set([instructionIndex, ...this.state[itemType]]); this.setState({ [itemType]: t }); } /** * Removes the given index from the set of indices of items being edited * @param {Number} instructionIndex - index of the item being edited * @param {String} itemType - "recipe", "ingredients", or "meta" */ closeEdit(instructionIndex, itemType) { let t = this.state[itemType]; t.delete(instructionIndex); this.setState({ [itemType]: t }); } /** * Updates parent component with newItemText * @param {String} newItemText * @param {String} itemType - "recipe", "ingredients", or "meta" * @param {Number} index */ updateItem(newItemText, itemType, index) { this.props.updateRecipe({ ...this.props.recipe, /* Only give back the new text if it is the index matches the index of the item that we are editing */ [itemType]: this.props.recipe[itemType].map((item, i) => { if (i !== index) { return item; } else { return newItemText; } }) }); } /** * Displays UI for item information and editing. * @param {Array} itemSet - Array of strings containing thing like recipe steps or ingredient list * @param {String} itemType - "recipe", "ingredients", or "meta" */ renderItem(itemSet, itemType) { return ( <ListGroup> {itemSet.map((step, i) => ( <ListGroupItem key={i}> {this.state[itemType].has(i) ? ( <div className="itemContainer"> <textarea className="itemText" type="text" value={step} onChange={e => this.updateItem(e.target.value, itemType, i)} wrap="hard" rows="8" /> <Button onClick={() => this.closeEdit(i, itemType)} bsStyle="primary" className={["button", "crudButton"]} > <Glyphicon glyph="ok" /> </Button> </div> ) : ( <div className="itemContainer"> <span className="itemText">{step}</span> <Button onClick={() => this.openEditItem(i, itemType)} bsStyle="info" className={["editItem", "button", "crudButton"]} > <Glyphicon glyph="pencil" /> </Button> <Button bsStyle="danger" className={["button", "crudButton"]}> <Glyphicon glyph="trash" /> </Button> </div> )} </ListGroupItem> ))} </ListGroup> ); } render() { return ( <div> <Tabs defaultActiveKey="Recipe" id="Recipe Details"> <Tab eventKey="Recipe" title="Recipe"> {this.renderItem(this.props.recipe.recipe, "recipe")} </Tab> <Tab eventKey="ingredients" title="Ingredients"> {this.renderItem(this.props.recipe.ingredients, "ingredients")} </Tab> </Tabs> </div> ); } }
JavaScript
class RequiredError extends Error { constructor(field, msg) { super(msg); this.field = field; this.name = 'RequiredError'; } }
JavaScript
class FaceboxApi extends BaseAPI { /** * Use the /tagbox/check endpoint to get tags for a specified image. * @summary checkFaceprint * @param {CheckFaceprintParamsBody} checkFaceprintParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ checkFaceprint(checkFaceprintParamsBody, options) { return exports.FaceboxApiFp(this.configuration).checkFaceprint(checkFaceprintParamsBody, options)(this.basePath); } /** * Use the /tagbox/check endpoint to get tags for a specified image. * @summary checkImage * @param {CheckImageParamsBody} checkImageParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ checkImage(checkImageParamsBody, options) { return exports.FaceboxApiFp(this.configuration).checkImage(checkImageParamsBody, options)(this.basePath); } /** * Compare multiple faceprints. * @summary compareFaceprint * @param {CompareFaceprintParamsBody} compareFaceprintParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ compareFaceprint(compareFaceprintParamsBody, options) { return exports.FaceboxApiFp(this.configuration).compareFaceprint(compareFaceprintParamsBody, options)(this.basePath); } /** * Get similar faces to a new or unknown face * @summary getSimilar * @param {GetSimilarParamsBody} getSimilarParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ getSimilar(getSimilarParamsBody, options) { return exports.FaceboxApiFp(this.configuration).getSimilar(getSimilarParamsBody, options)(this.basePath); } /** * * @summary getSimilarById * @param {string} id * @param {number} [limit] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ getSimilarById(id, limit, options) { return exports.FaceboxApiFp(this.configuration).getSimilarById(id, limit, options)(this.basePath); } /** * * @summary rename * @param {string} id * @param {RenameParamsBody} renameParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ rename(id, renameParamsBody, options) { return exports.FaceboxApiFp(this.configuration).rename(id, renameParamsBody, options)(this.basePath); } /** * Teach facebox a face * @summary teach * @param {TeachFaceParamsBody} teachFaceParamsBody * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof FaceboxApi */ teach(teachFaceParamsBody, options) { return exports.FaceboxApiFp(this.configuration).teach(teachFaceParamsBody, options)(this.basePath); } }
JavaScript
class MetadataApi extends BaseAPI { /** * Returns some basic details about the box. * @summary GetBoxInfo * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MetadataApi */ getBoxInfo(options) { return exports.MetadataApiFp(this.configuration).getBoxInfo(options)(this.basePath); } }
JavaScript
class PlayheadEvent{ /** * creates a new PlayheadEvent * @param {Node} node node to be used as timeline base */ constructor(playhead){ /** * @type {Node} */ this.target = target; /** * @type {Node[]} */ this.path = playhead.path; /** * @type {Node[]} */ this.entered = null; /** * @type {Node[]} */ this.exited = null; /** * @type {Number} */ this.timeStamp = Date.now(); } }
JavaScript
class UpperContainer extends Component { constructor(props) { super(props); this.state = { id: "", img: "", photo: "", signInId: "", mouseOn: "", scrolled: false, openDrop: false }; this.upload = this.upload.bind(this); } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.tracks !== prevState.tracks) { return { id: nextProps.id, username: nextProps.displayName, signInId: nextProps.id }; } return null; } componentDidMount() { window.addEventListener("scroll", () => { const isTop = window.scrollY < 80; if (isTop !== true) { this.setState({ scrolled: true }); } else this.setState({ scrolled: false }); }); } /** * A function to call handleFollowClick() function which handles the follow click on the whole artist page * @function * @returns {void} */ handleFollowClick = event => { this.props.handleFollowClick(event); }; /** * A function to change the mouse over on * @function * @returns {void} */ handleMouseOver = event => { this.setState({ mouseOn: true }); }; /** * A function to change the mouse over out * @function * @returns {void} */ handleMouseOut = event => { this.setState({ mouseOn: false }); }; /** * A function to handle upload action * @function * @returns {void} */ upload(event) { if (this.props.userId === this.state.signInId) document.getElementById("avatar").click(); } handlePlay = () => {}; render() { return ( <div className="artist-user" data-testid="artist-user-upper-container"> <div className={this.state.scrolled ? "upperNav" : "upperContainerProfile"} data-testid="UpperContainer" style={ this.state.scrolled ? { backgroundColor: "#000000" } : { backgroundImage: `url(${this.props.cover})` } } > <div className="avatarContainer" data-testid="avatar"> {!this.state.scrolled && this.props.userId === this.state.signInId && ( <p className="changeImage" onClick={this.upload}> change </p> )} </div> <div data-testid="userName" className={ this.state.scrolled ? "userName-profile-scrolled" : "userName-profile" } > <h1>{this.props.username}</h1> </div> {!this.state.scrolled ? ( <div> <button data-testid="artist-follow-button" className="btn btn-outline-warning play-artist" onClick={this.handlePlay} > Play </button> <button id="artist-follow-button-upperContainer" className={ this.props.followStatus ? "btn btn-outline-warning upperContainerFollowingButton" : "btn btn-outline-light upperContainerFollowButton" } onClick={this.handleFollowClick} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} > {this.props.followStatus ? ( this.state.mouseOn ? ( <>UNFOLLOW</> ) : ( <> FOLLOWING </> ) ) : ( <> FOLLOW</> )} </button> <Options className="artist-options-dropdown" followStatus={this.props.followStatus} artistId={this.props.artistId} handleFollowClick={this.handleFollowClick} /> </div> ) : null} <div data-testid="profile-links" className="profile-links" style={ this.state.scrolled ? { marginTop: "0", marginLeft: "30px", paddingTop: "inherit" } : { paddingTop: "inherit" } } > <Link id="overview-upperContainer" to={`/artist/${this.props.artistId}/overview`} > Overview </Link> <Link id="publicPlaylists-upperContainer" to={`/artist/${this.props.artistId}/related`} > Related Artists </Link> <Link id="following-upperContainer" to={`/artist/${this.props.artistId}/about`} > About </Link> <Link id="following-upperContainer" to={`/artist/${this.props.artistId}/statistics`} > Statistics </Link> </div> </div> {this.state.scrolled && <div style={{ height: "250px" }}></div>} </div> ); } }
JavaScript
class ConfigurationProvider { /** * Fetching credentials for authentication in the following order * 1) Fetch credentials from user provided service * 2) Fetch credentials from service binding of SAP IoT service * 3) Fetch credentials from local default-env.json file * 4) Fetch credentials from environment variables * This method is not throwing any error in case no credentials have been found as this library can also be used in a mode in which all access tokens are handled manually * * @param {string} [serviceName] - Name of service which is providing tenant information * @returns {{uaaUrl, clientId, clientSecret}|undefined} Xsuaa configuration from SAP IoT instance if it can be found. Otherwise returns undefined. */ static getCredentials(serviceName) { debug('Fetching authentication options'); const sapIoTService = this._getSAPIoTService(serviceName); if (sapIoTService && sapIoTService.credentials) { return sapIoTService.credentials.uaa; } return undefined; } /** * Creating a repository of service destination URLs considering the current landscape. Landscape information is fetched in the following order * 1) Fetch landscape information from service binding of SAP IoT service * 2) Fetch landscape information from local default-env.json file * 3) Fetch landscape information from environment variables * * In case no landscape information can be determined the default landscape is EU10. * This method returns a key value map where key equals the service name (i.e. appiot-mds) and value equals the full destination URI (i.e. https://appiot-mds.cfapps.eu10.hana.ondemand.com) * * @param {string} [serviceName] - Name of service which is providing tenant information * @returns {*} List of endpoints from SAP IoT */ static getDestinations(serviceName) { debug('Fetching destinations options from service binding'); const sapIoTService = this._getSAPIoTService(serviceName); if (sapIoTService && sapIoTService.credentials) { return sapIoTService.credentials.endpoints; } return undefined; } /** * Return service object of bound SAP IoT service instance if available * * @param {string} [serviceName] - Name of service which is providing tenant information * @returns {*} SAP IoT servie object from environment * @private */ static _getSAPIoTService(serviceName) { if (serviceName) { return this._getService({ name: serviceName }); } return this._getService({ tag: 'leonardoiot' }); } /** * Return service object of bound XSUAA service instance if available * * @returns {*} Xsuaa service object from environment */ static getXsuaaService() { return this._getService({ tag: 'xsuaa' }); } /** * Return service object which fits query parameters * * @param {object} [configuration] - Service configuration query parameters for filtering * @param {string} [configuration.name] - Filters service by name, selection parameter with highest priority * @param {string} [configuration.tag] - Filters service by tag, selection parameter with lower priority than name * @throws {Error} Throws Error if runtime environment configuration cant be loaded * @returns {object} Matching service object from environment * @private */ static _getService({ name, tag } = {}) { if (!process.env.VCAP_SERVICES) { xsenv.loadEnv(); if (!process.env.VCAP_SERVICES) { throw new Error('Runtime environment configuration (default-env.json file) missing'); } } const services = xsenv.readCFServices(); let result; if (name) { result = Object.values(services).find((service) => service && service.name && service.name === name); } if (tag && !result) { result = Object.values(services).find((service) => service && service.tags && service.tags.includes(tag)); } return result; } }
JavaScript
class GenericResponse { constructor(code, body, headers, request) { this.code = code; this.body = body; this.headers = headers; this.request = request; } }
JavaScript
class ParseHolyLandPhone { constructor(phoneNumber) { this.phoneNumber = phoneNumber; this.fromInternational(); } static create(phoneNumber) { return new ParseHolyLandPhone(phoneNumber); } /** * Checks if phone number is a valid Israeli/Palestinian phone number * * @return boolean */ isValid() { return this.phoneNumber.match(/^((0[23489][2356789]|0[57][102345689]\d|1(2(00|12)|599|70[05]|80[019]|90[012]|919))\d{6}|\*\d{4})$/) !== null; } /** * Checks if phone number is Israeli * * @return boolean */ isIsraeli() { return this.phoneNumber.match(/^((0[23489][356789]|0[57][1023458]\d|1(2(00|12)|599|70[05]|80[019]|90[012]|919))\d{6}|\*\d{4})$/) !== null; } /** * Checks if phone number is Palestinian * * @return boolean */ isPalestinian() { return this.phoneNumber.match(/^(0[23489]2|05[69]\d|)\d{6}$/) !== null; } /** * Checks if phone number is land line * * @return boolean */ isLandLine() { return this.phoneNumber.match(/^0([23489][2356789]|7\d{2})\d{6}$/) !== null; } /** * Checks if phone number is mobile * * @return boolean */ isMobile() { return this.phoneNumber.match(/^0[5][102345689]\d{7}$/) !== null; } /** * Checks if phone number is special (*1234) * * @return boolean */ isSpecial() { return this.phoneNumber.match(/^\*\d{4}$/) !== null; } /** * Checks if phone number is business (1800, etc) * * @return boolean */ isBusiness() { return this.phoneNumber.match(/^1(2(00|12)|599|70[05]|80[019]|90[012]|919)\d{6}$/) !== null; } /** * Checks if phone number is toll free (1800) * * @return boolean */ isTollFree() { return this.phoneNumber.match(/^180[019]\d{6}$/) !== null; } /** * Checks if phone number is premium (1900) * * @return boolean */ isPremium() { return this.phoneNumber.match(/^19(0[012]|19)\d{6}$/) !== null; } /** * Checks if phone number is Kosher (phone supports only calls) * * @return boolean */ isKosher() { return this.phoneNumber.match(/^0([23489]80|5041|5271|5276|5484|5485|5331|5341|5832|5567)\d{5}$/) !== null; } /** * Checks if phone number is erotic (1919) * * @return boolean */ isErotic() { return this.phoneNumber.match(/^1919\d{6}$/) !== null; } /** * Checks if phone number can receive sms * * @return boolean */ isSmsable() { return this.isNotKosher() && this.isMobile(); } fromInternational() { this.phoneNumber = this.phoneNumber.replace(/^(972)(\d{8,9})$/, '0$2'); } /** * Returns phone number transformed to international format * 021231234 > 97221231234 * 0501231234 > 972501231234 */ getInternational() { return this.phoneNumber.replace(/^(0)(\d{8,9})$/, '972$2'); } isNotValid() { return !this.isValid(); } isNotIsraeli() { return !this.isIsraeli(); } isNotPalestinian() { return !this.isPalestinian(); } isNotLandLine() { return !this.isLandLine(); } isNotMobile() { return !this.isMobile(); } isNotBusiness() { return !this.isBusiness(); } isNotTollFree() { return !this.isTollFree(); } isNotPremium() { return !this.isPremium(); } isNotKosher() { return !this.isKosher(); } isNotErotic() { return !this.isErotic(); } isNotSmsable() { return !this.isSmsable(); } }
JavaScript
class App extends EventEmitter { /** * Constructor - instancie les objets nécessaire à l'app * @return {void} */ constructor() { super(); // authors console.log('________________________________________'); console.log('_______________ Crée par _______________'); console.log('_______ Julien Martins Da Costa ________'); console.log('__________________ & ___________________'); console.log('___________ Adrien Scholaert ___________'); console.log('________________________________________'); console.log('___________ Gobelins - CRM14 ___________'); console.log('________________________________________'); // enable html Interface this.interface = new Interface(); // enable threejs this.sceneManager = new SceneManager(); this.dataVisuManager = new DataVisuManager(this.sceneManager); // enable sound manager this.soundManager = new SoundManager(); // enable webcamRTC manager this.webcamRtcManager = new WebcamRtcManager(); this.webcamRtcManager.on('motionDetecting', this.onMotionDetecting.bind(this)); //this.webcamRtcManager.on('movePosition', this.onChangeSound.bind(this)); // enable speechapi this.speechApiManager = new SpeechApiManager(this.interface, this.webcamRtcManager); // initialize app this.init(); } /** * Initialise la scène webGL * * @return {void} */ init() { this.sceneManager.on('sceneManagerLoaded', this.onSceneManagerLoaded.bind(this)); this.sceneManager.init(); this.speechApiManager.init(); } /** * Méthode appellée quand un mouvement est détecté * * @param {boolean} bool true lorsqu'un mouvement est detecté * @return {void} */ onMotionDetecting(bool) { console.log('[EVENT] onMotionDetecting'); this.interface.setWarningMessage(bool); this.sceneManager.setGlitch(bool); } /** * Méthode appelée quand la scène webGL est chargée pour * initialiser ensuite le soundManager * @return {[type]} [description] */ onSceneManagerLoaded() { console.log('[EVENT] onSceneManagerLoaded'); this.soundManager.on('soundManagerLoaded', this.onSoundManagerLoaded.bind(this)); this.soundManager.init(); } /** * Méthode appellée quand le SoundManager est chargé * * @return {void} */ onSoundManagerLoaded() { console.log('[EVENT] onSoundManagerLoaded'); let number = Math.floor((Math.random() * 1) + 1); // play background sound let sound = this.soundManager.playSound('sound' + number, 1, 1); let sound2 = this.soundManager.playSound('sound' + number, 1, 1); // init data visu manager this.dataVisuManager.init(sound); this.dataVisuManager.initSmallAnalyser1(sound2); // listen render this.sceneManager.on('render', this.render.bind(this)); } /*onChangeSound() { console.log('[EVENT] onChangeSound'); let number = Math.floor((Math.random() * 9) + 1); // play background sound let sound = this.soundManager.playSound('sound' + number, 1, 1); let sound2 = this.soundManager.playSound('sound' + number, 1, 1); // init data visu manager this.dataVisuManager.updateSound(sound); //this.dataVisuManager.initSmallAnalyser1(sound2); }*/ /** * Rendre la scène * * @return {void} */ render() { this.dataVisuManager.render(); } }
JavaScript
class ItemCreator { constructor(newItemInputElement) { this.eInput = newItemInputElement; this.eParentList = $(newItemInputElement).closest(`.${ListHtml.Elements.CONTAINER}`); this.parentListID = $(this.eParentList).attr('data-list-id'); this.content = null; this.itemID = null; this.rank = $(this.eParentList).find(`.${ItemHtml.Elements.TOP}`).length; this.loadInputValue = this.loadInputValue.bind(this); this.assignNewItemID = this.assignNewItemID.bind(this); this.sendPostRequest = this.sendPostRequest.bind(this); this._inputToFormData = this._inputToFormData.bind(this); this.clearInputValue = this.clearInputValue.bind(this); this.appendToList = this.appendToList.bind(this); } /********************************************************** Retrieve the input element's value. Returns a bool: true: the input is not empty and has a value false: value is empty or null **********************************************************/ loadInputValue() { const inputElementValue = $(this.eInput).val(); if (inputElementValue.length > 0) { this.content = inputElementValue; return true; } else { this.content = null; return false; } } /********************************************************** Set the item id's value to a newly generated uuid **********************************************************/ assignNewItemID() { this.itemID = Utilities.getNewUUID(); return this; } /********************************************************** Send the request to the api to create the new item **********************************************************/ async sendPostRequest() { const formData = this._inputToFormData(); try { ApiWrapper.itemsPut(this.itemID, formData); return true; } catch(error) { return false; } } /********************************************************** Transform the input value into a FormData object so it can be sent to the api correctly. **********************************************************/ _inputToFormData() { return Utilities.objectToFormData({ content: this.content, list_id: this.parentListID, rank: this.rank, }); } /********************************************************** Clear the input's value **********************************************************/ clearInputValue() { $(this.eInput).val(''); } /********************************************************** Append the item to the active list's html **********************************************************/ appendToList() { const itemHtml = new ItemHtml({ id: this.itemID, content: this.content, }); const html = itemHtml.getHtml(); // $(this.eParentList).find('.active-list-items-container').prepend(html); $(this.eParentList).find('.active-list-items-container').append(html); } }
JavaScript
class RenkuMarkdown extends Component { render() { const { singleLine, style, fixRelativePaths } = this.props; if (fixRelativePaths) return <RenkuMarkdownWithPathTranslation {...this.props} />; let className = "text-break renku-markdown"; if (singleLine) className += " children-no-spacing"; if (this.props.className) className += " " + this.props.className; return <div className={className} style={style} dangerouslySetInnerHTML={{ __html: sanitizedHTMLFromMarkdown(this.props.markdownText, singleLine) }}> </div>; } }
JavaScript
class Codeman extends Component { state = { contextValue: "default value", val: '' }; constructor(props){ super(props) this.test = this.test.bind(this) this.getval = this.getval.bind(this) this.set = props.set this.get = props.get } componentDidCatch(error, info){ console.log('error') } getval(){ return this.state.val } test(e){ // console.log(e) this.setState({val: e}) } render() { return ( <div> <GoldenLayoutComponent //config from simple react example: https://golden-layout.com/examples/#qZXEyv htmlAttrs={{ style: { height: "100vh", width: "100vw" } }} config={{ content: [ { type: "row", content: [ { title: "Main contents", type: "react-component", component: "main", isClosable: false, props: {location: this.props.location, set: this.set} }, { type: "column", content: [{ title: "Main Code", type: "react-component", component: "code", isClosable: false, props: { set: this.test, get: this.get } },{ title: "Main result", type: "react-component", component: "result", isClosable: false, props: { get: this.getval, getlen: this.get} }] } ] } ] }} registerComponents={myLayout => { myLayout.registerComponent("main", coursemain); myLayout.registerComponent("result", result); myLayout.registerComponent("code", python); }} /> </div> ); } }
JavaScript
class MRPTextBox extends Polymer.Element { static get is() { return 'mrp-text-box'; } static get properties() { return { id: {type: String, value: ''}, //The ID of the element class: {type: String, value: ''}, //The class of the element maxlength: {type: Number, value: -1}, //The maxlength of the <input> value: {type: String, value: '', observer: 'changed', reflectToAttribute:true}, //If not blank this will be the default value of the text box regex: {type: String, value: ''}, //The regex expression that text of the text box will ba validation against placeholder: {type: String, value: ''}, //The placeholder of the <input> validation: {type: Number, value: -1, reflectToAttribute: true, observer: 'validationReset'}, //This value will represent the validation status of the element. 0=invalid, 1=valid, -1=default. errorMsg: {type: String, value: ''}, //The message displayed when the validation fails. required: {type: Boolean, value:false} //If true and empty textbox will not be considered valid, if false, then the element will not test it's validation until it's value it changed }; } isInvalid(validation) { //Check the validation status of the properties so it can display or hide the error message if (validation === 0) { return true; } else { return false; } } changed(event) { //The text is changed then trigger the changed event and check the validation if (event.type === "blur") { var value = this.get('value'); this.checkValidation(this.get('validation'), true); var triggerObj = {textBox: this, event: event, text:value}; Lib.Polymer.triggerEventsWithTable(this,triggerObj, 'mrp-text-box_changed'); } } validationReset(validation){ //This will cause the validation to run again if(validation ===2){ this.checkValidation(validation, true); } } checkValidation(validation, isNotStart = false) { //This will check the validation against the regex property, also if the required property is true //the text box must has some text, or the validation will fail. if (isNotStart || validation !== -1) { if (this.get('regex') !== '') { var text = $(this).val(); var res = text.match(this.get('regex')); if (res === null) { //validation failed //display error message this.set('validation', 0); } else { this.set('validation', 1); } } else { this.set('validation', 1); } } if(!this.get('required') && $(this).val()===''){ this.set('validation', 1); } } }
JavaScript
class QueryString { /** * Reads or sets a new query string. If used as an empty constructor, * will load the query string from the current document URL. If an object * is passed, a new query string will be initialised from it. * @constructs * @param {object} obj - Optional initialiser for new query string. */ constructor(obj) { if (arguments.length) { // If an object was passed, use it to initialise the .values member. this.values = typeof obj === 'object' ? obj : {}; } else { // No parameters to the constructor => parse the query string // from the current document URL. this.values = {}; const pars = window.location.search.substr(1).split('&'); for (const p of pars) { // Can't use split() because the limit is two parts, but // the second part may include the separator (and more), // and split() would cut that off. const m = p.match(/^([^=]*)=?(.*)$/m); // Index 1 is the key, index 2 is the value. Both can be // empty, but an empty key makes no sense. if (m && m.length == 3 && m[1].length) { const key = decodeURIComponent(m[1]); let val = decodeURIComponent(m[2]); // Try to convert string values to integer, float, boolean // or null. No conversion if not a complete & valid match. const im = val.match(/^-?(0|[1-9]\d*)/); if (im) { if (im[0].length == val.length) { // The whole thing completely matches // a valid integer. val = parseInt(val); } else { const sub = val.substr(im[0].length); const fm = sub.match(/^(\.\d+)?(e[+-]?\d+)?$/i); if (fm) { // The rest completely matches a valid // fractional part and/or exponent. val = parseFloat(val); } } } else { // Check for boolean or null values as strings. if (val === 'true') { val = true; } else if (val === 'false') { val = false; } else if (val === 'null') { val = null; } } // Store the parameter in the .values member. this.values[key] = val; } } } } /** * Serializes and returns the current object collection of query * parameters. By default, returns a query string as plain text. * If the first argument to the method is '&amp;' or ';', returns * it with special characters encoded for use in HTML. * @method * @param {string} [arg0='&'] - Separator between query parameters. * @param {string} [arg1='='] - Separator between keys and values. * @param {string} [arg2='?'] - Prefix of the query string. * @returns {string} Current search query as a string, can be empty. */ serialize(...args) { const sep = args.length ? args.shift() : '&'; const eq = args.length ? args.shift() : '='; const qm = args.length ? args.shift() : '?'; const a = []; // array to collect all key=val combinations if (sep === '&amp;' || sep === ';') { // HTML encoding requested. Object.entries(this.values).forEach(([k, v]) => { a.push(encodeURIComponent(k) + eq + encodeURIComponent(v)); }); } else { // Plain text requested. Object.entries(this.values).forEach(([k, v]) => { a.push('' + k + eq + v); }); } return a.length ? qm + a.join(sep) : ''; } /** * Makes a plain text query string from the current query parameters. * @method * @returns {string} Query string as plain text. */ toText() { return this.serialize('&'); } /** * Makes an HTML encoded query string from the current query parameters. * Can be directly written to the href property of a link tag <a ...></a> * in HTML source code. * @method * @returns {string} Query string as HTML encoded text. */ toHtml() { return this.serialize('&amp;'); } /** * Default toString() method that is automatically called when a class * instance is used in a string context. Serializes the current query * parameters as HTML encoded text. * @method * @returns {string} Query string as HTML encoded text. */ toString() { return this.toHtml(); } /** * Navigate to a new URL with the query string of this class instance. If * no argument is supplied, go to the current document + the query string. * @method * @param {string} [newpage=''] - Optional new page address. */ goto(newpage) { const page = arguments.length ? newpage : ''; location = page + this.toText(); } /** * Get the integer value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @returns {number} Integer value of the query parameter, or undefined. */ getInt(key) { return key in this.values ? parseInt(this.values[key]) : undefined; } /** * Get the float value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @returns {number} Float value of the query parameter, or undefined. */ getFloat(key) { return key in this.values ? parseFloat(this.values[key]) : undefined; } /** * Get the boolean value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @returns {boolean} Boolean value of the query parameter, or undefined. */ getBool(key) { return key in this.values ? !!(this.values[key]) : undefined; } /** * Get the string value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @returns {string} String value of the query parameter, or undefined. */ getStr(key) { return key in this.values ? '' + this.values[key] : undefined; } /** * Get the stored value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @returns Value of the query parameter, any type, could be undefined. */ get(key) { return this.values[key]; } /** * Set the value of the named query parameter. * @method * @param {string} key - Name of the query parameter. * @param val - Value of the query parameter, any assignable type. */ set(key, val) { this.values[key] = val; } /** * Unset the named query parameter, return the old value. * @method * @param {string} key - Name of the query parameter. * @returns Deleted value of the query parameter, any type, could be undefined. */ unset(key) { const tmp = this.values[key]; delete this.values[key]; return tmp; } }
JavaScript
class Add extends Component { static contextTypes = { router: PropTypes.object.isRequired } constructor(props) { super(props) // const data = [{ // url: 'https://zos.alipayobjects.com/rmsportal/PZUUCKTRIHWiZSY.jpeg', // id: '2121' // }, { // url: 'https://zos.alipayobjects.com/rmsportal/hqQWgTXdrlmVVYi.jpeg', // id: '2122' // }] const data = [] this.state = { files: data, multiple: false, birth: '', // 出生日期 gender: '1', // 性别 height: '', // 身高 constellation: '', // 星座 birthplace: '', // 出生地 livingplace: '', // 现居地 degree: '', // 学历 occupational: '', // 职业 webchat: '', // 微信号 // 自我介绍 character: '', // 性格 habits: '', // 生活习惯 hobby: '', // 兴趣爱好 other: '', // 其它 photos: [], // 生活照 // 理想对象 he_agerange: '', // 年龄范围 he_appearance: '', // 外貌要求 he_character: '', // 性格要求 he_degree: '', // 学历要求 he_coordinate: '', // 他(她)坐标 } this.handleChange = handleChange.bind(this) // mixin } genData = async (data) => { let dataBlob = {} let result = await userService.getdetail(data) if (result.code === 200) { dataBlob = result.data } return dataBlob } async componentDidMount () { // you can scroll to the specified position // setTimeout(() => this.lv.scrollTo(0, 120), 800); // simulate initial Ajax // this.rData = await this.genData() // console.log('rdata', this.rData) // this.setState({ // dataSource: this.state.dataSource.cloneWithRows(this.rData), // isLoading: false // }) let id = this.props.params.id let rData = await this.genData({ _id: id }) this.setState({ ...rData }) } onImageClick = (index, fs) => { let token = storage.get('token') if (token) { Zmage.browsing({ src: fs[index].url }) } else { alert('查看高清大图需要登录') } } getnumber = async (id) => { console.log(id, 'getnumber') let result = await userService.getwebchat({ id }) console.log(result) if (result.code === 200) { alert(`微信号为${result.data.webchat}`) } else { alert(result.msg) } } getWebchat = (id) => { let token = storage.get('token') if (token) { let userdata = storage.get('userdata') if (userdata._id) { if (userdata.isVip != 0) { alert('注意', '尊金的超级会员,您好!为了健康交友,请慎重获取微信号,是否继续?', [ { text: '取消', onPress: () => console.log('cancel') }, { text: '确定', onPress: () => this.getnumber(id) }, ]) } else { alert('注意', '为了健康交友,普通会员每周只能获取一个微信号,是否继续?', [ { text: '取消', onPress: () => console.log('cancel') }, { text: '确定', onPress: () => this.getnumber(id) }, ]) } } else { alert('该操作需要登录') } } else { alert('该操作需要登录') } } render () { const data = this.state const files = [] return ( <div className="jumbotron" > <div className="title" style={{ textAlign: 'center' }}> <h1> {data.username}</h1> </div> {/* <p> <Link to="/msg" role="button" className="btn btn-success btn-lg"> 前往留言板 &gt; </Link> &nbsp; <Link to="/todo" role="button" className="btn btn-success btn-lg"> 前往待办事项(新功能) &gt; </Link> </p> */} <form onSubmit={ (e) => { e.preventDefault() // 防页面跳转 } } > <div style={{ height: '30px', lineHeight: '30px', fontSize: '20px', textAlign: 'center', margin: '0 80px 10px', borderBottom: '1px solid #a190df' }}>基本信息</div> { data.birth ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">出生日期</label> {data.birth} </div> : null } { data.gender ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">性别</label> {data.gender === '2' ? '女' : '男'} </div> : null } { data.height ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">身高</label> {data.height} </div> : null } { data.constellation ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">星座</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.constellation}</span> </div> : null } { data.birthplace ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">出生地</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.birthplace}</span> </div> : null } { data.livingplace ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">现居地</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.livingplace}</span> </div> : null } { data.degree ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">学历</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.degree}</span> </div> : null } { data.occupational ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">职业</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.occupational}</span> </div> : null } { data.webchat ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">微信号</label> {data.webchat} </div> : null } <div style={{ height: '30px', lineHeight: '30px', fontSize: '20px', textAlign: 'center', margin: '0 80px 10px', borderBottom: '1px solid #a190df' }}>自我介绍</div> { data.character ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">性格</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.character}</span> </div> : null } { data.habits ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">生活习惯</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}> {data.habits}</span> </div> : null } { data.hobby ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">兴趣爱好</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}> {data.hobby}</span> </div> : null } { data.other ? <div className="form-group"> <label style={{ width: '80px', verticalAlign: 'top' }} for="birth">其它</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.other}</span> </div> : null } <label style={{ width: '80px' }} for="he_degree">生活照</label> <div style={{ color: '#aa9999', fontSize: '8' }}>点击查看大图</div> <WingBlank> <ImagePicker files={data.photos} onChange={this.onChange} onImageClick={this.onImageClick} selectable={files.length < 7} multiple={this.state.multiple} accept="image/*" disableDelete={true} selectable={false} style={{ marginLeft: '-15px' }} /> </WingBlank> <div style={{ height: '30px', lineHeight: '30px', fontSize: '20px', textAlign: 'center', margin: '0 80px 10px', borderBottom: '1px solid #a190df' }}>理想对象</div> { data.he_agerange ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">年龄范围</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}> {data.he_agerange}</span> </div> : null } { data.he_appearance ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">外貌要求</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.he_appearance}</span> </div> : null } { data.he_character ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">性格要求</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.he_character}</span> </div> : null } { data.he_degree ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">学历要求</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.he_degree}</span> </div> : null } { data.he_coordinate ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">他(她)坐标</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.he_coordinate}</span> </div> : null } { data.he_other ? <div className="form-group"> <label style={{ width: '80px' }} for="birth">其它</label> <span style={{ display: 'inline-block', maxWidth: '200px' }}>{data.he_other}</span> </div> : null } <button onClick={() => this.getWebchat(data._id)} className="btn btn-default" style={{ display: 'block', margin: '0 auto' }}>进一步了解</button> </form > </div > ) } }
JavaScript
class App extends Component { componentWillMount() { this.props.loadUserFromToken(); } render() { return ( <div className="container"> {this.props.children} </div> ); } }
JavaScript
class SourceChain { constructor(sources = []) { this.sources = sources; } }
JavaScript
class Ratelimiter { constructor() { this.buckets = {}; this.global = false; this.globalResetAt = 0; // eslint-disable-next-line @typescript-eslint/no-this-alias const limiter = this; this._timeoutFN = function () { for (const routeKey of Object.keys(limiter.buckets)) { const bkt = limiter.buckets[routeKey]; if (bkt.resetAt && bkt.resetAt < Date.now()) { if (bkt.fnQueue.length) bkt.resetRemaining(); else delete limiter.buckets[routeKey]; } else if (!bkt.resetAt && limiter.global && limiter.globalResetAt < Date.now()) { if (bkt.fnQueue.length) bkt.checkQueue(); else delete limiter.buckets[routeKey]; } } }; this._timeoutDuration = 1000; this._timeout = setInterval(() => { limiter._timeoutFN(); }, limiter._timeoutDuration); } /** * Returns a key for saving ratelimits for routes * (Taken from https://github.com/abalabahaha/eris/blob/master/lib/rest/RequestHandler.js) -> I luv u abal <3 * @param url url to reduce to a key something like /channels/266277541646434305/messages/266277541646434305/ * @param method method of the request, usual http methods like get, etc. * @returns reduced url: /channels/266277541646434305/messages/:id/ */ routify(url, method) { let route = url.replace(/\/([a-z-]+)\/(?:\d+)/g, function (match, p) { return p === "channels" || p === "guilds" || p === "webhooks" ? match : `/${p}/:id`; }).replace(/\/reactions\/[^/]+/g, "/reactions/:id").replace(/^\/webhooks\/(\d+)\/[A-Za-z0-9-_]{64,}/, "/webhooks/$1/:token"); if (method.toUpperCase() === "DELETE" && route.endsWith("/messages/:id")) { // Delete Messsage endpoint has its own ratelimit route = method + route; } return route; } /** * Queue a rest call to be executed * @param fn function to call once the ratelimit is ready * @param url Endpoint of the request * @param method Http method used by the request */ queue(fn, url, method) { const routeKey = this.routify(url, method); if (!this.buckets[routeKey]) { this.buckets[routeKey] = new LocalBucket_1.default(this); } this.buckets[routeKey].queue(fn); } }
JavaScript
class BPRow extends React.Component { onDelete = () => this.props.onDelete(this.props.bpData._id); onEdit = () => this.props.onEdit(this.props.bpData._id); render(){ return ( <tr> <td>{this.props.bpData.datetime}</td> <td>{this.props.bpData.sys}</td> <td>{this.props.bpData.dia}</td> <td>{this.props.bpData.pulse}</td> <td>{this.props.bpData.notes}</td> <td> <button onClick={this.onEdit} style={btnStyle} className="btn btn-sm"> Edit </button> &nbsp;/&nbsp; <button onClick={this.onDelete} style={btnStyle} className="btn btn-sm"> Delete </button> </td> </tr> ); } }
JavaScript
class StatusModal extends React.Component { constructor(props) { super(props); this.title = props.title === null || props.title === undefined ? "" : props.title; this.text = props.text === null || props.text === undefined ? "" : props.text; this.onClose = props.onClose === null || props.onClose === undefined ? () => true : props.onClose; } render() { let type = getUserTypeExplicit(); return ( <div id="statusModalBlackout" className="fillContainer flex verticalCentre" > <div id="statusModalSubBlackout" className="flex horizontalCentre"> <div id="statusModalWindow" className={`${type}InnerButton`}> <h1>{this.title}</h1> <p>{this.text}</p> <button onClick={e => this.onClose()}>OK</button> </div> </div> </div> ); } }
JavaScript
class View { //pass in top groups and user -- with username, id, notifications constructor(thread, user, actions, socket, data) { //set thread this.thread = thread; //unpack actions onto our class this.removePost = actions.removePost; this.editPost = actions.editPost; this.handleSubmit = actions.handleSubmit; this.handleUpload = actions.handleUpload; //set auth this.user = user; this.popular = data.popular; //setup commands for view actions this.viewCommands = { goBack: e => this._goBack(e), toggleNM: e => this._toggleNM(e), toggleDM: e => this._toggleDM(e), openDirectly: e => this._openDirectly(e), toggleListSize: e => this._toggleListSize(e) }; //save a ref to app-container (so if we need to switch nightmode we can) this.$container = $id('app-container'); this.$main = $id('Main'); //bring in list to render this.listing = new Listing(true, this.thread.posts, this.thread.group, this.user); this.writer = new Writer(true, this.user.user.usernames, this.group); //lets us render posts added post initial-render properly this.authors = {}; //bind socket socket.connection.onmessage = event => { let message = JSON.parse(event.data).body; this.listing.addPost(message); } } //binds events --> mostly delegated events up in here bind() { //get references (as elements are dynamically rendered) let $prev = $id('prevpage'); let $popular = $id('Poplisting'); let $previouspg = $id('previous-pg'); let $nightmode = $id('nightmode'); let $devmode = $id('devmode'); let $listsizetoggle = $id('List-size-switch'); //bind handlers $on($popular, 'click', this.listing.handlePostClick.bind(this.listing), false); $on($prev, 'click', this.viewCommands.goBack.bind(this), false); $on($nightmode, 'click', this.viewCommands.toggleNM.bind(this), false); $on($devmode, 'click', this.viewCommands.toggleDM.bind(this), false); $on($previouspg, 'click', this.viewCommands.goBack.bind(this), false); $on($listsizetoggle, 'change', this._toggleListSize.bind(this), false); //bind listing & writer this.listing.bind(); this.writer.bind(); } _toggleListSize(e) { $id('Main-container').classList.toggle('threadenlarge'); e.stopPropagation(); } _goBack(e) { router.back(); } _toggleNM(e) { this.$container.classList.toggle('nightmode'); e.target.classList.toggle('Tools-selected'); } _toggleDM(e) { this.$container.classList.toggle('devmode'); e.target.classList.toggle('Tools-selected'); let termMount = $id('term'); //if there's no terminal mounted, mount it. if (!termMount.firstChild) { term.open($id('term')); handler(term); } if (this.$container.classList.contains('devmode')) { term.fit(); } } _toggleInputSize(e) { e.target.parentNode.classList.toggle('Writer-fs'); e.target.parentNode.classList.contains('Writer-fs') ? e.target.textContent = '–' : e.target.textContent = '+'; $id('writer-input').focus(); } _prevPage(e) { if (page <= 1) router.navigate(this.group); router.navigate(`${this.group}${--page}`); } _nextPage(e) { router.navigate(`${this.group}${++page}`); } //generate html generateStaticView(thread) { const getpopularposts = async () => { let promises = this.popular.map(post => generatePopularPost(post, this.user)); let results = await Promise.all(promises); return results.join(''); }; const buildView = async () => { //wrapper for listing const list = await this.listing.generateStaticView(); //generate writer const writer = this.writer.generateStaticView(); //pagination controls const footer = ` <div class="Main-Footer"> <a class="Main-Footer-btn mobile" id="prevpage" href="javascript:;">back</a> </div> `; //desktop view information --> popular posts and stuff like that const popularInfo = ` <div id="Poplisting" class="desktop"> <div class="PopularList"> <span id="Poplisting-title"> Popular Today </span> <span id="Poplisting-title-label">replies</span> ${await getpopularposts()} </div> <div class="Mixroom-info" > <span><a href="static/placeholder.html">Terms</a></span> <span><a href="static/placeholder.html">Privacy</a></span> <span><a href="static/placeholder.html">Advertise</a></span> </div> </div> `; const tools = generateTools(true, this.$container.classList.contains('nightmode'), this.$container.classList.contains('devmode')); //user object const user = this.user.user; const listingHeader = ` <div id="Main-listing-header" class="desktop unselectable"> <div class="Main-listing-group unselectable">Thread Posts <label id="List-size-switch" class="rb-switcher"> <input type="checkbox"> <i></i> </label></div> </div> `; //final template for section return ` <div id="Main-container"> ${listingHeader} ${popularInfo} ${writer} ${tools} ${list} ${footer} </div> `; }; return buildView(); } //bake html into view render() { let that = this; let tmp = this.generateStaticView(this.thread); tmp.then(tmp => { $id('main').innerHTML = tmp; that.bind(); }); } }
JavaScript
class CustomTestKeystore { constructor (storage) { // Use just one key throughout the keystore // for mock purposes this.key = this.createKey() } hasKey () { return this.key !== undefined ? true : false } createKey (id) { const key = ec.genKeyPair() const keyPair = { public: { marshal: () => key.getPublic('hex') }, priv: key.getPrivate('hex'), privEnc: 'hex', pubEnc: 'hex', } return keyPair } getKey (id) { return this.key } sign (key, data) { return Promise.resolve('<signature>') } verify (signature, publicKey, data) { return Promise.resolve(true) } getPublic (key) { return key.public.marshal() } }
JavaScript
class IndeterminateProgressBar extends _react.default.Component { render() { return _react.default.createElement( "div", { className: "text-center padded" }, _react.default.createElement("span", { className: "loading loading-spinner-medium inline-block" }) ); } }
JavaScript
class FBAuth { /** Sets up the basic connection details to firebase and state change * events * @param {Function} signInCallback - the callback when sign in occurs - * returns user id, photoURL, name & email * @param {Function} signOutCallBack - the callback when sign out occurs * @param {Function} childAddedCallback - the callback when new data is added - * returns all data * @param {Function} childChangedCallback - the callback when data is changed - * returns all data */ constructor(signInCallback, signOutCallBack, childAddedCallback, childChangedCallback) { let fbAuth = this; let config = { apiKey: 'AIzaSyCQmNa81aSqSBHExjDXKWkx2uDoAMPexOw', authDomain: 'open-sesame-f1f51.firebaseapp.com', databaseURL: 'https://open-sesame-f1f51.firebaseio.com', }; // Connect to firebase firebase.initializeApp(config); // Set user variables to null initially fbAuth.uid = null; fbAuth.photoURL = null; fbAuth.name = null; fbAuth.email = null; // Set-up callbacks if supplied fbAuth.signInCallback = signInCallback || null; fbAuth.signOutCallback = signOutCallBack || null; fbAuth.childAddedCallback = childAddedCallback || null; fbAuth.childChangedCallback = childChangedCallback || null; // On auth state change, record the userId firebase.auth().onAuthStateChanged(function(user) { // console.log('Firebase auth state change'); // console.log(user); if (user) { fbAuth.uid = user.uid; fbAuth.photoURL = user.photoURL || null; fbAuth.name = user.displayName; fbAuth.email = user.email; let userRef = firebase.database().ref('users/' + user.uid); // Once authenticated, register the correct callbacks if supplied if (fbAuth.childAddedCallback) { userRef.on('child_added', function(data) { fbAuth.childAddedCallback(data.val()); }); } if (fbAuth.childChangedCallback) { userRef.on('child_changed', function(data) { fbAuth.childChangedCallback(data.val()); }); } // If supplied, call the sign in callback if (fbAuth.signInCallback) { fbAuth.signInCallback({ userId: fbAuth.uid, photoURL: fbAuth.photoURL, name: fbAuth.name, email: fbAuth.email, }); } } else { fbAuth.uid = null; fbAuth.photoURL = null; fbAuth.name = null; fbAuth.email = null; // If supplied, call the sign out callback if (fbAuth.signOutCallback) { fbAuth.signOutCallback(); } } }); } /** Authenticates the user if not already authenticated * @return {Promise} - a promise with the result of calling sign in */ logIn() { if (!firebase.auth().currentUser) { // Already signed in // Sign in using google let provider = new firebase.auth.GoogleAuthProvider(); return firebase.auth().signInWithRedirect(provider); } } /** Authenticates the user if not already authenticated using supplied token * @param {Object} token - the auth token to use * @return {Promise} - a promise with the result of calling sign in */ logInWithToken(token) { if (!firebase.auth().currentUser) { let credential = firebase.auth.GoogleAuthProvider.credential(null, token); return firebase.auth().signInWithCredential(credential); } } /** Check result of redirect logIn * @return {Promise} result of whether user is authenticated */ isAuthenticated() { return new Promise(function(resolve, reject) { firebase.auth().getRedirectResult().then(function(result) { resolve(true); }).catch(function(error) { reject(error); }); }); } /** Returns current user's Id or null if not authenticated * * @return {String} - the userId or null if not authenticated */ getUserId() { let fbAuth = this; if (fbAuth.uid) { return fbAuth.uid; } else { return null; } } /** Returns current user's photo or null if not authenticated / no photo * * @return {String} - the URL for the user's photo */ getUserPhotoURL() { let fbAuth = this; if (fbAuth.uid && fbAuth.photoURL) { return fbAuth.photoURL; } else { return null; } } /** Logs user out */ logOut() { if (firebase.auth().currentUser) { firebase.auth().signOut(); } } }
JavaScript
class Application { constructor(opts = {}) { this.width = Math.min(window.innerWidth, 400); this.height = Math.min(window.innerHeight, 600); if (opts.container) { this.container = opts.container; } else { const div = Application.createContainer(); document.body.appendChild(div); this.container = div; } if (Detector.webgl) { this.firstTimeInit(); this.resetGame(); this.render(); } else { // TODO: style warning message console.log("WebGL NOT supported in your browser!"); const warning = Detector.getWebGLErrorMessage(); this.container.appendChild(warning); } } firstTimeInit() { this.autoplay = true; this.ignoreFailure = false; this.runSpeed = INITIAL_SPEED; this.scene = new THREE.Scene(); this.scene.background = new THREE.Color(0x87ceeb); this.setupRenderer(); this.setupCamera(); this.setupHelpers(); // this.setupControls(); this.setupGUI(); this.cursorX = 0; document.onmousemove = e => { e.preventDefault(); this.cursorX = e.pageX; return false; }; document.addEventListener("touchstart", e => this.onTouch(e)); document.addEventListener("touchmove", e => this.onTouch(e)); document.addEventListener("touchend", e => this.onTouchEnd(e)); } onTouch(event) { event.preventDefault(); this.cursorX = event.changedTouches[0].clientX; return false; } onTouchEnd(event) { event.preventDefault(); this.cursorX = null; return false; } resetGame() { this.pause = false; this.runSpeed = INITIAL_SPEED; this.clock = new THREE.Clock(); // Remove any existing objects from the scene this.clearScene(); this.setupLights(); this.floor = new Floor(this.clock); this.scene.add(this.floor); this.frog = new Frog(this.clock); this.scene.add(this.frog); this.turtles = this.setUpTurtles(); this.turtles.forEach(t => this.scene.add(t)); } clearScene() { while (this.scene.children.length) { this.scene.remove(this.scene.children[0]); } } setUpTurtles() { const turtles = []; const NUM_TURTLES = 15; const OFFSET_PER_TURTLE = 25; for (let i = 0; i < NUM_TURTLES; i++) { turtles.push( new Turtle( i, OFFSET_PER_TURTLE, (NUM_TURTLES - 1) * OFFSET_PER_TURTLE, this.clock ) ); } return turtles; } render() { if (this.controls) { this.controls.update(); } if (!this.pause) { this.updateGameState(); } this.renderer.render(this.scene, this.camera); // when render is invoked via requestAnimationFrame(this.render) there is // no 'this', so either we bind it explicitly or use an es6 arrow function. // requestAnimationFrame(this.render.bind(this)); requestAnimationFrame(() => this.render()); } updateGameState() { const delta = this.clock.getDelta(); this.runSpeed += SPEED_INCREMENT * delta; this.floor.update(this.runSpeed, delta); this.turtles.forEach(t => t.update(this.runSpeed, delta)); try { this.frog.update( this.cursorX, this.width, this.runSpeed, delta, this.turtles, this.autoplay ); } catch (e) { if (!this.ignoreFailure) { this.pause = true; console.error(e); alert("game over click restart in the top right to reset"); } } } static createContainer() { const div = document.createElement("div"); div.setAttribute("id", "canvas-container"); div.setAttribute("class", "container"); // div.setAttribute('width', window.innerWidth); // div.setAttribute('height', window.innerHeight); return div; } setupRenderer() { this.renderer = new MainRenderer(this.width, this.height); this.container.appendChild(this.renderer.domElement); } setupCamera() { this.camera = new MainCamera(this.width, this.height); this.camera.lookAt(this.scene.position); } setupLights() { // // directional light // this.dirLight = new THREE.DirectionalLight(0x4682b4, 1); // steelblue // this.dirLight.position.set(120, 30, -200); // this.dirLight.castShadow = true; // this.dirLight.shadow.camera.near = 10; // this.scene.add(this.dirLight); // // spotlight // this.spotLight = new THREE.SpotLight(0xffaa55); // this.spotLight.position.set(120, 30, 0); // this.spotLight.castShadow = true; // this.dirLight.shadow.camera.near = 10; // this.scene.add(this.spotLight); // Ambient Light const ambientLight = new THREE.AmbientLight(0xffaa55); this.scene.add(ambientLight); } setupHelpers() { // floor grid helper // const gridHelper = new THREE.GridHelper(200, 16); // this.scene.add(gridHelper); // // XYZ axes helper (XYZ axes are RGB colors, respectively) // const axisHelper = new THREE.AxisHelper(75); // this.scene.add(axisHelper); // // directional light helper + shadow camera helper // const dirLightHelper = new THREE.DirectionalLightHelper(this.dirLight, 10); // this.scene.add(dirLightHelper); // const dirLightCameraHelper = new THREE.CameraHelper( // this.dirLight.shadow.camera // ); // this.scene.add(dirLightCameraHelper); // // spot light helper + shadow camera helper // const spotLightHelper = new THREE.SpotLightHelper(this.spotLight); // this.scene.add(spotLightHelper); // const spotLightCameraHelper = new THREE.CameraHelper( // this.spotLight.shadow.camera // ); // this.scene.add(spotLightCameraHelper); } setupControls() { this.controls = new OrbitControls(this.camera, this.renderer.domElement); this.controls.enabled = true; this.controls.maxDistance = 1500; this.controls.minDistance = 0; this.controls.autoRotate = false; } setupGUI() { const gui = new DAT.GUI(); // gui // .add(this.camera.position, "x") // .name("Camera X") // .min(0) // .max(100); // gui // .add(this.camera.position, "y") // .name("Camera Y") // .min(0) // .max(100); // gui // .add(this.camera.position, "z") // .name("Camera Z") // .min(0) // .max(100); gui .add(this, "runSpeed") .name("Speed") .min(0) .max(100) .listen(); gui.add(this, "autoplay").name("Autoplay"); gui.add(this, "ignoreFailure").name("Don't Die"); gui.add(this, "resetGame").name("Restart"); gui.add(this, "setupControls").name("Add Orbital Controlls"); } setupCustomObject() { this.customMesh = new TestCustomObject(); this.scene.add(this.customMesh); } updateCustomObject() { this.customMesh.update(); } }
JavaScript
class Button extends BaseButton { /** * @constructor * @param {string} upFrame - Frame when button do nothing. * @param {?string} [downFrame = null] - Frame when button activated. * @param {?string} [overFrame = null] - Frame when button hover. * @param {?string} [disabledFrame = null] - Frame when button disabled. */ constructor(upFrame, downFrame = null, overFrame = null, disabledFrame = null) { super(upFrame, INTERACTIVE_STATE.UP); this.collider.addState(downFrame, INTERACTIVE_STATE.DOWN); if (Boot.isDesktop()) { this.collider.addState(overFrame, INTERACTIVE_STATE.OVER); } this.collider.addState(disabledFrame, INTERACTIVE_STATE.DISABLED); this.uiType = UI_ELEMENT.BUTTON; /** * @desc Flag is button currently over. * @type {boolean} * @private */ this._isOver = false; } /** * PUBLIC METHODS * ----------------------------------------------------------------------------------------------------------------- */ /** * @desc Calls by pool when object get from pool. Don't call it only override. * @method * @public * @param {string} upFrame - Frame when button do nothing. * @param {?string} [downFrame = null] - Frame when button activated. * @param {?string} [overFrame = null] - Frame when button hover. * @param {?string} [disabledFrame = null] - Frame when button disabled. */ reuse(upFrame, downFrame = null, overFrame = null, disabledFrame = null) { super.reuse(upFrame, INTERACTIVE_STATE.UP); this.collider.addState(downFrame, INTERACTIVE_STATE.DOWN); if (Boot.isDesktop()) { this.collider.addState(overFrame, INTERACTIVE_STATE.OVER); } this.collider.addState(disabledFrame, INTERACTIVE_STATE.DISABLED); } /** * @desc Calls when interactive manager emit event. * @method * @public * @param {MANTICORE.enumerator.ui.INTERACTIVE_EVENT} eventType * @param {Object} event */ emitInteractiveEvent(eventType, event) { super.emitInteractiveEvent(eventType, event); switch (eventType) { case INTERACTIVE_EVENT.UP: { if (this._isOver) { this.changeStateWithFallback(INTERACTIVE_STATE.OVER, INTERACTIVE_STATE.UP); } else { this.changeEnabledState(INTERACTIVE_STATE.UP); } break; } case INTERACTIVE_EVENT.DOWN: { this.changeEnabledState(INTERACTIVE_STATE.DOWN); break; } case INTERACTIVE_EVENT.OVER: { this._isOver = true; this.changeEnabledState(INTERACTIVE_STATE.OVER); break; } case INTERACTIVE_EVENT.OUT: { this._isOver = false; this.changeEnabledState(INTERACTIVE_STATE.UP); break; } } } /** * PROTECTED METHODS * ----------------------------------------------------------------------------------------------------------------- */ /** * @desc Calls when button change enable. * @method * @protected * @param {boolean} enabled */ onEnabledChange(enabled) { this.changeState(enabled ? INTERACTIVE_STATE.UP : INTERACTIVE_STATE.DISABLED); } /** * PROPERTIES * ----------------------------------------------------------------------------------------------------------------- */ /** * @public * @type {string | null} */ get upFrame() { return this.collider.getFrameByState(INTERACTIVE_STATE.UP); } set upFrame(value) { this.collider.setFrameByState(value, INTERACTIVE_STATE.UP); } /** * @public * @type {string | null} */ get downFrame() { return this.collider.getFrameByState(INTERACTIVE_STATE.DOWN); } set downFrame(value) { this.collider.setFrameByState(value, INTERACTIVE_STATE.DOWN); } /** * @public * @type {string | null} */ get overFrame() { return this.collider.getFrameByState(INTERACTIVE_STATE.OVER); } set overFrame(value) { this.collider.setFrameByState(value, INTERACTIVE_STATE.OVER); } /** * @public * @type {string | null} */ get disabledFrame() { return this.collider.getFrameByState(INTERACTIVE_STATE.DISABLED); } set disabledFrame(value) { this.collider.setFrameByState(value, INTERACTIVE_STATE.DISABLED); } }
JavaScript
class FontObserverProvider extends React.Component { static displayName = "FontObserver.Provider"; static propTypes = { /** * The fonts to load and observe. The font files themselves should already * be specified somewhere (in CSS), this component simply uses `FontFaceObserver` * to force them to load (if necessary) and observe when they are ready. * * Each item in the array specifies the font `family`, `weight`, `style`, * and `stretch`, with only `family` being required. Additionally, each item * can contain a custom `testString` and `timeout` for that font, if they * should differ from the defaults. If only the family name is needed, the * array item can just be a string. */ fonts: PropTypes.arrayOf( PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ /** * The font family name. */ family: PropTypes.string.isRequired, /** * The named or numeric font weight. */ weight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The font style value. */ style: PropTypes.string, /** * The font stretch value. */ stretch: PropTypes.string, /** * A custom test string to pass to `FontFaceObserver` for this font. */ testString: PropTypes.string, /** * A custom timeout to pass to `FontFaceObserver` for this font. */ timeout: PropTypes.number }) ]) ).isRequired, /** * A custom test string to pass to the `load` method of `FontFaceObserver`, * to be used for all fonts that do not specify their own `testString`. */ testString: PropTypes.string, /** * A custom timeout in milliseconds to pass to the `load` method of * `FontFaceObserver`, to be used for all fonts that do not specify their * own `timeout`. */ timeout: PropTypes.number, /** * The content that will have access to font loading status via context. */ children: PropTypes.node }; mounted = false; fontDescriptors = this.props.fonts.map(font => { if (typeof font === "string") { font = { family: font }; } return { font, observer: null, promise: null }; }); state = { fonts: this.fontDescriptors.map(descriptor => { return { ...descriptor.font, loaded: false, error: null }; }), loaded: false, error: null }; handleLoad(font, i) { if (this.mounted) { debug( "Loaded font “%s” (#%s of %s)", font.family, i + 1, this.fontDescriptors.length ); this.setState(state => { const fonts = state.fonts.slice(); fonts[i] = { ...fonts[i], loaded: true }; return { fonts, loaded: fonts.length === 1 || fonts.every(font => font.loaded) }; }); } } handleError(font, i, err) { if (this.mounted) { debug( "Error loading font “%s” (#%s of %s)", font.family, i + 1, this.fontDescriptors.length ); this.setState(state => { const fonts = state.fonts.slice(); const error = err || new Error("Font failed to load"); fonts[i] = { ...fonts[i], error }; return { fonts, error: state.error || error }; }); } } componentDidMount() { this.mounted = true; const { testString: defaultTestString, timeout: defaultTimeout } = this.props; this.fontDescriptors.forEach((descriptor, i) => { const { family, testString = defaultTestString, timeout = defaultTimeout, ...variation } = descriptor.font; debug( "Creating FontFaceObserver for “%s” (#%s of %s)", family, i + 1, this.fontDescriptors.length ); const observer = new FontFaceObserver(family, variation); const promise = observer.load(testString, timeout); promise.then( this.handleLoad.bind(this, descriptor.font, i), this.handleError.bind(this, descriptor.font, i) ); descriptor.observer = observer; descriptor.promise = promise; }); } componentWillUnmount() { this.mounted = false; this.fontDescriptors = undefined; } render() { const { children } = this.props; return <Context.Provider value={this.state}>{children}</Context.Provider>; } }
JavaScript
class GalleryDND extends Component { componentDidMount() { // workaround for dropzone using `e.stopPropagation()` when a file is dropped to be uploaded window.addEventListener('drop', this.handleDrop, true); } componentWillUnmount() { window.removeEventListener('drop', this.handleDrop, true); } handleDrop() { const backend = capturedManager && capturedManager.backend; if (backend && backend.isDraggingNativeItem()) { backend.endDragNativeItem(); } } render() { const { className, children, } = this.props; return ( <div className={className}> {children} <GalleryItemDragLayer /> </div> ); } }
JavaScript
class Intern extends Employee { constructor(name, id ,email, school){ // passes name id email to the parent class super(name,id,email) this.school = school; } // method returns scchool getSchool(){ return this.school } // method overrides parent and returns the role getRole(){ return 'Intern' } }
JavaScript
class ProvideBlur extends PureComponent { static propTypes = { onBlur: PropTypes.func, onFocus: PropTypes.func } static defaultProps = { onBlur: () => {}, onFocus: () => {} } state = { isFocused: false } componentDidMount() { this.el = findDOMNode(this); this.el.addEventListener('focusin', this.handleFocusIn); this.el.addEventListener('focusout', this.handleFocusOut); } componentDidUpdate(prevProps, prevState) { const prevFocused = prevState.isFocused; const { isFocused } = this.state; if (isFocused && prevFocused !== isFocused) { this.props.onFocus() } if (!isFocused && prevFocused !== isFocused) { this.props.onBlur() } } componentWillUnmount() { this.el.removeEventListener('focusin', this.handleFocusIn) this.el.removeEventListener('focusout', this.handleFocusOut) } handleFocusIn = event => { // IE11 & firefox trigger focusout when you click on PlainMarkdownInput. // In order to eliminate it we can stop listening for focusout when focusin occurs. this.el.removeEventListener('focusout', this.handleFocusOut); setTimeout(_ => this.el && this.el.addEventListener('focusout', this.handleFocusOut)); return this.setState(prevState => prevState.isFocused ? {} : { isFocused: true }) }; timeout = null; abortFocusOut = _ => { clearTimeout(this.timeout); } handleFocusOut = event => { this.el.addEventListener('focusin', this.abortFocusOut); this.timeout = setTimeout(_ => { if (this.el) { this.el.removeEventListener('focusin', this.abortFocusOut); } this.setState({ isFocused: false }); }); } render() { const { children } = this.props; return children instanceof Function ? children() : children; } }
JavaScript
class UserSession { constructor(fields) { this.id = fields.id; this.UserSession_artifact_id = fields.UserSession_artifact_id; this.UserSession_User_id = fields.UserSession_User_id; this.UserSession_Start = fields.UserSession_Start; this.UserSession_Expired = fields.UserSession_Expired; this.UserSession_IsAnonymous = fields.UserSession_IsAnonymous; this.UserSession_created_by = fields.UserSession_created_by; this.UserSession_created_on = fields.UserSession_created_on; this.UserSession_modified_on = fields.UserSession_modified_on; this.UserSession_modified_by = fields.UserSession_modified_by; }}
JavaScript
class IssueView extends UI.Widget { constructor(parent, issue) { super(false); this._parent = parent; this._issue = issue; this._details = issueDetails[issue.code]; this.contentElement.classList.add('issue'); this.contentElement.classList.add('collapsed'); this.appendHeader(); this.appendBody(); } appendHeader() { const header = createElementWithClass('div', 'header'); header.addEventListener('click', this._handleSelect.bind(this)); const icon = UI.Icon.create('largeicon-breaking-change', 'icon'); header.appendChild(icon); const title = createElementWithClass('div', 'title'); title.innerText = this._details.title; header.appendChild(title); const priority = createElementWithClass('div', 'priority'); switch (this._details.priority) { case Priority.High: priority.innerText = ls`High Priority`; break; default: console.warn('Unknown issue priority', this._details.priority); } header.appendChild(priority); this.contentElement.appendChild(header); } appendBody() { const body = createElementWithClass('div', 'body'); const message = createElementWithClass('div', 'message'); message.innerText = this._details.message; body.appendChild(message); const code = createElementWithClass('div', 'code'); code.innerText = this._issue.code; body.appendChild(code); const link = UI.XLink.create(this._details.link, 'Read more · ' + this._details.linkTitle, 'link'); body.appendChild(link); const linkIcon = UI.Icon.create('largeicon-link', 'link-icon'); link.prepend(linkIcon); const bodyWrapper = createElementWithClass('div', 'body-wrapper'); bodyWrapper.appendChild(body); this.contentElement.appendChild(bodyWrapper); } _handleSelect() { this._parent.handleSelect(this); } toggle() { this.contentElement.classList.toggle('collapsed'); } }
JavaScript
class MonetaryCurrency { /** * Constructs a new <code>MonetaryCurrency</code>. * @alias module:model/MonetaryCurrency */ constructor() { MonetaryCurrency.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>MonetaryCurrency</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/MonetaryCurrency} obj Optional instance to populate. * @return {module:model/MonetaryCurrency} The populated <code>MonetaryCurrency</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new MonetaryCurrency(); if (data.hasOwnProperty('code')) { obj['code'] = ApiClient.convertToType(data['code'], 'String'); } if (data.hasOwnProperty('digitsAfterDecimal')) { obj['digitsAfterDecimal'] = ApiClient.convertToType(data['digitsAfterDecimal'], 'Number'); } if (data.hasOwnProperty('currencyInMultiplesOf')) { obj['currencyInMultiplesOf'] = ApiClient.convertToType(data['currencyInMultiplesOf'], 'Number'); } } return obj; } }
JavaScript
class Drag { constructor ( element ) { this.element = element; this.dragger = this.element.find( ".js-drag-node" ); this.options = { bounds: this.element[ 0 ], cursor: "grab", dragClickables: true, dragResistance: 0.25, edgeResistance: 0.6, lockAxis: true, throwProps: true, type: "x", onDragStart: this.onDragStart.bind( this ), onDragEnd: this.onDragEnd.bind( this ), zIndexBoost: false }; this.bind(); this.load(); } bind () { this.resizer = new ResizeController(); this.resizer.on( "resize", () => { this.draggable.applyBounds( this.element[ 0 ] ); }); } load () { this.draggable = new window.Draggable( this.dragger, this.options ); } onDragStart () { this.element.addClass( "is-drag-start" ); } onDragEnd () { this.element.removeClass( "is-drag-start" ); } destroy () { if ( this.draggable ) { this.draggable.kill(); } if ( this.resizer ) { this.resizer.off( "resize" ); this.resizer.destroy(); } } }
JavaScript
class DragController { constructor ( elements ) { this.elements = elements; this.instances = []; this.init(); } init () { this.elements.forEach(( element, i ) => { this.instances.push( new Drag( this.elements.eq( i ) ) ); }); } destroy () { this.instances.forEach(( instance ) => { instance.destroy(); }); } }
JavaScript
class Artistc extends Component { constructor(props) { super(props); this.state = {artists: this.props.artists}; } render = () => { const subPath = base === prodUrl ? subUrl : ''; return ( <div className="Artists"> <div className="row ArtistMap"> {this.props.artists.map(( element, index /** here i map the artist and send the props the name and the display name */ ) => ( <ArtistCards displayName={element.displayName} image={`${subPath}${element.images[0]}`} key={index} handleSelect={this.props.handleSelect} handleRelated={this.props.handleRelated} id={element.id} /> ))} </div> </div> ); }; }
JavaScript
class Web3Shim extends web3_1.default { constructor(options) { super(); if (options) { this.networkType = options.networkType || "ethereum"; if (options.provider) { this.setProvider(options.provider); } } else { this.networkType = "ethereum"; } this.initInterface(); } setNetworkType(networkType) { this.networkType = networkType; this.initInterface(); } initInterface() { switch (this.networkType) { case "quorum": { this.initQuorum(); break; } case "ethereum": default: { this.initEthereum(); break; } } } initEthereum() { // truffle has started expecting gas used/limit to be // hex strings to support bignumbers for other ledgers ethereumOverloads.getBlock(this); ethereumOverloads.getTransaction(this); ethereumOverloads.getTransactionReceipt(this); } initQuorum() { // duck punch some of web3's output formatters quorumOverloads.getBlock(this); quorumOverloads.getTransaction(this); quorumOverloads.getTransactionReceipt(this); } }
JavaScript
class Method { constructor(actorId, name, duration) { this.actorId = actorId; this.name = name; this.duration = duration / 1000000.0; } }
JavaScript
class UnderexcitationLimiterDynamics extends StandardModels.DynamicsFunctionBlock { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UnderexcitationLimiterDynamics; if (null == bucket) cim_data.UnderexcitationLimiterDynamics = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UnderexcitationLimiterDynamics[obj.id]; } parse (context, sub) { let obj = StandardModels.DynamicsFunctionBlock.prototype.parse.call (this, context, sub); obj.cls = "UnderexcitationLimiterDynamics"; base.parse_attribute (/<cim:UnderexcitationLimiterDynamics.RemoteInputSignal\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "RemoteInputSignal", sub, context); base.parse_attribute (/<cim:UnderexcitationLimiterDynamics.ExcitationSystemDynamics\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ExcitationSystemDynamics", sub, context); let bucket = context.parsed.UnderexcitationLimiterDynamics; if (null == bucket) context.parsed.UnderexcitationLimiterDynamics = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = StandardModels.DynamicsFunctionBlock.prototype.export.call (this, obj, false); base.export_attribute (obj, "UnderexcitationLimiterDynamics", "RemoteInputSignal", "RemoteInputSignal", fields); base.export_attribute (obj, "UnderexcitationLimiterDynamics", "ExcitationSystemDynamics", "ExcitationSystemDynamics", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UnderexcitationLimiterDynamics_collapse" aria-expanded="true" aria-controls="UnderexcitationLimiterDynamics_collapse" style="margin-left: 10px;">UnderexcitationLimiterDynamics</a></legend> <div id="UnderexcitationLimiterDynamics_collapse" class="collapse in show" style="margin-left: 10px;"> ` + StandardModels.DynamicsFunctionBlock.prototype.template.call (this) + ` {{#RemoteInputSignal}}<div><b>RemoteInputSignal</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{RemoteInputSignal}}");}); return false;'>{{RemoteInputSignal}}</a></div>{{/RemoteInputSignal}} {{#ExcitationSystemDynamics}}<div><b>ExcitationSystemDynamics</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ExcitationSystemDynamics}}");}); return false;'>{{ExcitationSystemDynamics}}</a></div>{{/ExcitationSystemDynamics}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UnderexcitationLimiterDynamics_collapse" aria-expanded="true" aria-controls="{{id}}_UnderexcitationLimiterDynamics_collapse" style="margin-left: 10px;">UnderexcitationLimiterDynamics</a></legend> <div id="{{id}}_UnderexcitationLimiterDynamics_collapse" class="collapse in show" style="margin-left: 10px;"> ` + StandardModels.DynamicsFunctionBlock.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_RemoteInputSignal'>RemoteInputSignal: </label><div class='col-sm-8'><input id='{{id}}_RemoteInputSignal' class='form-control' type='text'{{#RemoteInputSignal}} value='{{RemoteInputSignal}}'{{/RemoteInputSignal}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ExcitationSystemDynamics'>ExcitationSystemDynamics: </label><div class='col-sm-8'><input id='{{id}}_ExcitationSystemDynamics' class='form-control' type='text'{{#ExcitationSystemDynamics}} value='{{ExcitationSystemDynamics}}'{{/ExcitationSystemDynamics}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UnderexcitationLimiterDynamics" }; super.submit (id, obj); temp = document.getElementById (id + "_RemoteInputSignal").value; if ("" !== temp) obj["RemoteInputSignal"] = temp; temp = document.getElementById (id + "_ExcitationSystemDynamics").value; if ("" !== temp) obj["ExcitationSystemDynamics"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["RemoteInputSignal", "0..1", "0..1", "RemoteInputSignal", "UnderexcitationLimiterDynamics"], ["ExcitationSystemDynamics", "1", "0..1", "ExcitationSystemDynamics", "UnderexcitationLimiterDynamics"] ] ) ); } }
JavaScript
class UnderexcLimX2 extends UnderexcitationLimiterDynamics { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UnderexcLimX2; if (null == bucket) cim_data.UnderexcLimX2 = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UnderexcLimX2[obj.id]; } parse (context, sub) { let obj = UnderexcitationLimiterDynamics.prototype.parse.call (this, context, sub); obj.cls = "UnderexcLimX2"; base.parse_element (/<cim:UnderexcLimX2.kf2>([\s\S]*?)<\/cim:UnderexcLimX2.kf2>/g, obj, "kf2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.km>([\s\S]*?)<\/cim:UnderexcLimX2.km>/g, obj, "km", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.melmax>([\s\S]*?)<\/cim:UnderexcLimX2.melmax>/g, obj, "melmax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.qo>([\s\S]*?)<\/cim:UnderexcLimX2.qo>/g, obj, "qo", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.r>([\s\S]*?)<\/cim:UnderexcLimX2.r>/g, obj, "r", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.tf2>([\s\S]*?)<\/cim:UnderexcLimX2.tf2>/g, obj, "tf2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX2.tm>([\s\S]*?)<\/cim:UnderexcLimX2.tm>/g, obj, "tm", base.to_string, sub, context); let bucket = context.parsed.UnderexcLimX2; if (null == bucket) context.parsed.UnderexcLimX2 = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = UnderexcitationLimiterDynamics.prototype.export.call (this, obj, false); base.export_element (obj, "UnderexcLimX2", "kf2", "kf2", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "km", "km", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "melmax", "melmax", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "qo", "qo", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "r", "r", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "tf2", "tf2", base.from_string, fields); base.export_element (obj, "UnderexcLimX2", "tm", "tm", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UnderexcLimX2_collapse" aria-expanded="true" aria-controls="UnderexcLimX2_collapse" style="margin-left: 10px;">UnderexcLimX2</a></legend> <div id="UnderexcLimX2_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.template.call (this) + ` {{#kf2}}<div><b>kf2</b>: {{kf2}}</div>{{/kf2}} {{#km}}<div><b>km</b>: {{km}}</div>{{/km}} {{#melmax}}<div><b>melmax</b>: {{melmax}}</div>{{/melmax}} {{#qo}}<div><b>qo</b>: {{qo}}</div>{{/qo}} {{#r}}<div><b>r</b>: {{r}}</div>{{/r}} {{#tf2}}<div><b>tf2</b>: {{tf2}}</div>{{/tf2}} {{#tm}}<div><b>tm</b>: {{tm}}</div>{{/tm}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UnderexcLimX2_collapse" aria-expanded="true" aria-controls="{{id}}_UnderexcLimX2_collapse" style="margin-left: 10px;">UnderexcLimX2</a></legend> <div id="{{id}}_UnderexcLimX2_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kf2'>kf2: </label><div class='col-sm-8'><input id='{{id}}_kf2' class='form-control' type='text'{{#kf2}} value='{{kf2}}'{{/kf2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_km'>km: </label><div class='col-sm-8'><input id='{{id}}_km' class='form-control' type='text'{{#km}} value='{{km}}'{{/km}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_melmax'>melmax: </label><div class='col-sm-8'><input id='{{id}}_melmax' class='form-control' type='text'{{#melmax}} value='{{melmax}}'{{/melmax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_qo'>qo: </label><div class='col-sm-8'><input id='{{id}}_qo' class='form-control' type='text'{{#qo}} value='{{qo}}'{{/qo}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_r'>r: </label><div class='col-sm-8'><input id='{{id}}_r' class='form-control' type='text'{{#r}} value='{{r}}'{{/r}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tf2'>tf2: </label><div class='col-sm-8'><input id='{{id}}_tf2' class='form-control' type='text'{{#tf2}} value='{{tf2}}'{{/tf2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tm'>tm: </label><div class='col-sm-8'><input id='{{id}}_tm' class='form-control' type='text'{{#tm}} value='{{tm}}'{{/tm}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UnderexcLimX2" }; super.submit (id, obj); temp = document.getElementById (id + "_kf2").value; if ("" !== temp) obj["kf2"] = temp; temp = document.getElementById (id + "_km").value; if ("" !== temp) obj["km"] = temp; temp = document.getElementById (id + "_melmax").value; if ("" !== temp) obj["melmax"] = temp; temp = document.getElementById (id + "_qo").value; if ("" !== temp) obj["qo"] = temp; temp = document.getElementById (id + "_r").value; if ("" !== temp) obj["r"] = temp; temp = document.getElementById (id + "_tf2").value; if ("" !== temp) obj["tf2"] = temp; temp = document.getElementById (id + "_tm").value; if ("" !== temp) obj["tm"] = temp; return (obj); } }
JavaScript
class UnderexcLimIEEE1 extends UnderexcitationLimiterDynamics { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UnderexcLimIEEE1; if (null == bucket) cim_data.UnderexcLimIEEE1 = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UnderexcLimIEEE1[obj.id]; } parse (context, sub) { let obj = UnderexcitationLimiterDynamics.prototype.parse.call (this, context, sub); obj.cls = "UnderexcLimIEEE1"; base.parse_element (/<cim:UnderexcLimIEEE1.kuc>([\s\S]*?)<\/cim:UnderexcLimIEEE1.kuc>/g, obj, "kuc", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.kuf>([\s\S]*?)<\/cim:UnderexcLimIEEE1.kuf>/g, obj, "kuf", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.kui>([\s\S]*?)<\/cim:UnderexcLimIEEE1.kui>/g, obj, "kui", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.kul>([\s\S]*?)<\/cim:UnderexcLimIEEE1.kul>/g, obj, "kul", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.kur>([\s\S]*?)<\/cim:UnderexcLimIEEE1.kur>/g, obj, "kur", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.tu1>([\s\S]*?)<\/cim:UnderexcLimIEEE1.tu1>/g, obj, "tu1", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.tu2>([\s\S]*?)<\/cim:UnderexcLimIEEE1.tu2>/g, obj, "tu2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.tu3>([\s\S]*?)<\/cim:UnderexcLimIEEE1.tu3>/g, obj, "tu3", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.tu4>([\s\S]*?)<\/cim:UnderexcLimIEEE1.tu4>/g, obj, "tu4", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vucmax>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vucmax>/g, obj, "vucmax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vuimax>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vuimax>/g, obj, "vuimax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vuimin>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vuimin>/g, obj, "vuimin", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vulmax>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vulmax>/g, obj, "vulmax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vulmin>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vulmin>/g, obj, "vulmin", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE1.vurmax>([\s\S]*?)<\/cim:UnderexcLimIEEE1.vurmax>/g, obj, "vurmax", base.to_string, sub, context); let bucket = context.parsed.UnderexcLimIEEE1; if (null == bucket) context.parsed.UnderexcLimIEEE1 = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = UnderexcitationLimiterDynamics.prototype.export.call (this, obj, false); base.export_element (obj, "UnderexcLimIEEE1", "kuc", "kuc", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "kuf", "kuf", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "kui", "kui", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "kul", "kul", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "kur", "kur", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "tu1", "tu1", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "tu2", "tu2", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "tu3", "tu3", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "tu4", "tu4", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vucmax", "vucmax", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vuimax", "vuimax", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vuimin", "vuimin", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vulmax", "vulmax", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vulmin", "vulmin", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE1", "vurmax", "vurmax", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UnderexcLimIEEE1_collapse" aria-expanded="true" aria-controls="UnderexcLimIEEE1_collapse" style="margin-left: 10px;">UnderexcLimIEEE1</a></legend> <div id="UnderexcLimIEEE1_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.template.call (this) + ` {{#kuc}}<div><b>kuc</b>: {{kuc}}</div>{{/kuc}} {{#kuf}}<div><b>kuf</b>: {{kuf}}</div>{{/kuf}} {{#kui}}<div><b>kui</b>: {{kui}}</div>{{/kui}} {{#kul}}<div><b>kul</b>: {{kul}}</div>{{/kul}} {{#kur}}<div><b>kur</b>: {{kur}}</div>{{/kur}} {{#tu1}}<div><b>tu1</b>: {{tu1}}</div>{{/tu1}} {{#tu2}}<div><b>tu2</b>: {{tu2}}</div>{{/tu2}} {{#tu3}}<div><b>tu3</b>: {{tu3}}</div>{{/tu3}} {{#tu4}}<div><b>tu4</b>: {{tu4}}</div>{{/tu4}} {{#vucmax}}<div><b>vucmax</b>: {{vucmax}}</div>{{/vucmax}} {{#vuimax}}<div><b>vuimax</b>: {{vuimax}}</div>{{/vuimax}} {{#vuimin}}<div><b>vuimin</b>: {{vuimin}}</div>{{/vuimin}} {{#vulmax}}<div><b>vulmax</b>: {{vulmax}}</div>{{/vulmax}} {{#vulmin}}<div><b>vulmin</b>: {{vulmin}}</div>{{/vulmin}} {{#vurmax}}<div><b>vurmax</b>: {{vurmax}}</div>{{/vurmax}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UnderexcLimIEEE1_collapse" aria-expanded="true" aria-controls="{{id}}_UnderexcLimIEEE1_collapse" style="margin-left: 10px;">UnderexcLimIEEE1</a></legend> <div id="{{id}}_UnderexcLimIEEE1_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kuc'>kuc: </label><div class='col-sm-8'><input id='{{id}}_kuc' class='form-control' type='text'{{#kuc}} value='{{kuc}}'{{/kuc}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kuf'>kuf: </label><div class='col-sm-8'><input id='{{id}}_kuf' class='form-control' type='text'{{#kuf}} value='{{kuf}}'{{/kuf}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kui'>kui: </label><div class='col-sm-8'><input id='{{id}}_kui' class='form-control' type='text'{{#kui}} value='{{kui}}'{{/kui}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kul'>kul: </label><div class='col-sm-8'><input id='{{id}}_kul' class='form-control' type='text'{{#kul}} value='{{kul}}'{{/kul}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kur'>kur: </label><div class='col-sm-8'><input id='{{id}}_kur' class='form-control' type='text'{{#kur}} value='{{kur}}'{{/kur}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu1'>tu1: </label><div class='col-sm-8'><input id='{{id}}_tu1' class='form-control' type='text'{{#tu1}} value='{{tu1}}'{{/tu1}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu2'>tu2: </label><div class='col-sm-8'><input id='{{id}}_tu2' class='form-control' type='text'{{#tu2}} value='{{tu2}}'{{/tu2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu3'>tu3: </label><div class='col-sm-8'><input id='{{id}}_tu3' class='form-control' type='text'{{#tu3}} value='{{tu3}}'{{/tu3}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu4'>tu4: </label><div class='col-sm-8'><input id='{{id}}_tu4' class='form-control' type='text'{{#tu4}} value='{{tu4}}'{{/tu4}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vucmax'>vucmax: </label><div class='col-sm-8'><input id='{{id}}_vucmax' class='form-control' type='text'{{#vucmax}} value='{{vucmax}}'{{/vucmax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vuimax'>vuimax: </label><div class='col-sm-8'><input id='{{id}}_vuimax' class='form-control' type='text'{{#vuimax}} value='{{vuimax}}'{{/vuimax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vuimin'>vuimin: </label><div class='col-sm-8'><input id='{{id}}_vuimin' class='form-control' type='text'{{#vuimin}} value='{{vuimin}}'{{/vuimin}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vulmax'>vulmax: </label><div class='col-sm-8'><input id='{{id}}_vulmax' class='form-control' type='text'{{#vulmax}} value='{{vulmax}}'{{/vulmax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vulmin'>vulmin: </label><div class='col-sm-8'><input id='{{id}}_vulmin' class='form-control' type='text'{{#vulmin}} value='{{vulmin}}'{{/vulmin}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vurmax'>vurmax: </label><div class='col-sm-8'><input id='{{id}}_vurmax' class='form-control' type='text'{{#vurmax}} value='{{vurmax}}'{{/vurmax}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UnderexcLimIEEE1" }; super.submit (id, obj); temp = document.getElementById (id + "_kuc").value; if ("" !== temp) obj["kuc"] = temp; temp = document.getElementById (id + "_kuf").value; if ("" !== temp) obj["kuf"] = temp; temp = document.getElementById (id + "_kui").value; if ("" !== temp) obj["kui"] = temp; temp = document.getElementById (id + "_kul").value; if ("" !== temp) obj["kul"] = temp; temp = document.getElementById (id + "_kur").value; if ("" !== temp) obj["kur"] = temp; temp = document.getElementById (id + "_tu1").value; if ("" !== temp) obj["tu1"] = temp; temp = document.getElementById (id + "_tu2").value; if ("" !== temp) obj["tu2"] = temp; temp = document.getElementById (id + "_tu3").value; if ("" !== temp) obj["tu3"] = temp; temp = document.getElementById (id + "_tu4").value; if ("" !== temp) obj["tu4"] = temp; temp = document.getElementById (id + "_vucmax").value; if ("" !== temp) obj["vucmax"] = temp; temp = document.getElementById (id + "_vuimax").value; if ("" !== temp) obj["vuimax"] = temp; temp = document.getElementById (id + "_vuimin").value; if ("" !== temp) obj["vuimin"] = temp; temp = document.getElementById (id + "_vulmax").value; if ("" !== temp) obj["vulmax"] = temp; temp = document.getElementById (id + "_vulmin").value; if ("" !== temp) obj["vulmin"] = temp; temp = document.getElementById (id + "_vurmax").value; if ("" !== temp) obj["vurmax"] = temp; return (obj); } }
JavaScript
class UnderexcLimIEEE2 extends UnderexcitationLimiterDynamics { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UnderexcLimIEEE2; if (null == bucket) cim_data.UnderexcLimIEEE2 = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UnderexcLimIEEE2[obj.id]; } parse (context, sub) { let obj = UnderexcitationLimiterDynamics.prototype.parse.call (this, context, sub); obj.cls = "UnderexcLimIEEE2"; base.parse_element (/<cim:UnderexcLimIEEE2.k1>([\s\S]*?)<\/cim:UnderexcLimIEEE2.k1>/g, obj, "k1", base.to_float, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.k2>([\s\S]*?)<\/cim:UnderexcLimIEEE2.k2>/g, obj, "k2", base.to_float, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.kfb>([\s\S]*?)<\/cim:UnderexcLimIEEE2.kfb>/g, obj, "kfb", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.kuf>([\s\S]*?)<\/cim:UnderexcLimIEEE2.kuf>/g, obj, "kuf", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.kui>([\s\S]*?)<\/cim:UnderexcLimIEEE2.kui>/g, obj, "kui", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.kul>([\s\S]*?)<\/cim:UnderexcLimIEEE2.kul>/g, obj, "kul", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p0>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p0>/g, obj, "p0", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p1>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p1>/g, obj, "p1", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p10>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p10>/g, obj, "p10", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p2>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p2>/g, obj, "p2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p3>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p3>/g, obj, "p3", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p4>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p4>/g, obj, "p4", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p5>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p5>/g, obj, "p5", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p6>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p6>/g, obj, "p6", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p7>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p7>/g, obj, "p7", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p8>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p8>/g, obj, "p8", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.p9>([\s\S]*?)<\/cim:UnderexcLimIEEE2.p9>/g, obj, "p9", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q0>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q0>/g, obj, "q0", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q1>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q1>/g, obj, "q1", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q10>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q10>/g, obj, "q10", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q2>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q2>/g, obj, "q2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q3>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q3>/g, obj, "q3", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q4>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q4>/g, obj, "q4", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q5>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q5>/g, obj, "q5", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q6>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q6>/g, obj, "q6", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q7>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q7>/g, obj, "q7", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q8>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q8>/g, obj, "q8", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.q9>([\s\S]*?)<\/cim:UnderexcLimIEEE2.q9>/g, obj, "q9", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tu1>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tu1>/g, obj, "tu1", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tu2>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tu2>/g, obj, "tu2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tu3>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tu3>/g, obj, "tu3", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tu4>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tu4>/g, obj, "tu4", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tul>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tul>/g, obj, "tul", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tup>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tup>/g, obj, "tup", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tuq>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tuq>/g, obj, "tuq", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.tuv>([\s\S]*?)<\/cim:UnderexcLimIEEE2.tuv>/g, obj, "tuv", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.vuimax>([\s\S]*?)<\/cim:UnderexcLimIEEE2.vuimax>/g, obj, "vuimax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.vuimin>([\s\S]*?)<\/cim:UnderexcLimIEEE2.vuimin>/g, obj, "vuimin", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.vulmax>([\s\S]*?)<\/cim:UnderexcLimIEEE2.vulmax>/g, obj, "vulmax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimIEEE2.vulmin>([\s\S]*?)<\/cim:UnderexcLimIEEE2.vulmin>/g, obj, "vulmin", base.to_string, sub, context); let bucket = context.parsed.UnderexcLimIEEE2; if (null == bucket) context.parsed.UnderexcLimIEEE2 = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = UnderexcitationLimiterDynamics.prototype.export.call (this, obj, false); base.export_element (obj, "UnderexcLimIEEE2", "k1", "k1", base.from_float, fields); base.export_element (obj, "UnderexcLimIEEE2", "k2", "k2", base.from_float, fields); base.export_element (obj, "UnderexcLimIEEE2", "kfb", "kfb", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "kuf", "kuf", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "kui", "kui", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "kul", "kul", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p0", "p0", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p1", "p1", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p10", "p10", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p2", "p2", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p3", "p3", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p4", "p4", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p5", "p5", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p6", "p6", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p7", "p7", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p8", "p8", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "p9", "p9", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q0", "q0", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q1", "q1", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q10", "q10", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q2", "q2", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q3", "q3", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q4", "q4", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q5", "q5", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q6", "q6", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q7", "q7", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q8", "q8", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "q9", "q9", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tu1", "tu1", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tu2", "tu2", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tu3", "tu3", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tu4", "tu4", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tul", "tul", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tup", "tup", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tuq", "tuq", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "tuv", "tuv", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "vuimax", "vuimax", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "vuimin", "vuimin", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "vulmax", "vulmax", base.from_string, fields); base.export_element (obj, "UnderexcLimIEEE2", "vulmin", "vulmin", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UnderexcLimIEEE2_collapse" aria-expanded="true" aria-controls="UnderexcLimIEEE2_collapse" style="margin-left: 10px;">UnderexcLimIEEE2</a></legend> <div id="UnderexcLimIEEE2_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.template.call (this) + ` {{#k1}}<div><b>k1</b>: {{k1}}</div>{{/k1}} {{#k2}}<div><b>k2</b>: {{k2}}</div>{{/k2}} {{#kfb}}<div><b>kfb</b>: {{kfb}}</div>{{/kfb}} {{#kuf}}<div><b>kuf</b>: {{kuf}}</div>{{/kuf}} {{#kui}}<div><b>kui</b>: {{kui}}</div>{{/kui}} {{#kul}}<div><b>kul</b>: {{kul}}</div>{{/kul}} {{#p0}}<div><b>p0</b>: {{p0}}</div>{{/p0}} {{#p1}}<div><b>p1</b>: {{p1}}</div>{{/p1}} {{#p10}}<div><b>p10</b>: {{p10}}</div>{{/p10}} {{#p2}}<div><b>p2</b>: {{p2}}</div>{{/p2}} {{#p3}}<div><b>p3</b>: {{p3}}</div>{{/p3}} {{#p4}}<div><b>p4</b>: {{p4}}</div>{{/p4}} {{#p5}}<div><b>p5</b>: {{p5}}</div>{{/p5}} {{#p6}}<div><b>p6</b>: {{p6}}</div>{{/p6}} {{#p7}}<div><b>p7</b>: {{p7}}</div>{{/p7}} {{#p8}}<div><b>p8</b>: {{p8}}</div>{{/p8}} {{#p9}}<div><b>p9</b>: {{p9}}</div>{{/p9}} {{#q0}}<div><b>q0</b>: {{q0}}</div>{{/q0}} {{#q1}}<div><b>q1</b>: {{q1}}</div>{{/q1}} {{#q10}}<div><b>q10</b>: {{q10}}</div>{{/q10}} {{#q2}}<div><b>q2</b>: {{q2}}</div>{{/q2}} {{#q3}}<div><b>q3</b>: {{q3}}</div>{{/q3}} {{#q4}}<div><b>q4</b>: {{q4}}</div>{{/q4}} {{#q5}}<div><b>q5</b>: {{q5}}</div>{{/q5}} {{#q6}}<div><b>q6</b>: {{q6}}</div>{{/q6}} {{#q7}}<div><b>q7</b>: {{q7}}</div>{{/q7}} {{#q8}}<div><b>q8</b>: {{q8}}</div>{{/q8}} {{#q9}}<div><b>q9</b>: {{q9}}</div>{{/q9}} {{#tu1}}<div><b>tu1</b>: {{tu1}}</div>{{/tu1}} {{#tu2}}<div><b>tu2</b>: {{tu2}}</div>{{/tu2}} {{#tu3}}<div><b>tu3</b>: {{tu3}}</div>{{/tu3}} {{#tu4}}<div><b>tu4</b>: {{tu4}}</div>{{/tu4}} {{#tul}}<div><b>tul</b>: {{tul}}</div>{{/tul}} {{#tup}}<div><b>tup</b>: {{tup}}</div>{{/tup}} {{#tuq}}<div><b>tuq</b>: {{tuq}}</div>{{/tuq}} {{#tuv}}<div><b>tuv</b>: {{tuv}}</div>{{/tuv}} {{#vuimax}}<div><b>vuimax</b>: {{vuimax}}</div>{{/vuimax}} {{#vuimin}}<div><b>vuimin</b>: {{vuimin}}</div>{{/vuimin}} {{#vulmax}}<div><b>vulmax</b>: {{vulmax}}</div>{{/vulmax}} {{#vulmin}}<div><b>vulmin</b>: {{vulmin}}</div>{{/vulmin}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UnderexcLimIEEE2_collapse" aria-expanded="true" aria-controls="{{id}}_UnderexcLimIEEE2_collapse" style="margin-left: 10px;">UnderexcLimIEEE2</a></legend> <div id="{{id}}_UnderexcLimIEEE2_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_k1'>k1: </label><div class='col-sm-8'><input id='{{id}}_k1' class='form-control' type='text'{{#k1}} value='{{k1}}'{{/k1}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_k2'>k2: </label><div class='col-sm-8'><input id='{{id}}_k2' class='form-control' type='text'{{#k2}} value='{{k2}}'{{/k2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kfb'>kfb: </label><div class='col-sm-8'><input id='{{id}}_kfb' class='form-control' type='text'{{#kfb}} value='{{kfb}}'{{/kfb}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kuf'>kuf: </label><div class='col-sm-8'><input id='{{id}}_kuf' class='form-control' type='text'{{#kuf}} value='{{kuf}}'{{/kuf}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kui'>kui: </label><div class='col-sm-8'><input id='{{id}}_kui' class='form-control' type='text'{{#kui}} value='{{kui}}'{{/kui}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kul'>kul: </label><div class='col-sm-8'><input id='{{id}}_kul' class='form-control' type='text'{{#kul}} value='{{kul}}'{{/kul}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p0'>p0: </label><div class='col-sm-8'><input id='{{id}}_p0' class='form-control' type='text'{{#p0}} value='{{p0}}'{{/p0}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p1'>p1: </label><div class='col-sm-8'><input id='{{id}}_p1' class='form-control' type='text'{{#p1}} value='{{p1}}'{{/p1}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p10'>p10: </label><div class='col-sm-8'><input id='{{id}}_p10' class='form-control' type='text'{{#p10}} value='{{p10}}'{{/p10}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p2'>p2: </label><div class='col-sm-8'><input id='{{id}}_p2' class='form-control' type='text'{{#p2}} value='{{p2}}'{{/p2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p3'>p3: </label><div class='col-sm-8'><input id='{{id}}_p3' class='form-control' type='text'{{#p3}} value='{{p3}}'{{/p3}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p4'>p4: </label><div class='col-sm-8'><input id='{{id}}_p4' class='form-control' type='text'{{#p4}} value='{{p4}}'{{/p4}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p5'>p5: </label><div class='col-sm-8'><input id='{{id}}_p5' class='form-control' type='text'{{#p5}} value='{{p5}}'{{/p5}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p6'>p6: </label><div class='col-sm-8'><input id='{{id}}_p6' class='form-control' type='text'{{#p6}} value='{{p6}}'{{/p6}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p7'>p7: </label><div class='col-sm-8'><input id='{{id}}_p7' class='form-control' type='text'{{#p7}} value='{{p7}}'{{/p7}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p8'>p8: </label><div class='col-sm-8'><input id='{{id}}_p8' class='form-control' type='text'{{#p8}} value='{{p8}}'{{/p8}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_p9'>p9: </label><div class='col-sm-8'><input id='{{id}}_p9' class='form-control' type='text'{{#p9}} value='{{p9}}'{{/p9}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q0'>q0: </label><div class='col-sm-8'><input id='{{id}}_q0' class='form-control' type='text'{{#q0}} value='{{q0}}'{{/q0}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q1'>q1: </label><div class='col-sm-8'><input id='{{id}}_q1' class='form-control' type='text'{{#q1}} value='{{q1}}'{{/q1}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q10'>q10: </label><div class='col-sm-8'><input id='{{id}}_q10' class='form-control' type='text'{{#q10}} value='{{q10}}'{{/q10}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q2'>q2: </label><div class='col-sm-8'><input id='{{id}}_q2' class='form-control' type='text'{{#q2}} value='{{q2}}'{{/q2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q3'>q3: </label><div class='col-sm-8'><input id='{{id}}_q3' class='form-control' type='text'{{#q3}} value='{{q3}}'{{/q3}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q4'>q4: </label><div class='col-sm-8'><input id='{{id}}_q4' class='form-control' type='text'{{#q4}} value='{{q4}}'{{/q4}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q5'>q5: </label><div class='col-sm-8'><input id='{{id}}_q5' class='form-control' type='text'{{#q5}} value='{{q5}}'{{/q5}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q6'>q6: </label><div class='col-sm-8'><input id='{{id}}_q6' class='form-control' type='text'{{#q6}} value='{{q6}}'{{/q6}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q7'>q7: </label><div class='col-sm-8'><input id='{{id}}_q7' class='form-control' type='text'{{#q7}} value='{{q7}}'{{/q7}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q8'>q8: </label><div class='col-sm-8'><input id='{{id}}_q8' class='form-control' type='text'{{#q8}} value='{{q8}}'{{/q8}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_q9'>q9: </label><div class='col-sm-8'><input id='{{id}}_q9' class='form-control' type='text'{{#q9}} value='{{q9}}'{{/q9}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu1'>tu1: </label><div class='col-sm-8'><input id='{{id}}_tu1' class='form-control' type='text'{{#tu1}} value='{{tu1}}'{{/tu1}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu2'>tu2: </label><div class='col-sm-8'><input id='{{id}}_tu2' class='form-control' type='text'{{#tu2}} value='{{tu2}}'{{/tu2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu3'>tu3: </label><div class='col-sm-8'><input id='{{id}}_tu3' class='form-control' type='text'{{#tu3}} value='{{tu3}}'{{/tu3}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tu4'>tu4: </label><div class='col-sm-8'><input id='{{id}}_tu4' class='form-control' type='text'{{#tu4}} value='{{tu4}}'{{/tu4}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tul'>tul: </label><div class='col-sm-8'><input id='{{id}}_tul' class='form-control' type='text'{{#tul}} value='{{tul}}'{{/tul}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tup'>tup: </label><div class='col-sm-8'><input id='{{id}}_tup' class='form-control' type='text'{{#tup}} value='{{tup}}'{{/tup}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tuq'>tuq: </label><div class='col-sm-8'><input id='{{id}}_tuq' class='form-control' type='text'{{#tuq}} value='{{tuq}}'{{/tuq}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tuv'>tuv: </label><div class='col-sm-8'><input id='{{id}}_tuv' class='form-control' type='text'{{#tuv}} value='{{tuv}}'{{/tuv}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vuimax'>vuimax: </label><div class='col-sm-8'><input id='{{id}}_vuimax' class='form-control' type='text'{{#vuimax}} value='{{vuimax}}'{{/vuimax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vuimin'>vuimin: </label><div class='col-sm-8'><input id='{{id}}_vuimin' class='form-control' type='text'{{#vuimin}} value='{{vuimin}}'{{/vuimin}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vulmax'>vulmax: </label><div class='col-sm-8'><input id='{{id}}_vulmax' class='form-control' type='text'{{#vulmax}} value='{{vulmax}}'{{/vulmax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vulmin'>vulmin: </label><div class='col-sm-8'><input id='{{id}}_vulmin' class='form-control' type='text'{{#vulmin}} value='{{vulmin}}'{{/vulmin}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UnderexcLimIEEE2" }; super.submit (id, obj); temp = document.getElementById (id + "_k1").value; if ("" !== temp) obj["k1"] = temp; temp = document.getElementById (id + "_k2").value; if ("" !== temp) obj["k2"] = temp; temp = document.getElementById (id + "_kfb").value; if ("" !== temp) obj["kfb"] = temp; temp = document.getElementById (id + "_kuf").value; if ("" !== temp) obj["kuf"] = temp; temp = document.getElementById (id + "_kui").value; if ("" !== temp) obj["kui"] = temp; temp = document.getElementById (id + "_kul").value; if ("" !== temp) obj["kul"] = temp; temp = document.getElementById (id + "_p0").value; if ("" !== temp) obj["p0"] = temp; temp = document.getElementById (id + "_p1").value; if ("" !== temp) obj["p1"] = temp; temp = document.getElementById (id + "_p10").value; if ("" !== temp) obj["p10"] = temp; temp = document.getElementById (id + "_p2").value; if ("" !== temp) obj["p2"] = temp; temp = document.getElementById (id + "_p3").value; if ("" !== temp) obj["p3"] = temp; temp = document.getElementById (id + "_p4").value; if ("" !== temp) obj["p4"] = temp; temp = document.getElementById (id + "_p5").value; if ("" !== temp) obj["p5"] = temp; temp = document.getElementById (id + "_p6").value; if ("" !== temp) obj["p6"] = temp; temp = document.getElementById (id + "_p7").value; if ("" !== temp) obj["p7"] = temp; temp = document.getElementById (id + "_p8").value; if ("" !== temp) obj["p8"] = temp; temp = document.getElementById (id + "_p9").value; if ("" !== temp) obj["p9"] = temp; temp = document.getElementById (id + "_q0").value; if ("" !== temp) obj["q0"] = temp; temp = document.getElementById (id + "_q1").value; if ("" !== temp) obj["q1"] = temp; temp = document.getElementById (id + "_q10").value; if ("" !== temp) obj["q10"] = temp; temp = document.getElementById (id + "_q2").value; if ("" !== temp) obj["q2"] = temp; temp = document.getElementById (id + "_q3").value; if ("" !== temp) obj["q3"] = temp; temp = document.getElementById (id + "_q4").value; if ("" !== temp) obj["q4"] = temp; temp = document.getElementById (id + "_q5").value; if ("" !== temp) obj["q5"] = temp; temp = document.getElementById (id + "_q6").value; if ("" !== temp) obj["q6"] = temp; temp = document.getElementById (id + "_q7").value; if ("" !== temp) obj["q7"] = temp; temp = document.getElementById (id + "_q8").value; if ("" !== temp) obj["q8"] = temp; temp = document.getElementById (id + "_q9").value; if ("" !== temp) obj["q9"] = temp; temp = document.getElementById (id + "_tu1").value; if ("" !== temp) obj["tu1"] = temp; temp = document.getElementById (id + "_tu2").value; if ("" !== temp) obj["tu2"] = temp; temp = document.getElementById (id + "_tu3").value; if ("" !== temp) obj["tu3"] = temp; temp = document.getElementById (id + "_tu4").value; if ("" !== temp) obj["tu4"] = temp; temp = document.getElementById (id + "_tul").value; if ("" !== temp) obj["tul"] = temp; temp = document.getElementById (id + "_tup").value; if ("" !== temp) obj["tup"] = temp; temp = document.getElementById (id + "_tuq").value; if ("" !== temp) obj["tuq"] = temp; temp = document.getElementById (id + "_tuv").value; if ("" !== temp) obj["tuv"] = temp; temp = document.getElementById (id + "_vuimax").value; if ("" !== temp) obj["vuimax"] = temp; temp = document.getElementById (id + "_vuimin").value; if ("" !== temp) obj["vuimin"] = temp; temp = document.getElementById (id + "_vulmax").value; if ("" !== temp) obj["vulmax"] = temp; temp = document.getElementById (id + "_vulmin").value; if ("" !== temp) obj["vulmin"] = temp; return (obj); } }
JavaScript
class UnderexcLimX1 extends UnderexcitationLimiterDynamics { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UnderexcLimX1; if (null == bucket) cim_data.UnderexcLimX1 = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UnderexcLimX1[obj.id]; } parse (context, sub) { let obj = UnderexcitationLimiterDynamics.prototype.parse.call (this, context, sub); obj.cls = "UnderexcLimX1"; base.parse_element (/<cim:UnderexcLimX1.k>([\s\S]*?)<\/cim:UnderexcLimX1.k>/g, obj, "k", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX1.kf2>([\s\S]*?)<\/cim:UnderexcLimX1.kf2>/g, obj, "kf2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX1.km>([\s\S]*?)<\/cim:UnderexcLimX1.km>/g, obj, "km", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX1.melmax>([\s\S]*?)<\/cim:UnderexcLimX1.melmax>/g, obj, "melmax", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX1.tf2>([\s\S]*?)<\/cim:UnderexcLimX1.tf2>/g, obj, "tf2", base.to_string, sub, context); base.parse_element (/<cim:UnderexcLimX1.tm>([\s\S]*?)<\/cim:UnderexcLimX1.tm>/g, obj, "tm", base.to_string, sub, context); let bucket = context.parsed.UnderexcLimX1; if (null == bucket) context.parsed.UnderexcLimX1 = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = UnderexcitationLimiterDynamics.prototype.export.call (this, obj, false); base.export_element (obj, "UnderexcLimX1", "k", "k", base.from_string, fields); base.export_element (obj, "UnderexcLimX1", "kf2", "kf2", base.from_string, fields); base.export_element (obj, "UnderexcLimX1", "km", "km", base.from_string, fields); base.export_element (obj, "UnderexcLimX1", "melmax", "melmax", base.from_string, fields); base.export_element (obj, "UnderexcLimX1", "tf2", "tf2", base.from_string, fields); base.export_element (obj, "UnderexcLimX1", "tm", "tm", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UnderexcLimX1_collapse" aria-expanded="true" aria-controls="UnderexcLimX1_collapse" style="margin-left: 10px;">UnderexcLimX1</a></legend> <div id="UnderexcLimX1_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.template.call (this) + ` {{#k}}<div><b>k</b>: {{k}}</div>{{/k}} {{#kf2}}<div><b>kf2</b>: {{kf2}}</div>{{/kf2}} {{#km}}<div><b>km</b>: {{km}}</div>{{/km}} {{#melmax}}<div><b>melmax</b>: {{melmax}}</div>{{/melmax}} {{#tf2}}<div><b>tf2</b>: {{tf2}}</div>{{/tf2}} {{#tm}}<div><b>tm</b>: {{tm}}</div>{{/tm}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UnderexcLimX1_collapse" aria-expanded="true" aria-controls="{{id}}_UnderexcLimX1_collapse" style="margin-left: 10px;">UnderexcLimX1</a></legend> <div id="{{id}}_UnderexcLimX1_collapse" class="collapse in show" style="margin-left: 10px;"> ` + UnderexcitationLimiterDynamics.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_k'>k: </label><div class='col-sm-8'><input id='{{id}}_k' class='form-control' type='text'{{#k}} value='{{k}}'{{/k}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kf2'>kf2: </label><div class='col-sm-8'><input id='{{id}}_kf2' class='form-control' type='text'{{#kf2}} value='{{kf2}}'{{/kf2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_km'>km: </label><div class='col-sm-8'><input id='{{id}}_km' class='form-control' type='text'{{#km}} value='{{km}}'{{/km}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_melmax'>melmax: </label><div class='col-sm-8'><input id='{{id}}_melmax' class='form-control' type='text'{{#melmax}} value='{{melmax}}'{{/melmax}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tf2'>tf2: </label><div class='col-sm-8'><input id='{{id}}_tf2' class='form-control' type='text'{{#tf2}} value='{{tf2}}'{{/tf2}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tm'>tm: </label><div class='col-sm-8'><input id='{{id}}_tm' class='form-control' type='text'{{#tm}} value='{{tm}}'{{/tm}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UnderexcLimX1" }; super.submit (id, obj); temp = document.getElementById (id + "_k").value; if ("" !== temp) obj["k"] = temp; temp = document.getElementById (id + "_kf2").value; if ("" !== temp) obj["kf2"] = temp; temp = document.getElementById (id + "_km").value; if ("" !== temp) obj["km"] = temp; temp = document.getElementById (id + "_melmax").value; if ("" !== temp) obj["melmax"] = temp; temp = document.getElementById (id + "_tf2").value; if ("" !== temp) obj["tf2"] = temp; temp = document.getElementById (id + "_tm").value; if ("" !== temp) obj["tm"] = temp; return (obj); } }
JavaScript
class PartialDate extends Date { /** @inheritDoc */ constructor( ...args ) { if ( args.length > 0 ) { super( ...args ); } else if ( process.env.node === "test" ) { super( 2019, 4, 31, 16, 32, 30 ); } else { super(); } if ( args.length > 0 ) { /** @property int @readonly @protected */ this._year = this.getFullYear(); /** @property int @readonly @protected */ this._month = this.getMonth(); /** @property int @readonly @protected */ this._date = this.getDate(); /** @property int @readonly @protected */ this._hours = this.getHours(); /** @property int @readonly @protected */ this._minutes = this.getMinutes(); /** @property int @readonly @protected */ this._seconds = this.getSeconds(); } else { this._year = this._month = this._date = this._hours = this._minutes = this._seconds = NaN; } Object.defineProperties( this, { /** * Indicates if instance provides incomplete date information. * * @name PartialDate#isIncompleteDate * @property boolean * @readonly */ isIncompleteDate: { get: () => isNaN( this._date ) || isNaN( this._month ) || isNaN( this._year ), }, /** * Indicates if instance provides incomplete date of time information. * * @name PartialDate#isIncompleteTimeOfDay * @property boolean * @readonly */ isIncompleteTimeOfDay: { get: () => isNaN( this._hours ) || isNaN( this._minutes ) || isNaN( this._seconds ), }, } ); } /** @inheritDoc */ setFullYear( ...args ) { const result = super.setFullYear( ...args ); this._year = this.getFullYear(); if ( args.length > 1 ) { this._month = this.getMonth(); } if ( args.length > 2 ) { this._date = this.getDate(); } return result; } /** @inheritDoc */ setMonth( ...args ) { const [month] = args; if ( isNaN( this._date ) ) { // adjust internally existing day of month to prevent auto-adjusting // month when assigning desired value below const dayOfMonth = super.getDate(); const copy = new Date( this ); copy.setMonth( month + 1 ); copy.setDate( 0 ); if ( dayOfMonth > copy.getDate() ) { super.setDate( copy.getDate() ); } } const result = super.setMonth( ...args ); this._month = this.getMonth(); if ( args.length > 1 ) { this._date = this.getDate(); } return result; } /** @inheritDoc */ setDate( ...args ) { const [dayOfMonth] = args; if ( isNaN( this._month ) ) { // adjust internally existing month to prevent auto-adjusting day of // month when assigning desired value below const copy = new Date( this ); copy.setMonth( super.getMonth() + 1 ); copy.setDate( 0 ); if ( dayOfMonth > 0 && dayOfMonth < 32 && dayOfMonth > copy.getDate() ) { super.setMonth( ( super.getMonth() + 1 ) % 12 ); } } const result = super.setDate( ...args ); this._date = this.getDate(); return result; } /** @inheritDoc */ setHours( ...args ) { const result = super.setHours( ...args ); this._hours = this.getHours(); if ( args.length > 1 ) { this._minutes = this.getMinutes(); } if ( args.length > 2 ) { this._seconds = this.getSeconds(); } return result; } /** @inheritDoc */ setMinutes( ...args ) { const result = super.setMinutes( ...args ); this._minutes = this.getMinutes(); if ( args.length > 1 ) { this._seconds = this.getSeconds(); } return result; } /** @inheritDoc */ setSeconds( ...args ) { const result = super.setSeconds( ...args ); this._seconds = this.getSeconds(); return result; } /** * Detects if provided date describes same day as current instance obeying * either date probably providing incomplete information limiting comparison * to existing information. * * @param {Date} date date to compare current one with * @return {boolean} true if both dates describe same day w/o obeying missing information in either date */ isSameDay( date ) { if ( date instanceof Date ) { let y, m, d; if ( date instanceof PartialDate ) { y = date._year; m = date._month; d = date._date; } else { y = date.getFullYear(); m = date.getMonth(); d = date.getDate(); } if ( !isNaN( this._year ) && !isNaN( y ) && this._year !== y ) { return false; } if ( !isNaN( this._month ) && !isNaN( m ) && this._month !== m ) { return false; } return isNaN( this._date ) || isNaN( d ) || this._date === d; } return false; } /** * Describes current date using simple Javascript data suitable for * serialization. * * @return {object} serialized data */ serialize() { const serialized = {}; if ( !isNaN( this._year ) ) { serialized.y = this._year; } if ( !isNaN( this._month ) ) { serialized.m = this._month; } if ( !isNaN( this._date ) ) { serialized.d = this._date; } if ( !isNaN( this._hours ) ) { serialized.h = this._hours; } if ( !isNaN( this._minutes ) ) { serialized.i = this._minutes; } if ( !isNaN( this._seconds ) ) { serialized.s = this._seconds; } return serialized; } /** * Restores instance of `PartialDate` from a serialized description of a * date. * * @param {object<string,int>} serialized serializable description of a partial date * @return {PartialDate|null} recovered instance of `PartialDate` */ static deserialize( serialized ) { if ( serialized && typeof serialized === "object" ) { const names = "ymdhis"; const numNames = names.length; const date = new PartialDate(); for ( let i = 0; i < numNames; i++ ) { const name = names[i]; const value = parseInt( serialized[name] ); if ( !isNaN( value ) ) { switch ( name ) { case "y" : date.setFullYear( value ); break; case "m" : date.setMonth( value ); break; case "d" : date.setDate( value ); break; case "h" : date.setHours( value ); break; case "i" : date.setMinutes( value ); break; case "s" : date.setSeconds( value ); break; } } } return date; } return null; } }
JavaScript
class DateProcessor { /** * @param{string[]|string} format single or array of dateFormats for example: yyyy-mm-dd */ constructor( format = "yyyy-mm-dd" ) { this.normalizer = {}; this.format = []; this.addFormat( format ); } /** * Adds formats and caches corresponding DateNormalizer and DateValidator. * * @param{string[]|string} format single or array of dateFormats for example: yyyy-mm-dd * @returns {this} fluent interface */ addFormat( format ) { const _formats = Array.isArray( format ) ? format : [format]; const numFormats = _formats.length; for ( let index = 0; index < numFormats; index++ ) { const _format = _formats[index]; if ( typeof _format === "string" && _format && !this.normalizer[_format] ) { this.format.push( _format ); this.normalizer[_format] = new DateNormalizer( _format ); } } return this; } /** * Normalizes provided date information. * * @param{string} input date to validate for given format * @param{object} options refers to object selecting optional customizations to date checking * @returns {FormatCheckResult} validated textual input or list of errors if checking failed */ normalize( input, options = {} ) { const { format } = options; if ( format ) { this.addFormat( format ); } const formats = this.format; const numFormats = formats.length; let firstError = null; let bestIncompleteDate = null; for ( let i = 0, l = numFormats; i < l; i++ ) { const _format = formats[i]; try { const date = this.normalizer[_format].normalize( input, options ); if ( date ) { if ( !date.isIncompleteDate ) { return date; } if ( !bestIncompleteDate ) { bestIncompleteDate = date; } } } catch ( error ) { if ( !firstError ) { firstError = error; } } } if ( bestIncompleteDate ) { return bestIncompleteDate; } throw firstError; } /** * Normalizes a date for given format. * * @param{Date} input date to validate for given format * @param{object} options refers to object selecting optional customizations to date checking * @returns {FormatCheckResult} validated textual input or list of errors if checking failed */ validate( input, options ) { return DateValidator.validate( input, options ); } /** * Parses provided input value for definition of business days. * * @param {string|string[]|int|int[]} input one or more days of week each selected by its index or its abbreviated English name * @returns {object<int,boolean>} maps indices of found week days into boolean `true` */ static parseBusinessDays( input ) { const _days = Array.isArray( input ) ? input : [input]; const numDays = _days.length; const parsed = {}; const map = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }; for ( let i = 0; i < numDays; i++ ) { const _day = _days[i]; const range = /^(?:([0-6])|([sunmotewdhfria]+))\s*-\s*(?:([0-6])|([sunmotewdhfria]+))$/i.exec( _day ); if ( range ) { const from = range[1] ? parseInt( range[1] ) : map[range[2]]; const thru = range[3] ? parseInt( range[3] ) : map[range[4]]; if ( from > -1 && thru > -1 ) { for ( let j = Math.min( from, thru ); j <= Math.max( from, thru ); j++ ) { parsed[j] = true; } } } else { const index = parseInt( _day ); if ( isNaN( index ) ) { const name = String( _day ).trim().toLowerCase(); const mapped = map[name]; if ( mapped != null ) { parsed[mapped] = true; } } else if ( index > -1 && index < 7 ) { parsed[index] = true; } } } return parsed; } /** * Parses provided input value for definition of one or more holidays. * * @param {string|string[]|Date|Date[]} input one or more descriptions of (recurring) holidays * @returns {PartialDate[]} maps indices of found week days into boolean `true` */ static parseHolidays( input ) { const _holidays = Array.isArray( input ) ? input : [input]; const numHolidays = _holidays.length; const parsed = []; let write = 0; for ( let i = 0; i < numHolidays; i++ ) { const source = _holidays[i]; if ( source instanceof Date ) { parsed[write++] = source; continue; } const match = /^(?:(\d{4})-)?(\d{2})-(\d{2})$/.exec( source ); if ( match ) { const holiday = new PartialDate(); if ( match[1] ) { holiday.setFullYear( match[1] ); } holiday.setMonth( parseInt( match[2] ) - 1 ); holiday.setDate( parseInt( match[3] ) ); parsed[write++] = holiday; } } parsed.splice( write ); return parsed; } /** * Converts description of a date into according instance of Date. * * This method supports several input values for selecting/describing a date: * * - Any provided instance of `Date` is returned as is. * - `now`, `today`, `tomorrow` and `yesterday` select either day accordingly. * - Strings describing timestamps supported by `Date.parse()` are supported. * - Providing number of seconds since Unix Epoch is supported. * - Relative distances to current date can be provided as string: * - Syntax is `+xu` or `-xu` or just `xu` with `x` being sequence of digits and `u` being unit. * - Supported units are: * - `d` for days (which is default when omitting unit) * - `w` for weeks * - `m` for months * - `y` for years * - In addition special units are supported: * - `bom` selects first day of month that would be selected when using unit `m` * - `eom` selects last day of month that would be selected when using unit `m` * - `boy` selects first day of year that would be selected when using unit `y` * - `eoy` selects last day of year that would be selected when using unit `y` * - `bd` selects _business days_ obeying provided set of weekdays considered business days and a list of holidays * - Use `DateProcessor.parseBusinessDays()` to prepare list of weekdays considered business days. * - Use `DateProcessor.parseHolidays()` to prepare list of holidays. * - All names and units are supported case-insensitively. * * @param {string|Date} selector description of a date * @param {object<int,boolean>} businessDays map of permitted weekdays into boolean `true` for calculating relative business days * @param {Date[]} holidays list of allowed dates * @param {Date} reference date selector is relative to instead of now * @return {Date} instance of Date matching date described by provided selector */ static normalizeSelector( selector, { businessDays = DefaultBusinessDays, holidays = DefaultHolidays, reference = null } = {} ) { if ( selector instanceof Date ) { return selector; } const now = reference instanceof Date ? new PartialDate( reference ) : new PartialDate(); const _selector = selector == null ? null : String( selector ).toLowerCase(); switch ( _selector ) { case "now" : case "today" : return now; case "tomorrow" : return new Date( now.getTime() + 86400000 ); case "yesterday" : return new Date( now.getTime() - 86400000 ); } const relative = /^([+-])?\s*?(\d+)\s*(d|m|y|bom|eom|boy|eoy|bd)?/.exec( _selector ); if ( !relative ) { // does not look like relative description of a date // -> try parsing as some actual date string const date = Date.parse( selector ); if ( isNaN( date ) ) { throw new Error( "Invalid description of date." ); } return date; } const [ , sign = "+", amount, unit ] = relative; if ( amount.length > 6 && unit == null ) { // got integer value considered number of seconds since Unix Epoch return new Date( parseInt( amount ) * 1000 ); } let value = parseInt( `${sign}${amount}` ); switch ( unit ) { case "d" : default : now.setDate( now.getDate() + value ); return now; case "w" : now.setDate( now.getDate() + ( value * 7 ) ); return now; case "m" : { const ref = new Date( now ); // choose date available in any month to prevent `Date` auto-adjusting month below ref.setDate( 20 ); // choose month following the one selected by range ref.setMonth( now.getMonth() + value + 1 ); // choose last day of previous month a.k.a. the desired month ref.setDate( 0 ); if ( now.getDate() < ref.getDate() ) { ref.setDate( now.getDate() ); } return ref; } case "bom" : // choose first day of selected month now.setDate( 1 ); now.setMonth( now.getMonth() + value ); return now; case "eom" : // choose last day of selected month now.setDate( 20 ); // use safe day of month to prevent `setMonth()` auto-adjusting below now.setMonth( now.getMonth() + value + 1 ); now.setDate( 0 ); return now; case "y" : { const fixed = now.getMonth() === 1 && now.getDate() === 29; // resulting year might be missing Feb 29th now.setFullYear( now.getFullYear() + value ); if ( fixed && now.getDate() === 1 ) { now.setMonth( 1 ); now.setDate( 28 ); } return now; } case "boy" : // choose first day of selected year now.setFullYear( now.getFullYear() + value ); now.setMonth( 0 ); now.setDate( 1 ); return now; case "eoy" : // choose last day of selected year now.setFullYear( now.getFullYear() + value ); now.setMonth( 11 ); now.setDate( 31 ); return now; case "bd" : { // iterate over dates looking for some business day with provided distance const step = value < 0 ? -1 : 1; const numHolidays = holidays.length; while ( value !== 0 ) { now.setDate( now.getDate() + step ); if ( businessDays[now.getDay()] ) { let isHoliday = false; for ( let i = 0; i < numHolidays; i++ ) { if ( now.isSameDay( holidays[i] ) ) { isHoliday = true; break; } } if ( !isHoliday ) { value -= step; } } } return now; } } } }
JavaScript
class DateNormalizer { /** * @param{string} initialFormat format that date should be parsed for */ constructor( initialFormat = "yyyy-mm-dd" ) { const format = initialFormat.toLowerCase(); const separator = DateNormalizer.extractSeparator( format ); const parts = format.split( separator ); if ( parts.length > 3 ) { throw new Error( "Date format descriptor does not consist of up to three parts." ); } const patterns = {}; const identifiers = parts.map( part => { const _part = part.toLowerCase(); const key = FormatTypeToProperty[_part]; const regExp = { regular: SegmentPatterns[_part], acceptPartial: PartialSegmentPatterns[_part], }; if ( !key || !regExp.regular || !regExp.acceptPartial ) { throw new TypeError( "invalid element in provided format pattern" ); } patterns[key] = regExp; return { regExp, value: part, key, }; } ); const length = identifiers.length; const acceptPartialArray = new Array( length * 2 ); for ( let identifierIndex = 0; identifierIndex < length; identifierIndex++ ) { const partialArray = new Array( identifierIndex + 1 ); for ( let partialIndex = 0; partialIndex <= identifierIndex; partialIndex++ ) { const partialIdentifier = identifiers[partialIndex]; if ( partialIndex < identifierIndex ) { partialArray[partialIndex] = partialIdentifier.regExp.regular.source.slice( 1, -1 ); } else { const writeIndex = identifierIndex * 2; partialArray[partialIndex] = partialIdentifier.regExp.acceptPartial.source.slice( 1, -1 ); acceptPartialArray[writeIndex] = partialArray.join( "\\" + separator ); partialArray[partialIndex] = partialIdentifier.regExp.regular.source.slice( 1, -1 ); acceptPartialArray[writeIndex + 1] = partialArray.join( "\\" + separator ) + "\\" + separator + "?"; } } } patterns.complete = { regular: new RegExp( "^" + identifiers.map( identifier => `(${identifier.regExp.regular.source.replace( "^", "" ).replace( "$", "" )})` ).join( separator ) + "$" ), acceptPartial: new RegExp( "^(" + acceptPartialArray.join( "|" ) + ")$" ), }; this.separator = separator; this.identifiers = identifiers; this.format = format; this.patterns = patterns; } /** * normalizes input that is in the given format to Date * @param{string} input input that obeys the given format * @param{boolean} acceptPartial set true to accept partial input * @param{number} yearBuffer if "yy" is the year format, this is added to current year to decide which century to use * @returns {Date} parsed date */ normalize( input = "", { acceptPartial = false, yearBuffer = 0 } = {} ) { const preparedInput = input; const parts = preparedInput.split( this.separator ); const { complete } = this.patterns; const isValid = complete.acceptPartial.test( preparedInput ); if ( !isValid ) { throw new Error( "invalid input provided" ); } const isParsable = complete.regular.test( preparedInput ); if ( !acceptPartial && !isParsable ) { throw new Error( "input is not complete" ); } const date = new PartialDate(); if ( ( acceptPartial && isValid ) || isParsable ) { const parsed = {}; for ( let index = 0, length = parts.length; index < length; index++ ) { const part = parts[index]; const identifier = this.identifiers[index]; switch ( identifier.key ) { case "day" : parsed.date = Number( part ); break; case "month" : parsed.month = Number( part ) - 1; break; case "year" : switch ( identifier.value ) { case "yy" : { const currentYear = new Date().getFullYear(); const upperLimit = currentYear + yearBuffer; const lastTwoDigits = upperLimit % 100; const century = currentYear - ( currentYear % 100 ); const year = Number( part ); parsed.year = century + year - ( year >= lastTwoDigits ? 100 : 0 ); break; } case "yyyy" : parsed.year = Number( part ); break; default : throw new TypeError( "invalid format detected" ); } break; default : throw new TypeError( "invalid input detected" ); } } if ( parsed.hasOwnProperty( "year" ) ) { date.setFullYear( parsed.year ); } if ( parsed.hasOwnProperty( "month" ) ) { date.setMonth( parsed.month ); } if ( parsed.hasOwnProperty( "date" ) ) { date.setDate( parsed.date ); } } return date; } /** * Extracts the separator from a given format. * * @param{string} format string in the date format * @return {string} separator of the identifier in a date format; */ static extractSeparator( format ) { let separator = false; for ( let index = 0, length = format.length; index < length; index++ ) { const char = format.charAt( index ); if ( !isIdentifier( char ) ) { if ( separator && char !== separator ) { throw new Error( "Date format definition uses multiple different separators." ); } separator = char; } } if ( separator ) { return separator; } throw new Error( "Date format does not contain any separator." ); } }
JavaScript
class DateValidator { /** * Checks if a given date complies with an optional set of conditions. * * @param {DateInput} input date to validate * @param {DateInput} minDate minimal Date * @param {DateInput} maxDate maximal Date * @param {object<int,boolean>} businessDays numeric values of the allowed weekdays * @param {Date[]} holidays numeric values of the allowed weekdays * @returns {FormatCheckResult} validated textual input or list of errors if checking failed */ static validate( input, { minDate = null, maxDate = null, businessDays = null, holidays = null } = {} ) { if ( typeof input !== "string" && !( input instanceof Date ) ) { throw new TypeError( "Input needs to be a Date or a string containing parsable date." ); } const inputDate = new PartialDate( input ); if ( minDate ) { let date = minDate; if ( typeof minDate === "string" ) { date = new Date( date ); } if ( !( date instanceof Date ) ) { throw new TypeError( "minDate needs to be a Date or a parsable dateString" ); } if ( Math.floor( inputDate.getTime() / 8.64e+7 ) < Math.floor( date.getTime() / 8.64e+7 ) ) { throw new Error( "Selected day is beyond earliest permitted day." ); } } if ( maxDate ) { let date = maxDate; if ( typeof maxDate === "string" ) { date = new Date( date ); } if ( !( date instanceof Date ) ) { throw new TypeError( "maxDate needs to be a Date or a parsable dateString" ); } if ( Math.floor( inputDate.getTime() / 8.64e+7 ) > Math.floor( date.getTime() / 8.64e+7 ) ) { throw new Error( "Selected day is beyond latest permitted day." ); } } if ( businessDays && !businessDays[inputDate.getDay()] ) { throw new Error( "Selected day of week is not a business day." ); } if ( holidays ) { for ( let length = holidays.length, index = 0; index < length; index++ ) { if ( inputDate.isSameDay( holidays[index] ) ) { throw new Error( "Selected day is a holiday." ); } } } } /** * validates a single weekday against a selector * @param{Number} weekday the integer presentation of a weekday * @param{Range|Number} selector selector that describes the limit of an allowed weekday * @returns {void} */ static checkWeekday( weekday, selector ) { if ( typeof selector === "string" ) { const range = new Range( selector ); if ( range.isAboveRange( weekday ) || range.isBelowRange( weekday ) ) { throw new Error( "this weekday is not allowed" ); } } if ( typeof selector === "number" ) { if ( selector !== weekday ) { throw new Error( "this weekday is not allowed" ); } } } }
JavaScript
class News extends React.Component { render() { let news = this.props.data.allNews.value let recentNews = this.props.data.recentNews.value let categories = this.props.data.categories.value let category = undefined if(this.props.slug){ category = categories.find(p => p.slug === this.props.slug) } // console.log(categories) return ( <div id="page-width" style={{marginTop: 60}}> <div id="page-section"> <section id="blog"> <div className="container-fluid"> <div className="jumbo-heading"> {/* Heading */} <h1>Trang tin tức của Sunkids</h1> <ul className="breadcrumb"> <li><a href="/">Trang chủ</a> <span className="divider" /></li> <li className="active" style={{color: 'white'}}>Tin tức</li> </ul> </div> {/* /jumbo-heading */} {/* Blog Home */} <div className="container"> <div id="blog-container" className="col-md-9"> {news.map((el, idx) => { return ( <div key={idx} className="blog-post row"> <div className="img-date"> <div className="img-blog"> <a href={"/p/" + el.slug} > <img className="img-responsive" src={el.coverUrl} /> </a> </div> </div> <div className="col-md-12"> {/* Post header */} <h3> <a href={"/p/" + el.slug} >{el.title}</a> </h3> <p> {el.description} </p> <a className="btn" href={"/p/" + el.slug} >Xem thêm <i className="fa fa-angle-right" /></a> </div> </div>) })} </div> {/* /blog-container */} {/* Sidebar Starts */} <div className="sidebar col-md-3"> {/* About Us Widget */} <div className="well"> <h4 className="sidebar-header">Hệ thống Anh Ngữ Quốc Tế Sunkids</h4> <h5 style={{color: 'orange'}}> Education for future </h5> </div> {/* Blog Search */} {/* /well */} <div className="well"> <h4 className="sidebar-header">Tin tức mới nhất</h4> <div className="row"> {recentNews.map((el, idx) => { return ( <div key={idx} className="blog-latest col-xs-12"> <a href={"/p/" + el.slug}> <div className="col-xs-4"> <img src={el.coverUrl} alt className="img-circle img-responsive" /> </div> <div className="col-xs-8"> <span> {el.title} </span> </div> </a> </div> ) })} </div> </div> {/* /well */} {/* Blog Categories */} <div className="well"> <h4 className="sidebar-header">Danh mục</h4> <div className="row"> <ul className="list-unstyled"> {categories.map((el, idx) => { return ( <li key={idx}><a href="#">{el.title}</a></li> ) })} </ul> {/* /ul */} </div> {/* /.row */} </div> {/* /well */} {/* Tags Widget */} <div className="well"> <div className="fb-page" data-href="https://www.facebook.com/sunkidsvietnam/" data-tabs="timeline" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/sunkidsvietnam/" className="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/sunkidsvietnam/">Sunkids Khoái Châu</a></blockquote></div> </div> </div> <div className="text-center col-md-12"> <ul className="pagination"> <li className="active"><a href="#">1</a></li> {/*<li><a href="#">2</a></li>*/} {/*<li><a href="#">3</a></li>*/} {/*<li><a href="#">4</a></li>*/} {/*<li><a href="#">5</a></li>*/} <li><a href="#">»</a></li> </ul> </div> {/* /text-center */} </div> {/* /container*/} </div> {/* /container-fluid*/} </section> {/*Section Blog ends */} </div> {/*/page-section*/} {/* Newsletter */} {/* /Section ends */} {/* Footer starts */} </div> ); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = {videos: [] }; //updates the list of videos with every search using this.state.videos YTSearch({key: API_KEY, term: 'Golden State Warriors'}, (videos) => { this.setState({ videos }); //same name ({videos: videos}) }); } render() { return ( <div> <SearchBar /> <VideoList /> </div> ); } }
JavaScript
class Slider { constructor (element, initial, min, max, changeCallback) { this.value = initial this.min = min this.max = max this.div = element this.innerDiv = document.createElement('div') this.innerDiv.style.position = 'absolute' this.innerDiv.style.height = this.div.offsetHeight + 'px' this.div.appendChild(this.innerDiv) this.changeCallback = changeCallback this.mousePressed = false this.redraw() this.div.addEventListener('mousedown', function (event) { this.mousePressed = true this.onChange(event) }.bind(this)) document.addEventListener('mouseup', function (event) { this.mousePressed = false }.bind(this)) document.addEventListener('mousemove', function (event) { if (this.mousePressed) { this.onChange(event) } }.bind(this)) } redraw () { var fraction = (this.value - this.min) / (this.max - this.min) this.innerDiv.style.width = fraction * this.div.offsetWidth + 'px' this.innerDiv.style.height = this.div.offsetHeight + 'px' } onChange (event) { var mouseX = Utilities.getMousePosition(event, this.div).x this.value = Utilities.clamp((mouseX / this.div.offsetWidth) * (this.max - this.min) + this.min, this.min, this.max) this.redraw() this.changeCallback(this.value) } }
JavaScript
class BaseCoachmarksStore { /** * Return the name for this store's localStorage object. Overriden in child classes. * @return string */ cookieName() { return ''; } /** * Properties to skip during state write/restore. Overriden in child classes * @return string[] */ skipProperties() { return []; } /** * Serialize the store as a JSON object, skipping specified attributes. * @return string */ serialize() { const data = {}; Object.keys(this) .filter(key => key.indexOf('_') === 0 && this[key] !== undefined && !this.skipProperties().includes(key)) .forEach(key => { data[key] = this[key]; }); return JSON.stringify(data); } /** * Deserialize state from JSON object * @param {string} json * @return null */ @action.bound deserialize(json) { try { if (!json) { this.reset(); return; } const data = JSON.parse(json); Object.keys(data) .filter(key => data[key] !== undefined && !this.skipProperties().includes(key)) .forEach(key => this.set(key, data[key], false)); } catch (e) { console.error(e); console.log(json); console.error('reseting'); this.reset(); } } /** * Write current state as JSON to localStorage * @return null */ writeState() { console.log('writeState', this.cookieName()); localStorage.setItem(this.cookieName(), this.serialize()); } /** * Restore stage from localStorage * @return null */ @action.bound restore() { const state = localStorage.getItem(this.cookieName()); this.deserialize(state); } /** * Set some default values for the store, overridden in child classes * @return null */ @action.bound reset() { } /** * Generic setter. Writes state after setting value * @param {string} prop * @param {*} val * @param {boolean} write * @return null */ @action.bound set(prop, val, write = true) { this[prop] = val; if (write) { this.writeState(); } } }
JavaScript
class IP { /** * @constructor */ constructor (address) { this.integer = 0; this.short = 0; this.version = this._checkVersion(address); this.address = this._checkAddress(address, this.version); } // Public methods /** * toInteger - Converts dotquad or hextet IP to integer * @return {BigInt} -> 2130706432 */ toInteger () { let bigInt; if (this.version === 4) { let splittedAddr = this.address.split('.').reverse(); bigInt = splittedAddr.reduce(function (bigInt, octet, index) { return (octet * Math.pow(256, index) + bigInt )}, 0); } else { let joinedAddr = this.address.split(':').join(''); bigInt = BigInt('0x' + joinedAddr); } this.integer = BigInt(bigInt); return BigInt(bigInt); } /** * toDottedNotation - Converts big integer IP to full dotquad or hextet representation * @param {bigint} bigInt * @return {string} -> "184.170.96.196" */ toDottedNotation(bigInt) { if (this.version === 4) { return ( [ (bigInt>>BigInt(24) & BigInt(255)), (bigInt>>BigInt(16) & BigInt(255)), (bigInt>>BigInt(8) & BigInt(255)), (bigInt & BigInt(255)) ].join('.') ); } else { let hex = bigInt.toString(16); let groups = []; while (hex.length < 32) { hex = '0' + hex; } for (let i = 0; i < 8; i++) { groups.push(hex.slice(i * 4, (i + 1) * 4)); } return groups.join(':'); } } /** * toBinary - Converts decimal IP to full-length binary representation. * @return {string} -> 01111111000000000000000000000001 */ toBinary() { if (this.integer === 0) { this.toInteger(); } let binary = this.integer.toString(2); let v = this.version; let marks = { 4: 32, 6: 128 }; if ( binary.length < marks[v] ) { while (binary.length < marks[v]) { binary = '0' + binary; } } return binary; } /** * toHEX - Converts both IP versions to hexadecimal representation. * @return {string} -> 7f000001 */ toHEX() { if (this.integer === 0) { this.toInteger(); } return this.integer.toString(16); } /** * toCompressed - Compress an IP address to its shortest possible form. * IP('127.1.0.0').toCompressed * @return {string} -> "127.1" */ toCompressed(addr, ver) { if (ver === 4) { let splittedAddr = addr.split('.'); let sRange = [[1, 3], [2, 2], [3, 1], [0,0]]; for (let i = splittedAddr.length-1; i>=0; i--) { if (splittedAddr[i] === '0') { continue; } else { splittedAddr.splice(sRange[i][0], sRange[i][1]); this.short = splittedAddr.join('.'); return this.short; } } } else { let splitted = addr.split(':'); // finding longest zero group let [startOfLongest, longestLength] = _longestZerosGroup(splitted); // 'N/A' - _longestZerosGroup fn return in case if there is NO // '0000' blocks in address if (startOfLongest !== 'N/A' || longestLength !== 'N/A') { splitted.splice(startOfLongest, longestLength, ''); if (startOfLongest === 0) { splitted.unshift(''); } if (startOfLongest + longestLength === 8) { splitted.push(''); } } // removing single '0000' blocks and leading zeros for (let i = 0; i < splitted.length; i++) { if (splitted[i] === '0000') { splitted.splice(i, 1, '0'); } loopStr: for (let j = 0; j < splitted[i].length; j++) { if (splitted[i][j] === '0' && splitted[i] !== '0') { splitted[i] = splitted[i].substring(j+1); j--; continue; } else { break loopStr; } } } this.short = splitted.join(':'); return this.short; } } // Private methods /** * checkVersion - Determins this IP version. * @private * @param {string} addr * @return {number} -> 4 or 6 */ _checkVersion (addr) { //matches all possible chars in both versions of IP const reGen = /^[0-9a-f.:]+$/i; if ( reGen.test(addr) ) { //checks if there is .. and more or whole IP is just a dot const reDots = /\.{2,}|^\.{1}$/; //checks if there is ::: and more or whole IP is just a colon const reColon = /:{3,}|^:{1}$/; //checks if there is only digits in integer IP const reNum = /^[0-9]+$/; if ( reNum.test(addr) ) { addr = BigInt(addr); if (addr > IPv6MAX || addr <= 0) { throw new Error('Tips: IP address cant be bigger than 2 to the 128-th power or negative number'); } else if (addr <= IPv4MAX) { return 4; } else if (addr > IPv4MAX) { return 6; } } else if ( addr.includes('.') && !reDots.test(addr) ) { return 4; } else if ( addr.includes(':') && !reColon.test(addr) ) { return 6; } } throw new Error('Tips: Please, enter a valid IP address (Like "127.1.0.0", long integer, short or long IPv6)'); } /** * checkAddress - Validates this IP address. * @private * @return {string} as a valid address */ _checkAddress (addr, v) { const reNum = /^[0-9]+$/; if ( reNum.test(addr) ) { this.integer = BigInt(addr); return this.toDottedNotation(this.integer); } const marks = { 4: ['.', this._isIPv4, 4], 6: [':', this._isIPv6, 8] }; let splittedAddr = addr.split( marks[v][0] ); if (v === 6 && splittedAddr.length < 8) { let dbColon = (addr.match(/::/g)||[]).length; if (dbColon !== 1) { throw new Error('Tips: Please, enter a valid IP address (Like "127.1.0.0", long integer, short or long IPv6)'); } } if ( marks[v][1].call(this, splittedAddr) ) { //TODO: make ifs more readable if (splittedAddr.length === marks[v][2] && this.short === 0) { return addr; } else { return this._toRepresentation(splittedAddr); } } else { throw new Error('Tips: Please, enter a valid IP address (Like "127.1.0.0", long integer, short or long IPv6)'); } } /** * _isIPv6 - Validates IPv6. * @private * @return {boolean} whether splitted address is valid IPv6 or not */ _isIPv6 (splittedAddr) { if (splittedAddr.length <= 8) { let checked = false; let [isShort, cleanedAddr] = this._isShort(splittedAddr); const regex = /^[0-9a-f]{1,4}$/i; const isValid = function (hextet) { return regex.test(hextet); }; checked = cleanedAddr.every(isValid); if (checked && isShort) { this.short = splittedAddr.join(':');} return checked; } else { throw new Error('Tips: IPv6 cannot contain more than 8 bytes'); } } /** * _isIPv4 - Validates IPv4. * @private * @return {boolean} whether splitted address is valid IPv4 or not */ _isIPv4 (splittedAddr) { if (splittedAddr.length <= 4) { if (splittedAddr.length < 4) { this.short = splittedAddr.join('.');} const isValid = function (octet) { return ( (octet <= 255 && octet >= 0) ? true : false ); }; return splittedAddr.every(isValid); } else { throw new Error('Tips: IPv4 cannot contain more than 4 bytes'); } } /** * _isShort - checks if IPv6 addres was compressed like this "234:f:34:34:1:1:2:2" or like "1234::1234:1234" and removes empty strings for future validation * @private * @param {array} splittedAddr * @return {array} with both results boolean and cleaned array */ _isShort (splittedAddr) { let isShort = false; let cleanedAddr = [...splittedAddr]; for (let i=0; i < cleanedAddr.length; i++) { if (cleanedAddr[i].length === 0) { cleanedAddr.splice(i, 1); isShort = true; i--; //code chunk similar to toCompressed method // for addr '::1' can happen that there are 2 empty strings // together, so by i-- we check every el of array but not next but one } else if (cleanedAddr[i].length < 4) { isShort = true; } } return [isShort, cleanedAddr]; } /** * toRepresentation - Converts short version to canonical representation of IP. * IP('::1').address * @private * @param {array} splittedAddr * @return {string} -> "0000:0000:0000:0000:0000:0000:0000:0001" */ _toRepresentation(splittedAddr) { if ( this.version === 4 ) { for (let i = 0; i <= 4; i++) { if (splittedAddr[i] === '') { let missOcts = 5 - splittedAddr.length; let flag = true; while (missOcts > 0) { if (flag) { splittedAddr.splice(i, 1, '0'); missOcts--; flag = false; } else { splittedAddr.splice(i, 0, '0'); missOcts--; } } } } while (splittedAddr.length < 4) { splittedAddr.push('0'); } return splittedAddr.join('.'); } else { for (let i = 0; i <= 8; i++) { if (splittedAddr[i] === '') { let missHex = 9 - splittedAddr.length; let flag = true; while (missHex > 0) { if (flag) { splittedAddr.splice(i, 1, '0000'); missHex--; flag = false; } else { splittedAddr.splice(i, 0, '0000'); missHex--; } } } } for (let i = 0; i < splittedAddr.length; i++) { if (splittedAddr[i].length < 4) { let missNum = 4 - splittedAddr[i].length; while (missNum > 0) { splittedAddr[i] = '0' + splittedAddr[i]; missNum--; } } } } return splittedAddr.join(':'); } }//IP class end
JavaScript
class EventModal extends React.PureComponent { state = { title: this.props.title || "", startDate: this.props.startDate, startTime: this.props.startTime, endDate: this.props.endDate, endTime: this.props.endTime, message: this.props.message, id: this.props.id, titleErrorMessage: "" }; /** * * onValueChanged * @param {string} field * @param {string} value */ onValueChanged = (field, value) => { if (field && value) { this.setState({ [field]: value }); } }; /** * * onButtonClicked * @param {object} e * @param {string} type */ onButtonClicked = (e, type = this.props.type) => { if (!this.state.title.length) { this.setState({ titleErrorMessage: "Please fill title." }); } else { this.setState({ titleErrorMessage: "" }); this.props.onAction(e, type, this.state); } }; render() { const { timeslots, type, onHide } = this.props; const actions = [ <Button raised onClick={onHide}> Cancel </Button>, <Button raised primary onClick={this.onButtonClicked}> {constants[type].buttonText || "save"} </Button> ]; if (type === "EDIT") { actions.splice( 1, 0, <Button tooltipLabel="Remove from calendar" tooltipPosition="top" className="event-delete" raised primary iconEl={ <i icon className="md-icon material-icons"> delete </i> } onClick={e => this.onButtonClicked(e, "DELETE")} > Delete </Button> ); } return ( <DialogContainer id="simple-list-page-dialog" visible={true} fullPage={false} onHide={onHide} width={"40%"} aria-labelledby="simple-full-page-dialog-title" actions={actions} > <Toolbar fixed colored title={constants[type].dialogTitle || "Title"} titleId="simple-full-page-dialog-title" actions={ <span title="Close" className="icon cancel" onClick={onHide}> cancel </span> } /> <section className="md-toolbar-relative"> <TextField id="floating-center-title" label="Title" lineDirection="center" placeholder="Enter Title" defaultValue={this.state.title} error={this.state.titleErrorMessage.length ? true : false} errorText={this.state.titleErrorMessage} onChange={e => { this.onValueChanged("title", e); }} /> <div className="md-grid events-field-grid"> <DatePicker id="show-all-days" label="From" defaultValue={this.state.startDate} displayMode="portrait" firstDayOfWeek={1} autoOk onChange={(e, obj) => { this.onValueChanged("startDate", obj); }} /> <SelectField id="floating-start-time" label=" " menuItems={timeslots} defaultValue={this.state.startTime} onChange={e => { this.onValueChanged("startTime", e); }} /> </div> <div className="md-grid events-field-grid"> <DatePicker id="show-all-days" label="To" defaultValue={this.state.endDate} displayMode="portrait" firstDayOfWeek={1} autoOk onChange={(e, obj) => { this.onValueChanged("endDate", obj); }} /> <SelectField id="floating-start-time" label=" " menuItems={timeslots} defaultValue={this.state.endTime} onChange={e => { this.onValueChanged("endTime", e); }} /> </div> <TextField id="email-body" label="Message" placeholder="Enter..." rows={4} paddedBlock maxLength={160} defaultValue={this.state.message} errorText="Max 160 characters." onChange={e => { this.onValueChanged("message", e); }} /> </section> </DialogContainer> ); } }
JavaScript
class GetFileByParameterMiddleware extends ParameterMiddleware { /** * @override * @inheritDoc */ async handler(req, res, next, id) { try { let file = await File.findOne({_id: id}); req.fil3 = file; // req.file is used by multer if (file) { next(); } else { next(new Error("No file is found.")); } } catch (e) { next(e); } } }
JavaScript
class Timer { /** * Sets a timer with the specified delay and callback function. * * @param {Number} time the time in milliseconds * @param {Function} callback the function to call */ constructor (time, callback) { this.time = time; this.callback = callback; } update(ticks) { if (ticks >= this.time) { this.callback; console.log("Time working"); } } }
JavaScript
class TrainingAPI { fetchTrainings() { return Promise.resolve(trainingsMockData); } }
JavaScript
class ValidationError extends Error { /** * @param {String} message custom message * @param {Object} errors error messages * @param {String} errors.attributePath error for particular field * @param {String} errors.attributePath.message human readible message * @param {String} errors.attributePath.kind string type (i.e. required) */ constructor(message, errors) { super(message) this.errors = errors this.message = message || 'Resource cannot be stored because of validation errors' this.name = 'ValidationError' } }
JavaScript
class DString { /** * Creates a new dstring */ constructor() { console.warn("Warning: This feature is experimental and may be removed in the future"); }; }
JavaScript
class VertexLayout { // Attribs are an array, in layout order, of: name, size, type, normalized // ex: { name: 'position', size: 3, type: gl.FLOAT, normalized: false } constructor (attribs) { this.attribs = attribs; // dictionary of attributes, specified as standard GL attrib options this.components = []; // list of type and offset info about each attribute component this.index = {}; // linear buffer index of each attribute component, e.g. this.index.position.x // Calc vertex stride this.stride = 0; var count = 0; for (var attrib of this.attribs) { attrib.offset = this.stride; attrib.byte_size = attrib.size; var shift = 0; switch (attrib.type) { case gl.FLOAT: case gl.INT: case gl.UNSIGNED_INT: attrib.byte_size *= 4; shift = 2; break; case gl.SHORT: case gl.UNSIGNED_SHORT: attrib.byte_size *= 2; shift = 1; break; } // Force 4-byte alignment on attributes this.stride += attrib.byte_size; if (this.stride & 3) { // pad to multiple of 4 bytes this.stride += 4 - (this.stride & 3); } // Add info to list of attribute components // Used to build the vertex data, provides pointers and offsets into each typed array view // Each component is an array of: // [GL attrib type, pointer to typed array view, bits to shift right to determine buffer offset, additional buffer offset for the component] var offset_typed = attrib.offset >> shift; if (attrib.size > 1) { for (var a=0; a < attrib.size; a++) { this.components.push([attrib.type, null, shift, offset_typed++]); } } else { this.components.push([attrib.type, null, shift, offset_typed]); } // Provide an index into the vertex data buffer for each attribute component this.index[attrib.name] = count; count += attrib.size; } } // Setup a vertex layout for a specific GL program // Assumes that the desired vertex buffer (VBO) is already bound // If a given program doesn't include all attributes, it can still use the vertex layout // to read those attribs that it does recognize, using the attrib offsets to skip others. enable (gl, program, force) { var attrib, location; // Enable all attributes for this layout for (var a=0; a < this.attribs.length; a++) { attrib = this.attribs[a]; location = program.attribute(attrib.name).location; if (location !== -1) { if (!VertexLayout.enabled_attribs[location] || force) { gl.enableVertexAttribArray(location); } gl.vertexAttribPointer(location, attrib.size, attrib.type, attrib.normalized, this.stride, attrib.offset); VertexLayout.enabled_attribs[location] = program; } } // Disable any previously bound attributes that aren't for this layout for (location in VertexLayout.enabled_attribs) { this.disableUnusedAttribute(gl, location, program); } } // Disable an attribute if it was not enabled for the specified program // NOTE: this was moved out of the inner loop in enable() to assist w/VM optimization disableUnusedAttribute (gl, location, program) { if (VertexLayout.enabled_attribs[location] !== program) { gl.disableVertexAttribArray(location); delete VertexLayout.enabled_attribs[location]; } } createVertexData () { return new VertexData(this); } }
JavaScript
class Mapcreator extends mix(EventEmitter, Injectable) { /** * @param {OAuth|string} auth - Authentication flow * @param {string} host - Remote API host */ constructor (auth = new DummyFlow(), host = process.env.HOST) { super(); if (typeof auth === 'string') { const token = auth; auth = new DummyFlow(); auth.token = new OAuthToken(token, 'Bearer', new Date('2100-01-01T01:00:00'), ['*']); } this.auth = auth; this.host = host; this._logger = new Logger(process.env.LOG_LEVEL); this.wrapKy(wrapKyCancelable); this.wrapKy(wrapKyPrefixUrl, `${this.host}/${this.version}`); } /** * Get api version * @returns {string} - Api version * @constant */ get version () { return 'v1'; } /** * Get authentication provider instance * @returns {OAuth} - OAuth instance */ get auth () { return this._auth; } /** * Get logger instance * @returns {Logger} - Logger instance */ get logger () { return this._logger; } /** * Set authentication provider instance * @param {OAuth} value -- OAuth instance */ set auth (value) { if (!isParentOf(OAuth, value)) { throw new TypeError('auth must be an instance of OAuth'); } this._auth = value; } /** * Test if the client is authenticated with the api and has a valid token * @returns {boolean} - If the client is authenticated with the api */ get authenticated () { return this.auth.authenticated; } /** * The current host * @returns {string} - The current host */ get host () { return this._host; } /** * The remote host * @param {string} value - A valid url */ set host (value) { value = value.replace(/\/+$/, ''); this._host = value; this.auth.host = value; } get url () { return `${this.host}/${this.version}`; } /** * Saves the session token so that it can be recovered at a later time. The wrapper can * find the token most of the time if the name parameter is left blank. * @param {string?} name - name of the token */ saveToken (name) { this.auth.token.save(name); } /** * Authenticate with the api using the authentication method provided. * @returns {Promise<Mapcreator>} - Current instance * @throws {OAuthError} * @throws {ApiError} - If the api returns errors */ async authenticate () { await this.auth.authenticate(); return this; } /** * Mapcreator ky instance * This ky instance takes care of the API communication. It has the following responsibilities: * - Send authenticated requests to the API * - Transform errors returned from the API into ApiError and ValidationError if possible * - Wait when the rate limiter responds with a 429 and retry later * - Prefix urls with the api domain if needed * @returns {function} * @see {@link https://github.com/sindresorhus/ky} */ get ky () { if (this._ky) { return this._ky; } const hooks = { beforeRequest: [ request => { if (this.authenticated) { request.headers.set('Authorization', this.auth.token.toString()); } }, ], afterResponse: [ // 429 response async (request, _options, response) => { if (response.status !== 429) { return response; } const resetDelay = (response.headers.get('x-ratelimit-reset') * 1000) || 500; await delay(resetDelay); return this._ky(request); }, // transform errors async (request, options, response) => { if (response.status < 400 || response.status >= 600) { return response; } const data = await response.json(); const params = { data, request, options, response }; if (data.error['validation_errors']) { throw new ValidationError(params); } const error = new ApiError(params); if (error.type === 'AuthenticationException') { /** * Critical api errors (AuthenticationException) * * @event Mapcreator#error * @type {ApiError} */ this.emit('error', error); } throw error; }, ], }; this._ky = ky.create({ timeout: 30000, // 30 seconds // throwHttpErrors: false, // This is done through a custom hook // redirect: 'error', retry: 0, headers: { 'Accept': 'application/json', 'X-No-CDN-Redirect': 'true', }, hooks, }); return this._ky; } wrapKy (wrapper, ...args) { this._ky = wrapper(this.ky, ...args); const requestMethods = [ 'get', 'post', 'put', 'patch', 'head', 'delete', ]; for (const method of requestMethods) { this._ky[method] = (input, options) => this._ky(input, { ...options, method }); } } /** * Static proxy generation * @param {string|Class} Target - Constructor or url * @param {Class?} Constructor - Constructor for a resource that the results should be cast to * @returns {ResourceProxy} - A proxy for accessing the resource * @example * api.static('/custom/resource/path/{id}/').get(123); * * @example * class FooBar extends ResourceBase { * static get resourceName() { * return 'custom'; * } * } * * api.static(FooBar) * .get(1) * .then(console.log); * * api.static('/foo-bar-custom', FooBar).lister(); */ static (Target, Constructor = ResourceBase) { if (typeof Target === 'string') { const path = Target; const name = Constructor.name || 'AnonymousResource'; Target = class AnonymousResource extends Constructor { static get resourceName () { return Object.getPrototypeOf(this).resourceName || 'anonymous'; } static get resourcePath () { return path; } }; Object.defineProperty(Target, 'name', { value: `${name}_${fnv32b(path)}`, }); } if (isParentOf(ResourceBase, Target)) { return new ResourceProxy(this, Target); } throw new TypeError('Expected Target to be of type string and Constructor to be a ResourceBase constructor'); } /** * Choropleth accessor * @see {@link Choropleth} * @returns {GeoResourceProxy} - A proxy for accessing the resource */ get choropleths () { return new GeoResourceProxy(this, Choropleth); } /** * VectorChoropleth accessor * @see {@link VectorChoropleth} * @returns {GeoResourceProxy} - A proxy for accessing the resource */ get vectorChoropleths () { return new GeoResourceProxy(this, VectorChoropleth); } /** * Color accessor * @see {@link Color} * @returns {ResourceProxy} - A proxy for accessing the resource */ get colors () { return this.static(Color); } /** * Tag accessor * @see {@link Tag} * @returns {ResourceProxy} - A proxy for accessing the resource */ get tags () { return this.static(Tag); } /** * Tag accessor * @see {@link Tag} * @returns {ResourceProxy} - A proxy for accessing the resource */ get tagTypes () { return this.static(TagType); } /** * Contract accessor * @see {@link Contract} * @returns {ResourceProxy} - A proxy for accessing the resource */ get contracts () { return this.static(Contract); } /** * Dimension accessor * @see {@link Dimension} * @returns {ResourceProxy} - A proxy for accessing the resource */ get dimensions () { return this.static(Dimension); } /** * Dimension set accessor * @see {@link DimensionSet} * @returns {ResourceProxy} - A proxy for accessing the resource */ get dimensionSets () { return this.static(DimensionSet); } /** * Faq accessor * @see {@link Faq} * @returns {ResourceProxy} - A proxy for accessing the resource */ get faqs () { return this.static(Faq); } /** * Feature accessor * @see {@link Feature} * @returns {ResourceProxy} - A proxy for accessing the resource */ get features () { return this.static(Feature); } /** * Featured jobs accessor * @see {@link Job} * @returns {SimpleResourceProxy} - A proxy for accessing the resource */ get featuredMaps () { return new SimpleResourceProxy(this, Job, '/jobs/featured'); } /** * Font accessor * @see {@link Font} * @returns {ResourceProxy} - A proxy for accessing the resource */ get fonts () { return this.static(Font); } /** * FontFamily accessor * @see {@link FontFamily} * @returns {ResourceProxy} - A proxy for accessing the resource */ get fontFamilies () { return this.static(FontFamily); } /** * Highlight accessor * @see {@link Highlight} * @returns {GeoResourceProxy} - A proxy for accessing the resource */ get highlights () { return new GeoResourceProxy(this, Highlight); } /** * VectorHighlight accessor * @see {@link VectorHighlight} * @returns {GeoResourceProxy} - A proxy for accessing the resource */ get vectorHighlights () { return new GeoResourceProxy(this, VectorHighlight); } /** * InsetMap accessor * @see {@link InsetMap} * @returns {GeoResourceProxy} - A proxy for accessing the resource */ get insetMaps () { return new GeoResourceProxy(this, InsetMap); } /** * Job accessor * @see {@link Job} * @returns {ResourceProxy} - A proxy for accessing the resource */ get jobs () { return this.static(Job); } /** * JobShare accessor * @see {@link JobShare} * @returns {ResourceProxy} - A proxy for accessing the resource */ get jobShares () { return this.static(JobShare); } /** * JobType accessor * @see {@link JobType} * @returns {ResourceProxy} - A proxy for accessing the resource */ get jobTypes () { return this.static(JobType); } /** * Language accessor * @see {@link Language} * @returns {ResourceProxy} - A proxy for accessing the resource */ get languages () { return this.static(Language); } /** * Layer accessor * @see {@link Layer} * @returns {ResourceProxy} - A proxy for accessing the resource */ get layers () { return this.static(Layer); } /** * Mapstyle accessor * @see {@link Mapstyle} * @returns {ResourceProxy} - A proxy for accessing the resource */ get mapstyles () { return this.static(Mapstyle); } /** * MapstyleSet accessor * @see {@link MapstyleSet} * @returns {ResourceProxy} - A proxy for accessing the resource */ get mapstyleSets () { return this.static(MapstyleSet); } /** * Notification accessor * @see {@link Notification} * @returns {ResourceProxy} - A proxy for accessing the resource */ get notifications () { return this.static(Notification); } /** * Organisation accessor * @see {@link Organisation} * @returns {ResourceProxy} - A proxy for accessing the resource */ get organisations () { return this.static(Organisation); } /** * Permission accessor * @see {@link Permission} * @returns {ResourceProxy} - A proxy for accessing the resource */ get permissions () { return this.static(Permission); } /** * Role accessor * @see {@link Role} * @returns {ResourceProxy} - A proxy for accessing the resource */ get roles () { return this.static(Role); } /** * Svg accessor * @see {@link Svg} * @returns {ResourceProxy} - A proxy for accessing the resource */ get svgs () { return this.static(Svg); } /** * SvgSet accessor * @see {@link SvgSet} * @returns {ResourceProxy} - A proxy for accessing the resource */ get svgSets () { return this.static(SvgSet); } /** * User accessor * @see {@link User} * @returns {ResourceProxy} - A proxy for accessing the resource */ get users () { return this.static(User); } /** * Get SVG set types * @see {@link SvgSet} * @returns {CancelablePromise<Enum>} - Contains all the possible SVG set types * @throws {ApiError} - If the api returns errors */ getSvgSetTypes () { return makeCancelable(async signal => { const { data } = await this.ky.get('svgs/sets/types', { signal }).json(); return new Enum(data, true); }); } /** * Get font styles * @see {@link Font} * @returns {CancelablePromise<Enum>} - Contains all the possible font styles * @throws {ApiError} - If the api returns errors */ getFontStyles () { return makeCancelable(async signal => { const { data } = await this.ky.get('fonts/styles', { signal }).json(); return new Enum(data, true); }); } /** * Forget the current session * This will clean up any stored OAuth states stored using {@link StateContainer} and any OAuth tokens stored * @returns {CancelablePromise} * @throws {ApiError} - If the api returns errors */ logout () { return this.auth.logout(); } }
JavaScript
class WorkflowForm extends Form { constructor(workflow) { super('Workflow', workflow); this._init(workflow); } _init() { this._initPackageFormatList(); this._initBagItProfileList(); this._initStorageServiceList(); } _initPackageFormatList() { let formats = [ { id: 'None', name: 'None' }, { id: 'BagIt', name: 'BagIt' } ]; for (let writer of PluginManager.getModuleCollection('FormatWriter')) { let description = writer.description(); for (let format of description.writesFormats) { formats.push({ id: description.id, name: format }); }; } this.fields['packageFormat'].choices = Choice.makeList( formats, this.obj.packageFormat, false ); } _initBagItProfileList() { var profiles = BagItProfile.list(null, { limit: 0, offset: 0, orderBy: 'name', sortDirection: 'asc' }); this.fields['bagItProfileId'].choices = Choice.makeList( profiles, this.obj.bagItProfileId, true ); this.fields['bagItProfileId'].help = Context.y18n.__('JobPackageOp_bagItProfileId_help'); } _initStorageServiceList() { let listOptions = { orderBy: 'name', sortDirection: 'asc' } let filterFn = function(ss) { return ss.allowsUpload }; this.fields['storageServiceIds'].choices = Choice.makeList( StorageService.list(filterFn, listOptions), this.obj.storageServiceIds, false ); } parseFromDOM() { super.parseFromDOM(); let selectedPluginId = this.obj.packageFormat; let formatName = $('#workflowForm_packageFormat option:selected').text(); this.obj.packagePluginId = selectedPluginId; if (formatName) { this.obj.packageFormat = formatName.trim(); } } }
JavaScript
class KnockOffWander extends KnockOff { constructor(game, resources) { super(game, resources); // Constants for how far the circle's center can move this.xleft = -100; this.xright = 100; this.yup = -25; this.ydown = 25; // Move everything to the up right corner this.arenaGraphic.x = -100; this.arenaGraphic.y = -25; this.moveHelperX = true; this.moveHelperY = false; } // Called before the game objects are updated. preUpdate(dt) { super.preUpdate(dt); if (this.moveHelperX && !this.moveHelperY) { // Move right this.moveRight(dt * moveSpeed); } else if (!this.moveHelperX && !this.moveHelperY) { // Move Down this.moveDown(dt * moveSpeed); } else if (!this.moveHelperX && this.moveHelperY) { // Move Left this.moveLeft(dt * moveSpeed); } else if (this.moveHelperX && this.moveHelperY) { // Move up this.moveUp(dt * moveSpeed); } } // X == true && Y == false moveRight(dt) { if (this.arenaGraphic.x + dt > this.xright) { this.moveHelperX = false; } else { this.arenaGraphic.x += dt; } } // X == false && Y == false moveDown(dt) { if (this.arenaGraphic.y + dt > this.ydown) { this.moveHelperY = true; } else { this.arenaGraphic.y += dt; } } // X == false && Y == true moveLeft(dt) { if (this.arenaGraphic.x - dt < this.xleft) { this.moveHelperX = true; } else { this.arenaGraphic.x -= dt; } } // X == true && Y == true moveUp(dt) { if (this.arenaGraphic.y - dt < this.yup) { this.moveHelperY = false; } else { this.arenaGraphic.y -= dt; } } // eslint-disable-next-line onWindowResize() { this.xright = this.game.gameStageWidth * 0.5 - this.arenaRadius; this.xleft = -this.xright; } }
JavaScript
class QuestionnaireItemMediaVideoRepeatable extends QuestionnaireItemMediaVideo { /** @param {string} [className] CSS class @param {string} [question] @param {boolean} [required=false] @param {string|array<string>} url The URL of the media element to be loaded; if supported by the browser also data URI. @param {boolean} required Element must report ready before continue. @param {boolean} [readyOnError=true] Sets ready=true if an error occures. @param {string} buttonCaption The string shown in the replay button. */ constructor(className, question, required, url, readyOnError, buttonCaption) { super(className, question, required, url, readyOnError); this.buttonCaption = buttonCaption; } _createAnswerNode() { const answerNode = super._createAnswerNode(); var div = document.createElement("div"); var button = document.createElement("button"); button.innerHTML = this.buttonCaption; button.onclick = () => this._onReplayClick(); div.appendChild(button); answerNode.appendChild(div); return answerNode; } _onReplayClick() { this.replay(); } }
JavaScript
class ElementTemplates extends DefaultElementTemplates { constructor() { super(); this._templates = {}; } /** * Get template with given ID and optional version or for element. * * @param {String|djs.model.Base} id * @param {number} [version] * * @return {ElementTemplate} */ get(id, version) { const templates = this._templates; let element; if (isUndefined(id)) { return null; } else if (isString(id)) { if (isUndefined(version)) { version = '_'; } if (templates[ id ] && templates[ id ][ version ]) { return templates[ id ][ version ]; } else { return null; } } else { element = id; return this.get(getTemplateId(element), getTemplateVersion(element)); } } }
JavaScript
class RpBadge extends LitElement { static get properties() { return { size: {type: String}, href: {type: String}, maxWidth: {type: Number, attribute: 'max-width'}, ellipsis: {type: Boolean}, colorSequence: {type: Number, attribute: 'color-sequence'}, hideFromTab: {type: Boolean} }; } constructor() { super(); this.maxColor = 6; this.href = ""; this.maxWidth = 0; this.ellipsis = false; this.hideFromTab = false; this.render = render.bind(this); } /** * @method _constructClasses * @description Makes a class map object based on element properties/attributes. * Classes are applied to the element. * * @returns {Object} - {class1: true, class2: false} */ _constructClasses() { let classes = {'main': true}; if (this.size) { classes['size-' + this.size] = true; } if (this.colorSequence) { let n = Math.floor(this.colorSequence); classes['color-' + n.toString()] = true; } else if ( this.ellipsis ) { classes['ellipsis'] = true; } else { let siblings = [...this.parentNode.childNodes].filter(n => n.tagName === this.tagName); if (siblings.length > 0) { let n = siblings.indexOf(this) % this.maxColor; classes['color-' + n.toString()] = true; } else { classes['color-0'] = true; } } if (this.maxWidth > 0) classes['has-max-width'] = true; return classes; } /** * @method _constructStyles * @description Constructs CSS styles based on element properties * * @returns {Object} */ _constructStyles(){ let styles = {}; if (this.maxWidth > 0) styles['max-width'] = `${this.maxWidth}px`; return styles; } /** * @method _renderBadge * @description Renders badge as a link or not. * * @returns {TemplateResult} */ _renderBadge() { if (this.href) { return html` <a style="color:inherit;" tabindex="${this.hideFromTab ? "-1": "0"}" href=${this.href}> ${this._renderSpan()} </a>`; } return html`<a style="color:inherit;" tabindex="${this.hideFromTab ? "-1": "0"}" @keyup="${this._onKeyUp}"> ${this._renderSpan()} </a>`; } /** * @method _onKeyUp * @description fake click events on keyup in no href * * @param {*} e * @returns */ _onKeyUp(e) { if( e.which !== 13 ) return; this.dispatchEvent(new CustomEvent('click')); } /** * @method _renderSpan * @description Renders the badge content * * @returns {TemplateResult} */ _renderSpan() { return html`<span class=${classMap(this._constructClasses())} style=${styleMap(this._constructStyles())}> ${this.ellipsis ? html` <iron-icon icon="more-horiz"></iron-icon> <span class="sr-only">See more subjects</span> ` : html`<slot></slot>`} </span>`; } }
JavaScript
class Listar extends React.Component { state = { list: [] } ListUser = async()=>{ var list= await UserService.getListUser() this.setState({list}) } async componentDidMount () { await this.ListUser(); } render(){ return( <div> <div> <h3>Lista de usuarios </h3> <div> {this.state.list.map((user) => ( <li key={user.guid}> { user.name } - { user.lastName } </li> ))} </div> </div> </div> ) } }
JavaScript
class Reports { constructor() { this.common = new daoCommon(); } /** * Updates the given entity in the database * @params Employee * @return true if the entity has been updated, false if not found and not updated */ async getUsersInAndOut() { let sqlRequest = ` SELECT * FROM ( -- logged out SELECT e.*, 1 AS is_logged_out, COALESCE(r.description, 'UNKNOWN') as reason_description, r.work as work_related_reason FROM ( SELECT DISTINCT(c.employee_id), c.id, c.reason_id, max(c.clock_out) FROM clocking c WHERE c.clock_out IS NOT NULL GROUP BY c.employee_id ) logged_out INNER JOIN employee e ON e.id = logged_out.employee_id LEFT JOIN reason r ON r.id = logged_out.reason_id WHERE logged_out.employee_id NOT IN ( SELECT DISTINCT(c.employee_id) FROM clocking c WHERE c.clock_out IS NULL ) AND e.active = 1 UNION -- logged in SELECT e.*, 0 AS is_logged_out, '' as reason_description, 0 as work_related_reason FROM ( SELECT DISTINCT(c.employee_id), c.id, max(c.clock_in) FROM clocking c WHERE c.clock_out IS NULL GROUP BY c.employee_id ) logged_in INNER JOIN employee e ON e.id = logged_in.employee_id WHERE e.active = 1 ) ORDER BY is_logged_out DESC `; const rows = await this.common.findAll(sqlRequest); let employees = []; for (const row of rows) { employees.push(row); } return employees; } fetchReportCalendars(empIds, end) { let filterByEmp = ""; if (empIds.length) { filterByEmp = "AND employee_id IN ($empIds)"; } let sqlRequest = ` SELECT c.id ,c.name ,ct.startWeek ,ct.startDay ,ct.startTime ,ct.endDay ,ct.endTime FROM calender c INNER JOIN calender_times ct ON ct.calender_id = c.id WHERE c.id IN ( SELECT DISTINCT calender_id FROM employee_calender WHERE active_date <= $end ${filterByEmp} ) ORDER BY c.id, ct.startWeek, ct.startDay, ct.startTime ; `; let sqlParams = { $end: end }; if (empIds.length) { sqlParams["$empIds"] = empIds; } return this.common.findMany(sqlRequest, sqlParams); } fetchReportEmployeeCalendars(end, empIds, calIds) { let filterByEmp = ""; let filterByCal = ""; if (empIds.length) { filterByEmp = "AND ec.employee_id IN ($empIds)"; } if (empIds.length) { calIds = "AND ec.calender_id IN ($calIds)"; } let sqlRequest = ` SELECT * FROM employee_calender ec WHERE ec.active_date <= $end ${filterByEmp} ${filterByCal} ORDER BY ec.employee_id, ec.active_date ; `; let sqlParams = { $end: end }; if (empIds.length) { sqlParams["$empIds"] = empIds; } if (calIds.length) { sqlParams["$calIds"] = calIds; } return this.common.findMany(sqlRequest, sqlParams); } fetchReportEmployeeTimes(start, end, empIds) { let filterByEmp = ""; if (empIds.length) { filterByEmp = "AND e.id IN ($empIds)"; } let sqlRequest = ` SELECT e.id employee_id , e.name employee_name , c.clock_in , c.clock_out , r.description reason_description , r.work work_related FROM clocking c INNER JOIN employee e ON e.id = c.employee_id ${filterByEmp} LEFT JOIN reason r ON r.id = c.reason_id WHERE c.clock_in <= $end AND (CASE WHEN c.clock_out IS NULL THEN 1 ELSE c.clock_out END >= $start) ORDER BY e.id, c.clock_in ; `; let sqlParams = { $start: start, $end: end }; if (empIds.length) { sqlParams["$empIds"] = empIds; } return this.common.findMany(sqlRequest, sqlParams); } }
JavaScript
class Boat { constructor(x, y, size, rotated = false) { this.positions = []; for (let i = 0; i < size; i++) { const container = document.getElementById("grid-square-" + x + "-" + y); svgrect(container, 0, 0, rect_width, rect_height, "grid-boat"); if (!rotated) { x++; } else { y++; } } } }
JavaScript
class ClusterDetailStore extends Store { constructor(...args) { super(...args); this.defaultStatus = [ 'active', 'stopped', 'ceased', 'pending', 'suspended' ]; this.defineObservables(function () { this.currentPage = 1; this.isLoading = false; this.cluster = {}; // vmbase this.clusterNodes = []; // helm this.helmClusterNodes = []; this.clusterJobs = []; this.extendedRowKeys = []; this.nodeType = ''; this.selectedNodeKeys = []; this.selectedNodeIds = []; this.selectedNodeRole = ''; this.currentNodePage = 1; this.totalNodeCount = 0; this.searchNode = ''; this.selectNodeStatus = ''; this.env = ''; // json string for current cluster env this.changedEnv = ''; // string for changed env }); } get clusterStore() { return this.getStore('cluster'); } get describeActionName() { // developer query user instances relatived runtiems if (this.clusterStore.onlyView) { return 'clusters'; } return this.getUser().isUserPortal ? 'clusters' : 'debug_clusters'; } @action fetch = async clusterId => { this.isLoading = true; const result = await this.request.get(this.describeActionName, { with_detail: true, cluster_id: clusterId }); this.cluster = _.get(result, 'cluster_set[0]', {}); this.env = this.cluster.env || ''; this.isLoading = false; }; @action fetchNodes = async (params = {}) => { this.isLoading = true; params = this.normalizeParams(params); if (this.searchNode) { params.search_word = this.searchNode; } if (!params.status) { params.status = this.selectNodeStatus ? this.selectNodeStatus : this.defaultStatus; } if (this.nodeIds && this.nodeIds.length) { params.node_id = params.node_id || this.nodeIds; } // clusterStore.cluster_id = clusterId; // await userStore.fetchDetail(cluster.owner); if (params.isHelm) { this.formatClusterNodes({ type: this.nodeType || 'Deployment', searchWord: this.searchNode }); this.totalNodeCount = _.get(this.helmClusterNodes, 'length', 0); } else { const result = await this.request.get(`clusters/nodes`, params); this.clusterNodes = _.get(result, 'cluster_node_set', []); this.totalNodeCount = _.get(result, 'total_count', 0); } this.isLoading = false; }; getClusterRoles = () => _.get(this.cluster, 'cluster_role_set', []).map(cl => cl.role); // todo: inject clusterStore // fixme: table search, filter no effect @action formatClusterNodes = ({ type, searchWord = '' }) => { const { cluster_role_set, cluster_node_set } = this.cluster; if (_.isEmpty(cluster_role_set)) { return false; } const clusterNodes = []; const keys = ['name', 'host_id', 'host_ip', 'instance_id', 'private_ip']; cluster_role_set.forEach(roleItem => { if (!roleItem.role) { return false; } if (!roleItem.role.includes(`-${type}`)) { return false; } const nodes = []; const status = { maxStatus: '', maxNumber: 0 }; if (Array.isArray(cluster_node_set)) { cluster_node_set.forEach(nodeItem => { if (nodeItem.role !== roleItem.role) { return; } const hasWord = _.some(keys, key => nodeItem[key].includes(searchWord)); if (!hasWord) { return; } nodes.push(nodeItem); const nodeStatus = _.get(status, nodeItem.status); let number = 0; if (!nodeStatus) { number = 1; } else { number = nodeStatus + 1; } status[nodeItem.status] = number; if (status.maxStatus === '') { status.maxStatus = nodeItem.status; status.maxNumber = number; } else if (status.maxNumber < number) { status.maxStatus = nodeItem.status; status.maxNumber = number; } }); } roleItem.nodes = nodes; roleItem.name = _.get(roleItem.role.split(`-${type}`), '[0]'); roleItem.status = status.maxStatus; roleItem.statusText = `(${status.maxNumber}/${nodes.length})`; if (nodes.length > 0) { clusterNodes.push(roleItem); } }); this.helmClusterNodes = clusterNodes; return clusterNodes; }; @action fetchJobs = async clusterId => { this.isLoading = true; const result = await this.request.get(`jobs`, { cluster_id: clusterId }); this.clusterJobs = _.get(result, 'job_set', []); this.isLoading = false; }; @action addNodes = async params => { const res = await this.request.post('clusters/add_nodes', params); return res && res.job_id; }; @action setNodeRole = (role = '') => { this.selectedNodeRole = role; }; @action deleteNodes = async params => { const res = await this.request.post('clusters/delete_nodes', params); return res && res.job_id; }; @action cancelDeleteNodes = () => { this.selectedNodeIds = []; this.selectedNodeKeys = []; }; @action resizeCluster = async params => { const res = await this.request.post('clusters/resize', params); return res && res.job_id; }; @action onChangeExtend = e => { const { value } = e.target; const { extendedRowKeys } = this; const index = extendedRowKeys.indexOf(value); if (index === -1) { extendedRowKeys.push(value); } else { extendedRowKeys.splice(index, 1); } this.extendedRowKeys = _.union([], this.extendedRowKeys); }; /** * @param env * @returns {*} */ formatEnv = (env = '') => { if (typeof env === 'string') { // first transform arg into obj env = yaml.safeLoad(env); } if (this.isHelm) { // output yaml string return yaml.safeDump(env); } // output json string return JSON.stringify(env, null, 2); }; @action onChangeK8sTag = async name => { this.extendedRowKeys = []; const type = name.split(' ')[0]; if (this.nodeType !== type) { this.nodeType = type; this.isLoading = true; await sleep(300); this.isLoading = false; this.formatClusterNodes({ type }); } }; @action onChangeSelectNodes = (rowKeys, rows) => { this.selectedNodeKeys = rowKeys; this.selectedNodeIds = rows.map(row => row.node_id); }; @action cancelSelectNodes = () => { this.selectedNodeKeys = []; this.selectedNodeIds = []; }; @action onSearchNode = async word => { this.searchNode = word; this.currentNodePage = 1; await this.fetchNodes({ cluster_id: this.cluster.cluster_id }); }; @action onClearNode = async () => { await this.onSearchNode(''); }; @action onRefreshNode = async () => { const { cluster_id } = this.cluster; this.isLoading = true; if (this.isHelm) { await this.fetch(cluster_id); } else { await this.fetchNodes({ cluster_id }); } this.isLoading = false; }; @action changePaginationNode = async page => { this.currentNodePage = page; await this.fetchNodes({ cluster_id: this.cluster.cluster_id }); }; @action onChangeNodeStatus = async status => { this.currentNodePage = 1; this.selectNodeStatus = this.selectNodeStatus === status ? '' : status; await this.fetchNodes({ cluster_id: this.cluster.cluster_id }); }; @action changeEnv = env => { this.changedEnv = env; }; @action cancelChangeEnv = () => { this.changedEnv = ''; this.getStore('cluster').hideModal(); }; }
JavaScript
class FileHelper { /** * Construct the file helper. * * @param {EthAvatar} [ethavatar] - Instance of EthAvatar object. * * @constructor */ constructor (ethavatar) { if (available === false) /* istanbul ignore next */ { throw new BrowserError('Filesystem operations not available in browser') } this.ethavatar = ethavatar this.writeFile = promisify(fs.writeFile) this.readFile = promisify(fs.readFile) } /** * Download avatar to file. * * @param {string} [filename] - File name to get avatar. * @param {string} [address] - Address or ENS domain to get avatar (default is current Ethereum address). * * @return {void} * * @async */ async toFile (filename, address = null) { address = await this.ethavatar._address(address) const avatar = await this.ethavatar.get(address) try { await this.writeFile( filename, avatar, 'binary' ) } catch (error) /* istanbul ignore next */ { const err = new DownloadFileError(error) err.stack = error.stack throw err } } /** * Upload avatar from file. * * @param {string} [filename] - File name of avatar. * * @return {void} * * @async */ async fromFile (filename) { let data = null let avatar = null try { data = await this.readFile(filename) avatar = Buffer.from(data) } catch (error) /* istanbul ignore next */ { const err = new UploadFileError(error) err.stack = error.stack throw err } await this.ethavatar.set(avatar) } }
JavaScript
class Workflow extends Component { static navigationOptions = { title: 'Workflow', headerStyle: { backgroundColor: '#635ad2', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold', alignSelf: 'center' }, } render() { return ( <View style={styles.comingsoon} > <LottieView source={require('./coming_soon.json')} autoPlay loop /> </View> ); } }
JavaScript
class HTTPHeaderEditor extends React.Component { constructor(props) { super(props); this.state = { headers: props.headers || [], addingHeader: false }; } sendHeaderListUpdate() { if (this.props.onCreateHeaders) { this.props.onCreateHeaders( _.zipObject(_.map(this.state.headers, (val) => [val.key, val.value])) ); } } addHeader = () => { this.setState({ addingHeader: true }); } completeAdd = () => { this.setState({ headers: [ ...this.state.headers, { key: ReactDOM.findDOMNode(this.newKeyInput).value, value: ReactDOM.findDOMNode(this.newValInput).value, editing: false } ] }, () => { this.setState({ addingHeader: false }); this.sendHeaderListUpdate(); }); } cancelAdd = () => { this.setState({ addingHeader: false }); } removeRow = (i, event) => { const newHeaders = [...this.state.headers]; newHeaders.splice(i, 1); this.setState({ headers: newHeaders }, () => { this.sendHeaderListUpdate(); }); } editRow(i) { const newHeaders = [...this.state.headers]; const header = newHeaders[i]; header.editing = true; this.setState({ headers: newHeaders }, () => { this.sendHeaderListUpdate(); }); } completeEdit(i) { const newHeaders = [...this.state.headers]; const header = newHeaders[i]; header.key = ReactDOM.findDOMNode(this[`editingRow${i}KeyInput`]).value; header.value = ReactDOM.findDOMNode(this[`editingRow${i}ValueInput`]).value; header.editing = false; this.setState({ headers: newHeaders }, () => { this.sendHeaderListUpdate(); }); } cancelEdit(i) { const newHeaders = [...this.state.headers]; const header = newHeaders[i]; header.editing = false; this.setState({ headers: newHeaders }, () => { this.sendHeaderListUpdate(); }); } completedRow(header, i) { return ( <tr key={i}> <td>{header.key}</td> <td>{header.value.length > 40 ? header.value.substr(0, 40) + '...' : header.value}</td> <td> <button onClick={() => this.editRow(i)}>Edit</button> <button onClick={() => this.removeRow(i)}>&times;</button> </td> </tr> ) } editingRow(header, i) { return ( <tr key={`editing-row-${i}`}> <td> <input ref={(c) => (this[`editingRow${i}KeyInput`] = c)} type="text" placeholder="Header Key" defaultValue={header.key} style={{ width: '100%' }} /> </td> <td> <input ref={(c) => (this[`editingRow${i}ValueInput`] = c)} type="text" placeholder="Header Value" defaultValue={header.value} style={{ width: '100%' }} /> </td> <td> <button onClick={() => this.completeEdit(i)}>&#x2713;</button> <button onClick={() => this.cancelEdit(i)}>&times;</button> </td> </tr> ) } render() { let addHeader = null; if (this.state.addingHeader) { addHeader = ( <tr> <td> <input ref={(c) => (this.newKeyInput = c)} type="text" placeholder="Header Key" style={{ width: '100%' }} /> </td> <td> <input ref={(c) => (this.newValInput = c)} type="text" placeholder="Header Value" style={{ width: '100%' }} /> </td> <td> <button onClick={this.completeAdd}>&#x2713;</button> <button onClick={this.cancelAdd}>&times;</button> </td> </tr> ) } return ( <div className="headerEditor"> <h2>Edit HTTP Headers</h2> <div> <a href="javascript:;" onClick={this.addHeader}>+ Add Header</a> <table className="pure-table pure-table-striped" style={styles.table}> <thead> <tr> <th>Key</th> <th>Value</th> <th></th> </tr> </thead> <tbody> {this.state.headers.map((header, i) => ( header.editing ? this.editingRow(header, i) : this.completedRow(header, i) ))} {addHeader} </tbody> </table> </div> </div> ); } }
JavaScript
class Buyer { /** * Constructs a new <code>Buyer</code>. * Information about the buyer. * @alias module:client/models/Buyer * @class */ constructor() { } /** * Constructs a <code>Buyer</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:client/models/Buyer} obj Optional instance to populate. * @return {module:client/models/Buyer} The populated <code>Buyer</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Buyer(); if (data.hasOwnProperty('buyerId')) { obj['buyerId'] = ApiClient.convertToType(data['buyerId'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('phone')) { obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); } if (data.hasOwnProperty('isPrimeMember')) { obj['isPrimeMember'] = ApiClient.convertToType(data['isPrimeMember'], 'Boolean'); } } return obj; } /** * The identifier of the buyer. * @member {String} buyerId */ 'buyerId' = undefined; /** * The name of the buyer. * @member {String} name */ 'name' = undefined; /** * The phone number of the buyer. * @member {String} phone */ 'phone' = undefined; /** * When true, the service is for an Amazon Prime buyer. * @member {Boolean} isPrimeMember */ 'isPrimeMember' = undefined; }
JavaScript
class Logger { constructor (fileName) { this._fileName = fileName } // Convert arguments to string via util.format(), write as a log message. log () { this._print(arguments) } // Like log, but only if debug enabled. debug () { if (!utils.isDebug()) return this._print(arguments, {debug: true}) } }
JavaScript
class EventEmitter { /** * Constructs a new event emitter. * @param {...(string|RegExp|'*')} eventTypes - events we will emit */ constructor(...eventTypes) { this._eventEmitter = this this._eventRegex = null this._registerEventTypes(...eventTypes) } /** * Register an event type. * If an unregistered event is passed to {@link EventEmitter.on} or * {@link EventEmitter.emit}, it will throw. * @param {(string|RegExp|'*')} eventType */ registerEventType(eventType) { if (!this._callbacks) this._callbacks = {} if (eventType === '*') { this._addRegexEvent(/.+/) } else if (eventType instanceof RegExp) { this._addRegexEvent(eventType) } else if (!this._callbacks[eventType]) { this._callbacks[eventType] = [] } } _registerEventTypes(...eventTypes) { for (const eventType of eventTypes) this.registerEventType(eventType) } _addRegexEvent(regex) { regex = `(?:${regex.source})` if (this._regexEvents) { this._eventRegex = new RegExp(`${this._regexEvents.source}|${regex}`) } else { this._eventRegex = new RegExp(regex) } } /** * Forwards events from another event emitter * @param {EventEmitter} other - other emitter * @param {(string|RegExp)[]} eventTypes - event types to forward */ forwardEvents(other, ...eventTypes) { for (const eventType of eventTypes) { this.registerEventType(eventType) other.on(eventType, (...args) => this.emit(eventType, ...args)) } } /** * Is this a valid event type? * @param {string} eventType * @see EventEmitter.registerEventType */ isValidEvent(eventType) { return !!this._callbacks[eventType] || (this._eventRegex && this._eventRegex.test(eventType)) } /** * Adds an event callback. * @param {(string|RegExp)} eventType - event type * @param {function} callback - callback for this event * @throws Throws an error if the event type is invalid */ on(eventType, callback) { if (eventType instanceof RegExp) { if (!this._regexCallbacks) this._regexCallbacks = [] this._regexCallbacks.push([eventType, callback]) } else if (this._callbacks[eventType]) { this._callbacks[eventType].push(callback) } else if (this._eventRegex && this._eventRegex.test(eventType)) { this._callbacks[eventType] = [callback] } else { throw new Error(`Invalid event type: ${eventType}`) } } /** * Emits an event, calling any registered callbacks. * @param {string} eventType - event type * @param {...*} args - arguments to the event callback * @see EventEmitter#on */ emit(eventType, ...args) { const callbacks = this._callbacksFor(eventType) if (!callbacks) { if (this.isValidEvent(eventType)) { return // valid event but no events are registered } else { throw new Error(`Invalid event type: ${eventType}`) } } for (const callback of callbacks) { // setTimeout here insulates this function from errors in the callback setTimeout(callback.bind(this, ...args), 0) } } _callbacksFor(eventType) { const callbacks = this._callbacks[eventType] // Add regex callbacks if (this._regexCallbacks) { const regexCallbacks = [] for (const [regex, callback] of this._regexCallbacks) { if (regex.test(eventType)) regexCallbacks.push(callback) } if (regexCallbacks) return (callbacks || []).concat(regexCallbacks) } return callbacks } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.state = { step: STEPS.INSERT_CARD, isCardPresent: false, cardImg: null, processMsg: 'Processing...' }; // Since I am using a ES6 class the methods need to be bound this.previousStep = this.previousStep.bind(this); this.handleCardAction = this.handleCardAction.bind(this); this.updateStep = this.updateStep.bind(this); this.reset = this.reset.bind(this); this.handleAbort = this.handleAbort.bind(this); } componentDidMount() { // A listener for when the user presses the cancel button window.addEventListener('cancel', this.handleAbort); } componentWillUnmount() { // Clean up memory window.removeEventListener('cancel', this.handleAbort); if (processingTimeout) { clearTimeout(processingTimeout); } } handleAbort() { this.reset(); } reset(message) { this.updateStep(STEPS.INSERT_CARD, message); this.handleCardAction(false, null); } // Controls the step execution from a central place updateStep(nextStep, message = 'Processing...') { this.setState({processMsg: message}); this.setState({step: STEPS.PROCESSING}); // The waiting time is a random value between 1-3 seconds processingTimeout = setTimeout(() => this.setState({step: nextStep}), Math.random() * 3000); } previousStep() { this.setState({step: (this.state.step - 1)}); } // Determines whether a card is inserted or not handleCardAction(cardInserted, img) { this.setState({isCardPresent: cardInserted}); this.setState({cardImg: img}); } render() { let step; // The app consists of 4 Main steps plus the 'processing' screen switch (this.state.step) { case STEPS.INSERT_CARD: step = <Welcome onInsertCard={this.handleCardAction} updateStep={this.updateStep} />; break; case STEPS.ENTER_PIN: step = <EnterPIN updateStep={this.updateStep} previousStep={this.previousStep} />; break; case STEPS.SELECT_AMOUNT: step = <SelectAmount updateStep={this.updateStep} previousStep={this.previousStep} />; break; case STEPS.TAKE_YOUR_MONEY: step = <TakeYourMoney reset={this.reset}/>; break; default: // Processing is the default step step = <ProcessingScreen updateStep={this.updateStep} message={this.state.processMsg} />; break; } return ( <div className={styles.app}> <div className={styles.screen}> {step} </div> <Pad currentCard={this.state.cardImg}/> </div> ); } }
JavaScript
class CodeBlock extends Component { // function CodeBlock({ children, ...props }) { constructor(props) { super(props); this.state = { timeoutCnt: 0 }; this.copyToClipBoard = this.copyToClipBoard.bind(this); this.copyTimeout = this.copyTimeout.bind(this); } copyToClipBoard(e) { this.props.enqueueSnackbar('Code is now in your clipboard', { variant: 'info' }); const el = document.createElement('textarea'); el.value = this.props.children; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); let timeoutCnt = this.state.timeoutCnt; timeoutCnt++; this.setState({ timeoutCnt: timeoutCnt }); setTimeout(this.copyTimeout, 5000); } copyTimeout() { let timeoutCnt = this.state.timeoutCnt; if (timeoutCnt > 0) { timeoutCnt--; this.setState({ timeoutCnt: timeoutCnt++ }); } } render() { let buttonShow = []; let buttonText; let buttonColor; if (this.state.timeoutCnt > 0) { buttonText = '!! Copied !!'; buttonColor = 'primary'; } else { buttonText = 'Copy code'; buttonColor = 'primary'; } // const { classes } = props; /*copy the clipboard */ let code_content; let lineNumber = 1; if ((this.props.className !== undefined) && this.props.className.includes('lang-')) { let filteredLanguageName = this.props.className.split('lang-').pop() /*handle -nc tag */ if (filteredLanguageName.includes('-nc')) { filteredLanguageName = filteredLanguageName.replace('-nc', ''); } else { buttonShow = ( <div> <Button variant="contained" size="small" style={{ marginBottom: 12 }} color={buttonColor} onClick={this.copyToClipBoard}> {buttonText} </Button> </div>); } let codeLines = this.props.children.split(/\r\n|\r|\n/).length; let showLineNumbers; if (codeLines === 1) { showLineNumbers = false; } else { showLineNumbers = true; } if (filteredLanguageName.includes("-line")) { lineNumber = parseInt(filteredLanguageName.match(/-line(\d+)/)[0].replace('-line', '')); filteredLanguageName = filteredLanguageName.replace(/-line(\d+)/, ''); } else { showLineNumbers = false; } code_content = ( <div> <Divider /> <div> <SyntaxHighlighter language={filteredLanguageName} style={atomOneLight} showLineNumbers={showLineNumbers} startingLineNumber={lineNumber} wrapLongLines={true} codeTagProps={{ style: { fontFamily: 'inherit' } }}> {/* <SyntaxHighlighter language="cpp" style={prism} showLineNumbers="true" codeTagProps={{style: {fontFamily: 'inherit'} }}> */} {this.props.children} </SyntaxHighlighter> </div> {buttonShow} <Divider /> </div> ); } else { code_content = ( <i> <b> {/* // <Typography variant="i"> */} <code> {this.props.children} </code> {/* // </Typography> */} </b> </i> ); } return code_content; } }
JavaScript
class CacheImageService { constructor( db, fileCacheService ) { this.cacheService = fileCacheService; this.imageCacheFolder = 'images'; this.db = db['cache-images']; } /** * Router interceptor to download image and update cache before pass to express.static return this cached image. * * GET /:hash - Hash is a full external URL encoded in base64. * eg.: http://{host}/cache/images/aHR0cHM6Ly8xO...cXVUbmFVNDZQWS1LWQ== * * @returns * @memberof CacheImageService */ routerInterceptor() { const router = express.Router(); router.get('/:hash', async (req, res, next) => { try { const hash = req.params.hash; const imgItem = this.db.find({url: hash})[0]; if(imgItem) { const file = await this.getImageFromCache(imgItem.url); if(!file.length) { const fileMimeType = await this.requestImageAndStore(Buffer.from(imgItem.url, 'base64').toString('ascii'), imgItem); res.set('content-type', fileMimeType); next(); } else { res.set('content-type', imgItem.mimeType); next(); } } } catch(err) { console.error(err); res.status(500).send("error"); } }); return router; } /** * Routers exported to use on express.use() function. * Use on api routers, like `{host}/api/cache/images` * * `DELETE /` - Clear all files on .dizquetv/cache/images * * @returns {Router} * @memberof CacheImageService */ apiRouters() { const router = express.Router(); router.delete('/', async (req, res, next) => { try { await this.clearCache(); res.status(200).send({msg: 'Cache Image are Cleared'}); } catch (error) { console.error(error); res.status(500).send("error"); } }); return router; } /** * * * @param {*} url External URL to get file/image * @param {*} dbFile register of file from db * @returns {promise} `Resolve` when can download imagem and store on cache folder, `Reject` when file are inaccessible over network or can't write on directory * @memberof CacheImageService */ async requestImageAndStore(url, dbFile) { return new Promise( async(resolve, reject) => { const requestConfiguration = { method: 'get', url }; request(requestConfiguration, (err, res) => { if (err) { reject(err); } else { const mimeType = res.headers['content-type']; this.db.update({_id: dbFile._id}, {url: dbFile.url, mimeType}); request(requestConfiguration) .pipe(fs.createWriteStream(`${this.cacheService.cachePath}/${this.imageCacheFolder}/${dbFile.url}`)) .on('close', () =>{ resolve(mimeType); }); } }); }); } /** * Get image from cache using an filename * * @param {*} fileName * @returns {promise} `Resolve` with file content * @memberof CacheImageService */ getImageFromCache(fileName) { return new Promise(async(resolve, reject) => { try { const file = await this.cacheService.getCache(`${this.imageCacheFolder}/${fileName}`); resolve(file); } catch (error) { reject(error); } }); } /** * Clear all files on .dizquetv/cache/images * * @returns {promise} * @memberof CacheImageService */ async clearCache() { return new Promise( async(resolve, reject) => { const cachePath = `${this.cacheService.cachePath}/${this.imageCacheFolder}`; fs.rmdir(cachePath, { recursive: true }, (err) => { if(err) { reject(); } fs.mkdirSync(cachePath); resolve(); }); }); } registerImageOnDatabase(imageUrl) { const url = Buffer.from(imageUrl).toString('base64'); const dbQuery = {url}; if(!this.db.find(dbQuery)[0]) { this.db.save(dbQuery); } return url; } }
JavaScript
class Render_loop_state_data { /** * Creates a Render_loop_state_data instance. * * @param {String=} render_loop_name - The name of the render loop to execute on * @param {Number=} cancel - Controls whether rendering should be cancelled to * execute the commands sooner. Pass `0` to cancel, and if possible * continues rendering without restarting progression. Pass `1` to * cancel faster at the expense of always needing to restart. Any * other value will not cancel rendering. * @param {Boolean=} continue_on_error Controls error handling when an error occurs. * If `true` then sub-commands will continue to be processed, if `false` * processing will end at the first error and any subsequent commands * will be aborted and get error resposes. Defaults to true. */ constructor(render_loop_name, cancel=undefined, continue_on_error=true) { this._render_loop_name = render_loop_name; this._cancel = cancel; this._continue_on_error = continue_on_error; if (this._cancel !== 0 && this._cancel !== 1) { this._cancel = -1; } if (this._continue_on_error === null || this._continue_on_error === undefined) { this._continue_on_error = true; } this._continue_on_error = !!this._continue_on_error; } /** * The name of the render loop to execute on. * @type {String} */ get render_loop_name() { return this._render_loop_name; } set render_loop_name(value) { this._render_loop_name = value; } /** * The cancel level. * @type {Number} */ get cancel() { return this._cancel; } set cancel(value) { if (value !== 0 && value !== 1) { this._cancel = -1; } else { this._cancel = value; } } /** * Whether to continue on error. * @type {Boolean} */ get continue_on_error() { return this._continue_on_error; } set continue_on_error(value) { this._continue_on_error = !!value; } }
JavaScript
class GoogleSheetsApi { // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. static get tokenPath() { return 'google-token.json'; } static handleApiError(error, message) { if (message) { console.error('[GoogleSheetsAPI]', 'API request failed with error:', error, message); } else { console.error('[GoogleSheetsAPI]', 'API request failed with error:', error); } } /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. */ static authorize() { return new Promise((resolve, reject) => { const { client_secret, client_id, redirect_uris } = config.google_credentials; const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. fs.readFile(this.tokenPath, (err, token) => { if (err) return this.getNewToken(oAuth2Client).then((oAuthClient) => resolve(oAuthClient)); oAuth2Client.setCredentials(JSON.parse(token)); resolve(oAuth2Client); }); }); } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for. * @param {getEventsCallback} callback The callback for the authorized client. */ static getNewToken(oAuth2Client) { return new Promise((resolve, reject) => { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('Enter the code from that page here: ', (code) => { rl.close(); oAuth2Client.getToken(code, (err, token) => { if (err) { this.handleApiError(err, 'Error while trying to retrieve access token'); return reject(err); } oAuth2Client.setCredentials(token); // Store the token to disk for later program executions fs.writeFile(this.tokenPath, JSON.stringify(token), (err) => { if (err) { this.handleApiError(err, 'Error while trying to store access token'); return reject(err); } console.log('Token stored to', this.tokenPath); }); resolve(oAuth2Client); }); }); }); } /** * Prints the names and majors of students in a sample spreadsheet: * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit * @param {google.auth.OAuth2} auth The authenticated Google OAuth client. */ static fetchData(spreadSheet) { return this.authorize().then((auth) => new Promise((resolve, reject) => { const sheets = google.sheets({ version: 'v4', auth }); sheets.spreadsheets.values.get({ spreadsheetId: spreadSheet.id, range: spreadSheet.range }, (err, res) => { if (err) { this.handleApiError(err, 'The Api returned an error'); return reject(err); } const rows = res.data.values; if (rows.length) { const headers = spreadSheet.headers.split(','); // Map row columns to object propertiesPrint columns A and E, which correspond to indices 0 and 4. const mappedRows = rows.map((row) => { const newRow = {}; for (var i = 0; i < headers.length; i++) { newRow[headers[i]] = row[i]; } return newRow; }); resolve(mappedRows); } else { console.log('No data found.'); this.handleApiError(err, 'No data found'); reject(err); } }); })); } }
JavaScript
class word { //drawing variables, location, destination, opacity, speed, and whether it is to be shown or not. constructor(txt, dp, ps) { this.focus = sketch.createVector(window.innerWidth/2, window.innerHeight/2); this.range = 700; this.show = true; this.coord = sketch.createVector(sketch.random((this.focus.x - this.range), (this.focus.x + this.range)), sketch.random((this.focus.y - this.range), (this.focus.y + this.range))); this.speed = 0.2; //sketch.random(0.2, 1.0); this.dest = sketch.createVector(sketch.random((this.focus.x - this.range), (this.focus.x + this.range)), sketch.random((this.focus.y - this.range), (this.focus.y + this.range))); this.opac = 0; this.opacmax = sketch.random(50, 225); //data from returned NLP JSON this.color = sketch.random(colours); this.color.setAlpha(100); this.text = txt; this.dep = dp; //refers to position in speech, not position in sketch. that is the property of this.coord. this.pos = ps; } updateCoord() { if (sketch.dist(this.coord.x, this.coord.y, this.dest.x, this.dest.y) > 0.0) { if(this.coord.x < this.dest.x && this.coord.y < this.dest.y) { this.coord.x += this.speed; this.coord.y += this.speed; } else if (this.coord.x > this.dest.x && this.coord.y > this.dest.y) { this.coord.x -= this.speed; this.coord.y -= this.speed; } else if (this.coord.x > this.dest.x && this.coord.y < this.dest.y) { this.coord.x -= this.speed; this.coord.y += this.speed; } else if (this.coord.x < this.dest.x && this.coord.y > this.dest.y) { this.coord.x += this.speed; this.coord.y -= this.speed; } } if (sketch.dist(this.coord.x, this.coord.y, this.dest.x, this.dest.y) <= 1.0 || sketch.dist(this.coord.x, this.coord.y, this.dest.x, this.dest.y) <= 0.0 ) { this.setDest(sketch.random((this.focus.x - this.range), (this.focus.x + this.range)), sketch.random((this.focus.y - this.range), (this.focus.y + this.range))) this.color = sketch.random(colours); } } renderIn() { if (this.opac < this.opacmax) { this.opac += this.speed; } if (toggleText.checked() == false) { sketch.textAlign(sketch.CENTER); sketch.textSize(20); sketch.fill(0, 255); sketch.text(this.text, this.coord.x, this.coord.y); } this.updateCoord(); } setSpeed(speed) { this.speed = speed; } setRange (range) { this.range = range; } setFocus(x, y) { this.focus.x = x; this.focus.y = y; } setDest(x, y) { this.dest.x = x; this.dest.y = y; } getCoord() { return this.coord; } getDest() { return this.dest; } getPos() { return this.pos; } }