language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Loader extends BaseObject { /** * builds the loader * @method constructor * @param {Object} externalPlugins the external plugins * @param {Number} playerId you can embed multiple instances of clappr, therefore this is the unique id of each one. */ constructor(externalPlugins = [], playerId = 0, useOnlyPlainHtml5Plugins = PLAIN_HTML5_ONLY) { super() this.playerId = playerId this.playbackPlugins = [] if (!useOnlyPlainHtml5Plugins) { this.playbackPlugins = [ ...this.playbackPlugins, HLSVideoPlayback, ] } this.playbackPlugins = [ ...this.playbackPlugins, HTML5VideoPlayback, HTML5AudioPlayback, ] if (!useOnlyPlainHtml5Plugins) { this.playbackPlugins = [ ...this.playbackPlugins, FlashVideoPlayback, FlasHLSVideoPlayback ] } this.playbackPlugins = [ ...this.playbackPlugins, HTMLImgPlayback, NoOp ] this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin] this.corePlugins = [DVRControls, ClosedCaptions, Favicon, SeekTime, SourcesPlugin, EndVideo, Strings, ErrorScreen] if (!Array.isArray(externalPlugins)) this.validateExternalPluginsType(externalPlugins) this.addExternalPlugins(externalPlugins) } /** * groups by type the external plugins that were passed through `options.plugins` it they're on a flat array * @method addExternalPlugins * @private * @param {Object} an config object or an array of plugins * @return {Object} plugins the config object with the plugins separated by type */ groupPluginsByType(plugins) { if (Array.isArray(plugins)) { plugins = plugins.reduce(function(memo, plugin) { memo[plugin.type] || (memo[plugin.type] = []) memo[plugin.type].push(plugin) return memo }, {}) } return plugins } removeDups(list) { const groupUp = (plugins, plugin) => { plugins[plugin.prototype.name] && delete plugins[plugin.prototype.name] plugins[plugin.prototype.name] = plugin return plugins } const pluginsMap = list.reduceRight(groupUp, Object.create(null)) const plugins = [] for (let key in pluginsMap) plugins.unshift(pluginsMap[key]) return plugins } /** * adds all the external plugins that were passed through `options.plugins` * @method addExternalPlugins * @private * @param {Object} plugins the config object with all plugins */ addExternalPlugins(plugins) { plugins = this.groupPluginsByType(plugins) if (plugins.playback) this.playbackPlugins = this.removeDups(plugins.playback.concat(this.playbackPlugins)) if (plugins.container) this.containerPlugins = this.removeDups(plugins.container.concat(this.containerPlugins)) if (plugins.core) this.corePlugins = this.removeDups(plugins.core.concat(this.corePlugins)) PlayerInfo.getInstance(this.playerId).playbackPlugins = this.playbackPlugins } /** * validate if the external plugins that were passed through `options.plugins` are associated to the correct type * @method validateExternalPluginsType * @private * @param {Object} plugins the config object with all plugins */ validateExternalPluginsType(plugins) { const plugintypes = ['playback', 'container', 'core'] plugintypes.forEach((type) => { (plugins[type] || []).forEach((el) => { const errorMessage = 'external ' + el.type + ' plugin on ' + type + ' array' if (el.type !== type) throw new ReferenceError(errorMessage) }) }) } }
JavaScript
class Database { constructor() { this._connect() } _connect() { mongoose.connect(`mongodb://${server}/${database}`) .then(() => { console.log('Database connection successful') }) .catch(err => { console.error('Database connection error') }) } }
JavaScript
class Renderer extends AbstractRenderer { /** * Create renderer if WebGL is available. Overrideable * by the **@pixi/canvas-renderer** package to allow fallback. * throws error if WebGL is not available. * @static * @private */ static create(options) { if (isWebGLSupported()) { return new Renderer(options); } throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); } /** * @param {object} [options] - The optional renderer parameters. * @param {number} [options.width=800] - The width of the screen. * @param {number} [options.height=600] - The height of the screen. * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. * @param {boolean} [options.transparent=false] - If the render view is transparent. * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for * resolutions other than 1. * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA * antialiasing is used. * @param {boolean} [options.forceFXAA=false] - Forces FXAA antialiasing to be used over native. * FXAA is faster, but may not always look as great. * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. * The resolution of the renderer retina would be 2. * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear * the canvas or not before the new render pass. If you wish to set this to false, you *must* set * preserveDrawingBuffer to `true`. * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, * enable this if you need to call toDataUrl on the WebGL context. * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area * (shown if not transparent). * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance" * for devices with dual graphics card. * @param {object} [options.context] If WebGL context already exists, all parameters must be taken from it. */ constructor(options = {}) { super('WebGL', options); // the options will have been modified here in the super constructor with pixi's default settings.. options = this.options; /** * The type of this renderer as a standardized const * * @member {number} * @see PIXI.RENDERER_TYPE */ this.type = RENDERER_TYPE.WEBGL; /** * WebGL context, set by the contextSystem (this.context) * * @readonly * @member {WebGLRenderingContext} */ this.gl = null; this.CONTEXT_UID = 0; // TODO legacy! /** * Internal signal instances of **runner**, these * are assigned to each system created. * @see PIXI.Runner * @name PIXI.Renderer#runners * @private * @type {object} * @readonly * @property {PIXI.Runner} destroy - Destroy runner * @property {PIXI.Runner} contextChange - Context change runner * @property {PIXI.Runner} reset - Reset runner * @property {PIXI.Runner} update - Update runner * @property {PIXI.Runner} postrender - Post-render runner * @property {PIXI.Runner} prerender - Pre-render runner * @property {PIXI.Runner} resize - Resize runner */ this.runners = { destroy: new Runner('destroy'), contextChange: new Runner('contextChange', 1), reset: new Runner('reset'), update: new Runner('update'), postrender: new Runner('postrender'), prerender: new Runner('prerender'), resize: new Runner('resize', 2), }; /** * Global uniforms * @member {PIXI.UniformGroup} */ this.globalUniforms = new UniformGroup({ projectionMatrix: new Matrix(), }, true); /** * Mask system instance * @member {PIXI.systems.MaskSystem} mask * @memberof PIXI.Renderer# * @readonly */ this.addSystem(MaskSystem, 'mask') /** * Context system instance * @member {PIXI.systems.ContextSystem} context * @memberof PIXI.Renderer# * @readonly */ .addSystem(ContextSystem, 'context') /** * State system instance * @member {PIXI.systems.StateSystem} state * @memberof PIXI.Renderer# * @readonly */ .addSystem(StateSystem, 'state') /** * Shader system instance * @member {PIXI.systems.ShaderSystem} shader * @memberof PIXI.Renderer# * @readonly */ .addSystem(ShaderSystem, 'shader') /** * Texture system instance * @member {PIXI.systems.TextureSystem} texture * @memberof PIXI.Renderer# * @readonly */ .addSystem(TextureSystem, 'texture') /** * Geometry system instance * @member {PIXI.systems.GeometrySystem} geometry * @memberof PIXI.Renderer# * @readonly */ .addSystem(GeometrySystem, 'geometry') /** * Framebuffer system instance * @member {PIXI.systems.FramebufferSystem} framebuffer * @memberof PIXI.Renderer# * @readonly */ .addSystem(FramebufferSystem, 'framebuffer') /** * Stencil system instance * @member {PIXI.systems.StencilSystem} stencil * @memberof PIXI.Renderer# * @readonly */ .addSystem(StencilSystem, 'stencil') /** * Projection system instance * @member {PIXI.systems.ProjectionSystem} projection * @memberof PIXI.Renderer# * @readonly */ .addSystem(ProjectionSystem, 'projection') /** * Texture garbage collector system instance * @member {PIXI.systems.TextureGCSystem} textureGC * @memberof PIXI.Renderer# * @readonly */ .addSystem(TextureGCSystem, 'textureGC') /** * Filter system instance * @member {PIXI.systems.FilterSystem} filter * @memberof PIXI.Renderer# * @readonly */ .addSystem(FilterSystem, 'filter') /** * RenderTexture system instance * @member {PIXI.systems.RenderTextureSystem} renderTexture * @memberof PIXI.Renderer# * @readonly */ .addSystem(RenderTextureSystem, 'renderTexture') /** * Batch system instance * @member {PIXI.systems.BatchSystem} batch * @memberof PIXI.Renderer# * @readonly */ .addSystem(BatchSystem, 'batch'); this.initPlugins(Renderer.__plugins); /** * The options passed in to create a new WebGL context. */ if (options.context) { this.context.initFromContext(options.context); } else { this.context.initFromOptions({ alpha: this.transparent, antialias: options.antialias, premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', stencil: true, preserveDrawingBuffer: options.preserveDrawingBuffer, powerPreference: this.options.powerPreference, }); } /** * Flag if we are rendering to the screen vs renderTexture * @member {boolean} * @readonly * @default true */ this.renderingToScreen = true; sayHello(this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); this.resize(this.options.width, this.options.height); } /** * Add a new system to the renderer. * @param {Function} ClassRef - Class reference * @param {string} [name] - Property name for system, if not specified * will use a static `name` property on the class itself. This * name will be assigned as s property on the Renderer so make * sure it doesn't collide with properties on Renderer. * @return {PIXI.Renderer} Return instance of renderer */ addSystem(ClassRef, name) { if (!name) { name = ClassRef.name; } const system = new ClassRef(this); if (this[name]) { throw new Error(`Whoops! The name "${name}" is already in use`); } this[name] = system; for (const i in this.runners) { this.runners[i].add(system); } /** * Fired after rendering finishes. * * @event PIXI.Renderer#postrender */ /** * Fired before rendering starts. * * @event PIXI.Renderer#prerender */ /** * Fired when the WebGL context is set. * * @event PIXI.Renderer#context * @param {WebGLRenderingContext} gl - WebGL context. */ return this; } /** * Renders the object to its WebGL view * * @param {PIXI.DisplayObject} displayObject - The object to be rendered. * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to. * @param {boolean} [clear=true] - Should the canvas be cleared before the new render. * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass? */ render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { // can be handy to know! this.renderingToScreen = !renderTexture; this.runners.prerender.run(); this.emit('prerender'); // apply a transform at a GPU level this.projection.transform = transform; // no point rendering if our context has been blown up! if (this.context.isLost) { return; } if (!renderTexture) { this._lastObjectRendered = displayObject; } if (!skipUpdateTransform) { // update the scene graph const cacheParent = displayObject.parent; displayObject.parent = this._tempDisplayObjectParent; displayObject.updateTransform(); displayObject.parent = cacheParent; // displayObject.hitArea = //TODO add a temp hit area } this.renderTexture.bind(renderTexture); this.batch.currentRenderer.start(); if (clear !== undefined ? clear : this.clearBeforeRender) { this.renderTexture.clear(); } displayObject.render(this); // apply transform.. this.batch.currentRenderer.flush(); if (renderTexture) { renderTexture.baseTexture.update(); } this.runners.postrender.run(); // reset transform after render this.projection.transform = null; this.emit('postrender'); } /** * Resizes the WebGL view to the specified width and height. * * @param {number} screenWidth - The new width of the screen. * @param {number} screenHeight - The new height of the screen. */ resize(screenWidth, screenHeight) { super.resize(screenWidth, screenHeight); this.runners.resize.run(screenWidth, screenHeight); } /** * Resets the WebGL state so you can render things however you fancy! * * @return {PIXI.Renderer} Returns itself. */ reset() { this.runners.reset.run(); return this; } /** * Clear the frame buffer */ clear() { this.framebuffer.bind(); this.framebuffer.clear(); } /** * Removes everything from the renderer (event listeners, spritebatch, etc...) * * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. * See: https://github.com/pixijs/pixi.js/issues/2233 */ destroy(removeView) { this.runners.destroy.run(); for (const r in this.runners) { this.runners[r].destroy(); } // call base destroy super.destroy(removeView); // TODO nullify all the managers.. this.gl = null; } /** * Collection of installed plugins. These are included by default in PIXI, but can be excluded * by creating a custom build. Consult the README for more information about creating custom * builds and excluding plugins. * @name PIXI.Renderer#plugins * @type {object} * @readonly * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. * @property {PIXI.extract.Extract} extract Extract image data from renderer. * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. * @property {PIXI.prepare.Prepare} prepare Pre-render display objects. */ /** * Adds a plugin to the renderer. * * @method * @param {string} pluginName - The name of the plugin. * @param {Function} ctor - The constructor function or class for the plugin. */ static registerPlugin(pluginName, ctor) { Renderer.__plugins = Renderer.__plugins || {}; Renderer.__plugins[pluginName] = ctor; } }
JavaScript
class ActorQueryOperationTyped extends ActorQueryOperation_1.ActorQueryOperation { constructor(args, operationName) { super(Object.assign(Object.assign({}, args), { operationName })); if (!this.operationName) { throw new Error('A valid "operationName" argument must be provided.'); } } async test(action) { if (!action.operation) { throw new Error('Missing field \'operation\' in a query operation action.'); } if (action.operation.type !== this.operationName) { throw new Error('Actor ' + this.name + ' only supports ' + this.operationName + ' operations, but got ' + action.operation.type); } const operation = action.operation; return this.testOperation(operation, action.context); } async run(action) { const operation = action.operation; const subContext = action.context && action.context.set(exports.KEY_CONTEXT_QUERYOPERATION, operation); const output = await this.runOperation(operation, subContext); if (output.metadata) { output.metadata = ActorQueryOperation_1.ActorQueryOperation.cachifyMetadata(output.metadata); } return output; } }
JavaScript
class App extends React.Component { state = { temp: null, city: null, country: null, pressure: null, sunset: null, error: null, }; setWeatherData = data => { this.setState({ temp: data.main.temp, city: data.name, country: data.sys.country, pressure: data.main.pressure, sunset: sunset_date, error: null, }); } clearWeatherData = () => { this.setState({ temp: null, city: null, country: null, pressure: null, sunset: null, error: "Please enter city's name", }); } getWeather = async e => { e.preventDefault(); const city = e.target.elements.city.value; if (city) { const api_url = await fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`, ); const data = await api_url.json(); var sunset = data.sys.sunset; var date = new Date(); date.setTime(sunset); var sunset_date = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); const weatherData = { ...data, sunset_date }; this.setWeatherData(weatherData); } else { this.clearWeatherData(); } }; render() { return ( <div className="wrapper"> <div className="main"> <div className="container"> <div className="row"> <div className="col-sm-5 info"> <Info /> </div> <div className="col-sm-7 form"> <Form weatherMethod={this.getWeather} /> <Weather temp={this.state.temp} city={this.state.city} country={this.state.country} pressure={this.state.pressure} sunset={this.state.sunset} error={this.state.error} /> </div> </div> </div> </div> </div> ); } }
JavaScript
class GatesManager { // The single instance. static singleton; // The working HDL dir workingDir; // The BuiltIn HDL dir builtInDir; // The list of built in chips with gui chips; /** * Constructs a new GatesManager. */ constructor() { this.chips = []; } /** * Returns the single instance of GatesManager. */ static getInstance() { if (!this.singleton) { this.singleton = new GatesManager(); } return this.singleton; } /** * Returns the current HDL dir. */ getWorkingDir() { return this.workingDir; } /** * Sets the current HDL dir with the given dir. */ setWorkingDir(file) { this.workingDir = file; } /** * Returns the BuiltIn HDL dir. */ getBuiltInDir() { return this.builtInDir; } /** * Sets the BuiltIn HDL dir with the given dir. */ setBuiltInDir(file) { this.builtInDir = file; } /** * Returns the full HDL file name that matches the given gate name. * The HDL file is searched first in the current dir, and if not found, in the BuiltIn dir. * If not found in any of them, returns null. */ getHDLFileName(gateName) { let result = null; const name = `${gateName}.hdl`; if (fs.existsSync(path.join(this.workingDir, name))) { result = `${this.workingDir}/${name}`; } else if (fs.existsSync(path.join(this.builtInDir, name))) { result = `${this.builtInDir}/${name}`; } return result; } }
JavaScript
class ChipData { constructor (chip, chipSet) { this.chip = chip; this.chipSet = chipSet; } get checked () { let { filtered } = this.chipSet; let chipId = this.chipId; return !!filtered.find (chip => this.chipSet.getChipId (chip) === chipId); } get chipId () { return this.chipSet.getChipId (this.chip); } }
JavaScript
class MdcFilterChipSetComponent extends ChipSetComponent { get checkedKey () { return this.args.checkedKey || 'checked'; } @tracked _data; didSelection (ev) { const { target, detail: { chipId, selected } } = ev; if (!selected) { // The current filter chip component does not remove the hidden class from leading // icons when the chip is deselected. This is a patch for the problem so the leading // icon on a filter is restored, and visible, and the chip is deselected. let leadingIcon = target.querySelector ('.mdc-chip__icon--leading'); if (isPresent (leadingIcon)) { leadingIcon.classList.remove ('mdc-chip__icon--leading-hidden'); } } if (isPresent (this.chips)) { // The user wants us to automate the handling of selecting a chip. let chip = this.findChipById (chipId); assert (`The filter chip set does not have a chip with the id ${chipId}`, isPresent (chip)); if (selected) { this.filtered.addObject (chip); } else { this.filtered.removeObject (chip); } } } @action sync (element, [filtered]) { filtered.forEach (chip => this.select (this.getChipId (chip))); } get filtered () { return this.args.filtered || A (); } get data () { return this.chips.map (chip => new ChipData (chip, this)); } }
JavaScript
class AttributeMustacheProvider extends Provider { get FOR_NODE_TYPES () { return [ 1 ] } // document.ELEMENT_NODE constructor (params = {}) { super(params) this.ATTRIBUTES_TO_SKIP = new Set(params.attributesToSkip || ['data-bind']) this.ATTRIBUTES_BINDING_MAP = params.attributesBindingMap || DEFAULT_ATTRIBUTE_BINDING_MAP } * attributesToInterpolate (attributes) { for (const attr of Array.from(attributes)) { if (this.ATTRIBUTES_TO_SKIP.has(attr.name)) { continue } if (attr.specified && attr.value.includes('{{')) { yield attr } } } nodeHasBindings (node) { return !this.attributesToInterpolate(node.attributes).next().done } partsTogether (parts, context, node, ...valueToWrite) { if (parts.length > 1) { return parts .map(p => unwrap(p.asAttr(context, this.globals, node))).join('') } // It may be a writeable observable e.g. value="{{ value }}". const part = parts[0].asAttr(context, this.globals) if (valueToWrite.length) { part(valueToWrite[0]) } return part } attributeBinding (name, parts) { return [name, parts] } * bindingParts (node, context) { for (const attr of this.attributesToInterpolate(node.attributes)) { const parts = Array.from(parseInterpolation(attr.value)) if (parts.length) { yield this.attributeBinding(attr.name, parts) } } } getPossibleDirectBinding (attrName) { const bindingName = this.ATTRIBUTES_BINDING_MAP[attrName] return bindingName && this.bindingHandlers.get(attrName) } * bindingObjects (node, context) { for (const [attrName, parts] of this.bindingParts(node, context)) { const bindingForAttribute = this.getPossibleDirectBinding(attrName) const handler = bindingForAttribute ? attrName : `attr.${attrName}` const accessorFn = bindingForAttribute ? (...v) => this.partsTogether(parts, context, node, ...v) : (...v) => ({[attrName]: this.partsTogether(parts, context, node, ...v)}) node.removeAttribute(attrName) yield { [handler]: accessorFn } } } getBindingAccessors (node, context) { return Object.assign({}, ...this.bindingObjects(node, context)) } }
JavaScript
class SplunkLogDriver extends log_driver_1.LogDriver { /** * Constructs a new instance of the SplunkLogDriver class. * * @param props the splunk log driver configuration options. * @stability stable */ constructor(props) { super(); this.props = props; if (!props.token && !props.secretToken) { throw new Error('Please provide either token or secretToken.'); } if (props.gzipLevel) { utils_1.ensureInRange(props.gzipLevel, -1, 9); } } /** * Called when the log driver is configured on a container. * * @stability stable */ bind(_scope, _containerDefinition) { const options = utils_1.stringifyOptions({ 'splunk-token': this.props.token, 'splunk-url': this.props.url, 'splunk-source': this.props.source, 'splunk-sourcetype': this.props.sourceType, 'splunk-index': this.props.index, 'splunk-capath': this.props.caPath, 'splunk-caname': this.props.caName, 'splunk-insecureskipverify': this.props.insecureSkipVerify, 'splunk-format': this.props.format, 'splunk-verify-connection': this.props.verifyConnection, 'splunk-gzip': this.props.gzip, 'splunk-gzip-level': this.props.gzipLevel, ...utils_1.renderCommonLogDriverOptions(this.props), }); return { logDriver: 'splunk', options, secretOptions: this.props.secretToken && utils_1.renderLogDriverSecretOptions({ 'splunk-token': this.props.secretToken }, _containerDefinition.taskDefinition), }; } }
JavaScript
class DecoderForI extends Decoder_1.Decoder { /** * Constructor of DecoderForI. */ constructor() { super(); /** * The string for error message. */ this.errMsg = ""; } /** * Method for getting the decoder for instruction of type-I. * @returns the decoder to validate and decode instructions of type-I. */ static getDecoder() { return this.decoder; } /** * Method for validating the instruction of type-I. * @returns true if the instruction is valid, otherwise false. */ validate() { let posOfSpace = this.ins.indexOf(" "); let operandRS = ""; let operandRT = ""; let IMM = ""; if (this.operator == "lui") { let operands = this.ins.substring(posOfSpace + 1, this.ins.length).split(",", 2); operandRT = operands[0]; IMM = operands[1]; } else if (this.operator == "beq" || this.operator == "bne") { let operands = this.ins.substring(posOfSpace + 1, this.ins.length).split(",", 3); operandRS = operands[0]; operandRT = operands[1]; IMM = operands[2]; } else if (this.operator == "addi" || this.operator == "addiu" || this.operator == "andi" || this.operator == "ori" || this.operator == "slti" || this.operator == "sltiu") { let operands = this.ins.substring(posOfSpace + 1, this.ins.length).split(",", 3); operandRT = operands[0]; operandRS = operands[1]; IMM = operands[2]; } else { // lbu, lhu, ll, lw, sb, sc, sh, sw let numLeftBracket = this.ins.split("(").length - 1; let numRightBracket = this.ins.split(")").length - 1; if (!(numLeftBracket == 1 && numRightBracket == 1)) { this.errMsg = this.errMsg + "Error 201: Invalid instruction format. -- " + this.getIns() + "\n"; return false; } let operands = this.ins.substring(posOfSpace + 1, this.ins.length).split(",", 2); let leftBracket = operands[1].indexOf("("); let rightBracket = operands[1].indexOf(")"); operandRT = operands[0]; operandRS = operands[1].substring(leftBracket + 1, rightBracket); IMM = operands[1].substring(0, leftBracket); } let patt1 = /^[0-9]+$/; let patt2 = /^[a-z0-9]+$/; let patt3 = /^(\-|\+)?\d+$/; if (!patt3.test(IMM)) { this.errMsg = this.errMsg + "Error 202: Invalid immediate number. -- " + this.getIns() + "\n"; return false; } else if (+IMM <= -32768 || +IMM >= 32767) { this.errMsg = this.errMsg + "Error 203: Invalid immediate number. Out of range. -- " + this.getIns() + "\n"; return false; } let operands = [operandRS, operandRT]; let i; for (i = 0; i < operands.length; i++) { let operand = operands[i].substring(1, operands[i].length); if (operands[i].charAt(0) == "$" && patt1.test(operand) && +operand > 31) { this.errMsg = this.errMsg + "Error 204: Invalid operand. -- " + this.getIns() + "\n"; return false; } else if (operands[i] == "" || (operands[i].charAt(0) == "$" && patt1.test(operand) && +operand <= 31)) { continue; } else if (operands[i].charAt(0) == "$" && patt2.test(operand)) { if (MapForRegister_1.MapForRegister.getMap().has(operand)) { let operandID = MapForRegister_1.MapForRegister.getMap().get(operand); if (operandID == undefined) { this.errMsg = this.errMsg + "Error 205: Invalid operand. -- " + this.getIns() + "\n"; return false; } else { this.ins = this.ins.replace(operand, operandID); } } else { this.errMsg = this.errMsg + "Error 206: Invalid operand. -- " + this.getIns() + "\n"; return false; } } else { this.errMsg = this.errMsg + "Error 207: Invalid operand. -- " + this.getIns() + "\n"; return false; } } return true; } /** * Method for decoding the instruction of type-I into binary code. * @returns void */ decode() { let instruction = new InstructionI_1.InstructionI(this.ins); this.binIns = instruction.getBinIns(); } /** * Method for getting the error message of invalid instruction of type-I. * @returns a string of error message. */ getErrMsg() { return this.errMsg; } }
JavaScript
class MyPlane extends CGFobject{ constructor(scene, nrDivs, minS, maxS, minT, maxT) { super(scene); // nrDivs = 1 if not provided nrDivs = typeof nrDivs !== 'undefined' ? nrDivs : 1; this.nrDivs = nrDivs; this.patchLength = 1.0 / nrDivs; this.minS = minS || 0; this.maxS = maxS || 1; this.minT = minT || 0; this.maxT = maxT || 1; this.q = (this.maxS - this.minS) / this.nrDivs; this.w = (this.maxT - this.minT) / this.nrDivs; this.initBuffers(); } initBuffers() { // Generate vertices, normals, and texCoords this.vertices = []; this.normals = []; this.texCoords = []; var yCoord = 0.5; for (var j = 0; j <= this.nrDivs; j++) { var xCoord = -0.5; for (var i = 0; i <= this.nrDivs; i++) { this.vertices.push(xCoord, yCoord, 0); this.normals.push(0, 0, 1); this.texCoords.push(this.minS + i * this.q, this.minT + j * this.w); xCoord += this.patchLength; } yCoord -= this.patchLength; } // Generating indices this.indices = []; var ind = 0; for (var j = 0; j < this.nrDivs; j++) { for (var i = 0; i <= this.nrDivs; i++) { this.indices.push(ind); this.indices.push(ind + this.nrDivs + 1); ind++; } if (j + 1 < this.nrDivs) { this.indices.push(ind + this.nrDivs); this.indices.push(ind); } } this.primitiveType = this.scene.gl.TRIANGLE_STRIP; this.initGLBuffers(); } setFillMode() { this.primitiveType=this.scene.gl.TRIANGLE_STRIP; } setLineMode() { this.primitiveType=this.scene.gl.LINES; }; }
JavaScript
class CachablePainting { /** * @param {!function(key: *) : !{width: !int, height: !int}} sizeFunc * @param {!function(painter: !Painter | !(function(!Painter, !string): void)) : void} drawingFunc */ constructor(sizeFunc, drawingFunc) { /** @type {!function(key: *) : !{width: !int, height: !int}} */ this.sizeFunc = sizeFunc; /** * @type {!(function(!Painter): void) | !(function(!Painter, !string): void)} * @private */ this._drawingFunc = drawingFunc; /** * @type {!Map.<!string, !HTMLCanvasElement>} * @private */ this._cachedCanvases = new Map(); } /** * @param {!int} x * @param {!int} y * @param {!Painter} painter * @param {!*=} key */ paint(x, y, painter, key=undefined) { if (!this._cachedCanvases.has(key)) { let canvas = /** @type {!HTMLCanvasElement} */ document.createElement('canvas'); let {width, height} = this.sizeFunc(key); canvas.width = width; canvas.height = height; this._drawingFunc(new Painter(canvas, fixedRng.restarted()), key); this._cachedCanvases.set(key, canvas); } painter.ctx.drawImage(this._cachedCanvases.get(key), x, y); } }
JavaScript
class NrqlFactory { static getFactory(data) { // console.debug(data); const hasSpa = get(data, 'actor.entity.spa.results[0].count'); if (hasSpa > 0) { return new SPAFactory(); } else { return new PageViewFactory(); } } constructor() { if (this.constructor === 'NrqlFactory') { throw new TypeError( 'Abstract class "NrqlFactory" cannot be instantiated.' ); } if (this.getType === undefined) { throw new TypeError('NrqlFactory classes must implement getType'); } if (this.getPerformanceTargets === undefined) { throw new TypeError( 'NrqlFactory classes must implement getPerformanceTargets' ); } if (this.getQuery1 === undefined) { throw new TypeError('NrqlFactory classes must implement getQuery1'); } if (this.getQuery2 === undefined) { throw new TypeError('NrqlFactory classes must implement getQuery2'); } if (this.getQuery3 === undefined) { throw new TypeError('NrqlFactory classes must implement getQuery3'); } if (this.getQuery4 === undefined) { throw new TypeError('NrqlFactory classes must implement getQuery4'); } if (this.getCohortGraphQL === undefined) { throw new TypeError( 'NrqlFactory classes must implement getCohortGraphQL' ); } } }
JavaScript
class AbstractGenerator { constructor(options = {}) { this.entities = []; this.indentation = 0; this.name = null; this.options = options; } addEntity(entity) { this.entities.push(entity); } /* * Should generate code based on the 'entities' array. */ generate() {} /* * Should return an object literal with allowed options (typically CLI arguments) as keys and options' descriptions as values. */ getAllowedOptions() { return null; } /* * Should return the output file's final content based on its name. Content will then be saved in the file, replacing its current content if any. */ getContent(file) { return null; } /* * Should return an array containing the output file(s) name(s) (specific to almost each generator) with the extension (e.g. 'file.sql'). */ getOutputFilesNames() { return null; } /* * Returns `this.indentation * 2` whitespaces (e.g. 2, 4...). */ indent() { var str = ''; for (var i = 0; i < this.indentation * 2; i++) str += ' '; return str; } sortEntities() { this.entities.sort(function(a, b) { return a.references.length - b.references.length; }); } }
JavaScript
class HardwareComponentGroup extends models['BaseModel'] { /** * Create a HardwareComponentGroup. * @member {string} displayName The display name the hardware component * group. * @member {date} lastUpdatedTime The last updated time. * @member {array} components The list of hardware components. */ constructor() { super(); } /** * Defines the metadata of HardwareComponentGroup * * @returns {object} metadata of HardwareComponentGroup * */ mapper() { return { required: false, serializedName: 'HardwareComponentGroup', type: { name: 'Composite', className: 'HardwareComponentGroup', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, kind: { required: false, serializedName: 'kind', type: { name: 'Enum', allowedValues: [ 'Series8000' ] } }, displayName: { required: true, serializedName: 'properties.displayName', type: { name: 'String' } }, lastUpdatedTime: { required: true, serializedName: 'properties.lastUpdatedTime', type: { name: 'DateTime' } }, components: { required: true, serializedName: 'properties.components', type: { name: 'Sequence', element: { required: false, serializedName: 'HardwareComponentElementType', type: { name: 'Composite', className: 'HardwareComponent' } } } } } } }; } }
JavaScript
class App extends React.Component{ constructor (props, context) { super(props, context); } componentDidMount () { const { loadNWBFile, reset, model, nwbFileLoaded, raiseError } = this.props; self = this; GEPPETTO.on(GEPPETTO.Events.Error_while_exec_python_command, error => { if (error) { raiseError(error); } }) if (nwbFileService.getNWBFileUrl()){ loadNWBFile(nwbFileService.getNWBFileUrl()); } const loadFromEvent = event => { // console.debug('Parent frame message received:', event) // Here we would expect some cross-origin check, but we don't do anything more than load a nwb file here if (typeof (event.data) == 'string') { if (self.props.model) { reset(); } loadNWBFile(event.data); // The message may be triggered after the notebook was ready } } // A message from the parent frame can specify the file to load window.addEventListener('message', loadFromEvent); window.load = loadFromEvent; GEPPETTO.on(GEPPETTO.Events.Model_loaded, () => { nwbFileLoaded(Model); }); GEPPETTO.on(GEPPETTO.Events.Hide_spinner, () => { // Handles when Geppetto is hiding the spinner on its logic if (Object.values(this.props.loading).length !== 0) { this.showSpinner(this.props.loading); } }); } componentDidUpdate () { const { notebookReady, model, loading, isLoadedInNotebook, isLoadingInNotebook, error } = this.props; if (!isLoadedInNotebook && model && notebookReady && !isLoadingInNotebook && !error) { // We may have missed the loading if notebook was not initialized at the time of the url change } // It would be better having the spinner as a parametrized react component if (Object.values(loading).length !== 0) { this.showSpinner(loading); } else { GEPPETTO.trigger(GEPPETTO.Events.Hide_spinner); } } showSpinner (loading) { if (Object.values(loading).length !== 0) { const msg = Object.values(loading)[0]; setTimeout(() => { GEPPETTO.trigger(GEPPETTO.Events.Show_spinner, msg); }, 500); } } render () { const { embedded, nwbFileUrl } = this.props; var page; if (nwbFileUrl) { page = <FileExplorerPage/> } else if (!embedded) { page = <WelcomePage /> } else { return null; } return ( <div style={{ height: '100%', width: '100%' }}> <div id="main-container-inner"> { page } </div> <div style={{ display: "none" }}> { // getConsole() } </div> </div> ) } }
JavaScript
class Square extends Rectangle { constructor(s) { super(s, s); } }
JavaScript
class WorkoutListScreen extends React.Component { static navigationOptions = { title: 'Workout List', }; state={ text:'' } componentDidMount(){ //error when adding a new schedule then viewing its workouts this.props.fetchSchedulesWorkouts(this.props.currentSchedule) } openDrawer = () => { this.props.navigation.dispatch(DrawerActions.openDrawer()); } renderNavBar() { return ( <View style={ styles.navBar }> <TouchableOpacity onPress={ this.openDrawer }> <FAIcon name='bars' size={22} style={{ color: colors.bdMainRed }} /> </TouchableOpacity> </View> ) } handleAddWorkout=()=>{ if ( this.state.text!=''){ const workout = { name:this.state.text, exercises:[] } this.props.postNewWorkout(workout, this.props.currentSchedule) this.setState({text:''}) } } renderWorkoutList=()=>{ return ( <WorkoutList workouts={this.props.workouts} handlePress={()=>{this.props.navigation.navigate('Workout',{pastWorkout:false})}} /> ) } renderAddWorkoutForm=()=>{ return ( <> <TextInput style={styles.input} placeholder='Enter a Workout Name' onChangeText={(text) => this.setState({text})} value={this.state.text} /> <TouchableOpacity style={styles.addButton} title="Add New Workout" onPress={() => this.handleAddWorkout()}> <FAIcon name='plus' size={35} style={{ color: colors.txtWhite,bottom:-5,right:-5, }} /> </TouchableOpacity> </> ) } renderNav=()=>{ return ( <> <Button title="Go to Home" onPress={() => this.props.navigation.navigate('Home')} /> <Button title="Go back" onPress={() => this.props.navigation.navigate('ScheduleList')} /> </> ) } render() { return ( <> {this.renderNavBar()} {this.renderAddWorkoutForm()} <ScrollView style={[ styles.container, this.props.style || {} ]}> {this.props.currentSchedule?this.renderWorkoutList():null} </ScrollView> </> ); } }
JavaScript
class Server { constructor (Context, Route, Logger, Exception) { this.Context = Context this.Route = Route this.Logger = Logger this.Exception = Exception this._httpInstance = null this._exceptionHandlerNamespace = null this._middleware = new MiddlewareBase('handle', this.Logger.warning.bind(this.Logger)) } /** * Returns the exception handler to handle the HTTP exceptions * * @method _getExceptionHandlerNamespace * * @return {Class} * * @private */ _getExceptionHandlerNamespace () { const exceptionHandlerFile = resolver.forDir('exceptions').getPath('Handler.js') try { fs.accessSync(exceptionHandlerFile, fs.constants.R_OK) return resolver.forDir('exceptions').translate('Handler') } catch (error) { return 'Adonis/Exceptions/BaseExceptionHandler' } } /** * Returns a middleware iterrable by composing server * middleware. * * @method _executeServerMiddleware * * @param {Object} ctx * * @return {Promise} * * @private */ _executeServerMiddleware (ctx) { return this._middleware .composeServer() .params([ctx]) .run() } /** * Returns a middleware iterrable by composing global and route * middleware. * * @method _executeRouteHandler * * @param {Array} routeMiddleware * @param {Object} ctx * @param {Function} finalHandler * * @return {Promise} * * @private */ _executeRouteHandler (routeMiddleware, ctx, routeHandler) { return this._middleware .composeGlobalAndNamed(routeMiddleware) .params([ctx]) .concat([routeHandler]) .run() } /** * Invokes the route handler and uses the return to set the * response, only when not set already * * @method _routeHandler * * @param {Object} ctx * @param {Function} next * @param {Array} params * * @return {Promise} * * @private */ async _routeHandler (ctx, next, params) { const { method } = resolver.forDir('httpControllers').resolveFunc(params[0]) const returnValue = await method(ctx) this._safelySetResponse(ctx.response, returnValue) await next() } /** * Pulls the route for the current request. If missing * will throw an exception * * @method _getRoute * * @param {Object} ctx * * @return {Route} * * @throws {HttpException} If * * @private */ _getRoute (ctx) { const route = this.Route.match(ctx.request.url(), ctx.request.method(), ctx.request.hostname()) if (!route) { throw new GE.HttpException(`Route not found ${ctx.request.method()} ${ctx.request.url()}`, 404) } debug('route found for %s url', ctx.request.url()) ctx.params = route.params ctx.subdomains = route.subdomains ctx.request.params = route.params return route } /** * Sets the response on the response object, only when it * has not been set already * * @method _safelySetResponse * * @param {Object} ctx * @param {Mixed} content * @param {String} method * * @return {void} * * @private */ _safelySetResponse (response, content, method = 'send') { if (!this._madeSoftResponse(response) && content !== undefined) { response.send(content) } } /** * End the response only when it's pending * * @method _endResponse * * @param {Object} response * * @return {void} * * @private */ _endResponse (response) { if (response.isPending && response.implicitEnd) { response.end() } } /** * Returns a boolean indicating if a soft response has been made * * @method _madeSoftResponse * * @param {Object} response * * @return {Boolean} * * @private */ _madeSoftResponse (response) { return response.lazyBody.content !== undefined && response.lazyBody.content !== null && response.lazyBody.method } /** * Finds if response has already been made, then ends the response. * * @method _evaluateResponse * * @param {Object} response * * @return {void} * * @private */ _evaluateResponse (response) { if (this._madeSoftResponse(response) && response.isPending) { debug('server level middleware ended the response') this._endResponse(response) } } /** * Handles the exception by invoking `handle` method * on the registered exception handler. * * @method _handleException * * @param {Object} error * @param {Object} ctx * * @return {void} * * @private */ async _handleException (error, ctx) { error.status = error.status || 500 try { const handler = ioc.make(ioc.use(this._exceptionHandlerNamespace)) if (typeof (handler.handle) !== 'function' || typeof (handler.report) !== 'function') { throw GE .RuntimeException .invoke(`${this._exceptionHandlerNamespace} class must have handle and report methods on it`) } handler.report(error, { request: ctx.request, auth: ctx.auth }) await handler.handle(error, ctx) } catch (error) { ctx.response.status(500).send(`${error.name}: ${error.message}\n${error.stack}`) } this._endResponse(ctx.response) } /** * Register an array of global middleware to be called * for each route. If route does not exists, middleware * will never will called. * * Calling this method multiple times will concat to the * existing list * * @method registerGlobal * * @param {Array} middleware * * @chainable * * @throws {InvalidArgumentException} If middleware is not an array * * @example * ```js * Server.registerGlobal([ * 'Adonis/Middleware/BodyParser', * 'Adonis/Middleware/Session' * ]) * ``` */ registerGlobal (middleware) { this._middleware.registerGlobal(middleware) return this } /** * Register server middleware to be called no matter * whether a route has been registered or not. The * great example is a middleware to serve static * resources from the `public` directory. * * @method use * * @param {Array} middleware * * @chainable * * @throws {InvalidArgumentException} If middleware is not an array * * @example * ```js * Server.use(['Adonis/Middleware/Static']) * ``` */ use (middleware) { this._middleware.use(middleware) return this } /** * Register named middleware. Calling this method for * multiple times will concat to the existing list. * * @method registerNamed * * @param {Object} middleware * * @chainable * * @throws {InvalidArgumentException} If middleware is not an object with key/value pair. * * @example * ```js * Server.registerNamed({ * auth: 'Adonis/Middleware/Auth' * }) * * // use it on route later * Route * .get('/profile', 'UserController.profile') * .middleware(['auth']) * * // Also pass params * Route * .get('/profile', 'UserController.profile') * .middleware(['auth:basic']) * ``` */ registerNamed (middleware) { this._middleware.registerNamed(middleware) return this } /** * Returns the http server instance. Also one can set * a custom http instance. * * @method getInstance * * @return {Object} */ getInstance () { if (!this._httpInstance) { this._httpInstance = http.createServer(this.handle.bind(this)) } return this._httpInstance } /** * Set a custom http instance instead of using * the default one * * @method setInstance * * @param {Object} httpInstance * * @return {void} * * @example * ```js * const https = require('https') * Server.setInstance(https) * ``` */ setInstance (httpInstance) { if (this._httpInstance) { throw GE.RuntimeException.invoke('Attempt to hot swap http instance failed. Make sure to call Server.setInstance before starting the http server', 500, 'E_CANNOT_SWAP_SERVER') } this._httpInstance = httpInstance } /** * Handle method executed for each HTTP request and handles * the request lifecycle by performing following operations. * * 1. Call server level middleware * 2. Resolve route * 3. Call global middleware * 4. Call route middleware * 5. Execute route handler. * * Also if route is not found. All steps after that are not * executed and 404 exception is thrown. * * @method handle * @async * * @param {Object} req * @param {Object} res * * @return {void} */ handle (req, res) { const ctx = new this.Context(req, res) const { request, response } = ctx debug('new request on %s url', request.url()) this._executeServerMiddleware(ctx) .then(() => { /** * We need to find out whether any of the server middleware has * ended the response or not. * * If they did, then simply do not execute the route. */ this._evaluateResponse(response) if (!response.isPending) { debug('ending request within server middleware chain') return } const route = this._getRoute(ctx) return this._executeRouteHandler(route.route.middlewareList, ctx, { namespace: this._routeHandler.bind(this), params: [route.route.handler] }) }) .then(() => { debug('ending response for %s url', request.url()) this._endResponse(response) }) .catch((error) => { debug('received error on %s url', request.url()) this._handleException(error, ctx) }) } /** * Binds the exception handler to be used for handling HTTP * exceptions. If `namespace` is not provided, the server * will choose the conventional namespace * * @method bindExceptionHandler * * @param {String} [namespace] * * @chainable */ bindExceptionHandler (namespace) { this._exceptionHandlerNamespace = namespace || this._getExceptionHandlerNamespace() debug('using %s binding to handle exceptions', this._exceptionHandlerNamespace) return this } /** * Listen on given host and port. * * @method listen * * @param {String} [host = localhost] * @param {Number} [port = 3333] * @param {Function} [callback] * * @return {Object} */ listen (host = 'localhost', port = 3333, callback) { if (!this._exceptionHandlerNamespace) { this.bindExceptionHandler() } this.Logger.info('serving app on http://%s:%s', host, port) return this.getInstance().listen(port, host, callback) } /** * Closes the HTTP server * * @method close * * @param {Function} callback * * @return {void} */ close (callback) { this.getInstance().close(callback) } }
JavaScript
class V2MissingSymbolCrashGroupsResponse { /** * Create a V2MissingSymbolCrashGroupsResponse. * @property {number} totalCrashCount total number of cashes for all the * groups * @property {array} groups list of crash groups formed by missing symbols * combination */ constructor() { } /** * Defines the metadata of V2MissingSymbolCrashGroupsResponse * * @returns {object} metadata of V2MissingSymbolCrashGroupsResponse * */ mapper() { return { required: false, serializedName: 'v2MissingSymbolCrashGroupsResponse', type: { name: 'Composite', className: 'V2MissingSymbolCrashGroupsResponse', modelProperties: { totalCrashCount: { required: true, serializedName: 'total_crash_count', type: { name: 'Number' } }, groups: { required: true, serializedName: 'groups', type: { name: 'Sequence', element: { required: false, serializedName: 'V2MissingSymbolCrashGroupElementType', type: { name: 'Composite', className: 'V2MissingSymbolCrashGroup' } } } } } } }; } }
JavaScript
class LocationPrecision extends ComparableEnum { /** * Constructor. * * @param {string} name the unique name for this precision * @param {number} precision a relative precision value for this precision */ constructor(name, precision) { super(name, precision); if (this.constructor === LocationPrecision) { Object.freeze(this); } } /** * Get the relative precision value. * * This is an alias for {@link #name}. * * @returns {number} the precision */ get precision() { return this.value; } /** * Get the {@link module:domain~LocationPrecisions} values. * * @override * @inheritdoc */ static enumValues() { return LocationPrecisionValues; } }
JavaScript
class ApiEntryPoint extends ApiItemContainerMixin_1.ApiItemContainerMixin(ApiNameMixin_1.ApiNameMixin(ApiItem_1.ApiItem)) { constructor(options) { super(options); } /** @override */ get kind() { return "EntryPoint" /* EntryPoint */; } /** @override */ get canonicalReference() { return this.name; } }
JavaScript
class Card extends Component { constructor(props, ...args){ super(props, ...args); // Bind component methods this.makeHeader = this.makeHeader.bind(this); } render(){ let bodyClass = "card-body"; if(this.props.extraData.padding){ bodyClass += ` p-${this.props.extraData.padding}`; } return h('div', { class: "cell card", style: this.props.extraData.divStyle, id: this.props.id, "data-cell-id": this.props.id, "data-cell-type": "Card" }, [ this.makeHeader(), h('div', { class: bodyClass }, [ this.getReplacementElementFor('contents') ]) ]); } makeHeader(){ if(this.replacements.hasReplacement('header')){ return h('div', {class: 'card-header'}, [ this.getReplacementElementFor('header') ]); } return null; } }
JavaScript
class MailosaurClient { /** * Create a MailosaurBaseClient. * @param {string} apiKey - Your Mailosaur API key. * @param {string} [baseUrl] - The base URL of the Mailosaur service. * */ constructor(apiKey, baseUrl) { if (!apiKey) { throw new Error('\'apiKey\' must be set.'); } this.request = new Request({ baseUrl: baseUrl || 'https://mailosaur.com/', apiKey }); this.analysis = new operations.Analysis(this); this.files = new operations.Files(this); this.messages = new operations.Messages(this); this.servers = new operations.Servers(this); this.usage = new operations.Usage(this); this.models = models; } httpError(response) { const httpStatusCode = response.statusCode; const httpResponseBody = response.body ? JSON.stringify(response.body) : null; switch (httpStatusCode) { case 400: return new MailosaurError('Request had one or more invalid parameters.', 'invalid_request', httpStatusCode, httpResponseBody); case 401: return new MailosaurError('Authentication failed, check your API key.', 'authentication_error', httpStatusCode, httpResponseBody); case 403: return new MailosaurError('Insufficient permission to perform that task.', 'permission_error', httpStatusCode, httpResponseBody); case 404: return new MailosaurError('Request did not find any matching resources.', 'invalid_request', httpStatusCode, httpResponseBody); default: return new MailosaurError('An API error occurred, see httpResponse for further information.', 'api_error', httpStatusCode, httpResponseBody); } } }
JavaScript
class Emulator extends Component { static propTypes = { emulator: PropTypes.object, // emulator service width: PropTypes.number, height: PropTypes.number, scale: PropTypes.number, refreshRate: PropTypes.number, // Refresh rate to use when falling back to screenshots. view: PropTypes.oneOf(["webrtc", "png", "fallback"]).isRequired }; static defaultProps = { width: 1080, // The width of the emulator display height: 1920, // The height of the emulator display scale: 0.35, // Scale factor of the emulator image refreshRate: 5, // Desired refresh rate if using screenshots. view: "webrtc" // Default view to be used. }; components = { webrtc: EmulatorWebrtcView, png: EmulatorPngView, fallback: EmulatorFallbackView }; render() { const { width, height, scale, refreshRate, view, emulator } = this.props; const SpecificView = this.components[view]; const styled = { outline: "none", maxWidth: width * scale }; return ( <div tabIndex="1" style={styled} > <SpecificView width={width * scale} height={height * scale} refreshRate={refreshRate} emulator={emulator} /> </div> ); } }
JavaScript
class Row { constructor (row) { this.dom = {} this.dom.self = $(row) this.dom.button = $('button', this.dom.self) this.action = this.dom.self.data('action') this.method = this.dom.self.data('method') this.dom.button.on('click', (e) => { e.preventDefault() this.serialize() }) } serialize () { $.ajax(this.action, { method: this.method || 'GET', data: $('input', this.dom.self).serialize() }) .done(function (data) { window.location = window.location.href }) } }
JavaScript
class ControlResult { /** * Construct a new instance. * * @param {Control} control * The control this result belongs to. * * @constructor */ constructor(control) { this.control = control; this.currentLine = null; this.raw = {stdout: '', stderr: ''}; this.stderr = []; this.stdout = []; } /** * Aborts the result. * * @param {String} [message='Aborted!'] * The message to use for CocoaDialogAbort. * * @return {ControlResult} */ abort(message = 'Aborted!') { return this.setError(new CocoaDialogAbort(message)); } /** * Processes the final result. */ process() { // Trim new lines from start/end and split into an array. let stdout = this.raw.stdout.replace(trimRegExp, ''); let stderr = this.raw.stderr.replace(trimRegExp, ''); this.stdout = stdout ? stdout.split('\n') : []; this.stderr = stderr ? stderr.split('\n') : []; // Check if there's a fatal error. if (this.stderr.length) { let message = chalk ? chalk.bold.red(this.stderr.join('\n')) : this.stderr.join('\n'); if (this.stdout.length) { message += chalk ? chalk.bold.yellow(this.stdout.join('\n')) : this.stdout.join('\n'); } this.setError(message); } // Check if the control has timed out. if (this.control.options.timeout && this.stdout[0] === 'timeout') { this.timeout(); } } /** * Indicates whether result has been aborted. * * Note: this can be true if timed out. * * @return {Boolean} */ hasAborted() { return !!(this.error && this.error instanceof CocoaDialogAbort); } /** * Indicates whether result has an error. * * Note: this can be true if aborted or timed out. * * @return {Boolean} */ hasError() { return !!(this.error && this.error instanceof CocoaDialogError); } /** * Indicates whether result has timed out. * * @return {Boolean} */ hasTimedOut() { return !!(this.error && this.error instanceof CocoaDialogTimeout); } /** * Sets an error on the result. * * @param {String|CocoaDialogError} [message='Error!'] * The message to use for CocoaDialogError. * * @return {ControlResult} */ setError(message = 'Error!') { if (message instanceof CocoaDialogError) { this.error = message; } else { this.error = new CocoaDialogError(message); } return this; } /** * Times out the result. * * @param {String} [message='Timed out!'] * The message to use for CocoaDialogTimeout. * * @return {ControlResult} */ timeout(message = 'Timed out!') { return this.setError(new CocoaDialogTimeout(message)); } }
JavaScript
class GridTreeColumnElement extends GridColumnElement { static get template() { return html` <template id="template"> <vaadin-grid-tree-toggle leaf="[[__isLeafItem(item, itemHasChildrenPath)]]" expanded="{{expanded}}" level="[[level]]"> [[__getToggleContent(path, item)]] </vaadin-grid-tree-toggle> </template> `; } static get is() { return 'vaadin-grid-tree-column'; } static get properties() { return { /** * JS Path of the property in the item used as text content for the tree toggle. */ path: String, /** * JS Path of the property in the item that indicates whether the item has child items. * @attr {string} item-has-children-path */ itemHasChildrenPath: { type: String, value: 'children' } }; } /** @private */ _prepareBodyTemplate() { const template = this._prepareTemplatizer(this.$.template); // needed to override the dataHost correctly in case internal template is used. template.templatizer.dataHost = this; return template; } __isLeafItem(item, itemHasChildrenPath) { return !(item && item[itemHasChildrenPath]); } __getToggleContent(path, item) { return path && this.get(path, item); } }
JavaScript
class YourComponent extends Component { constructor(props) { super(props); this.state = { activeMarker: {}, center: { lat: 19.432608, lng: -99.133290 }, defaultIcon: { url: 'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|0091ff|40|_|%E2%80%A2', // url scaledSize: new this.props.google.maps.Size(20, 30), // scaled size }, highlightedIcon: { url: 'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|FFFF24|40|_|%E2%80%A2', // url scaledSize: new this.props.google.maps.Size(20, 30), // scaled size }, selectedPlace: {}, showFavourites: false, showingInfoWindow: false, stores: [], } this.onMarkerClick = this.onMarkerClick.bind(this); this.toggleShowFavourites = this.toggleShowFavourites.bind(this); } componentWillMount() { if ( localStorage.getItem('stores') ) { let stores = JSON.parse(localStorage.getItem('stores')); this.setState(() => { return { stores: stores } }); //If we have some stores withouth a fetched position for( let i = 0; i < stores.length; i++ ) { let store = stores[i]; if ( !store.Position ) { //We try to fetch the coordinates from the addres this.fillMissingPositions(); break; } } } else { //Load data from JSON this.fetchStoresData(); } } /** * @param index in the array of the store */ centerOnMap(index) { this.setState((prevState) => { let arr = prevState.stores; let store = arr[index]; return { center: store.Position, } }); } fetchStoresData() { axios.get('./store_directory.json') .then(response => { let stores = response.data; for( let i = 0; i < stores.length; i++ ) { let store = stores[i]; store['Position'] = undefined; store['Favourite'] = false; } this.setState((prevState) => { return { stores: stores } }); localStorage.setItem('stores', JSON.stringify(stores)); this.fillMissingPositions(); }) .catch(function (error) { console.log(error); }); } /** * In order to avoid QUERY_LIMITS * we set a timeout to look for coordinates * of a store with an undefined Position */ fillMissingPositions() { if ( this.state.stores.length > 0 ) { for ( let i = 0; i < this.state.stores.length; i++ ) { let store = this.state.stores[i]; if ( !store.Position ) { Geocode.fromAddress(store.Address).then( response => { const { lat, lng } = response.results[0].geometry.location; this.setState((prevState) => { let arr = prevState.stores; let store = arr[i]; store.Position = { lat: lat, lng: lng }; localStorage.setItem('stores', JSON.stringify(arr)); return { stores: arr } }) }, error => { console.error(error); } ); break; } } } setTimeout(this.fillMissingPositions.bind(this), 500); } /** * * @param {*} props The props of the marker * @param {*} marker The marker that was clicked * @param {*} e */ onMarkerClick(props, marker, e) { this.setState((prevState) => { let arr = prevState.stores; let store = arr[props.index]; if ( !prevState.showFavourites ) { store.Favourite = !store.Favourite; } localStorage.setItem('stores', JSON.stringify(arr)); return { activeMarker: marker, showingInfoWindow: true, selectedPlace: props, stores: arr } }); }; /** * * @param {*} index of the store to changed his favourite attribute */ toggleFavouriteElement(index) { this.setState((prevState) => { let arr = prevState.stores; let store = arr[index]; store.Favourite = !store.Favourite; localStorage.setItem('stores', JSON.stringify(arr)); return { stores: arr, } }); } /** * We toggle if the user want to see their favourites or all the stores */ toggleShowFavourites() { this.setState((prevState) => { return { showFavourites: !prevState.showFavourites, showingInfoWindow: false } }) } render() { return ( <div> <div style={{display: "flex", justifyContent: "space-around"}} className="row"> <div className="col-sm-12 col-md-12 col-lg-3 col-xl-3"> { this.state.showFavourites && <div className="ButtonHeader"> <Button onClick={this.toggleShowFavourites} className="FullButton" outline color="info">Stores</Button> <Button className="FullButton" color="success">My Favourites</Button> </div> } { !this.state.showFavourites && <div className="ButtonHeader"> <Button className="FullButton" color="info">Stores</Button> <Button onClick={this.toggleShowFavourites} className="FullButton" outline color="success">My Favourites</Button> </div> } <div className="container" style={{overflow: "scroll", height: "870px", marginBottom: "10px" }}> { this.state.showFavourites && this.state.stores.map((store, index) => { if ( store.Favourite ) { return ( <Card key={index} body inverse color="success"> <CardTitle>{store.Name}</CardTitle> <CardText>{store.Address}</CardText> <Button onClick={() => { this.toggleFavouriteElement(index) }} className="ActionButton" size="sm" color={(!store.Favourite) ? 'warning' : 'secondary'}> { (!store.Favourite) ? `Add To Favourites` : `Remove From Favourites` } </Button> { store.Position && <Button onClick={() => { this.centerOnMap(index) }} size="sm" color="danger">Center on Map</Button> } </Card> ); } } ) } { !this.state.showFavourites && this.state.stores.map((store, index) => <Card key={index} body inverse color={(!store.Favourite) ? 'info' : 'success'}> <CardTitle>{store.Name}</CardTitle> <CardText>{store.Address}</CardText> <Button onClick={() => { this.toggleFavouriteElement(index) }} className="ActionButton" size="sm" color={(!store.Favourite) ? 'warning' : 'secondary'}> { (!store.Favourite) ? `Add To Favourites` : `Remove From Favourites` } </Button> { store.Position && <Button onClick={() => { this.centerOnMap(index) }} size="sm" color="danger">Center on Map</Button> } </Card> ) } </div> </div> <div className="col-sm-12 col-md-12 col-lg-9 col-xl-9"> <Map google={this.props.google} map={this.props.map} initialCenter={this.state.center} center={this.state.center} zoom={12} style={{ width: "96%", overflow: "hidden", marginTop: "35px" }} > { !this.state.showFavourites && this.state.stores.map((store, index) => { return store.Position && ( <Marker key={index} onClick={this.onMarkerClick} name={store.Name} favourite={store.Favourite} position={store.Position} address={store.Address} index={index} icon={(store.Position.lng == this.state.center.lng && store.Position.lat == this.state.center.lat) ? this.state.defaultIcon : this.state.highlightedIcon} /> ); }) } { this.state.showFavourites && this.state.stores.map((store, index) => { if ( store.Favourite ) { return ( <Marker key={index} onClick={this.onMarkerClick} name={store.Name} favourite={store.Favourite} position={store.Position} address={store.Address} index={index} icon={(store.Position.lng == this.state.center.lng && store.Position.lat == this.state.center.lat) ? this.state.defaultIcon : this.state.highlightedIcon} /> ); } }) } <InfoWindow marker={this.state.activeMarker} visible={this.state.showingInfoWindow}> <div> <h4>{this.state.selectedPlace.name}</h4> <p>{this.state.selectedPlace.address}</p> </div> </InfoWindow> </Map> </div> </div> </div> ); } }
JavaScript
class Connection { /** * Creates a new instance of {@link Connection}. * @param {String} url The resource uri. * @param {Object} [options] The connection options. * @param {Array} [options.ca] Trusted certificates. * @param {String|Array|Buffer} [options.cert] The certificate key. * @param {String} [options.mimeType] The mime type to use. * @param {String|Buffer} [options.pfx] The private key, certificate, and CA certs. * @param {GraphSONReader} [options.reader] The reader to use. * @param {Boolean} [options.rejectUnauthorized] Determines whether to verify or not the server certificate. * @param {String} [options.traversalSource] The traversal source. Defaults to: 'g'. * @param {GraphSONWriter} [options.writer] The writer to use. * @param {Authenticator} [options.authenticator] The authentication handler to use. * @param {Object} [options.headers] An associative array containing the additional header key/values for the initial request. * @constructor */ constructor(url, options) { this.url = url; options = options || {}; this._ws = new WebSocket(url, { headers: options.headers, ca: options.ca, cert: options.cert, pfx: options.pfx, rejectUnauthorized: options.rejectUnauthorized }); this._ws.on('open', () => { this.isOpen = true; if (this._openCallback) { this._openCallback(); } }); this._ws.on('message', data => this._handleMessage(data)); // A map containing the request id and the handler this._responseHandlers = {}; this._reader = options.reader || new serializer.GraphSONReader(); this._writer = options.writer || new serializer.GraphSONWriter(); this._openPromise = null; this._openCallback = null; this._closePromise = null; /** * Gets the MIME type. * @type {String} */ this.mimeType = options.mimeType || defaultMimeType; this._header = String.fromCharCode(this.mimeType.length) + this.mimeType; this.isOpen = false; this.traversalSource = options.traversalSource || 'g'; this._authenticator = options.authenticator; } /** * Opens the connection, if its not already opened. * @returns {Promise} */ open() { if (this._closePromise) { return this._openPromise = Promise.reject(new Error('Connection has been closed')); } if (this.isOpen) { return Promise.resolve(); } if (this._openPromise) { return this._openPromise; } return this._openPromise = new Promise((resolve, reject) => { // Set the callback that will be invoked once the WS is opened this._openCallback = err => err ? reject(err) : resolve(); }); } /** @override */ submit(bytecode, op, args, requestId, processor) { return this.open().then(() => new Promise((resolve, reject) => { if (requestId === null || requestId === undefined) { requestId = utils.getUuid(); this._responseHandlers[requestId] = { callback: (err, result) => err ? reject(err) : resolve(result), result: null }; } const message = Buffer.from(this._header + JSON.stringify(this._getRequest(requestId, bytecode, op, args, processor))); this._ws.send(message); })); } _getRequest(id, bytecode, op, args, processor) { if (args) { args = this._adaptArgs(args, true); } return ({ 'requestId': { '@type': 'g:UUID', '@value': id }, 'op': op || 'bytecode', // if using op eval need to ensure processor stays unset if caller didn't set it. 'processor': (!processor && op !== 'eval') ? 'traversal' : processor, 'args': args || { 'gremlin': this._writer.adaptObject(bytecode), 'aliases': { 'g': this.traversalSource } } }); } _handleMessage(data) { const response = this._reader.read(JSON.parse(data.toString())); if (response.requestId === null || response.requestId === undefined) { // There was a serialization issue on the server that prevented the parsing of the request id // We invoke any of the pending handlers with an error Object.keys(this._responseHandlers).forEach(requestId => { const handler = this._responseHandlers[requestId]; this._clearHandler(requestId); if (response.status !== undefined && response.status.message) { return handler.callback( new Error(util.format( 'Server error (no request information): %s (%d)', response.status.message, response.status.code))); } else { return handler.callback(new Error(util.format('Server error (no request information): %j', response))); } }); return; } const handler = this._responseHandlers[response.requestId]; if (!handler) { // The handler for a given request id was not found // It was probably invoked earlier due to a serialization issue. return; } if (response.status.code === responseStatusCode.authenticationChallenge && this._authenticator) { this._authenticator.evaluateChallenge(response.result.data).then(res => { return this.submit(null, 'authentication', res, response.requestId); }).catch(handler.callback); return; } else if (response.status.code >= 400) { // callback in error return handler.callback( new Error(util.format('Server error: %s (%d)', response.status.message, response.status.code))); } switch (response.status.code) { case responseStatusCode.noContent: this._clearHandler(response.requestId); return handler.callback(null, new ResultSet(utils.emptyArray)); case responseStatusCode.partialContent: handler.result = handler.result || []; handler.result.push.apply(handler.result, response.result.data); break; default: if (handler.result) { handler.result.push.apply(handler.result, response.result.data); } else { handler.result = response.result.data; } this._clearHandler(response.requestId); return handler.callback(null, new ResultSet(handler.result)); } } /** * Clears the internal state containing the callback and result buffer of a given request. * @param requestId * @private */ _clearHandler(requestId) { delete this._responseHandlers[requestId]; } /** * Takes the given args map and ensures all arguments are passed through to _write.adaptObject * @param {Object} args Map of arguments to process. * @param {Boolean} protocolLevel Determines whether it's a protocol level binding. * @returns {Object} * @private */ _adaptArgs(args, protocolLevel) { if (args instanceof Object) { let newObj = {}; Object.keys(args).forEach((key) => { // bindings key (at the protocol-level needs special handling. without this, it wraps the generated Map // in another map for types like EnumValue. Could be a nicer way to do this but for now it's solving the // problem with script submission of non JSON native types if (protocolLevel && key === 'bindings') newObj[key] = this._adaptArgs(args[key], false); else newObj[key] = this._writer.adaptObject(args[key]); }); return newObj; } return args; } /** * Closes the Connection. * @return {Promise} */ close() { if (!this._closePromise) { this._closePromise = new Promise(resolve => { this._ws.on('close', function () { this.isOpen = false; resolve(); }); this._ws.close(); }); } return this._closePromise; } }
JavaScript
class ApiError extends Error { /** * Constructs an API error. * * @param {string=} message Human-readable error message * @param {number=} status Used HTTP status code * @param {string=} code Internal error code, usually the error name * @param {any=} details Optional details depending on the error * @param {Map<string, any>=} headers Optional headers sent as HTTP headers and not as response body */ constructor(message, status, code, details, headers) { super(message || "Internal server error occurred"); this.status = status || 500; this.code = code || ApiErrorCode.INTERNAL_SERVER_ERROR; this.details = details; this.headers = headers; } toJSON() { return { status: this.status, code: this.code, message: this.message, details: this.details, }; } }
JavaScript
class SocketError extends Error { /** * Constructs an API error. * * @param {string=} message Human-readable error message * @param {string=} code Internal error code, usually the error name * @param {any=} details Optional details depending on the error */ constructor(message, code, details) { super(message || "Internal server error occurred"); this.code = code || SocketErrorCode.INTERNAL_SERVER_ERROR; this.details = details; } toJSON() { return { code: this.code, message: this.message, details: this.details, }; } }
JavaScript
class Il2CppGC { constructor() { } /** Gets the heap size in bytes. */ static get heapSize() { return Il2Cpp.Api._gcGetHeapSize(); } /** Determines whether the garbage collector is disabled. */ static get isEnabled() { return !Il2Cpp.Api._gcIsDisabled(); } /** Determines whether the garbage collector is incremental. */ static get isIncremental() { return !!Il2Cpp.Api._gcIsIncremental(); } /** Gets the number of nanoseconds the garbage collector can spend in a collection step. */ static get maxTimeSlice() { return Il2Cpp.Api._gcGetMaxTimeSlice(); } /** Gets the used heap size in bytes. */ static get usedHeapSize() { return Il2Cpp.Api._gcGetUsedSize(); } /** Enables or disables the garbage collector. */ static set isEnabled(value) { value ? Il2Cpp.Api._gcEnable() : Il2Cpp.Api._gcDisable(); } /** Sets the number of nanoseconds the garbage collector can spend in a collection step. */ static set maxTimeSlice(nanoseconds) { Il2Cpp.Api._gcSetMaxTimeSlice(nanoseconds); } /** Returns the heap allocated objects of the specified class. This variant reads GC descriptors. */ static choose(klass) { const matches = []; const callback = (objects, size, _) => { for (let i = 0; i < size; i++) { matches.push(new Il2Cpp.Object(objects.add(i * Process.pointerSize).readPointer())); } }; const chooseCallback = new NativeCallback(callback, "void", ["pointer", "int", "pointer"]); const onWorld = new NativeCallback(() => { }, "void", []); const state = Il2Cpp.Api._livenessCalculationBegin(klass.handle, 0, chooseCallback, NULL, onWorld, onWorld); Il2Cpp.Api._livenessCalculationFromStatics(state); Il2Cpp.Api._livenessCalculationEnd(state); return matches; } /** Forces a garbage collection of the specified generation. */ static collect(generation) { Il2Cpp.Api._gcCollect(generation < 0 ? 0 : generation > 2 ? 2 : generation); } /** Forces a garbage collection. */ static collectALittle() { Il2Cpp.Api._gcCollectALittle(); } /** Resumes all the previously stopped threads. */ static startWorld() { return Il2Cpp.Api._gcStartWorld(); } /** Performs an incremental garbage collection. */ static startIncrementalCollection() { return Il2Cpp.Api._gcStartIncrementalCollection(); } /** Stops all threads which may access the garbage collected heap, other than the caller. */ static stopWorld() { return Il2Cpp.Api._gcStopWorld(); } }
JavaScript
class Il2CppReference extends native_struct_1.NativeStruct { type; constructor(handle, type) { super(handle); this.type = type; } /** Gets the element referenced by the current reference. */ get value() { return (0, utils_1.read)(this.handle, this.type); } /** Sets the element referenced by the current reference. */ set value(value) { (0, utils_1.write)(this.handle, value, this.type); } toString() { return `->${this.value}`; } }
JavaScript
class Il2CppValueType extends native_struct_1.NativeStruct { type; constructor(handle, type) { super(handle); this.type = type; } /** Gets the fields of this value type. */ get fields() { return (0, utils_1.makeIterable)((0, utils_1.addLevenshtein)((0, utils_1.filterMap)(this.type.class.fields, (field) => !field.isStatic, (field) => field.withHolder(this)))); } /** Boxes the current value type in a object. */ box() { return new Il2Cpp.Object(Il2Cpp.Api._valueBox(this.type.class, this)); } toString() { return this.box().toString(); } }
JavaScript
class NonNullNativeStruct extends NativeStruct { constructor(handle) { super(handle); if (handle.isNull()) { throw new Error(`Handle for "${this.constructor.name}" cannot be NULL.`); } } }
JavaScript
class Version { static pattern; /** @internal */ #source; /** @internal */ #major; /** @internal */ #minor; /** @internal */ #revision; /** @internal */ constructor(source) { if (Version.pattern == undefined) { throw new Error(`The version match pattern has not been set.`); } const matches = source.match(Version.pattern); this.#source = matches ? matches[0] : source; this.#major = matches ? Number(matches[1]) : -1; this.#minor = matches ? Number(matches[2]) : -1; this.#revision = matches ? Number(matches[3]) : -1; if (matches == null) { throw new Error(`"${source}" is not a valid version.`); } } isEqual(other) { return this.compare(other) == 0; } isAbove(other) { return this.compare(other) == 1; } isBelow(other) { return this.compare(other) == -1; } isEqualOrAbove(other) { return this.compare(other) >= 0; } isEqualOrBelow(other) { return this.compare(other) <= 0; } /** @internal */ compare(otherSource) { const other = new Version(otherSource); if (this.#major > other.#major) return 1; if (this.#major < other.#major) return -1; if (this.#minor > other.#minor) return 1; if (this.#minor < other.#minor) return -1; if (this.#revision > other.#revision) return 1; if (this.#revision < other.#revision) return -1; return 0; } /** @internal */ toJSON() { return this.toString(); } toString() { return this.#source; } }
JavaScript
class PeerGroup extends EventEmitter { constructor (params, opts) { utils.assertParams(params) super() this._params = params opts = opts || {} this._numPeers = opts.numPeers || 10 this.peers = [] this._hardLimit = opts.hardLimit || false this.websocketPort = null // pxp not supported: this._connectPxpWeb = false // opts.connectWeb != null ? opts.connectWeb : process.browser this.connectTimeout = opts.connectTimeout != null ? opts.connectTimeout : 15 * 1000 this.peerOpts = opts.peerOpts != null ? opts.peerOpts : {} this.wsOpts = opts.wsOpts != null ? opts.wsOpts : {} this.acceptIncoming = opts.acceptIncoming this.connecting = false this.closed = false this.accepting = false this.fConnectPlainWeb = opts.connectPlainWeb ? opts.connectPlainWeb : false this.retryInterval = 10000 this.methods = 0 if (this.fConnectPlainWeb) { let wrtc = opts.wrtc || getBrowserRTC() let envWebSeeds = process.env.WEB_SEED ? process.env.WEB_SEED.split(',').map((s) => s.trim()) : [] // maintain addresses state: // last successful connect time // unsuccessful retries count // if lastConnectTime == 0 (never connected) && retries count > 10 then this address is not used (to prevent spam addresses overusing) // after 3h retry count is cleared and the address is again available // when addresses are selected it first checked that lastConnectTime != 0 but it is least recently connected let webSeeds = []; if (this._params.webSeeds) webSeeds = webSeeds.concat(this._params.webSeeds) // add web seeds from params if (envWebSeeds) webSeeds = webSeeds.concat(envWebSeeds) // add web seeds from env if (this._params.network && this._params.network.webSeeds) // add web seeds from network config webSeeds = webSeeds.concat(this._params.network.webSeeds) this.webAddrs = new AddrStates(webSeeds); /* do not use pxp (save for possible use): if (this._connectPxpWeb) { try { this._exchange = Exchange(params.magic.toString(16), assign({ wrtc, this.acceptIncoming }, opts.exchangeOpts)) } catch (err) { return this._error(err) } this._exchange.on('error', this._error.bind(this)) this._exchange.on('connect', (stream) => { this._onConnection(null, stream) }) if (!process.browser && this.acceptIncoming) { this._acceptWebsocket() } }*/ } else { this.resolvedAddrs = new AddrStates([]); // init empty resolved this._dnsSeeds = []; if (this._params.dnsSeeds) this._dnsSeeds = this._dnsSeeds.concat(this._params.dnsSeeds) // add seeds from params if (this._params.network && this._params.network.dnsSeeds) this._dnsSeeds = this._dnsSeeds.concat(this._params.network.dnsSeeds) // add seeds from network config let staticPeers = []; if (this._params.staticPeers) staticPeers = staticPeers.concat(this._params.staticPeers) // add static peers from params if (this._params.network && this._params.network.staticPeers) staticPeers = staticPeers.concat(this._params.network.staticPeers) // add static peers from network config this.tcpAddrs = new AddrStates(staticPeers); } this.on('block', (block) => { this.emit(`block:${utils.getBlockHash(block.header).toString('base64')}`, block) }) this.on('merkleblock', (block) => { this.emit(`merkleblock:${utils.getBlockHash(block.header).toString('base64')}`, block) }) this.on('tx', (tx) => { this.emit(`tx:${utils.getTxHash(tx).toString('base64')}`, tx) }) this.once('peer', () => this.emit('connect')) if (this.fConnectPlainWeb) this.on('wsaddr', this._onWsAddr) // process "wsaddr" messages (websockets must be supported at the server side) else this.on('addr', this._onAddr) // process "addr" messages } _error (err) { this.emit('peerGroupError', err) } // callback for peer discovery methods _onConnection (err, socket, addrstates, addr) { if (err) { if (socket) socket.destroy() logdebug(`discovery connection error: ${err}`) this.emit('connectError', err, null) // emit user's event if (this.connecting) { // setImmediate(this._connectPeer.bind(this)) // lets wait for some time before logdebug(`waiting for ${this.retryInterval} ms before connection retry`) setTimeout(this._connectPeer.bind(this), this.retryInterval) } if (addrstates) addrstates.setClear(addr, err) return } if (this.closed) return socket.destroy() let opts = assign({ socket }, this.peerOpts) let peer = new Peer(this._params, opts) // peer error callback let onPeerError = (err) => { err = err || Error('Connection error') logdebug(`peer connection error: ${err}`) peer.removeListener('disconnect', onPeerError) peer.clearTimers() this.emit('connectError', err, peer) // emit user's event // clear inuse state: if (addrstates) addrstates.setClear(addr, err) if (this.connecting) this._connectPeer() // try to connect new peer } // peer success callback let onPeerReady = () => { if (this.closed) return peer.disconnect() // remove once listeners to replace with new ones peer.removeListener('error', onPeerError) peer.removeListener('disconnect', onPeerError) this.addPeer(peer, addrstates, addr) // set conn time if (addrstates) addrstates.setConnected(addr) //this.emit('newpeer', peer); // new event to notify external listeners } // wait for socket connection errors: peer.once('error', onPeerError) peer.once('disconnect', onPeerError) // socket connected: peer.once('ready', onPeerReady) } // connects to a new peer, via a randomly selected peer discovery method _connectPeer () { // cb = cb || this._onConnection.bind(this) let onConnectionCb = this._onConnection.bind(this) // always need our onConnection callback to work properly if (this.closed) return false if (this.peers.length >= this._numPeers) return false let getPeerArray = [] // getPeerFuncs will be added here if (!process.browser) { // non-browser dns resolved connections: if (Array.isArray(this.dnsSeeds) && this.dnsSeeds.length > 0) { getPeerArray.push(this._connectDNSPeer.bind(this)) } // non-browser static peers connections //if (this._tcpAddrs && this._freeAddrCount(this._tcpAddrs) > 0) { if (this.tcpAddrs && this.tcpAddrs.freeCount() > 0) { getPeerArray.push(this._connectStaticPeer.bind(this, onConnectionCb)) } } /* pxp not supported: if (this._connectPxpWeb && !this.fConnectPlainWeb && this._exchange.peers.length > 0) { getPeerArray.push(this._exchange.getNewPeerCustom.bind(this._exchange)) } */ if (this.fConnectPlainWeb) { if (this.webAddrs && this.webAddrs.freeCount() > 0) { getPeerArray.push(this._getNewPlainWebPeer.bind(this)) } } // user-defined function: if (this._params.getNewPeerCustom) { getPeerArray.push(this._params.getNewPeerCustom.bind(this._params)) } if (getPeerArray.length === 0) { // could not find an addr to connect, let's retry in 8 sec this.connecting = false if (this.connectTimeout) { logdebug(`scheduling reconnection to peers in ${this.connectTimeout} ms`) setTimeout(() => { if (this.closed) return this.connecting = true logdebug(`resuming connecting to peers`) setImmediate(this.connect.bind(this)) }, this.connectTimeout) } this._onConnection(new Error(`No more methods available to get new peers for required ${this._numPeers} peers, current number ${this.peers.length}`)) //logdebug(`No more methods available to get new peers for required ${this._numPeers} peers`); return false } let getPeerFunc = utils.getRandom(getPeerArray) logdebug(`_connectPeer: selected getPeerFunc is '${getPeerFunc.name}'`) getPeerFunc(onConnectionCb) return true } // connects to a random TCP peer via a random DNS seed // (selected from `dnsSeeds` in the params) _connectDNSPeer (onConnectionCb) { // let seed = utils.getRandom(seeds) // cant get random as we should track addresses in use while(this.dnsSeeds.length > 0) { let seed = this.dnsSeeds.pop(); //this.dnsSeeds.forEach(seed => { let seedUrl = utils.parseAddress(seed); logdebug('_connectDNSPeer resolving seed', seedUrl.hostname); dns.resolve(seedUrl.hostname, (err, ips) => { // we should use resolve() here (as supposed for dns seeds) if (err) return onConnectionCb(err) //let addr = utils.getRandom(addresses) // we cant get random as we need track addresses in use ips.forEach(ip => { let resolvedUrl = new URL(seedUrl.protocol + '//' + ip +':' + seedUrl.port); let addrState = this.resolvedAddrs.add(resolvedUrl.href); // returns new or existing addr state if (AddrStates.canUse(addrState)) { // check if resolved addr not in use this.resolvedAddrs.setInUse(resolvedUrl.href); this._connectTCP(resolvedUrl.hostname, resolvedUrl.port /*|| this._params.defaultPort*/, (err, socket)=>{ // callback to update addr state for dns resolved addresses onConnectionCb(err, socket, this.resolvedAddrs, resolvedUrl.href); }); } }); }); } } // connects to a random TCP peer from `staticPeers` in the params _connectStaticPeer (onConnectionCb) { //let staticPeers = this._params.staticPeers //let address = utils.getRandom(staticPeers) let address = this.tcpAddrs.findBestAddr(); // getting random not supported if (address) { this.tcpAddrs.setInUse(address); let peerUrl = utils.parseAddress(address) this._connectTCP(peerUrl.hostname, peerUrl.port /*|| this._params.defaultPort*/, (err, socket)=>{ onConnectionCb(err, socket, this.tcpAddrs, address); }); } else logerror("internal error could not find free tcp address"); } // connects to a standard protocol TCP peer _connectTCP (host, port, cb) { logdebug(`_connectTCP: ${host}:${port}`) let socket = net.connect(port, host) let timeout if (this.connectTimeout) { timeout = setTimeout(() => { socket.destroy() cb(Error(`Connection timed out ${host}:${port}`)) }, this.connectTimeout) } socket.once('error', (err) => { clearTimeout(timeout) // clear timeout to prevent reconnection twice (both on error and timeout) cb(err, socket) }) socket.once('connect', () => { socket.ref() socket.removeListener('error', cb) clearTimeout(timeout) cb(null, socket) }) socket.unref() } // pxp not supported (code saved for possible use) // connects to the peer-exchange peers provided by the params /*_connectPxpWebSeeds () { this._webAddrs.forEach((elem) => { let seed = elem.wsaddr logdebug(`connecting to web seed: ${JSON.stringify(seed, null, ' ')}`) let socket = wsstream(seed) socket.on('error', (err) => this._error(err)) this._exchange.connect(socket, (err, peer) => { if (err) { logdebug(`error connecting to web seed (pxp): ${JSON.stringify(seed, null, ' ')} ${err.stack}`) return } logdebug(`connected to web seed: ${JSON.stringify(seed, null, ' ')}`) this.emit('webSeed', peer) }) }) }*/ // connects to a plain websocket _connectPlainWebPeer (addr, onConnectionCb) { logdebug(`_connectPlainWebPeer: ${addr}`); let socket = wsstream(addr, undefined , this.wsOpts); let timeout; if (this.connectTimeout) { timeout = setTimeout(() => { socket.destroy(); onConnectionCb(Error(`Connection timed out, peer ${addr}`), undefined, this.webAddrs, addr); }, this.connectTimeout); } socket.once('error', (err) => { clearTimeout(timeout); // clear timeout to prevent reconnection duplication (both on error and timeout) onConnectionCb(err, socket, this.webAddrs, addr); }) socket.once('connect', () => { socket.removeListener('error', onConnectionCb); clearTimeout(timeout); onConnectionCb(null, socket, this.webAddrs, addr); }) } // connects to a random plain (non-pxp) web peer from `webAddrs` in the params _getNewPlainWebPeer (cb) { //let wspeers = this._params.webSeeds //let wsaddr = utils.getRandom(this._webAddrs) let wsaddr = this.webAddrs.findBestAddr(); if (wsaddr) { this.webAddrs.setInUse(wsaddr); this._connectPlainWebPeer(wsaddr, cb) } } _assertPeers () { if (this.peers.length === 0) { throw Error('Not connected to any peers') } } _fillPeers () { if (this.closed) return // TODO: smarter peer logic (ensure we don't have too many peers from the // same seed, or the same IP block) let n = this._numPeers - this.peers.length // try hold up to 8 (by default) connections if (this._dnsSeeds) this.dnsSeeds = this._dnsSeeds.slice(); // copy dns seeds for connection logdebug(`_fillPeers: peers to add, n = ${n}, max numPeers = ${this._numPeers}, current peers.length = ${this.peers.length}`) this.methods = 0; for (let i = 0; i < n; i++) { if (!this._connectPeer()) break; this.methods ++; } } hasMethods() { /*let activeCount = 0; if (this.resolvedAddrs) activeCount += this.resolvedAddrs.inUseCount(); if (this.tcpAddrs) activeCount += this.tcpAddrs.inUseCount(); if (this.webSeeds) activeCount += this.webSeeds.inUseCount(); return activeCount;*/ return this.methods > 0 || this.peers.length > 0; } // sends a message to all peers send (command, payload, assert) { assert = assert != null ? assert : true if (assert) this._assertPeers() for (let peer of this.peers) { peer.send(command, payload) } } // initializes the PeerGroup by creating peer connections connect (onConnect) { logdebug('connect called') this.connecting = true if (onConnect) this.once('connect', onConnect) // call user function here /* pxp not supported // first, try to connect to pxp web seeds so we can get web peers // once we have a few, start filling peers via any random // peer discovery method if (this._connectPxpWeb && !this.fConnectPlainWeb && this._params.webSeeds && this._webAddrs.length) { this.once('webSeed', () => this._fillPeers()) // connect after pxp discovery return this._connectPxpWebSeeds() } */ // if we aren't using web seeds, start filling with other methods this._fillPeers() } // disconnect from all peers and stop accepting connections close (cb) { if (cb) cb = once(cb) else cb = (err) => { if (err) this._error(err) } this.emit('PeerGroupClose') logdebug(`close called: peers.length = ${this.peers.length}`) this.closed = true if (this.peers.length === 0) return cb(null) let peers = this.peers.slice(0) for (let peer of peers) { peer.once('disconnect', () => { if (this.peers.length === 0) cb(null) }) peer.disconnect(Error('PeerGroup closing')) } logdebug('finished:', this.peers.length) } /* pxp not supported _acceptWebsocket (port, cb) { if (process.browser) return cb(null) if (!port) port = DEFAULT_PXP_PORT this.websocketPort = port let server = http.createServer() wsstream.createServer({ server }, (stream) => { this._exchange.accept(stream) }) http.listen(port) cb(null) }*/ _onWsAddr(message) { //logdebug('received wsaddr message=', message); if (!Array.isArray(message)) return; message.forEach((elem)=> { // TODO: check nspv service bit //this._addWebAddr(elem.address, elem.port) this.wsAddrs.add(`${elem.address}:${elem.port}`) // TODO: enable!! (disable to connect always to only one node, for debug) }) } _onAddr(message) { //logdebug('received addr message=', message); if (!Array.isArray(message)) return; message.forEach((elem)=> { // TODO: check nspv service bit this.tcpAddrs.add(`${elem.address}:${elem.port}`) // TODO: enable!! (disable to connect always to only one node, for debug) }) } // manually adds a Peer addPeer (peer, addrstates, addr) { if (this.closed) throw Error('Cannot add peers, PeerGroup is closed') this.peers.push(peer) logdebug(`add peer: peers.length = ${this.peers.length}`) if (this._hardLimit && this.peers.length > this._numPeers) { let disconnectPeer = this.peers.shift() disconnectPeer.disconnect(Error('PeerGroup over limit')) } let onMessage = (message) => { this.emit('message', message, peer) this.emit(message.command, message.payload, peer) } peer.on('message', onMessage) peer.once('disconnect', (err) => { let index = this.peers.indexOf(peer) this.peers.splice(index, 1) peer.removeListener('message', onMessage) // clear in-use state: if (addrstates) addrstates.setClear(addr, err) logerror(`peer disconnected, peer.length = ${this.peers.length}, reason=${err}`) if (this.connecting) this._fillPeers() this.emit('disconnect', peer, err) }) peer.on('error', (err) => { logdebug(`peer.on error called ${err}`) this.emit('peerError', err) peer.disconnect(err) // clear in-use state: if (addrstates) addrstates.setClear(addr, err) }) this.emit('peer', peer) } randomPeer () { // could be that last peer disconnected in a concurrent call, so no _assertPeers // this._assertPeers() if (this.peers.length === 0) return null return utils.getRandom(this.peers) } getBlocks (hashes, opts, cb) { this._request('getBlocks', hashes, opts, cb) } // get transactions via the standard p2p 'getdata' message, // it would return transaction from the block passed or from relay queue or mempool getTransactions (blockHash, txids, opts, cb) { this._request('getTransactions', blockHash, txids, opts, cb) } getHeaders (locator, opts, cb) { this._request('getHeaders', locator, opts, cb) } getAddr (opts, cb) { this._request('getAddr', opts, cb) // forward to peer.GetAddr() } getWsAddr (opts, cb) { this._request('getWsAddr', opts, cb) // forward to peer.GetWsAddr() } // calls a method on a random peer, // and retries on another peer if it times out _request (method, ...args) { let cb = args.pop() while (!cb) cb = args.pop() let peer = this.randomPeer() if (!peer) { cb(new Error('no connected peers')) return } args.push((err, res) => { if (this.closed) return if (err && err.timeout) { // if request times out, disconnect peer and retry with another random peer logdebug(`peer request "${method}" timed out, disconnecting`) peer.disconnect(err) this.emit('requestError', err) return this._request(...arguments) } cb(err, res, peer) }) peer[method](...args) } // allow not to retry connections if needed stopConnecting() { this.connecting = false; } }
JavaScript
class ThreadsManager { /** * Constructor * * @param {EventEmitter} eventBus The global event bus * @param {Object} smartiesRunnerConstants Runner constants * * @returns {ThreadsManager} The thread manager */ constructor(eventBus, smartiesRunnerConstants) { this.threads = {}; this.eventBus = eventBus; this.smartiesRunnerConstants = smartiesRunnerConstants; } /** * Stringify a function. * Convert a class method to standard method definition, for example * `myFunction(a, b) {}` to `(a,b)=>{}` * Further detaisl : https://github.com/andywer/threads.js/issues/57 * This method can throw an error if the regex fails * * @param {Function} func A class method or classic function * @returns {string} The normalized function as string, needed to be eval */ stringifyFunc(func) { const regex = /(\()(.*)(\))([^]{0,1})({)([^]+)(\})/mg; let regexResults = regex.exec(func.toString()); if (regexResults.length === 8) { const prototype = "(" + regexResults[2] + ") => {" + regexResults[6] + " return this;}"; return prototype; } else { throw Error(ERROR_STRINGIFY_FUNCTION_THREAD); } } /** * Run a function or class method in a separated thread * Each code contains in the function is sanboxed and should communicate through data and/or callback API * All class methods / data can not be accessed * Can throw an error * * @param {Function} func A class method, or classic function. Prototype example : `run(data, message) {}` * @param {string} identifier The thread identifier * @param {Object} [data={}] Object passed to the threaded code * @param {Function} [callback=null] The callback when a message is received from the thread. Prototype example : `(tData) => {}` * @param {Object} [context=null] The context passed as parameter */ run(func, identifier, data = {}, callback = null, context = null) { const prototype = this.stringifyFunc(func); const self = this; const thread = threads.spawn((input, done, progress) => { const Logger = require(input.dirname + "/../../logger/Logger", "may-exclude"); try { let f = eval(input.prototype); let instance = f(input.data, progress); this.process.on("message", (d) => { if (d && d.event) { if (typeof instance[d.event] === "function") { instance[d.event](d.data); } else { Logger.err("Thread '" + input.identifier + "' has invalid or unimplemented function type for event '" + d.event + "'"); } } }); } catch(e) { // Log thread error ! const regex = /(.*)(:)([0-9]+)(:)(.*)/g; const lineStack = e.stack.toString().split("\n")[1]; const lineIdentified = parseInt(regex.exec(lineStack)[3]) - 1; let code = input.prototype.split("\n")[lineIdentified]; Logger.err("Exception '" + e.message + "' in thread " + input.identifier + " on l." + lineIdentified + ". Code : " + code); } done(input.identifier); }) .send({dirname: __dirname, identifier:identifier, prototype:prototype, data:data}) .on("progress", function message(tData) { if (callback) { callback(tData, self, context); } }) .on("error", function(error) { Logger.err("Error in thread " + identifier); Logger.err(error.message); Logger.err(error.stack); }) .on("done", () => { }); this.threads[identifier] = thread; this.eventBus.emit(this.smartiesRunnerConstants.PID_SPAWN, thread.slave.pid); } /** * Send data to thread. In the thread method, the `event` should be impelemented as : * myFunction(data, message) { * this.myEvent = (data) { * * } * } * Then call function : * `threadManager.send("identifier", "myEvent", {value:"foo"})` * Can throw error if thread does not exists * * @param {string} identifier The thread identifier * @param {string} event The event's name * @param {Object} [data=null] Any data passed to thread */ send(identifier, event, data = null) { if (this.threads[identifier] && this.isRunning(identifier)) { this.threads[identifier].slave.send({event:event, data:data}); } else { throw Error(ERROR_UNKNOWN_IDENTIFIER + " " + identifier); } } /** * Kill the thread * Throw a ERROR_UNKNOWN_IDENTIFIER error if the identifier is unknown * * @param {string} identifier Thread identifier */ kill(identifier) { if (this.threads[identifier] && this.isRunning(identifier)) { this.threads[identifier].kill(); delete this.threads[identifier]; Logger.info("Thread " + identifier + " has been terminated"); } else { throw Error(ERROR_UNKNOWN_IDENTIFIER); } } /** * Returns the pid of the thread * * @param {string} identifier Thread identifier * @returns {int} The pid, if not found send back null */ getPid(identifier) { if (this.threads[identifier]) { return this.threads[identifier].slave.pid; } else { return null; } } /** * Check if the thread is running or not * * @param {string} identifier Thread identifier * @returns {boolean} True or false */ isRunning(identifier) { const pid = this.getPid(identifier); return pid?isRunning(pid):false; } }
JavaScript
class YBNewMultiSelect extends Component { componentDidUpdate(prevProps) { let newSelection = null; // If AZ is changed from multi to single, take only last selection. if (this.props.isMulti !== prevProps.isMulti && this.props.isMulti === false) { const currentSelection = prevProps.input.value; if (isNonEmptyArray(currentSelection)) { newSelection = currentSelection.splice(-1, 1); } } // If provider has been changed, reset region selection. if (this.props.providerSelected !== prevProps.providerSelected) { newSelection = []; } if (isNonEmptyArray(newSelection) && isFunction(this.props.input.onChange)) { this.props.input.onChange(newSelection); } } render() { const { input, options, isMulti, isReadOnly, selectValChanged, ...otherProps } = this.props; const self = this; function onChange(val) { val = isMulti ? val: val.slice(-1); if (isFunction(self.props.input.onChange)) { self.props.input.onChange(val); } if (selectValChanged) { selectValChanged(val); } } const customStyles = { option: (provided, state) => ({ ...provided, padding: 10, }), control: (provided) => ({ // none of react-select's styles are passed to <Control /> ...provided, width: "auto", borderColor: "#dedee0", borderRadius: 7, boxShadow: "inset 0 1px 1px rgba(0, 0, 0, .075)", fontSize: "14px", height: 42 }), placeholder: (provided) => ({ ...provided, color: "#999999" }), container: (provided) => ({ ...provided, zIndex: 2 }), dropdownIndicator: (provided) => ({ ...provided, cursor: "pointer" }), clearIndicator: (provided) => ({ ...provided, cursor: "pointer", }), singleValue: (provided, state) => { const opacity = state.isDisabled ? 0.5 : 1; const transition = 'opacity 300ms'; return { ...provided, opacity, transition }; } }; return ( <Select className="Select" styles={customStyles} {...input} options={options} disabled={isReadOnly} isMulti={true} onBlur={() => {}} onChange={onChange} {...otherProps} /> ); } }
JavaScript
class Thread extends Component { constructor() { super(); this.onClick = this.onClick.bind(this); } /** * Handle click on thread and call ThreadActionCreator with id of thread * @param {object} event */ onClick(event) { event.preventDefault(); ThreadActionCreators.clickThread(this.props.id); } render() { return ( <a href="" onClick={this.onClick} className={classNames({ active: this.props.id === this.props.currentThreadId })} > <div className="row thread"> <div className="col-md-3 col-xs-3"> <div className="avatar"> <img src={batImage} alt="User name" /> </div> </div> <div className="col-md-9 col-xs-9 thread-name"> <div className="pull-left">{this.props.name}</div> </div> </div> </a> ); } }
JavaScript
class IOElement extends HyperHTMLElement { // exposes DOM helpers as read only utils static get utils() { return DOMUtils; } // get a unique ID or, if null, set one and returns it static getID(element) { return element.getAttribute("id") || IOElement.setID(element); } // set a unique ID to a generic element and returns the ID static setID(element) { const id = `${element.nodeName.toLowerCase()}-${counter++}`; element.setAttribute("id", id); return id; } // lazily retrieve or define a custom element ID get id() { return IOElement.getID(this); } // whenever an element is created, render its content once created() { this.render(); } // by default, render is a no-op render() {} // usually a template would contain a main element such // input, button, div, section, etc. // having a simple way to retrieve such element can be // both semantic and handy, as opposite of using // this.children[0] each time get child() { let element = this.firstElementChild; // if accessed too early, will render automatically if (!element) { this.render(); element = this.firstElementChild; } return element; } }
JavaScript
class Meta { constructor(options, cache = null) { this.options = options; this.cache = cache; } set cache(value) { this.__cache = value; } get cache_dir() { return this.options.cache_dir; } clean() { var path = this.cache_dir; if (fs.existsSync(path)) { this.__cache = null; return fs.removeSync(path); } } get cache() { if (!this.__cache) { var cache_dir = this.cache_dir; mkdir(cache_dir); this.__cache = createCache(cache_dir); } return this.__cache; } getOrSet(key, defaultValue) { var value = this.cache.getSync(key); if (_.isUndefined(value) && defaultValue) { value = defaultValue; this.set(key, value); } return value; } get(key, defaultValue) { return this.cache.getSync(key) || defaultValue; } set(key, value) { this.cache.putSync(key, value); return this; } }
JavaScript
class Component { constructor(name, fields, reviver) { this._name = name; this._fields = fields || [ ]; this._reviver = reviver; } /** * Name of the component. * * @public * @returns {String} */ get name() { return this._name; } /** * Type of the component. * * @public * @returns {ComponentType} */ get fields() { return this._fields; } /** * The reviver used to rebuild the entire component. * * @returns {Function} */ get reviver() { return this._reviver; } /** * The builds a {@link Component} for {@link Money}. * * @public * @returns {Component} */ static forMoney(name) { return new Component(name, [ new Field('decimal', DataType.DECIMAL), new Field('currency', DataType.forEnum(Currency, 'Currency')) ], x => Money.parse(x)); } toString() { return `[Component (name=${this._name})]`; } }
JavaScript
class Breadcrumb extends RtlMixin(LitElement) { static get properties() { return { /** * @ignore */ _compact: { attribute: 'data-compact', reflect: true, type: Boolean }, /** * @ignore */ _role: { type: 'string', attribute: 'role', reflect: true }, /** * The Url that breadcrumb is pointing to */ href: { type: String, reflect: true }, /** * The target of breadcrumb link */ target: { type: String, reflect: true }, /** * REQUIRED: text of the breadcrumb link */ text: { type: String, reflect: true }, /** * ARIA label of the breadcrumb */ ariaLabel: { attribute: 'aria-label', type: String, reflect: true } }; } static get styles() { return [linkStyles, css` :host { align-items: center; display: inline-flex; } :host([hidden]) { display: none; } :host([data-compact]) { flex-direction: row-reverse; } d2l-icon { height: 8px; padding-left: 8px; padding-right: 3px; width: 8px; } :host([dir="rtl"]) d2l-icon { padding-left: 3px; padding-right: 8px; } d2l-icon[icon="tier1:chevron-left"] { padding-left: 0; padding-right: 8px; } :host([dir="rtl"]) d2l-icon[icon="tier1:chevron-left"] { padding-left: 8px; padding-right: 0; } `]; } constructor() { super(); this._compact = false; this.text = ''; this._role = 'listitem'; } connectedCallback() { super.connectedCallback(); findComposedAncestor(this, (node) => { if (node.tagName === 'D2L-BREADCRUMBS') { this._compact = node.hasAttribute('compact'); } }); } render() { const icon = this._compact ? 'tier1:chevron-left' : 'tier1:chevron-right'; return html`<a class="d2l-link d2l-link-small" aria-label="${ifDefined(this.ariaLabel)}" href="${this.href}" target="${ifDefined(this.target)}">${this.text}</a><d2l-icon icon="${icon}"></d2l-icon>`; } }
JavaScript
class Raindrop { constructor({x, y, died, stopped, color, middleLetter}) { this.pos = p.createVector(x, y); this.symbols = new Map(); this.addSymbol({x, y}); this.died = died || (() => { }); this.middleLetter = middleLetter; this.stopped = stopped || (() => { }); this.color = color; this.symbolCount = 0; } addSymbol({x, y, symbol}) { const s = new Symbol({x, y, symbol, died: this.removeSymbol.bind(this)}); this.lowestSymbol = s; this.symbols.set(s, s); this.symbolCount += 1; } update() { this.pos.add(p.createVector(0, 4)); const nextSymbolY = this.symbolCount * font_size; const trueMiddle = p.height / 2; const middle = p.floor(trueMiddle / font_size) * font_size; const {x, y} = this.pos; if (this.middleLetter) { if (y < middle && y > nextSymbolY) { this.addSymbol({x, y: nextSymbolY}); } else if (y >= middle && y > nextSymbolY) { this.addSymbol({x, y: nextSymbolY, symbol: this.middleLetter}); this.stopped(); } else if (y >= middle) { this.pos.y = middle; } } else if (y < p.height + font_size && y > nextSymbolY) { this.addSymbol({x, y: nextSymbolY}); } else if (y > p.height && this.symbols.size === 1) { this.died(); } } display() { this.symbols.forEach((symbol, i) => { const lowestSymbol = symbol === this.lowestSymbol; const lowestSymbolColor = this.color || p.color(0, 0, 100); symbol.update(lowestSymbol && lowestSymbolColor); symbol.display(); }); } removeSymbol(key) { this.symbols.delete(key); } }
JavaScript
class FakeSocket { constructor(options = {}) { //$lab:coverage:off$ this.address = options.addr || Default.addr; this.remoteAddress = options.remoteAddr || Default.remoteAddr; this.remotePort = options.port || Default.port; this.encrypted = options.encrypted || false; //$lab:coverage:on$ this.writable = false; } write(chunk, encoding, callback) { } setTimeout(msecs) { } cork() { } uncork() { } disconnect() { } close(callback) { } destroy() { } end() { } }
JavaScript
class JSONSource extends Source { constructor( value, key ) { super(); this._key = key; this._value = JSON.stringify( value ); this._json = value; } source() { return this._value; } json() { return this._json; } key() { return this._key; } updateHash( hash ) { hash.update( this._value ); } }
JavaScript
class CurrentImageComponent extends AccessibleComponent { /** * @param {?} _platformId * @param {?} _ngZone * @param {?} ref */ constructor(_platformId, _ngZone, ref) { super(); this._platformId = _platformId; this._ngZone = _ngZone; this.ref = ref; /** * Output to emit an event when images are loaded. The payload contains an `ImageLoadEvent`. */ this.loadImage = new EventEmitter(); /** * Output to emit any changes of the current image. The payload contains an `ImageModalEvent`. */ this.changeImage = new EventEmitter(); /** * Output to emit an event when the modal gallery is closed. The payload contains an `ImageModalEvent`. */ this.close = new EventEmitter(); /** * Subject to play modal-gallery. */ this.start$ = new Subject(); /** * Subject to stop modal-gallery. */ this.stop$ = new Subject(); /** * Enum of type `Action` that represents a normal action. * Declared here to be used inside the template. */ this.normalAction = Action.NORMAL; /** * Enum of type `Action` that represents a mouse click on a button. * Declared here to be used inside the template. */ this.clickAction = Action.CLICK; /** * Enum of type `Action` that represents a keyboard action. * Declared here to be used inside the template. */ this.keyboardAction = Action.KEYBOARD; /** * Boolean that it's true when you are watching the first image (currently visible). * False by default */ this.isFirstImage = false; /** * Boolean that it's true when you are watching the last image (currently visible). * False by default */ this.isLastImage = false; /** * Boolean that it's true if an image of the modal gallery is still loading. * True by default */ this.loading = true; /** * Private object without type to define all swipe actions used by hammerjs. */ this.SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight', UP: 'swipeup', DOWN: 'swipedown' }; } /** * Listener to stop the gallery when the mouse pointer is over the current image. * @return {?} */ onMouseEnter() { // if carousel feature is disable, don't do anything in any case if (!this.configSlide || !this.configSlide.playConfig) { return; } if (!this.configSlide.playConfig.pauseOnHover) { return; } this.stopCarousel(); } /** * Listener to play the gallery when the mouse pointer leave the current image. * @return {?} */ onMouseLeave() { // if carousel feature is disable, don't do anything in any case if (!this.configSlide || !this.configSlide.playConfig) { return; } if (!this.configSlide.playConfig.pauseOnHover || !this.configSlide.playConfig.autoPlay) { return; } this.playCarousel(); } /** * Method ´ngOnInit´ to build `configCurrentImage` applying default values. * This is an Angular's lifecycle hook, so its called automatically by Angular itself. * In particular, it's called only one time!!! * @return {?} */ ngOnInit() { /** @type {?} */ const defaultLoading = { enable: true, type: LoadingType.STANDARD }; /** @type {?} */ const defaultDescriptionStyle = { bgColor: 'rgba(0, 0, 0, .5)', textColor: 'white', marginTop: '0px', marginBottom: '0px', marginLeft: '0px', marginRight: '0px' }; /** @type {?} */ const defaultDescription = { strategy: DescriptionStrategy.ALWAYS_VISIBLE, imageText: 'Image ', numberSeparator: '/', beforeTextDescription: ' - ', style: defaultDescriptionStyle }; /** @type {?} */ const defaultCurrentImageConfig = { navigateOnClick: true, loadingConfig: defaultLoading, description: defaultDescription, downloadable: false, invertSwipe: false }; this.configCurrentImage = Object.assign({}, defaultCurrentImageConfig, this.currentImageConfig); this.configCurrentImage.description = Object.assign({}, defaultDescription, this.configCurrentImage.description); this.configSlide = Object.assign({}, this.slideConfig); } /** * Method ´ngOnChanges´ to update `loading` status and emit events. * If the gallery is open, then it will also manage boundary arrows and sliding. * This is an Angular's lifecycle hook, so its called automatically by Angular itself. * In particular, it's called when any data-bound property of a directive changes!!! * @param {?} changes * @return {?} */ ngOnChanges(changes) { /** @type {?} */ const images = changes.images; /** @type {?} */ const currentImage = changes.currentImage; if (currentImage && currentImage.previousValue !== currentImage.currentValue) { this.updateIndexes(); } else if (images && images.previousValue !== images.currentValue) { this.updateIndexes(); } /** @type {?} */ const slideConfig = changes.slideConfig; if (slideConfig && slideConfig.previousValue !== slideConfig.currentValue) { this.configSlide = Object.assign({}, this.slideConfig); } } /** * @return {?} */ ngAfterContentInit() { // interval doesn't play well with SSR and protractor, // so we should run it in the browser and outside Angular if (isPlatformBrowser(this._platformId)) { this._ngZone.runOutsideAngular((/** * @return {?} */ () => { this.start$ .pipe(map((/** * @return {?} */ () => this.configSlide && this.configSlide.playConfig && this.configSlide.playConfig.autoPlay && this.configSlide.playConfig.interval)), filter((/** * @param {?} interval * @return {?} */ interval => interval > 0)), switchMap((/** * @param {?} interval * @return {?} */ interval => timer(interval).pipe(takeUntil(this.stop$))))) .subscribe((/** * @return {?} */ () => this._ngZone.run((/** * @return {?} */ () => { if (!this.isLastImage) { this.nextImage(Action.AUTOPLAY); } this.ref.markForCheck(); })))); this.start$.next(); })); } } /** * Method to handle keypress based on the `keyboardConfig` input. It gets the keyCode of * the key that triggered the keypress event to navigate between images or to close the modal gallery. * @param {?} keyCode * @return {?} */ onKeyPress(keyCode) { /** @type {?} */ const esc = this.keyboardConfig && this.keyboardConfig.esc ? this.keyboardConfig.esc : Keyboard.ESC; /** @type {?} */ const right = this.keyboardConfig && this.keyboardConfig.right ? this.keyboardConfig.right : Keyboard.RIGHT_ARROW; /** @type {?} */ const left = this.keyboardConfig && this.keyboardConfig.left ? this.keyboardConfig.left : Keyboard.LEFT_ARROW; switch (keyCode) { case esc: this.close.emit(new ImageModalEvent(Action.KEYBOARD, true)); break; case right: this.nextImage(Action.KEYBOARD); break; case left: this.prevImage(Action.KEYBOARD); break; } } /** * Method to get the image description based on input params. * If you provide a full description this will be the visible description, otherwise, * it will be built using the `Description` object, concatenating its fields. * @throws an Error if description isn't available * @param {?=} image * @return {?} String description of the image (or the current image if not provided) */ getDescriptionToDisplay(image = this.currentImage) { if (!this.configCurrentImage || !this.configCurrentImage.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } /** @type {?} */ const imageWithoutDescription = !image.modal || !image.modal.description || image.modal.description === ''; switch (this.configCurrentImage.description.strategy) { case DescriptionStrategy.HIDE_IF_EMPTY: return imageWithoutDescription ? '' : image.modal.description + ''; case DescriptionStrategy.ALWAYS_HIDDEN: return ''; default: // ----------- DescriptionStrategy.ALWAYS_VISIBLE ----------------- return this.buildTextDescription(image, imageWithoutDescription); } } /** * Method to get `alt attribute`. * `alt` specifies an alternate text for an image, if the image cannot be displayed. * @param {?=} image * @return {?} String alt description of the image (or the current image if not provided) */ getAltDescriptionByImage(image = this.currentImage) { if (!image) { return ''; } return image.modal && image.modal.description ? image.modal.description : `Image ${getIndex(image, this.images) + 1}`; } /** * Method to get the title attributes based on descriptions. * This is useful to prevent accessibility issues, because if DescriptionStrategy is ALWAYS_HIDDEN, * it prevents an empty string as title. * @throws an Error if description isn't available * @param {?=} image * @return {?} String title of the image based on descriptions */ getTitleToDisplay(image = this.currentImage) { if (!this.configCurrentImage || !this.configCurrentImage.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } /** @type {?} */ const imageWithoutDescription = !image.modal || !image.modal.description || image.modal.description === ''; /** @type {?} */ const description = this.buildTextDescription(image, imageWithoutDescription); return description; } /** * Method to get the left side preview image. * @return {?} Image the image to show as size preview on the left */ getLeftPreviewImage() { /** @type {?} */ const currentIndex = getIndex(this.currentImage, this.images); if (currentIndex === 0 && this.configSlide.infinite) { // the current image is the first one, // so the previous one is the last image // because infinite is true return this.images[this.images.length - 1]; } this.handleBoundaries(currentIndex); return this.images[Math.max(currentIndex - 1, 0)]; } /** * Method to get the right side preview image. * @return {?} Image the image to show as size preview on the right */ getRightPreviewImage() { /** @type {?} */ const currentIndex = getIndex(this.currentImage, this.images); if (currentIndex === this.images.length - 1 && this.configSlide.infinite) { // the current image is the last one, // so the next one is the first image // because infinite is true return this.images[0]; } this.handleBoundaries(currentIndex); return this.images[Math.min(currentIndex + 1, this.images.length - 1)]; } /** * Method called by events from both keyboard and mouse on an image. * This will invoke the nextImage method. * @param {?} event * @param {?=} action * @return {?} */ onImageEvent(event, action = Action.NORMAL) { // check if triggered by a mouse click // If yes, It should block navigation when navigateOnClick is false if (action === Action.CLICK && !this.configCurrentImage.navigateOnClick) { // a user has requested to block navigation via configCurrentImage.navigateOnClick property return; } /** @type {?} */ const result = super.handleImageEvent(event); if (result === NEXT) { this.nextImage(action); } } /** * Method called by events from both keyboard and mouse on a navigation arrow. * @param {?} direction * @param {?} event * @param {?=} action * @param {?=} disable * @return {?} */ onNavigationEvent(direction, event, action = Action.NORMAL, disable = false) { if (disable) { return; } /** @type {?} */ const result = super.handleNavigationEvent(direction, event); if (result === NEXT) { this.nextImage(action); } else if (result === PREV) { this.prevImage(action); } } /** * Method to go back to the previous image. * @param {?=} action Enum of type `Action` that represents the source * action that moved back to the previous image. `Action.NORMAL` by default. * @return {?} */ prevImage(action = Action.NORMAL) { // check if prevImage should be blocked if (this.isPreventSliding(0)) { return; } /** @type {?} */ const prevImage = this.getPrevImage(); this.loading = !prevImage.previouslyLoaded; this.changeImage.emit(new ImageModalEvent(action, getIndex(prevImage, this.images))); this.start$.next(); } /** * Method to go back to the previous image. * @param {?=} action Enum of type `Action` that represents the source * action that moved to the next image. `Action.NORMAL` by default. * @return {?} */ nextImage(action = Action.NORMAL) { // check if nextImage should be blocked if (this.isPreventSliding(this.images.length - 1)) { return; } /** @type {?} */ const nextImage = this.getNextImage(); this.loading = !nextImage.previouslyLoaded; this.changeImage.emit(new ImageModalEvent(action, getIndex(nextImage, this.images))); this.start$.next(); } /** * Method to emit an event as loadImage output to say that the requested image if loaded. * This method is invoked by the javascript's 'load' event on an img tag. * @param {?} event * @return {?} */ onImageLoad(event) { /** @type {?} */ const loadImageData = { status: true, index: getIndex(this.currentImage, this.images), id: this.currentImage.id }; this.loadImage.emit(loadImageData); this.loading = false; } /** * Method used by Hammerjs to support touch gestures (you can also invert the swipe direction with configCurrentImage.invertSwipe). * @param {?=} action String that represent the direction of the swipe action. 'swiperight' by default. * @return {?} */ swipe(action = this.SWIPE_ACTION.RIGHT) { switch (action) { case this.SWIPE_ACTION.RIGHT: if (this.configCurrentImage.invertSwipe) { this.prevImage(Action.SWIPE); } else { this.nextImage(Action.SWIPE); } break; case this.SWIPE_ACTION.LEFT: if (this.configCurrentImage.invertSwipe) { this.nextImage(Action.SWIPE); } else { this.prevImage(Action.SWIPE); } break; // case this.SWIPE_ACTION.UP: // break; // case this.SWIPE_ACTION.DOWN: // break; } } /** * Method used in `modal-gallery.component` to get the index of an image to delete. * @param {?=} image * @return {?} number the index of the image */ getIndexToDelete(image = this.currentImage) { return getIndex(image, this.images); } /** * Method to play modal gallery. * @return {?} */ playCarousel() { this.start$.next(); } /** * Stops modal gallery from cycling through items. * @return {?} */ stopCarousel() { this.stop$.next(); } /** * Method to cleanup resources. In fact, this will stop the modal gallery. * This is an Angular's lifecycle hook that is called when this component is destroyed. * @return {?} */ ngOnDestroy() { this.stopCarousel(); } /** * Private method to update both `isFirstImage` and `isLastImage` based on * the index of the current image. * @private * @param {?} currentIndex * @return {?} */ handleBoundaries(currentIndex) { if (this.images.length === 1) { this.isFirstImage = true; this.isLastImage = true; return; } if (!this.configSlide || this.configSlide.infinite === true) { // infinite sliding enabled this.isFirstImage = false; this.isLastImage = false; } else { switch (currentIndex) { case 0: // execute this only if infinite sliding is disabled this.isFirstImage = true; this.isLastImage = false; break; case this.images.length - 1: // execute this only if infinite sliding is disabled this.isFirstImage = false; this.isLastImage = true; break; default: this.isFirstImage = false; this.isLastImage = false; break; } } } /** * Private method to check if next/prev actions should be blocked. * It checks if configSlide.infinite === false and if the image index is equals to the input parameter. * If yes, it returns true to say that sliding should be blocked, otherwise not. * @private * @param {?} boundaryIndex * @return {?} boolean true if configSlide.infinite === false and the current index is * either the first or the last one. */ isPreventSliding(boundaryIndex) { return !!this.configSlide && this.configSlide.infinite === false && getIndex(this.currentImage, this.images) === boundaryIndex; } /** * Private method to get the next index. * This is necessary because at the end, when you call next again, you'll go to the first image. * That happens because all modal images are shown like in a circle. * @private * @return {?} */ getNextImage() { /** @type {?} */ const currentIndex = getIndex(this.currentImage, this.images); /** @type {?} */ let newIndex = 0; if (currentIndex >= 0 && currentIndex < this.images.length - 1) { newIndex = currentIndex + 1; } else { newIndex = 0; // start from the first index } return this.images[newIndex]; } /** * Private method to get the previous index. * This is necessary because at index 0, when you call prev again, you'll go to the last image. * That happens because all modal images are shown like in a circle. * @private * @return {?} */ getPrevImage() { /** @type {?} */ const currentIndex = getIndex(this.currentImage, this.images); /** @type {?} */ let newIndex = 0; if (currentIndex > 0 && currentIndex <= this.images.length - 1) { newIndex = currentIndex - 1; } else { newIndex = this.images.length - 1; // start from the last index } return this.images[newIndex]; } /** * Private method to build a text description. * This is used also to create titles. * @private * @param {?} image * @param {?} imageWithoutDescription * @return {?} String description built concatenating image fields with a specific logic. */ buildTextDescription(image, imageWithoutDescription) { if (!this.configCurrentImage || !this.configCurrentImage.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } // If customFullDescription use it, otherwise proceed to build a description if (this.configCurrentImage.description.customFullDescription && this.configCurrentImage.description.customFullDescription !== '') { return this.configCurrentImage.description.customFullDescription; } /** @type {?} */ const currentIndex = getIndex(image, this.images); // If the current image hasn't a description, // prevent to write the ' - ' (or this.description.beforeTextDescription) /** @type {?} */ const prevDescription = this.configCurrentImage.description.imageText ? this.configCurrentImage.description.imageText : ''; /** @type {?} */ const midSeparator = this.configCurrentImage.description.numberSeparator ? this.configCurrentImage.description.numberSeparator : ''; /** @type {?} */ const middleDescription = currentIndex + 1 + midSeparator + this.images.length; if (imageWithoutDescription) { return prevDescription + middleDescription; } /** @type {?} */ const currImgDescription = image.modal && image.modal.description ? image.modal.description : ''; /** @type {?} */ const endDescription = this.configCurrentImage.description.beforeTextDescription + currImgDescription; return prevDescription + middleDescription + endDescription; } /** * Private method to call handleBoundaries when ngOnChanges is called. * @private * @return {?} */ updateIndexes() { /** @type {?} */ let index; try { index = getIndex(this.currentImage, this.images); } catch (err) { console.error('Cannot get the current image index in current-image'); throw err; } if (this.isOpen) { this.handleBoundaries(index); } } }
JavaScript
class PostValidationError extends Error { constructor(data) { super(); this.message = 'Invalid Input Fields'; this.name = 'Post Validation Error'; this.code = 1006; this.data = data; } }
JavaScript
class StatsFilter extends Transform { /** * Tells the Stream we're operating in objectMode * @private */ constructor() { super({objectMode: true}); } /** * Filters out just the interesting part of a RTCStatsReport * @param {RTCStatsReport} report * @param {*} encoding * @param {Function} callback * @private * @returns {undefined} */ _transform(report, encoding, callback) { if (!report) { callback(); return; } const incomingAudio = { local: null, remote: null }; const incomingVideo = { local: null, remote: null }; const outgoingAudio = { local: null, remote: null }; const outgoingVideo = { local: null, remote: null }; for (const item of report.values()) { if (['outbound-rtp', 'outboundrtp'].includes(item.type) && !item.isRemote) { if (item.mediaType === 'audio') { outgoingAudio.local = item; outgoingAudio.remote = report.get(item.remoteId); } if (item.mediaType === 'video') { outgoingVideo.local = item; outgoingVideo.remote = report.get(item.remoteId); } } if (['inbound-rtp', 'inboundrtp'].includes(item.type) && !item.isRemote) { if (item.mediaType === 'audio') { incomingAudio.local = item; incomingAudio.remote = report.get(item.remoteId); } if (item.mediaType === 'video') { incomingVideo.local = item; incomingVideo.remote = report.get(item.remoteId); } } } this.push({ incomingAudio, incomingVideo, outgoingAudio, outgoingVideo, report }); callback(); } }
JavaScript
class InstagramPlatform extends OAuth2Platform{ /** * Creates a new platform. * * @param {Clavem} client The Clavem client. */ constructor(client){ super(client); /** * The Authorization URL. * * @type {string} */ this.authorizeUrl = "https://api.instagram.com/oauth/authorize"; /** * The Access Token URL. * * @type {string} */ this.accessTokenUrl = "https://api.instagram.com/oauth/access_token"; } }
JavaScript
class Games { constructor() { this.games = []; this.players = []; } addGame (hostID, roomName, difficulty, count, subject) { let game = { host: hostID, room: roomName, difficulty: difficulty, count: count, subjects: subject, players: [], active: false } // let game = new Game(hostID, roomName, difficulty, count, subject); this.games.push(game); console.log("game added, room list:") this.games.forEach(room => console.log(room)) return game; } addPlayer (username, room, hostID) { console.log("add player method") let player = { username: username, roomName: room, roomID: hostID, score: 0 } this.players.push(player); let game = this.games.find( y => y.room == room); try{ game.players.push(player); return player; } catch (err) { console.log("add player has : " + err) return { err: err } } } getPLayersForGame(roomName) { //get all players } filterRoom (roomName) { return this.games.room === roomName; } // getPlayerCount = (roomName) => { // console.log("check player count") // const game = this.games.filter(game => game.room === roomName); // console.log(game) // console.log(game.getPlayerCount) // // console.log(game.players.length); // return game.players.length; // } //check the room id //get player with room id getPlayerData (roomName) { //find room in games console.log("player data") // const game = this.games.filter(game => game.room === roomName); let game = this.games.find( y => y.room == roomName); console.log(game) // const players = this.players.filter(player => player.room === roomName) if(game === undefined ){ return "error" } return game.players; } addScore(room, username, score){ //find the game let game = this.games.find( y => y.room == room); //in the room find the player usernmae console.log(game) console.log(username) try{ let player = game.players.find(p => p.username === username) //and add the score player.score = score; //return all player scores for the gamae getPlayerData() return game.players } catch (err) { console.log("add score has : " + err) return { err: err } } } getGame (roomName){ let game = this.games.find( y => y.room == roomName); return game; } getGameByRoom(roomName) { console.log("Looking for room") console.log(roomName) // if(this.games){ this.games.forEach(game => console.log(game)) const game = this.games.filter(game => {console.log(game.room === roomName); return game.room === roomName}); return game; }; checkRoomName(room) { let game = this.getGameByRoom(room); console.log(game) if(game.length > 0 ) { return false; } else { return true; }; }; }
JavaScript
class Session extends Plugin { /** * @function * @async * @param {Defiant.Plugin} plugin * The Plugin to which the `action` pertains. * @param {String} action * The action being performed. Example actions include "pre-enable", * "enable", "disable", "update". * @param {Mixed} [data=NULL] * Any supplementary information. */ async notify(plugin, action, data=null) { super.notify(plugin, action, data); switch (action) { case 'pre:enable': /** * @member {Object} Defiant.Plugin.Sessions#sessions * For tracking the sessions objects. */ this.sessions = {}; // TODO: Come up with a way to track the age of this session. /** * @member {Object} Defiant.Plugin.Sessions#volatile * For tracking the volatile sessions objects. This is information which * should be given to the user, but it is not the end of the world if the * contents are lost. * * Sessions are ultimately stored on disk in a file. This information is * stored in RAM. If the server dies, it is wiped. */ this.volatile = {}; /** * @member {number} Defiant.Plugin.Session#sessionLifetime * The number of seconds that a session can last past its last use. */ this.sessionLifetime = 60 * 60 * 24 * 30; for (let existingPlugin of ['Router', 'Settings'].map(name => this.engine.pluginRegistry.get(name))) { if (existingPlugin instanceof Plugin) { await this.notify(existingPlugin, 'enable'); } } break; // pre:enable case 'enable': switch ((plugin || {}).id) { case 'Router': // Add session information to incoming HTTP requests. plugin .addHandler(new (require('./handler/sessionHandler'))()); break; // Router case 'Settings': // Declare the Session Reader Data item and set its defaults. plugin.cacheRegistry.set(new Data({ id: `session/sessionReader.json`, filename: Path.join('session', `sessionReader.json`), storage: 'settings', storageCanChange: true, // TODO: Translate. description: 'Stores the settings for the Session Reader.', default: { cookieName: 'sessionId', secret: '', // Default duration one week. duration: 7 * 24 * 60 * 60 * 1000, }, })); // Load the actual values. let sessionSettings = plugin.cacheRegistry.get(`session/sessionReader.json`); let sessionSettingsData = await sessionSettings.load(); if (!sessionSettingsData.secret) { // Generate a random secret and save it for future use. sessionSettingsData.secret = uuid.v4(); let e = await sessionSettings.save(); if (e) { // TODO: Translate. console.error(`Could not write Session Reader settings file.`); } } // Initialize the Session Reader function. let sessionReader = clientSessions(sessionSettingsData); this.sessionReader = async (req, res) => { await new Promise((accept, reject) => { sessionReader(req, res, () => { accept(); }); }); }; break; // Settings case this.id: break; // this.id } break; // enable case 'pre:disable': // @todo Cleanup entries in Router, Settings. break; // pre:disable } } /** * Read a session file from disk. * @function * @async * @param {String} id * The id of the session to be loaded. * @returns {Defiant.Plugin.Settings.Data} * The session as a Data object. */ async readSessionFile(id) { return new Data({ filename: Path.join(id.substring(0, 2), id + '.json'), storage: 'sessions', default: undefined }, this.engine.pluginRegistry.get('Settings')).load(); } /** * Write a session file to disk. * @function * @async * @param {Mixed} session * The session information. * @returns {Defiant.Plugin.Settings.Data} * The session as a Data object. */ async writeSessionFile(session) { return new Data({ filename: Path.join(session.id.substring(0, 2), session.id + '.json'), storage: 'sessions', data: session }, this.engine.pluginRegistry.get('Settings')).save(); } /** * Delete a session file from disk. * @param {String} id * The id of the session. * @returns {Object} * The result of the file delete. */ async deleteSessionFile(id) { return new Data({ filename: Path.join(id.substring(0, 2), id + '.json'), storage: 'sessions', }, this.engine.pluginRegistry.get('Settings')).remove(); } /** * Generate a new session for the current request. The session is added to * the Context. * @function * @async * @param {Defiant.Context} * The request context. */ async generateSession(context) { let newID, currentTime = Math.round(new Date().getTime() / 1000); do { newID = uuid.v4(); } while (this.sessions[newID]); let session = { id: newID, expire: currentTime + this.sessionLifetime }; let buff = await new Promise((accept, reject) => { crypto.randomBytes(32, (ex, buf) => {accept(buf);}); }); session.formApiKey = buff.toString('base64'); session.formApiKeyRaw = buff.toString('binary'); this.sessions[session.id] = session; this.volatile[session.id] = {}; context.request.sessionId = { id: session.id }; context.session = session; } // Cron not implemented yet... /* cron() { let currentTime = Math.round(new Date().getTime() / 1000); let killTime = currentTime + this.sessionLifetime; for (let key in this.sessions) { if (this.sessions[key].expire < currentTime) { console.log('Delete: ' + key); delete this.sessions[key]; delete this.volatile[key]; } } } startCron() { if (this.cronID) { clearInterval(this.cronID); } this.cronID = setInterval(this.cron, Session.cronFrequency * 1000); } */ }
JavaScript
class SentinelCommandProcessor { /** * Constructor. * @constructor */ constructor(redisPort) { this.redisPort = redisPort; this.messageParser = new MessageParser(); } /** * Process a command. */ process(msg, socket) { let commandType = this._getCommandType(msg); debug('Process sentinel command type of ' + commandType + ' from ' + socket.remoteAddress + ':' + socket.remotePort); switch(commandType) { case SentinelCommandProcessor.GET_MASTER_ADDR_BY_NAME: { this._processGetMasterAddrByName(msg, socket); break; } default: { this._processUnknownCommand(socket); break; } } } /** * Send message to client. */ _sendMessage(msg, socket) { let respString = this.messageParser.toString(msg); debug('Sentinel send response of\n' + respString + '\nto ' + socket.remoteAddress + ':' + socket.remotePort); socket.write(respString); } /** * Process unknown command. */ _processUnknownCommand(socket) { let respMsg = { type: '-', value: 'ERR unknown command' }; socket.write(this.messageParser.toString(respMsg)); } /** * Process get master address by name. */ _processGetMasterAddrByName(msg, socket) { let respMsg = { type: '*', length: 2, value: [ { type: '$', length: 9, value: '127.0.0.1' }, { type: '$', length: 4, value: '6379' } ] }; this._sendMessage(respMsg, socket); } /** * Get command type. */ _getCommandType(msg) { let commandType = null; // get-master-addr-by-name if (msg.type == '*' && msg.length == 3 && msg.value[0].type == '$' && msg.value[0].value == 'sentinel' && msg.value[1].type == '$' && msg.value[1].value == SentinelCommandProcessor.GET_MASTER_ADDR_BY_NAME) { commandType = SentinelCommandProcessor.GET_MASTER_ADDR_BY_NAME; } return commandType; } static get GET_MASTER_ADDR_BY_NAME() { return 'get-master-addr-by-name'; } }
JavaScript
class Controller { #connection; // ControlConnection instance #container; // HTMLElement for the service container #dialogs; // HTMLDialogElement[] for { error, notConnected, selectRoom } #userInterface; // HTMLElement[] for { configuration } // Name of the room this controller is responsible for. #room; // Array of element bindings that have been created for this controller. #bindings; constructor(connection, { container, dialogs, userInterface }) { this.#connection = connection; this.#container = container; this.#dialogs = dialogs; this.#userInterface = userInterface; // Attach connection listeners: connection.addEventListener('connect', Controller.prototype.onConnected.bind(this)); connection.addEventListener('disconnect', Controller.prototype.onDisconnected.bind(this)); // Attach event listeners to make the interface functional: this.initializeInterface(); // Attempt the connection: connection.connect(); } // --------------------------------------------------------------------------------------------- // Connection listeners // --------------------------------------------------------------------------------------------- // Called when the control connection has been established, either during device boot or when // connection was lost during operation. We assume a new environment each time this happens. async onConnected() { await this.displayConfiguration(/* manual= */ false); } onDisconnected() { this.toggleInterface(/* enabled= */ false); this.#dialogs.notConnected.showModal(); } // --------------------------------------------------------------------------------------------- // User Interface helpers // --------------------------------------------------------------------------------------------- // Displays a dialog that allows the user to configure the device, by selecting the room the // panel should control and displaying any debug information sent by the server. |manual| // indicates whether the dialog was manually requested by the user. async displayConfiguration(manual) { const { rooms } = await this.#connection.send({ command: 'environment-rooms' }); // (1) Close the connection dialog if it's open, as we are now connected, as well as the // user interface which shouldn't be visible during this operation. if (this.#dialogs.notConnected.open) this.#dialogs.notConnected.close(); this.toggleInterface(/* enabled= */ false); // (2) Require the user to select a valid room which this controller is responsible for. if (!this.#room || !rooms.includes(this.#room) || manual) this.#room = await this.selectRoom(rooms); // (3) Fetch the list of services that exist for that room. const { services } = await this.#connection.send({ command: 'environment-services', room: this.#room, }); // (4) Clear the list of displayed services, and add each of the services to the container // after clearing all services that are already being displayed, if any. while (this.#container.firstChild) this.#container.removeChild(this.#container.firstChild); this.toggleInterface(/* enabled= */ true); this.#bindings = []; for (const service of services) await this.initializeService(service); } // Displays a fatal error message. The message cannot be discarded without reloading the entire // page & controller, and thus should only be used in exceptional circumstances. displayFatalError(errorMessage) { const message = this.#dialogs.error.querySelector('#error-message'); const reload = this.#dialogs.error.querySelector('#error-reload-button'); message.textContent = errorMessage; reload.addEventListener('click', () => document.location.reload()); this.toggleInterface(/* enabled= */ false); this.#dialogs.error.show(); } // Initializes the user interface elements by attaching the necessary event listeners. This will // be called once per page load of the controller interface. initializeInterface() { // (1) Configuration button. this.#userInterface.configuration.addEventListener('click', () => { this.displayConfiguration(/* manual= */ true); }); } // Toggles whether the user interface should be visible or not. toggleInterface(enabled) { for (const element of Object.values(this.#userInterface)) element.style.display = enabled ? 'block' : 'none'; } // Renders the given |service| in the controller's container. The service's display will be // determined by a custom element specific to the given |service|. async initializeService({ label, service, options }) { let bindings = null; switch (service) { case 'Philips Hue': bindings = new PhilipsHueBindings(this.#connection, label, options); break; default: this.displayFatalError(`Cannot display unrecognised service: "${service}"`); return; } this.#container.appendChild(bindings.element); this.#bindings.push(bindings); } // Requires the user to select a room from a list of |rooms|. Will display a dialog for the // duration of this operation, that cannot be dismissed through other means. async selectRoom(rooms) { const roomList = this.#dialogs.selectRoom.querySelector('#room-list'); while (roomList.firstChild) roomList.removeChild(roomList.firstChild); let roomResolver = null; let roomPromise = new Promise(resolve => roomResolver = resolve); for (const room of rooms.sort()) { const roomElement = document.createElement('li'); if (room === this.#room) roomElement.classList.add('active'); roomElement.textContent = room; roomElement.addEventListener('click', () => { if (!roomResolver) return; this.#dialogs.selectRoom.close(); roomResolver(room); roomResolver = null; }); roomList.appendChild(roomElement); } for (const debugValue of this.#connection.debugValues) { const listElement = document.createElement('li'); listElement.classList.add('debug'); listElement.textContent = debugValue; roomList.appendChild(listElement); } this.#dialogs.selectRoom.show(); return await roomPromise; } }
JavaScript
class ButtonMouseShadowed extends MC { /** * @param {String} [modifier = ''] Modifier of the button block. * Default '' means mo modifier. * @param {function} postShadowFunction - function that performs * actions after the result of shadowFunction is applied * @param {function} shadowFunction - function that will * calculate the shadow of the dom elements * @returns {void} */ constructor( modifier = '', postShadowFunction, shadowFunction) { super( document.body, ['button'], `.button${modifier}` ); this._postShadowFunction = postShadowFunction; this._shadowFunction = shadowFunction; } /** * more specific version of {MouseShadowController}'s * mousemoveEventShadow that already specifies where to find the * passed shadow functions and what elements it applies to * @see MouseShadowController * @returns {void} */ mousemoveEventShadow() { super.mousemoveEventShadow( this._shadowFunction, '*', this._postShadowFunction ); } }
JavaScript
class BotStrategyGradientDescent extends BotStrategyBase { constructor(lower, upper, treasureWidth) { super(lower, upper, treasureWidth); this.gda = null; this.lastTarget = null; this.locations = new Set(); } /** * Return next probe location based on gradient descent. * * @param tangents {[{x:number,value:number,slope:number}]} * @param player * @param playerIndex {number} * @param players {[]} * @returns {number} */ getNextProbeLocation(tangents, player, playerIndex, players) { let x; if (this.lastTarget === null) { // There is no last target -> probe at the current location x = player.x; } else { // There is a last target const lastTargetTangent = tangents.find(t => t.x === this.lastTarget) || null; if (lastTargetTangent === null) { // The player didn't probe at the last target yet -> send the player there again x = this.lastTarget; } else { // There is a tangent for the last target -> continue from there try { // Try to do a local step x = this.getNextProbeLocationLocal(lastTargetTangent, tangents); } catch (e) { console.log('BotStrategyGradientDescent', e.message); // Local step failed -> do a global step x = this.getNextProbeLocationGlobal(tangents); } } } this.locations.add(x); this.lastTarget = x; return x; } getNextProbeLocationLocal(currentTangent, tangents) { console.log('BotStrategyGradientDescent', 'Local step with ', currentTangent); if (Math.abs(currentTangent.slope) < LOCAL_MIN_SLOPE) { throw new Error('Local minimum reached'); } if (this.gda === null) { this.locations.add(currentTangent.x); this.gda = new GradientDescentArmijo(); } let x; do { x = this.clamp(this.gda.step(currentTangent)); // TODO: Do not look for the adjacent tangents but for the last Armijo tangents and the // TODO: tangent on the opposite side of x // NOTE: This doesn't care about overshooting. Even though it could easily be prevented, // the regular gradient descent algorithm doesn't do it so we don't do it either const oppositeTangent = this.getOppositeTangentDistance( this.gda.lastArmijoTangent.x, x, tangents ); const oppositeTangentDistance = Math.abs(this.gda.lastArmijoTangent.x - oppositeTangent.x); const localMinimumInBetween = this.gda.lastArmijoTangent.slope * oppositeTangent.slope < 0; const tooNarrow = oppositeTangentDistance < this.treasureWidth; console.log( "oppositeTangentDistance", oppositeTangentDistance, "tooNarrow", tooNarrow ); if (x === this.gda.lastArmijoTangent.x || (localMinimumInBetween && tooNarrow)) { // No useful progress possible -> do global search step throw new Error('No local progress possible'); } } while (this.locations.has(x)); // don't probe the same position twice return x; } getNextProbeLocationGlobal(tangents) { console.log('BotStrategyGradientDescent', 'Global step'); try { // Try to find a tangent that we didn't use so far and that's above all currently known local maxima const bestLocalMaximum = tangents .filter(t => Math.abs(t.slope) < LOCAL_MIN_SLOPE) .reduce((acc, cur) => cur.value > acc.value ? cur : acc, 0); const unknownTangentsEqualGreaterLocalMaximum = tangents .filter(t => t.value >= bestLocalMaximum && !this.locations.has(t.x)); const bestTangentReducer = (acc, cur) => acc.value > cur.value ? acc : cur; // The following will throw an error if the array is empty -> continue with catch-clause. const bestTangent = unknownTangentsEqualGreaterLocalMaximum.reduce(bestTangentReducer); // We didn't probe at that location ourselves, but we can assume we did this.locations.add(bestTangent.x); // Start a local search from the new starting point this.gda = null; return this.getNextProbeLocationLocal(bestTangent) } catch (e) { // Jump to the mid point of the largest unknown territory this.gda = null; const largestUnknownTerritory = this.findLargestUnknownTerritory(tangents); return (largestUnknownTerritory.left.x + largestUnknownTerritory.right.x) / 2; } } }
JavaScript
class Node { constructor(value) { this.value = value; this.next = null; }; }
JavaScript
class ScreensharePicker extends React.Component { static propTypes = { advertisedAppName: PropTypes.string, onStartWiredScreenshare: PropTypes.func, onStartWirelessScreenshare: PropTypes.func, onStopScreensharing: PropTypes.func, screensharingType: PropTypes.string, shareDomain: PropTypes.string, wiredScreenshareEnabled: PropTypes.bool, wirelessScreenshareEnabled: PropTypes.bool }; /** * Ensures the screenshare select view displays when transitioning from * screensharing to not screensharing. * * @inheritdoc */ static getDerivedStateFromProps(props) { if (props.screensharingType) { return { displayWirelessInstructions: false, displayWiredInstructions: false }; } return null; } /** * Initializes a new {@code ScreensharePicker} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); this.state = { displayWirelessInstructions: false, displayWiredInstructions: false }; this._onShowStartWired = this._onShowStartWired.bind(this); this._onShowStartWireless = this._onShowStartWireless.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { return ( <div className = 'nav screenshare-select' data-qa-id = 'screenshare-picker'> { this._renderContent() } </div> ); } /** * Sets the state to show instructions on how to start wired screensharing. * * @private * @returns {void} */ _onShowStartWired() { this.setState({ displayWiredInstructions: true, displayWirelessInstructions: false }); } /** * Starts the wireless screensharing flow if supported. Otherwise sets the * state to show instructions on how to start wireless screensharing. * * @private * @returns {void} */ _onShowStartWireless() { if (this.props.wirelessScreenshareEnabled) { this.props.onStartWirelessScreenshare(); } else { this.setState({ displayWiredInstructions: false, displayWirelessInstructions: true }); } } /** * Helper for determining what view to display within the picker. The view * selects between screensharing instructions and stop states. * * @private * @returns {ReactElement} */ _renderContent() { // If screensharing is enabled, show a stop screensharing view. if (this.props.screensharingType) { return this._renderStopShare(); } // If no screensharing is supported, show tips on how to screenshare // wirelessly. Intentionally ignore wired in case wired screenshare is // intentionally not supported. if (!this.props.wirelessScreenshareEnabled && !this.props.wiredScreenshareEnabled) { return this._renderWirelessScreenshareNotSupported(); } // When wireless screenshare has been selected but not supported, then // display instructions on how to screenshare wirelessly. if (!this.props.wirelessScreenshareEnabled && this.state.displayWirelessInstructions) { return this._renderWirelessScreenshareNotSupported(); } // If wired screenshare has been selected then show instructions on how // start wired screenshare. if (this.props.wiredScreenshareEnabled && this.state.displayWiredInstructions) { return this._renderStartWiredScreenshare(); } // There are no instructions to display for starting a wireless // screenshare. Either the picker has been displayed or instructions // have been shown to go to another browser. // Default to choosing whether to start wired or wireless screensharing. return this._renderShareSelect(); } /** * Displays a view to start either the wireless screensharing flow or the * wired screensharing flow. * * @private * @returns {ReactElement} */ _renderShareSelect() { return ( <> <div className = 'title'> How would you like to screenshare? </div> <div className = 'options'> <NavButton className = 'screenshare' label = 'Wireless Screensharing' onClick = { this._onShowStartWireless } qaId = 'start-wireless-screenshare'> <WirelessScreenshare /> </NavButton> { this.props.wiredScreenshareEnabled && ( <NavButton className = 'screenshare' label = 'HDMI Screensharing' onClick = { this._onShowStartWired }> <WiredScreenshare /> </NavButton> ) } </div> </> ); } /** * Provides instructions on how to start a wired screenshare. * * @private * @returns {ReactElement} */ _renderStartWiredScreenshare() { return ( <> <div className = 'content'> <div className = 'icon'> <i className = 'material-icons'>wired_screen_share</i> </div> <div className = 'title'> Plug the HDMI dongle into your computer </div> <div className = 'subtitle'> If sharing doesn't start automatically click start sharing below. </div> </div> <div className = 'footer'> <Button appearance = 'subtle' className = 'cta-button' onClick = { this.props.onStartWiredScreenshare }> Share now </Button> </div> </> ); } /** * Renders a React Element to get confirmation for stopping a screenshare * in progress. The contents of the confirmation depends on the type of * screensharing in progress. * * @private * @returns {ReactElement} */ _renderStopShare() { const isWirelessScreensharing = this.props.screensharingType === 'proxy'; const icon = isWirelessScreensharing ? 'wireless_screen_share' : 'wired_screen_share'; let ctaTitle; if (isWirelessScreensharing) { ctaTitle = 'You can stop the wireless sharing below.'; } else if (this.props.screensharingType === 'device') { ctaTitle = 'To stop sharing content unplug the cable or click stop sharing.'; } else { ctaTitle = 'You can stop screen sharing below.'; } return ( <> <div className = 'content'> <div className = 'icon'> <i className = 'material-icons'>{ icon }</i> </div> <div className = 'title'> You're currently sharing content. </div> <div className = 'subtitle'> { ctaTitle } </div> </div> <div className = 'footer'> <Button appearance = 'subtle-danger' className = 'cta-button' onClick = { this.props.onStopScreensharing } qaId = 'stop-share-button'> Stop sharing </Button> </div> </> ); } /** * Displays a view explaining how to screenshare wirelessly. The view * displays depends on the current browser environment. * * @private * @returns {ReactElement} */ _renderWirelessScreenshareNotSupported() { const { shareDomain } = this.props; return ( <> <div className = 'content'> <div className = 'icon'> <i className = 'material-icons'> wireless_screen_share </i> </div> <div className = 'title'> To share, use Chrome desktop and go to </div> <div className = 'share-url'> { `${shareDomain || windowHandler.getHost()}/` } <RemoteJoinCode /> </div> </div> </> ); } }
JavaScript
class UADiscreteAlarm extends ua_alarm_condition_base_1.UAAlarmConditionBase { static instantiate(namespace, discreteAlarmTypeId, options, data) { const addressSpace = namespace.addressSpace; const discreteAlarmType = addressSpace.findEventType(discreteAlarmTypeId); /* istanbul ignore next */ if (!discreteAlarmType) { throw new Error(" cannot find Condition Type for " + discreteAlarmType); } const discreteAlarmTypeBase = addressSpace.findObjectType("DiscreteAlarmType"); node_opcua_assert_1.assert(discreteAlarmTypeBase, "expecting DiscreteAlarmType - please check you nodeset xml file!"); /* eventTypeNode should be subtypeOf("DiscreteAlarmType"); */ /* istanbul ignore next */ if (!discreteAlarmType.isSupertypeOf(discreteAlarmTypeBase)) { throw new Error("UADiscreteAlarm.instantiate : event found is not subType of DiscreteAlarmType"); } const alarmNode = ua_alarm_condition_base_1.UAAlarmConditionBase.instantiate(namespace, discreteAlarmType.nodeId, options, data); Object.setPrototypeOf(alarmNode, UADiscreteAlarm.prototype); return alarmNode; } }
JavaScript
class CAGovFeedback extends window.HTMLElement { constructor() { super(); if (document.querySelector('api-viewer')) { const link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('href', './src/css/index.css'); document.querySelector('api-viewer').shadowRoot.appendChild(link); } } connectedCallback() { const question = this.dataset.question ? this.dataset.question : 'Did you find what you were looking for?'; const yes = this.dataset.yes ? this.dataset.yes : 'Yes'; const no = this.dataset.no ? this.dataset.no : 'No'; const commentPrompt = this.dataset.commentPrompt ? this.dataset.commentPrompt : 'What was the problem?'; this.positiveCommentPrompt = this.dataset.positiveCommentPrompt ? this.dataset.positiveCommentPrompt : 'Great! What were you looking for today?'; const thanksFeedback = this.dataset.thanksFeedback ? this.dataset.thanksFeedback : 'Thank you for your feedback!'; const thanksComments = this.dataset.thanksComments ? this.dataset.thanksComments : 'Thank you for your comments!'; const submit = this.dataset.submit ? this.dataset.submit : 'Submit'; this.dataset.characterLimit ? this.dataset.characterLimit : 'You have reached your character limit.'; this.dataset.anythingToAdd ? this.dataset.anythingToAdd : 'If you have anything to add,'; this.dataset.anyOtherFeedback ? this.dataset.anyOtherFeedback : 'If you have any other feedback about this website,'; this.endpointUrl = this.dataset.endpointUrl; const html = ratingsTemplate( question, yes, no, commentPrompt, thanksFeedback, thanksComments, submit, ); this.innerHTML = html; this.applyListeners(); } applyListeners() { this.wasHelpful = ''; this.querySelector('.js-add-feedback').addEventListener('focus', () => { this.querySelector('.js-feedback-submit').style.display = 'block'; }); const feedback = this.querySelector('.js-add-feedback'); feedback.addEventListener('keyup', () => { if (feedback.value.length > 15) { feedback.setAttribute('rows', '3'); } else { feedback.setAttribute('rows', '1'); } }); feedback.addEventListener('blur', () => { if (feedback.value.length !== 0) { this.querySelector('.js-feedback-submit').style.display = 'block'; } }); this.querySelector('.js-feedback-yes').addEventListener('click', () => { this.querySelector('.js-feedback-field-label').innerHTML = this.positiveCommentPrompt; this.querySelector('.js-feedback-form').style.display = 'none'; this.querySelector('.feedback-form-add').style.display = 'block'; this.wasHelpful = 'yes'; this.dispatchEvent( new CustomEvent('ratedPage', { detail: this.wasHelpful, }), ); }); this.querySelector('.js-feedback-no').addEventListener('click', () => { this.querySelector('.js-feedback-form').style.display = 'none'; this.querySelector('.feedback-form-add').style.display = 'block'; this.wasHelpful = 'no'; this.dispatchEvent( new CustomEvent('ratedPage', { detail: this.wasHelpful, }), ); }); this.querySelector('.js-feedback-submit').addEventListener('click', () => { this.querySelector('.feedback-form-add').style.display = 'none'; this.querySelector('.feedback-thanks-add').style.display = 'block'; const postData = {}; postData.url = window.location.href; postData.helpful = this.wasHelpful; postData.comments = feedback.value; postData.userAgent = navigator.userAgent; fetch(this.endpointUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }) .then((response) => response.json()) .then((data) => console.log(data)); }); } }
JavaScript
class HeaderComponent extends Component { constructor() { super(); this.state = { dialogOpen: false, anchorEl: null, form: null }; } componentWillReceiveProps = nextProps => { if (nextProps.dialogClose !== this.props.dialogClose) { this.handleDialogClose(); } }; handleDialogOpen = formName => { this.setState({ dialogOpen: true, form: formName }); }; handleDialogClose = () => { this.setState({ dialogOpen: false }); }; handleMenuOpen = event => { this.setState({ anchorEl: event.currentTarget }); }; handleMenuClose = () => { this.setState({ anchorEl: null }); }; renderDialogTitle = () => { switch (this.state.form) { case 'login': return 'Log In'; case 'signup': return 'Registration'; default: return null; } }; renderDialogContent = () => { switch (this.state.form) { case 'login': return <LoginForm onSubmit={this.props.handleLogin} />; case 'signup': return <CompanySignupForm onSubmit={this.props.handleSignup} />; default: return null; } }; renderHeaderToolbar = () => { switch (this.props.authenticated) { case true: return [ <Link to="/dashboard" style={{ textDecoration: 'none', color: 'white' }} key="toolbar-dashboard" > <Button color="inherit">Dashboard</Button> </Link>, <Button color="inherit" onClick={this.props.handleLogout} key="toolbar-logout" > Logout </Button> ]; case false: return ( <FlexView> <Button color="inherit" onClick={this.handleDialogOpen.bind(this, 'signup')} > Sign Up </Button> <Button color="inherit" onClick={this.handleDialogOpen.bind(this, 'login')} > Login </Button> </FlexView> ); default: return null; } }; renderHeaderMenu = () => { switch (this.props.authenticated) { case true: return ( <FlexView column> <Link to="/dashboard" style={{ textDecoration: 'none', color: 'white' }} key="toolbar-dashboard" > <MenuItem>Dashboard</MenuItem> </Link> <MenuItem onClick={this.handleMenuClose && this.props.handleLogout}> Logout </MenuItem> </FlexView> ); case false: return ( <FlexView column> <MenuItem onClick={ this.handleMenuClose && this.handleDialogOpen.bind(this, 'login') } > Login </MenuItem> <MenuItem onClick={ this.handleMenuClose && this.handleDialogOpen.bind(this, 'signup') } > Sign Up </MenuItem> </FlexView> ); default: return null; } }; render() { const { fullScreen } = this.props; const { anchorEl } = this.state; const openMenu = Boolean(anchorEl); return ( <FlexView> <AppBar position="static"> <Toolbar> <FlexView grow> <Typography variant="title" color="inherit"> Referix </Typography> </FlexView> <Hidden xsDown>{this.renderHeaderToolbar()}</Hidden> <Hidden smUp> <IconButton color="inherit" aria-label="Menu" style={styles.menuButton} onClick={this.handleMenuOpen} > <MenuIcon /> </IconButton> <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={openMenu} onClick={this.handleMenuClose} > {this.renderHeaderMenu()} </Menu> </Hidden> </Toolbar> </AppBar> <Dialog fullScreen={fullScreen} open={this.state.dialogOpen} onClose={this.handleDialogClose} aria-labelledby="responsive-dialog-title" > <DialogTitle style={{ minWidth: fullScreen ? 0 : 400 }}> {this.renderDialogTitle()} <Close style={{ float: 'right', cursor: 'pointer', marginTop: '-10px', marginRight: '-10px', width: '20px' }} onClick={this.handleDialogClose} /> </DialogTitle> <DialogContent>{this.renderDialogContent()}</DialogContent> </Dialog> </FlexView> ); } }
JavaScript
class WebglLine extends WebglBaseLine { /** * Create a new line * @param c - the color of the line * @param numPoints - number of data pints * @example * ```typescript * x= [0,1] * y= [1,2] * line = new WebglLine( new ColorRGBA(0.1,0.1,0.1,1), 2); * ``` */ constructor(c, numPoints) { super(); this.currentIndex = 0; this.webglNumPoints = numPoints; this.numPoints = numPoints; this.color = c; this.xy = new Float32Array(2 * this.webglNumPoints); } /** * Set the X value at a specific index * @param index - the index of the data point * @param x - the horizontal value of the data point */ setX(index, x) { this.xy[index * 2] = x; } /** * Set the Y value at a specific index * @param index : the index of the data point * @param y : the vertical value of the data point */ setY(index, y) { this.xy[index * 2 + 1] = y; } /** * Get an X value at a specific index * @param index - the index of X */ getX(index) { return this.xy[index * 2]; } /** * Get an Y value at a specific index * @param index - the index of Y */ getY(index) { return this.xy[index * 2 + 1]; } /** * Make an equally spaced array of X points * @param start - the start of the series * @param stepSize - step size between each data point * * @example * ```typescript * //x = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8] * const numX = 10; * line.lineSpaceX(-1, 2 / numX); * ``` */ lineSpaceX(start, stepSize) { for (let i = 0; i < this.numPoints; i++) { // set x to -num/2:1:+num/2 this.setX(i, start + stepSize * i); } } /** * Automatically generate X between -1 and 1 * equal to lineSpaceX(-1, 2/ number of points) */ arrangeX() { this.lineSpaceX(-1, 2 / this.numPoints); } /** * Set a constant value for all Y values in the line * @param c - constant value */ constY(c) { for (let i = 0; i < this.numPoints; i++) { // set x to -num/2:1:+num/2 this.setY(i, c); } } /** * Add a new Y values to the end of current array and shift it, so that the total number of the pair remains the same * @param data - the Y array * * @example * ```typescript * yArray = new Float32Array([3, 4, 5]); * line.shiftAdd(yArray); * ``` */ shiftAdd(data) { const shiftSize = data.length; for (let i = 0; i < this.numPoints - shiftSize; i++) { this.setY(i, this.getY(i + shiftSize)); } for (let i = 0; i < shiftSize; i++) { this.setY(i + this.numPoints - shiftSize, data[i]); } } /** * Add new Y values to the line and maintain the position of the last data point */ addArrayY(yArray) { if (this.currentIndex + yArray.length <= this.numPoints) { for (let i = 0; i < yArray.length; i++) { this.setY(this.currentIndex, yArray[i]); this.currentIndex++; } } } /** * Replace the all Y values of the line */ replaceArrayY(yArray) { if (yArray.length == this.numPoints) { for (let i = 0; i < this.numPoints; i++) { this.setY(i, yArray[i]); } } } }
JavaScript
class TwitterConnect extends ConnectBase { /** * Constructor for twitter connect service. * * @param {object} params * @param {string} params.token: oAuth Token * @param {string} params.secret: oAuth Secret * @param {string} params.twitter_id: Twitter_id * @param {string} params.handle: Handle * * @augments ServiceBase * * @constructor */ constructor(params) { super(params); const oThis = this; oThis.token = params.token; oThis.secret = params.secret; oThis.twitterId = params.twitter_id; oThis.duplicateRequestIdentifier = oThis.twitterId; oThis.handle = params.handle; oThis.userTwitterEntity = null; oThis.twitterRespHeaders = null; } /** * Fetch Twitter User Obj if present * * @sets oThis.socialUserObj * * @return {Promise<Result>} * @private */ async _fetchSocialUser() { const oThis = this; logger.log('Start::Fetch Twitter User'); const twitterUserObjCacheResp = await new TwitterUserByTwitterIdsCache({ twitterIds: [oThis.twitterId] }).fetch(); if (twitterUserObjCacheResp.isFailure()) { return Promise.reject(twitterUserObjCacheResp); } if (twitterUserObjCacheResp.data[oThis.twitterId].id) { oThis.socialUserObj = twitterUserObjCacheResp.data[oThis.twitterId]; } return responseHelper.successWithData({}); } /** * Method to check whether user has connected twitter * * @param userObj * @private */ _sameSocialConnectUsed(userObj) { const propertiesArray = new UserModel().getBitwiseArray('properties', userObj.properties); return propertiesArray.indexOf(userConstants.hasTwitterLoginProperty) > -1; } /** * Method to validate Credentials and get profile data from twitter. * * @returns {Promise<void>} * @private */ async _validateAndFetchSocialInfo() { const oThis = this; logger.log('Start::Validate Twitter Credentials'); let twitterResp = null; twitterResp = await new AccountTwitterRequestClass().verifyCredentials({ oAuthToken: oThis.token, oAuthTokenSecret: oThis.secret }); if (twitterResp.isFailure()) { return Promise.reject( responseHelper.error({ internal_error_identifier: 's_t_c_vtc_2', api_error_identifier: 'unauthorized_api_request', debug_options: {} }) ); } oThis.twitterRespHeaders = twitterResp.data.headers; oThis.userTwitterEntity = twitterResp.data.userEntity; // validating the front end data if (oThis.userTwitterEntity.idStr != oThis.twitterId || oThis.userTwitterEntity.handle != oThis.handle) { return Promise.reject( responseHelper.error({ internal_error_identifier: 's_t_c_vtc_3', api_error_identifier: 'unauthorized_api_request', debug_options: {} }) ); } logger.log('End::Validate Twitter Credentials'); return responseHelper.successWithData({}); } /** * Call signup service for twitter connect. * * @return {void} * * @private */ async _performSignUp() { const oThis = this; logger.log('Start::Connect._performSignUp'); let requestParams = { twitterUserObj: oThis.socialUserObj, userTwitterEntity: oThis.userTwitterEntity, twitterRespHeaders: oThis.twitterRespHeaders, token: oThis.token, secret: oThis.secret, headers: oThis.headers }; Object.assign(requestParams, oThis._appendCommonSignupParams()); oThis.serviceResp = await new SignupTwitterClass(requestParams).perform(); logger.log('End::Connect._performSignUp'); } /** * Call signup service for twitter connect. * * @return {void} * * @private */ async _performLogin() { const oThis = this; logger.log('Start::Connect._performLogin'); let requestParams = { twitterUserObj: oThis.socialUserObj, userTwitterEntity: oThis.userTwitterEntity, twitterRespHeaders: oThis.twitterRespHeaders, token: oThis.token, secret: oThis.secret, userId: oThis.userId, isNewSocialConnect: oThis.newSocialConnect, apiSource: oThis.apiSource }; oThis.serviceResp = await new LoginTwitterClass(requestParams).perform(); logger.log('End::Connect._performLogin'); } /** * Get unique property from social platform info, like email or phone number * * @returns {{}|{kind: string, value: *}} * @private */ _getSocialUserUniqueProperties() { const oThis = this; if (!oThis.userTwitterEntity.email || !CommonValidators.isValidEmail(oThis.userTwitterEntity.email)) { return {}; } return { kind: userIdentifierConstants.emailKind, values: [oThis.userTwitterEntity.email] }; } }
JavaScript
class UserEntityBaseParameters { /** * Create a UserEntityBaseParameters. * @member {string} [state] Account state. Specifies whether the user is * active or not. Blocked users are unable to sign into the developer portal * or call any APIs of subscribed products. Default state is Active. Possible * values include: 'active', 'blocked', 'pending', 'deleted'. Default value: * 'active' . * @member {string} [note] Optional note about a user set by the * administrator. * @member {array} [identities] Collection of user identities. */ constructor() { } /** * Defines the metadata of UserEntityBaseParameters * * @returns {object} metadata of UserEntityBaseParameters * */ mapper() { return { required: false, serializedName: 'UserEntityBaseParameters', type: { name: 'Composite', className: 'UserEntityBaseParameters', modelProperties: { state: { required: false, serializedName: 'state', defaultValue: 'active', type: { name: 'String' } }, note: { required: false, serializedName: 'note', type: { name: 'String' } }, identities: { required: false, readOnly: true, serializedName: 'identities', type: { name: 'Sequence', element: { required: false, serializedName: 'UserIdentityContractElementType', type: { name: 'Composite', className: 'UserIdentityContract' } } } } } } }; } }
JavaScript
class BonAppetitScraper extends BaseScraper { constructor(url) { super(url, "bonappetit.com/recipe/"); } scrape($) { this.defaultSetImage($); this.defaultSetDescription($); const { ingredients, instructions } = this.recipe; this.recipe.name = $("meta[property='og:title']").attr("content"); const tags = $("meta[name='keywords']").attr("content"); this.recipe.tags = tags ? tags.split(',') : []; const container = $('div[data-testid="IngredientList"]'); const ingredientsContainer = container.children("div"); const units = ingredientsContainer.children("p"); const ingrDivs = ingredientsContainer.children("div"); units.each((i, el) => { ingredients.push(`${$(el).text()} ${$(ingrDivs[i]).text()}`); }); const instructionContainer = $('div[data-testid="InstructionsWrapper"]'); instructionContainer.find("p").each((i, el) => { instructions.push($(el).text()); }); this.recipe.servings = container .children("p") .text() .split(" ")[0]; } }
JavaScript
class App extends Component { render() { return ( <View style={{ flex: 1, backgroundColor: '#f3f3f3', justifyContent: 'center', alignContent: 'center', padding:20 }}> <Text style={{ fontSize: 30, textAlign: 'center', }}> Example of Action Button in React Native </Text> <Text style={{ textAlign: 'center', marginTop: 20, fontSize: 25 }}> Home </Text> <ActionButton buttonColor="rgba(231,76,60,1)"> {/*Inner options of the action button*/} {/*Icons here https://infinitered.github.io/ionicons-version-3-search/*/} <ActionButton.Item buttonColor="#9b59b6" title="Add to Watch Later" onPress={() => alert('Added to watch later')}> <Icon name="md-eye" style={styles.actionButtonIcon} /> </ActionButton.Item> <ActionButton.Item buttonColor="#3498db" title="Add to Favourite" onPress={() => alert('Added to favourite')}> <Icon name="md-star" style={styles.actionButtonIcon} /> </ActionButton.Item> <ActionButton.Item buttonColor="#1abc9c" title="Share" onPress={() => alert('Share Post')}> <Icon name="md-share-alt" style={styles.actionButtonIcon} /> </ActionButton.Item> </ActionButton> </View> ); } }
JavaScript
class SubscribableStream extends stream_1.Duplex { /** * Initializes a new instance of the [SubscribableStream](xref:botframework-streaming.SubscribableStream) class. * * @param options The `DuplexOptions` to use when constructing this stream. */ constructor(options) { super(options); this.length = 0; this.bufferList = []; } /** * Writes data to the buffered list. * All calls to writable.write() that occur between the time writable._write() is called and the callback is called will cause the written data to be buffered. * * @param chunk The Buffer to be written. * @param _encoding The encoding. Unused in the implementation of Duplex. * @param callback Callback for when this chunk of data is flushed. */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any _write(chunk, _encoding, callback) { const buffer = Buffer.from(chunk); this.bufferList.push(buffer); this.length += chunk.length; if (this._onData) { this._onData(buffer); } callback(); } /** * Reads the buffered list. * Once the readable._read() method has been called, it will not be called again until more data is pushed through the readable.push() method. * Empty data such as empty buffers and strings will not cause readable._read() to be called. * * @param size Number of bytes to read. */ _read(size) { if (this.bufferList.length === 0) { // null signals end of stream this.push(null); } else { let total = 0; while (total < size && this.bufferList.length > 0) { const buffer = this.bufferList[0]; this.push(buffer); this.bufferList.splice(0, 1); total += buffer.length; } } } /** * Subscribes to the stream when receives data. * * @param onData Callback to be called when onData is executed. */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any subscribe(onData) { this._onData = onData; } }
JavaScript
class ConfigModal extends React.PureComponent { constructor(props) { super(props); this.state = { decisionTaken: props.decisions[0] }; } updateDecision = value => { this.setState({ decisionTaken: value }); } handleSubmit = values => { this.props.evaluate({ variables: values.variables, decision: this.state.decisionTaken }); } render() { const { closeModal, decisions, initiallySelectedDecision } = this.props; const { decisionTaken = initiallySelectedDecision } = this.state; // flatten to make it easier to display and extend with own variables // TODO: get rid of nested loop const allInputVariables = decisions.flatMap(decision => { return decision.variables.map(variable => ({ decision: decision.decision, decisionId: decision.decisionId, name: variable.expression, type: variable.type, value: '' })); }); const allowedDecisions = [ decisionTaken.decisionId, ...decisionTaken.downstreamDecisions ]; const filteredInputVariables = allInputVariables.filter( variable => allowedDecisions.includes(variable.decisionId) ); const initialValues = { variables: filteredInputVariables }; const onClose = () => closeModal(); return ( <Modal onClose={ onClose }> <Modal.Title> DMN Testing </Modal.Title> <Modal.Body> <div> <h3>Decision to evaluate</h3> <DecisionsDropdown selected={ decisionTaken } decisions={ decisions } onDecisionChanged={ this.updateDecision } /> <h3>Variable inputs</h3> <Formik enableReinitialize initialValues={ initialValues } onSubmit={ this.handleSubmit } > {({ values }) => ( <Form id="dmnTestingInputVarsForm"> <FieldArray name="variables" render={ arrayHelpers => ( <div> {values.variables && values.variables.length > 0 ? ( values.variables.map((_, index) => ( <div key={ index }> <Field name={ `variables.${index}.decision` } disabled={ true } /> <Field name={ `variables.${index}.name` } /> <Field name={ `variables.${index}.value` } placeholder="<provide value>" /> <Field name={ `variables.${index}.type` } component="select"> <option value="">Select type</option> <option value="string">string</option> <option value="integer">integer</option> <option value="boolean">boolean</option> <option value="long">long</option> <option value="double">double</option> <option value="date">date</option> </Field> <button type="button" onClick={ () => arrayHelpers.remove(index) } > - </button> <button type="button" onClick={ () => arrayHelpers.insert(index + 1, '') } > + </button> </div> )) ) : ( <button type="button" onClick={ () => arrayHelpers.push('') }> Add a variable </button> )} </div> ) } /> </Form> )} </Formik> </div> </Modal.Body> <Modal.Footer> <div id="autoSaveConfigButtons"> <button type="button" className="btn btn-secondary" onClick={ () => onClose() }>Cancel</button> <button type="submit" className="btn btn-primary" form="dmnTestingInputVarsForm">Test</button> </div> </Modal.Footer> </Modal> ); } }
JavaScript
class HydraRenderer { constructor ({ pb = null, width = 1280, height = 720, numSources = 4, numOutputs = 4, makeGlobal = true, autoLoop = true, detectAudio = true, enableStreamCapture = true, canvas, precision = 'mediump', extendTransforms = {} // add your own functions on init } = {}) { ArrayUtils.init() this.pb = pb this.width = width this.height = height this.renderAll = false this.detectAudio = detectAudio this._initCanvas(canvas) // object that contains all properties that will be made available on the global context and during local evaluation this.synth = { time: 0, bpm: 30, width: this.width, height: this.height, fps: undefined, stats: { fps: 0 }, speed: 1, mouse: Mouse, render: this._render.bind(this), setResolution: this.setResolution.bind(this), update: (dt) => {},// user defined update function hush: this.hush.bind(this) } this.timeSinceLastUpdate = 0 this._time = 0 // for internal use, only to use for deciding when to render frames // window.synth = this.synth // only allow valid precision options let precisionOptions = ['lowp','mediump','highp'] let precisionValid = precisionOptions.includes(precision.toLowerCase()) this.precision = precisionValid ? precision.toLowerCase() : 'mediump' if(!precisionValid){ console.warn('[hydra-synth warning]\nConstructor was provided an invalid floating point precision value of "' + precision + '". Using default value of "mediump" instead.') } this.extendTransforms = extendTransforms // boolean to store when to save screenshot this.saveFrame = false // if stream capture is enabled, this object contains the capture stream this.captureStream = null this.generator = undefined this._initRegl() this._initOutputs(numOutputs) this._initSources(numSources) this._generateGlslTransforms() this.synth.screencap = () => { this.saveFrame = true } if (enableStreamCapture) { this.captureStream = this.canvas.captureStream(25) // to do: enable capture stream of specific sources and outputs this.synth.vidRecorder = new VidRecorder(this.captureStream) } if(detectAudio) this._initAudio() if(autoLoop) loop(this.tick.bind(this)).start() // final argument is properties that the user can set, all others are treated as read-only this.sandbox = new Sandbox(this.synth, makeGlobal, ['speed', 'update', 'bpm', 'fps']) } eval(code) { this.sandbox.eval(code) } getScreenImage(callback) { this.imageCallback = callback this.saveFrame = true } hush() { this.s.forEach((source) => { source.clear() }) this.o.forEach((output) => { this.synth.solid(1, 1, 1, 0).out(output) }) } setResolution(width, height) { // console.log(width, height) this.canvas.width = width this.canvas.height = height this.width = width this.height = height this.o.forEach((output) => { output.resize(width, height) }) this.s.forEach((source) => { source.resize(width, height) }) console.log(this.canvas.width) } canvasToImage (callback) { const a = document.createElement('a') a.style.display = 'none' let d = new Date() a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png` document.body.appendChild(a) var self = this this.canvas.toBlob( (blob) => { if(self.imageCallback){ self.imageCallback(blob) delete self.imageCallback } else { a.href = URL.createObjectURL(blob) console.log(a.href) a.click() } }, 'image/png') setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(a.href); }, 300); } _initAudio () { const that = this this.synth.a = new Audio({ numBins: 4, // changeListener: ({audio}) => { // that.a = audio.bins.map((_, index) => // (scale = 1, offset = 0) => () => (audio.fft[index] * scale + offset) // ) // // if (that.makeGlobal) { // that.a.forEach((a, index) => { // const aname = `a${index}` // window[aname] = a // }) // } // } }) } // create main output canvas and add to screen _initCanvas (canvas) { if (canvas) { this.canvas = canvas this.width = canvas.width this.height = canvas.height } else { this.canvas = document.createElement('canvas') this.canvas.width = this.width this.canvas.height = this.height this.canvas.style.width = '100%' this.canvas.style.height = '100%' this.canvas.style.imageRendering = 'pixelated' document.body.appendChild(this.canvas) } } _initRegl () { this.regl = require('regl')({ // profile: true, canvas: this.canvas, pixelRatio: 1//, // extensions: [ // 'oes_texture_half_float', // 'oes_texture_half_float_linear' // ], // optionalExtensions: [ // 'oes_texture_float', // 'oes_texture_float_linear' //] }) // This clears the color buffer to black and the depth buffer to 1 this.regl.clear({ color: [0, 0, 0, 1] }) this.renderAll = this.regl({ frag: ` precision ${this.precision} float; varying vec2 uv; uniform sampler2D tex0; uniform sampler2D tex1; uniform sampler2D tex2; uniform sampler2D tex3; void main () { vec2 st = vec2(1.0 - uv.x, uv.y); st*= vec2(2); vec2 q = floor(st).xy*(vec2(2.0, 1.0)); int quad = int(q.x) + int(q.y); st.x += step(1., mod(st.y,2.0)); st.y += step(1., mod(st.x,2.0)); st = fract(st); if(quad==0){ gl_FragColor = texture2D(tex0, st); } else if(quad==1){ gl_FragColor = texture2D(tex1, st); } else if (quad==2){ gl_FragColor = texture2D(tex2, st); } else { gl_FragColor = texture2D(tex3, st); } } `, vert: ` precision ${this.precision} float; attribute vec2 position; varying vec2 uv; void main () { uv = position; gl_Position = vec4(1.0 - 2.0 * position, 0, 1); }`, attributes: { position: [ [-2, 0], [0, -2], [2, 2] ] }, uniforms: { tex0: this.regl.prop('tex0'), tex1: this.regl.prop('tex1'), tex2: this.regl.prop('tex2'), tex3: this.regl.prop('tex3') }, count: 3, depth: { enable: false } }) this.renderFbo = this.regl({ frag: ` precision ${this.precision} float; varying vec2 uv; uniform vec2 resolution; uniform sampler2D tex0; void main () { gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y)); } `, vert: ` precision ${this.precision} float; attribute vec2 position; varying vec2 uv; void main () { uv = position; gl_Position = vec4(1.0 - 2.0 * position, 0, 1); }`, attributes: { position: [ [-2, 0], [0, -2], [2, 2] ] }, uniforms: { tex0: this.regl.prop('tex0'), resolution: this.regl.prop('resolution') }, count: 3, depth: { enable: false } }) } _initOutputs (numOutputs) { const self = this this.o = (Array(numOutputs)).fill().map((el, index) => { var o = new Output({ regl: this.regl, width: this.width, height: this.height, precision: this.precision }) // o.render() o.id = index self.synth['o'+index] = o return o }) // set default output this.output = this.o[0] } _initSources (numSources) { this.s = [] for(var i = 0; i < numSources; i++) { this.createSource() } } createSource () { let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height}) this.synth['s' + this.s.length] = s this.s.push(s) return s } _generateGlslTransforms () { var self = this this.generator = new Generator({ defaultOutput: this.o[0], defaultUniforms: this.o[0].uniforms, extendTransforms: this.extendTransforms, changeListener: ({type, method, synth}) => { if (type === 'add') { self.synth[method] = synth.generators[method] if(self.sandbox) self.sandbox.add(method) } else if (type === 'remove') { // what to do here? dangerously deleting window methods //delete window[method] } // } } }) this.synth.setFunction = this.generator.setFunction.bind(this.generator) } _render (output) { if (output) { this.output = output this.isRenderingAll = false } else { this.isRenderingAll = true } } // dt in ms tick (dt, uniforms) { this.sandbox.tick() if(this.detectAudio === true) this.synth.a.tick() // let updateInterval = 1000/this.synth.fps // ms if(this.synth.update) { try { this.synth.update(dt) } catch (e) { console.log(error) } } this.sandbox.set('time', this.synth.time += dt * 0.001 * this.synth.speed) this.timeSinceLastUpdate += dt if(!this.synth.fps || this.timeSinceLastUpdate >= 1000/this.synth.fps) { // console.log(1000/this.timeSinceLastUpdate) this.synth.stats.fps = Math.ceil(1000/this.timeSinceLastUpdate) // console.log(this.synth.speed, this.synth.time) for (let i = 0; i < this.s.length; i++) { this.s[i].tick(this.synth.time) } // console.log(this.canvas.width, this.canvas.height) for (let i = 0; i < this.o.length; i++) { this.o[i].tick({ time: this.synth.time, mouse: this.synth.mouse, bpm: this.synth.bpm, resolution: [this.canvas.width, this.canvas.height] }) } if (this.isRenderingAll) { this.renderAll({ tex0: this.o[0].getCurrent(), tex1: this.o[1].getCurrent(), tex2: this.o[2].getCurrent(), tex3: this.o[3].getCurrent(), resolution: [this.canvas.width, this.canvas.height] }) } else { this.renderFbo({ tex0: this.output.getCurrent(), resolution: [this.canvas.width, this.canvas.height] }) } this.timeSinceLastUpdate = 0 } if(this.saveFrame === true) { this.canvasToImage() this.saveFrame = false } // this.regl.poll() } }
JavaScript
class Input { /* @internal */ constructor() { } /** * Create instance of input from parameters. * @param address The address. * @param security The address security. * @param keyIndex The key index. * @param balance The balance of the address. * @returns New instance of Input. */ static fromParams(address, security, keyIndex, balance) { if (!objectHelper_1.ObjectHelper.isType(address, address_1.Address)) { throw new dataError_1.DataError("The address should be a valid Address object"); } if (!numberHelper_1.NumberHelper.isInteger(security) || security < addressSecurity_1.AddressSecurity.low || security > addressSecurity_1.AddressSecurity.high) { throw new dataError_1.DataError(`The security should be a number between ${addressSecurity_1.AddressSecurity.low} and ${addressSecurity_1.AddressSecurity.high}`); } if (!numberHelper_1.NumberHelper.isInteger(keyIndex) || keyIndex < 0) { throw new dataError_1.DataError("The keyIndex should be a number >= 0"); } if (!numberHelper_1.NumberHelper.isInteger(balance) || balance < 0) { throw new dataError_1.DataError("The balance should be a number >= 0"); } const input = new Input(); input.address = address; input.security = security; input.keyIndex = keyIndex; input.balance = balance; return input; } }
JavaScript
class LoopTheLoopPath extends AbstractPath { /** * @param {number=} start * @param {number=} finish * @param {string=} name * @param {string=} localName */ constructor(start, finish, name, localName) { if (typeof start !== 'number') { start = -3.7; } if (typeof finish !== 'number') { finish = 8.5; } name = name || LoopTheLoopPath.en.NAME; localName = localName || LoopTheLoopPath.i18n.NAME; super(name, localName, start, finish, /*closedLoop=*/false); }; /** @override */ getClassName() { return 'LoopTheLoopPath'; }; /** @override */ x_func(t) { if (t<0.5) { return t; } else if (t < 0.5 + LoopTheLoopPath.theta1 - LoopTheLoopPath.theta2) { return LoopTheLoopPath.radius * Math.cos(t - 0.5 + LoopTheLoopPath.theta2) + LoopTheLoopPath.xcenter; } else { return t - LoopTheLoopPath.theta1 + LoopTheLoopPath.theta2 - 1; } }; /** @override */ y_func(t) { if (t<0.5) { return (t+1)*(t+1) + LoopTheLoopPath.yoffset; } else if (t < 0.5 + LoopTheLoopPath.theta1 - LoopTheLoopPath.theta2) { return LoopTheLoopPath.radius * Math.sin(t - 0.5 + LoopTheLoopPath.theta2) + LoopTheLoopPath.ycenter + LoopTheLoopPath.yoffset; } else { const dd = t - LoopTheLoopPath.theta1 + LoopTheLoopPath.theta2 - 2; return dd*dd + LoopTheLoopPath.yoffset; } }; } // end class
JavaScript
class Window_JaftingEquip extends Window_Command { /** * @constructor * @param {Rectangle} rect The rectangle that represents this window. */ constructor(rect) { super(rect); this.initialize(rect); this.initMembers(); }; /** * Initializes the properties of this class. */ initMembers() { /** * The currently selected index of this equip selection window. * @type {number} */ this._currentIndex = null; /** * Whether or not this equip list window is the primary equip or not. * @type {boolean} */ this._isPrimaryEquipWindow = false; /** * The current equip that is selected as the base for refinement. * @type {rm.types.EquipItem} */ this._primarySelection = null; /** * The projected result of refining the base item with the selected material. * @type {rm.types.EquipItem} */ this._projectedOutput = null; }; /** * Gets the current index that was last assigned of this window. * @returns {number} */ get currentIndex() { return this._currentIndex; }; /** * Sets the current index to a given value. */ set currentIndex(index) { this._currentIndex = index; }; /** * Gets whether or not this equip list window is the primary equip or not. * @returns {boolean} */ get isPrimary() { return this._isPrimaryEquipWindow; }; /** * Sets whether or not this equip list window is the base equip or not. */ set isPrimary(primary) { this._isPrimaryEquipWindow = primary; this.refresh(); }; /** * Gets the base selection. * Always null if this is the primary equip window. * @returns {rm.types.EquipItem} */ get baseSelection() { return this._primarySelection; }; /** * Sets the primary selection. */ set baseSelection(equip) { this._primarySelection = equip; }; /** * OVERWRITE Sets the alignment for this command window to be left-aligned. */ itemTextAlign() { return "left"; }; /** * Creates a list of all available equipment in the inventory. */ makeCommandList() { // this command list is based purely off of all equipment. let equips = $gameParty.equipItems(); // don't make the list if we have nothing to draw. if (!equips.length) return; // if this is the primary equip window, don't show the "materials" equipment type. if (this.isPrimary) { // TODO: parameterize this. equips = equips.filter(equip => equip.atypeId !== 5); } // sort equips first by weapons > armor, then by id in descending order to group equips. equips.sort((a, b) => { if (a.etypeId > b.etypeId) return 1; if (a.etypeId < b.etypeId) return -1; if (a.id > b.id) return 1; if (a.id < b.id) return -1; }); // iterate over each equip the party has in their inventory. equips.forEach(equip => { // don't render equipment that are totally unrefinable. That's a tease! if (equip._jafting.unrefinable) return; const hasDuplicatePrimary = $gameParty.numItems(this.baseSelection) > 1; const isBaseSelection = equip === this.baseSelection; const canSelectBaseAgain = (isBaseSelection && hasDuplicatePrimary) || !isBaseSelection; let enabled = this.isPrimary ? true : canSelectBaseAgain; // only select the base again if you have 2+ copies of it. let iconIndex = equip.iconIndex; let errorText = ""; // if the equipment is completely unable to if (equip._jafting.unrefinable) { enabled = false; iconIndex = 90; } // if this is the second equip window... if (!this.isPrimary) { // and the equipment has no transferable traits, then disable it. if (!$gameJAFTING.parseTraits(equip).length) { enabled = false; errorText += `${J.JAFTING.Messages.NoTraitsOnMaterial}\n`; } // prevent equipment explicitly marked as "not usable as material" from being used. if (equip._jafting.notRefinementMaterial) { enabled = false; iconIndex = 90; } // or the projected equips combined would result in over the max refined count, then disable it. if (this.baseSelection) { const primaryHasMaxRefineCount = this.baseSelection._jafting.maxRefineCount > 0; if (primaryHasMaxRefineCount) { const primaryMaxRefineCount = this.baseSelection._jafting.maxRefineCount const projectedCount = this.baseSelection._jafting.refinedCount + equip._jafting.refinedCount; const overRefinementCount = primaryMaxRefineCount < projectedCount; if (overRefinementCount) { enabled = false; iconIndex = 90; errorText += `${J.JAFTING.Messages.ExceedRefineCount} ${projectedCount}/${primaryMaxRefineCount}.\n`; } } // check the max traits of the base equip and compare with the projected result of this item. // if the count is greater than the max (if there is a max), then prevent this item from being used. const baseMaxTraitCount = this.baseSelection._jafting.maxTraitCount; const projectedResult = $gameJAFTING.determineRefinementOutput(this.baseSelection, equip); const projectedResultTraitCount = $gameJAFTING.parseTraits(projectedResult).length; const overMaxTraitCount = baseMaxTraitCount > 0 && projectedResultTraitCount > baseMaxTraitCount; if (overMaxTraitCount) { enabled = false; iconIndex = 92 errorText += `${J.JAFTING.Messages.ExceedTraitCount} ${projectedResultTraitCount}/${baseMaxTraitCount}.\n`; } } // if this is the primary equip window... } else { const equipIsMaxRefined = (equip._jafting.maxRefineCount === 0) ? false // 0 max refinements means you can refine as much as you want. : equip._jafting.maxRefineCount <= equip._jafting.refinedCount; const equipHasMaxTraits = equip._jafting.maxTraitCount === 0 ? false // 0 max traits means you can have as many as you want. : equip._jafting.maxTraitCount <= $gameJAFTING.parseTraits(equip).length; if (equipIsMaxRefined) { enabled = false; iconIndex = 92; errorText += `${J.JAFTING.Messages.AlreadyMaxRefineCount}\n`; } if (equipHasMaxTraits) { enabled = false; iconIndex = 92; errorText += `${J.JAFTING.Messages.AlreadyMaxTraitCount}\n`; } // prevent equipment explicitly marked as "not usable as base" from being used. if (equip._jafting.notRefinementBase) { enabled = false; iconIndex = 92; } } // finally, if we are using this as the base, give it a check regardless. if (isBaseSelection) { iconIndex = 91; } const extData = {data: equip, error: errorText}; this.addCommand(equip.name, 'refine-object', enabled, extData, iconIndex); }); }; }
JavaScript
class Window_JaftingRefinementOutput extends Window_Base { /** * @constructor * @param {Rectangle} rect The rectangle that represents this window. */ constructor(rect) { super(rect); this.initialize(rect); this.initMembers(); this.opacity = 220; }; /** * Initializes all members of this window. */ initMembers() { /** * The primary equip that is the refinement target. * Traits from the secondary equip will be transfered to this equip. * @type {rm.types.EquipItem} */ this._primaryEquip = null; /** * The secondary equip that is the refinement material. * The transferable traits on this equip will be transfered to the target. * @type {rm.types.EquipItem} */ this._secondaryEquip = null; /** * The output of what would be the result from refining these items. * @type {rm.types.EquipItem} */ this._resultingEquip = null; }; /** * Gets the primary equip selected, aka the refinement target. * @returns {rm.types.EquipItem} */ get primaryEquip() { return this._primaryEquip; }; /** * Sets the primary equip selected, aka the refinement target. * @param {rm.types.EquipItem} equip The equip to set as the target. */ set primaryEquip(equip) { this._primaryEquip = equip; this.refresh(); }; /** * Gets the secondary equip selected, aka the refinement material. * @returns {rm.types.EquipItem} */ get secondaryEquip() { return this._secondaryEquip; }; /** * Sets the secondary equip selected, aka the refinement material. * @param {rm.types.EquipItem} equip The equip to set as the material. */ set secondaryEquip(equip) { this._secondaryEquip = equip; this.refresh(); }; /** * Gets the resulting equip from the output. */ get outputEquip() { return this._resultingEquip; }; /** * Sets the resulting equip to the output to allow for the scene to grab the data. * @param {rm.types.EquipItem} */ set outputEquip(equip) { this._resultingEquip = equip; }; lineHeight() { return 32; }; refresh() { // redraw all the contents. this.contents.clear(); this.drawContent(); }; /** * Draws all content in this window. */ drawContent() { // if we don't have anything in the target slot, do not draw anything. if (!this.primaryEquip) return; this.drawRefinementTarget(); this.drawRefinementMaterial(); this.drawRefinementResult(); }; /** * Draws the primary equip that is being used as a base for refinement. * Will draw whatever is being hovered over if nothing is selected. */ drawRefinementTarget() { this.drawEquip(this.primaryEquip, 0, "base"); }; /** * Draws the secondary equip that is being used as a material for refinement. * Will draw whatever is being hovered over if nothing is selected. */ drawRefinementMaterial() { if (!this.secondaryEquip) return; this.drawEquip(this.secondaryEquip, 350, "material"); }; /** * Draws one column of a piece of equip and it's traits. * @param {rm.types.EquipItem} equip The equip to draw details for. * @param {number} x The `x` coordinate to start drawing at. * @param {string} type Which column this is. */ drawEquip(equip, x, type) { const jaftingTraits = $gameJAFTING.combineBaseParameterTraits($gameJAFTING.parseTraits(equip)); this.drawEquipTitle(equip, x, type); this.drawEquipTraits(jaftingTraits, x); }; /** * Draws the title for this portion of the equip details. * @param {rm.types.EquipItem} equip The equip to draw details for. * @param {number} x The `x` coordinate to start drawing at. * @param {string} type Which column this is. */ drawEquipTitle(equip, x, type) { const lh = this.lineHeight(); switch (type) { case "base": this.drawTextEx(`\\PX[16]${J.JAFTING.Messages.TitleBase}`, x, lh * 0, 200); break; case "material": this.drawTextEx(`\\PX[16]${J.JAFTING.Messages.TitleMaterial}`, x, lh * 0, 200); break; case "output": this.drawTextEx(`\\PX[16]${J.JAFTING.Messages.TitleOutput}`, x, lh * 0, 200); break; } if (type === "output") { if (equip._jafting.refinedCount === 0) { this.drawTextEx(`\\I[${equip.iconIndex}] \\C[6]${equip.name} +1\\C[0]`, x, lh * 1, 200); } else { const suffix = `+${equip._jafting.refinedCount + 1}`; const index = equip.name.lastIndexOf("+"); if (index > -1) { // if we found a +, then strip it out and add the suffix to it. const name = `${equip.name.slice(0, index)}${suffix}`; this.drawTextEx(`\\I[${equip.iconIndex}] \\C[6]${name}\\C[0]`, x, lh * 1, 200); } else { // in cases where a refined equip is being used as a material for a never-before refined // equip, then there won't be any string manipulation for it's name. const name = `${equip.name} ${suffix}`; this.drawTextEx(`\\I[${equip.iconIndex}] \\C[6]${name}\\C[0]`, x, lh * 1, 200); } } } else { this.drawTextEx(`\\I[${equip.iconIndex}] \\C[6]${equip.name}\\C[0]`, x, lh * 1, 200); } }; /** * Draws all transferable traits on this piece of equipment. * @param {rm.types.Trait[]} traits A list of transferable traits. * @param {number} x The `x` coordinate to start drawing at. */ drawEquipTraits(traits, x) { const lh = this.lineHeight(); if (!traits.length) { this.drawTextEx(`${J.JAFTING.Messages.NoTransferableTraits}`, x, lh * 2, 250); return; } traits.sort((a, b) => a._code - b._code); traits.forEach((trait, index) => { const y = (lh * 2) + (index * lh); this.drawTextEx(`${trait.nameAndValue}`, x, y, 250); }); }; /** * Draws the projected refinement result of fusing the material into the base. */ drawRefinementResult() { // don't try to draw the result if the player hasn't made it to the material yet. if (!this.primaryEquip || !this.secondaryEquip) return; const result = $gameJAFTING.determineRefinementOutput(this.primaryEquip, this.secondaryEquip); // render the projected merge results. this.drawEquip(result, 700, "output"); // assign it for ease of retrieving from the scene. this.outputEquip = result; }; }
JavaScript
class Window_JaftingRefinementConfirmation extends Window_Command { /** * @constructor * @param {Rectangle} rect The rectangle that represents this window. */ constructor(rect) { super(rect); this.initialize(rect); }; /** * OVERWRITE Creates the command list for this window. */ makeCommandList() { this.addCommand(`${J.JAFTING.Messages.ExecuteRefinementCommandName}`, `ok`, true, null, 91); this.addCommand(`${J.JAFTING.Messages.CancelRefinementCommandName}`, `cancel`, true, null, 90); }; }
JavaScript
class Address extends Resource { static getSchema () { return { city: String, country: String, firstName: String, lastName: String, phone: String, postalCode: String, region: String, street1: String, street2: String } } }
JavaScript
class Car{ constructor(name,price,color) { this.name = name; this.price = price; this.color = color; } get getCarName() { return this.name; } get getColor() { return this.color; } set setPrice(newPrice) { if (newPrice < 0) { newPrice = 0; } this.price = newPrice; } }
JavaScript
class TmCubeImage extends PolymerElement { static get template() { return html` <style> :host { display: inline-block; box-sizing: border-box; //border: solid red 3px; //padding:2%; } svg { box-sizing: border-box; //border: solid red 1px; width: 100%; height: 100%; } </style> <svg id="svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" viewBox="1 1 50 50"> <defs id="defs4"> <radialGradient cx="353.37662" cy="147.47948" r="44.017399" fx="353.37662" fy="147.47948" id="radialGradient1960" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.631328,1.135721e-6,-5.471307e-8,7.630295e-2,-64.66975,-433.7018)" /> <radialGradient cx="353.37662" cy="147.47948" r="44.017399" fx="353.37662" fy="147.47948" id="radialGradient1956" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1,1.13575e-6,-8.666333e-8,7.630491e-2,62.40166,-106.3378)" /> <radialGradient cx="353.37662" cy="147.47948" r="44.017399" fx="353.37662" fy="147.47948" id="radialGradient1952" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.999999,1.135749e-6,-8.666328e-8,7.630488e-2,46.54787,-38.25948)" /> <radialGradient cx="353.37662" cy="147.47948" r="44.017399" fx="353.37662" fy="147.47948" id="radialGradient1941" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1,1.13575e-6,-8.666335e-8,7.630493e-2,-31.40988,-105.1712)" /> <radialGradient cx="353.37662" cy="147.47948" r="44.017399" fx="353.37662" fy="147.47948" id="radialGradient5525" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1,1.13575e-6,-8.666337e-8,7.630495e-2,4.489151,-101.038)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient5485" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" /> <linearGradient id="linearGradient5479"> <stop style="stop-color:white;stop-opacity:0.8041237" offset="0" id="stop5481" /> <stop style="stop-color:white;stop-opacity:0" offset="1" id="stop5483" /> </linearGradient> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient2255" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,143.3003,-75.85529)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient2259" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,106.9366,-30.87844)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3134" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,184.7133,9.929133)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3136" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,67.80771,160.6434)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3138" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,293.6365,-13.50047)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3140" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,1.315798,-11.39494)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3142" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,8.929597,220.2657)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3144" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,271.0349,203.7056)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3146" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,67.46476,275.6504)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3148" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,173.5612,240.1308)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3150" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,-51.57229,-46.01549)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3152" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,178.0989,133.5267)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3154" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,219.1007,-48.84854)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3156" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,-41.33862,163.6612)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3158" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,44.1082,-65.12856)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3160" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,281.2264,103.0299)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3162" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,4.747552,105.4623)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3164" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,-46.4846,62.45826)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3166" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,68.48029,34.56193)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3168" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,149.3342,-78.66773)" /> <radialGradient cx="228.39549" cy="273.52124" r="12.374369" fx="228.39549" fy="273.52124" id="radialGradient3170" xlink:href="#linearGradient5479" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.445728,0,0,0.445728,111.2432,-32.17062)" /> </defs> <g transform="scale(0.095) translate(20,20)" id="layer1"> <g transform="translate(2.86332,6.351005)" style="opacity:1" id="cube"> <path d="M 11.990545,44.17184 L 95.535232,31.13178 C 98.08193,30.656558 103.34562,32.728518 104.70364,34.460855 C 104.06164,32.551663 106.36305,29.397183 108.89089,28.733281 L 190.7389,17.118886 C 193.33305,16.619595 196.44753,17.641259 198.76149,19.103199 C 198.45906,18.21517 199.75762,16.526638 202.05681,16.078885 L 266.47078,5.5965704 C 269.91658,4.9897062 275.75758,4.0234275 279.37729,5.8075406 L 328.99443,25.448971 C 331.36692,26.641237 331.9783,28.233753 331.06874,29.986371 C 332.21379,28.563663 336.4808,28.421758 338.58646,29.560657 L 397.81662,52.989911 C 399.92228,53.915343 400.26683,55.401127 399.57073,56.72681 C 401.22277,55.731036 405.27631,55.855966 408.36925,57.101598 L 477.84585,84.373262 C 480.76945,86.058786 482.44775,89.555639 482.20152,93.392117 L 469.34956,192.52463 C 468.85804,194.45544 466.6118,196.49946 464.64858,196.78875 C 466.23255,197.13464 467.92972,199.06545 467.87217,200.82645 L 455.58626,293.67591 C 455.24569,295.3803 452.92398,298.10357 451.45133,298.56267 C 452.7334,298.92744 453.90228,300.42428 453.76925,301.69471 L 442.04937,382.48751 C 441.85001,384.87628 440.12233,388.39713 438.05503,389.14439 L 369.19245,418.10326 C 367.67233,418.81277 364.90692,418.78644 362.93396,417.4582 C 362.43271,419.73377 360.64094,421.15055 359.17742,421.95441 L 277.56755,455.05508 C 275.83987,456.02875 271.20763,454.45524 269.70637,453.56097 C 270.79004,454.87426 267.62203,460.04468 265.98869,460.50891 L 179.48977,495.06354 C 176.23542,496.72783 169.13199,496.92042 164.97197,493.26393 L 114.8566,435.25883 C 113.71546,434.26273 112.22833,431.11333 112.84192,430.17383 C 111.66305,430.36641 109.86153,429.93635 108.34303,428.48741 L 65.510165,378.23708 C 64.444502,376.82589 62.706615,374.04217 63.628113,373.66151 C 62.518512,373.47985 60.798671,373.82026 59.355648,372.14491 L 23.724535,329.8734 C 22.079585,328.37351 21.340299,326.42078 21.167054,324.35485 L 16.34541,249.2133 C 16.058958,246.77001 18.149875,245.79841 20.014377,245.61928 C 18.407161,244.30807 16.120698,242.31761 15.758773,239.30827 L 10.710713,154.20441 C 10.688412,151.83659 12.024608,150.26122 13.587221,149.3651 C 11.37623,148.58219 10.184112,146.554 9.6712425,143.95976 L 4.5099747,58.516275 C 3.9958347,53.080715 3.9817343,46.348545 11.990545,44.17184 z " style="opacity:1;fill:black;fill-opacity:1;fill-rule:evenodd;stroke:black;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" id="cube-path" /> <g id="reflection"> <path d="M 280.87897,362.047 C 280.87897,365.09318 278.40955,367.5626 275.36336,367.5626 C 272.31717,367.5626 269.84775,365.09318 269.84775,362.047 C 269.84775,359.00081 272.31717,356.53139 275.36336,356.53139 C 278.40955,356.53139 280.87897,359.00081 280.87897,362.047 L 280.87897,362.047 z " style="fill:url(#radialGradient3148);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2225" /> <path d="M 256.65192,43.248423 C 256.65192,46.294603 254.1825,48.764023 251.13631,48.764023 C 248.09012,48.764023 245.6207,46.294603 245.6207,43.248423 C 245.6207,40.202233 248.09012,37.732813 251.13631,37.732813 C 254.1825,37.732813 256.65192,40.202233 256.65192,43.248423 L 256.65192,43.248423 z " style="fill:url(#radialGradient3168);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2253" /> <path d="M 400.95431,108.41569 C 400.95431,111.46187 398.48489,113.93129 395.4387,113.93129 C 392.39251,113.93129 389.92309,111.46187 389.92309,108.41569 C 389.92309,105.3695 392.39251,102.90008 395.4387,102.90008 C 398.48489,102.90008 400.95431,105.3695 400.95431,108.41569 L 400.95431,108.41569 z " style="fill:url(#radialGradient3138);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2245" /> <path d="M 175.12554,282.55947 C 175.12554,285.60565 172.65612,288.07507 169.60993,288.07507 C 166.56375,288.07507 164.09433,285.60565 164.09433,282.55947 C 164.09433,279.51328 166.56375,277.04386 169.60993,277.04386 C 172.65612,277.04386 175.12554,279.51328 175.12554,282.55947 L 175.12554,282.55947 z " style="fill:url(#radialGradient3136);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2209" /> <path d="M 292.03106,131.84529 C 292.03106,134.89147 289.56164,137.36089 286.51545,137.36089 C 283.46926,137.36089 280.99984,134.89147 280.99984,131.84529 C 280.99984,128.7991 283.46926,126.32968 286.51545,126.32968 C 289.56164,126.32968 292.03106,128.7991 292.03106,131.84529 L 292.03106,131.84529 z " style="fill:url(#radialGradient3134);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2241" /> <path d="M 108.63363,110.52113 C 108.63363,113.56731 106.16421,116.03673 103.11802,116.03673 C 100.07184,116.03673 97.602418,113.56731 97.602418,110.52113 C 97.602418,107.47494 100.07184,105.00552 103.11802,105.00552 C 106.16421,105.00552 108.63363,107.47494 108.63363,110.52113 L 108.63363,110.52113 z " style="fill:url(#radialGradient3140);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2193" /> <path d="M 55.745544,75.900583 C 55.745544,78.946763 53.27612,81.416183 50.22993,81.416183 C 47.18375,81.416183 44.71433,78.946763 44.71433,75.900583 C 44.71433,72.854393 47.18375,70.384973 50.22993,70.384973 C 53.27612,70.384973 55.745544,72.854393 55.745544,75.900583 L 55.745544,75.900583 z " style="fill:url(#radialGradient3150);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2197" /> <path d="M 218.56105,89.745538 C 218.56105,92.791718 216.09163,95.261138 213.04544,95.261138 C 209.99925,95.261138 207.52983,92.791718 207.52983,89.745538 C 207.52983,86.699348 209.99925,84.229928 213.04544,84.229928 C 216.09163,84.229928 218.56105,86.699348 218.56105,89.745538 L 218.56105,89.745538 z " style="fill:url(#radialGradient3170);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2257" /> <path d="M 116.24743,342.18177 C 116.24743,345.22795 113.77801,347.69737 110.73182,347.69737 C 107.68564,347.69737 105.21622,345.22795 105.21622,342.18177 C 105.21622,339.13558 107.68564,336.66616 110.73182,336.66616 C 113.77801,336.66616 116.24743,339.13558 116.24743,342.18177 L 116.24743,342.18177 z " style="fill:url(#radialGradient3142);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2217" /> <path d="M 378.35268,325.62178 C 378.35268,328.66796 375.88326,331.13738 372.83707,331.13738 C 369.79088,331.13738 367.32146,328.66796 367.32146,325.62178 C 367.32146,322.57559 369.79088,320.10617 372.83707,320.10617 C 375.88326,320.10617 378.35268,322.57559 378.35268,325.62178 L 378.35268,325.62178 z " style="fill:url(#radialGradient3144);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2229" /> <path d="M 174.78259,397.56653 C 174.78259,400.61271 172.31317,403.08213 169.26698,403.08213 C 166.2208,403.08213 163.75138,400.61271 163.75138,397.56653 C 163.75138,394.52034 166.2208,392.05092 169.26698,392.05092 C 172.31317,392.05092 174.78259,394.52034 174.78259,397.56653 L 174.78259,397.56653 z " style="fill:url(#radialGradient3146);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2213" /> <path d="M 285.41671,255.44284 C 285.41671,258.48902 282.94729,260.95844 279.9011,260.95844 C 276.85491,260.95844 274.38549,258.48902 274.38549,255.44284 C 274.38549,252.39665 276.85491,249.92723 279.9011,249.92723 C 282.94729,249.92723 285.41671,252.39665 285.41671,255.44284 L 285.41671,255.44284 z " style="fill:url(#radialGradient3152);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2233" /> <path d="M 326.41854,73.067621 C 326.41854,76.113801 323.94912,78.583221 320.90293,78.583221 C 317.85674,78.583221 315.38732,76.113801 315.38732,73.067621 C 315.38732,70.021431 317.85674,67.552011 320.90293,67.552011 C 323.94912,67.552011 326.41854,70.021431 326.41854,73.067621 L 326.41854,73.067621 z " style="fill:url(#radialGradient3154);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2249" /> <path d="M 65.979221,285.57725 C 65.979221,288.62343 63.509801,291.09285 60.463611,291.09285 C 57.417427,291.09285 54.948007,288.62343 54.948007,285.57725 C 54.948007,282.53106 57.417427,280.06164 60.463611,280.06164 C 63.509801,280.06164 65.979221,282.53106 65.979221,285.57725 L 65.979221,285.57725 z " style="fill:url(#radialGradient3156);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2221" /> <path d="M 151.426,56.787599 C 151.426,59.833779 148.95658,62.303199 145.91039,62.303199 C 142.8642,62.303199 140.39478,59.833779 140.39478,56.787599 C 140.39478,53.741409 142.8642,51.271989 145.91039,51.271989 C 148.95658,51.271989 151.426,53.741409 151.426,56.787599 L 151.426,56.787599 z " style="fill:url(#radialGradient3158);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2261" /> <path d="M 388.54417,224.94606 C 388.54417,227.99224 386.07475,230.46166 383.02856,230.46166 C 379.98237,230.46166 377.51295,227.99224 377.51295,224.94606 C 377.51295,221.89987 379.98237,219.43045 383.02856,219.43045 C 386.07475,219.43045 388.54417,221.89987 388.54417,224.94606 L 388.54417,224.94606 z " style="fill:url(#radialGradient3160);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2237" /> <path d="M 112.06539,227.37836 C 112.06539,230.42454 109.59596,232.89396 106.54978,232.89396 C 103.5036,232.89396 101.03418,230.42454 101.03418,227.37836 C 101.03418,224.33217 103.5036,221.86275 106.54978,221.86275 C 109.59596,221.86275 112.06539,224.33217 112.06539,227.37836 L 112.06539,227.37836 z " style="fill:url(#radialGradient3162);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2201" /> <path d="M 60.833246,184.37433 C 60.833246,187.42051 58.363818,189.88993 55.317632,189.88993 C 52.271452,189.88993 49.802032,187.42051 49.802032,184.37433 C 49.802032,181.32814 52.271452,178.85872 55.317632,178.85872 C 58.363818,178.85872 60.833246,181.32814 60.833246,184.37433 L 60.833246,184.37433 z " style="fill:url(#radialGradient3164);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path2205" /> <path d="M 175.79812,156.478 C 175.79812,159.52418 173.3287,161.9936 170.28251,161.9936 C 167.23633,161.9936 164.76691,159.52418 164.76691,156.478 C 164.76691,153.43181 167.23633,150.96239 170.28251,150.96239 C 173.3287,150.96239 175.79812,153.43181 175.79812,156.478 L 175.79812,156.478 z " style="fill:url(#radialGradient3166);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" id="path5477" /> </g> <!-- Front Face --> <g id="right"> <path d="M 182.17851,158.38841 L 273.78892,136.41074 C 277.79427,135.88018 280.16513,138.03718 280.69568,142.04254 L 275.83445,238.47495 C 275.56451,242.32021 270.9283,248.68884 266.92295,250.34011 L 181.54929,272.7075 C 177.54393,273.23806 174.37258,267.40347 174.32233,263.39811 L 174.45151,169.72912 C 174.88155,165.56367 178.33326,160.03968 182.17851,158.38841 z " style$="opacity:0.9;fill:[[_getColour(colors,9)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1350" /> <path d="M 301.5336,130.91178 L 381.44587,113.6494 C 386.24653,112.77263 388.76524,113.36859 388.00516,120.52677 L 379.36552,210.84734 C 378.61528,214.5325 378.8365,220.5304 371.62913,221.70136 L 293.60402,243.45787 C 289.59866,243.98842 285.32631,241.08587 284.79575,237.08052 L 289.94014,142.5443 C 290.13703,136.89288 296.59842,132.55681 301.5336,130.91178 z " style$="opacity:0.9;fill:[[_getColour(colors,10)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000072;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1352" /> <path d="M 406.90745,110.06268 L 473.53483,95.080791 C 479.98335,94.205963 478.79976,98.364434 478.08796,104.19487 L 467.37424,185.58062 C 466.94871,190.26253 463.67895,194.01182 459.5135,195.66308 L 398.56888,214.05437 C 391.80715,215.88532 389.29697,209.67507 389.56692,205.18942 L 398.49568,119.71391 C 398.92573,115.70856 402.90209,111.95173 406.90745,110.06268 z " style$="opacity:0.9;fill:[[_getColour(colors,11)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000072;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1354" /> <path d="M 180.40397,283.86 L 263.36635,261.10501 C 267.3717,260.41435 274.52944,262.66237 274.09035,269.27153 L 270.06171,352.51573 C 269.63015,358.628 262.09891,361.82287 258.41376,363.31404 L 181.85775,388.14789 C 177.85239,388.67845 173.67155,388.18641 173.13322,383.34178 L 173.63525,298.80325 C 173.58499,295.59838 175.90626,285.67136 180.40397,283.86 z " style$="opacity:0.9;fill:[[_getColour(colors,12)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000072;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1356" /> <path d="M 292.97217,253.39372 L 369.04034,231.81055 C 373.04569,231.28 377.68055,234.10822 377.55715,240.24912 L 370.21979,316.72346 C 369.94984,321.52933 364.67758,326.48035 361.62227,327.49724 L 288.84955,352.52086 C 284.64492,354.01955 280.27332,348.35745 279.74276,344.35209 L 283.59773,265.296 C 283.70757,260.81035 287.82954,255.20508 292.97217,253.39372 z " style$="opacity:0.9;fill:[[_getColour(colors,13)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000072;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1358" /> <path d="M 393.25725,226.02833 L 459.13059,204.76273 C 463.83018,203.40088 464.56169,207.21315 464.13165,211.21851 L 453.01282,288.38429 C 452.66586,292.4877 451.54837,293.97306 447.96262,295.54207 L 383.52315,317.93758 C 379.27239,318.67088 377.82744,315.82109 378.33377,310.71599 L 385.76658,235.10353 C 386.05077,232.71345 388.87971,227.09991 393.25725,226.02833 z " style$="opacity:0.9;fill:[[_getColour(colors,14)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000107;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1360" /> <path d="M 181.8973,397.29924 L 261.70194,370.12728 C 271.50448,367.29998 270.64,373.52748 270.37005,377.53283 L 266.82738,448.04576 C 266.87764,452.05112 265.06181,457.3105 261.05646,459.44206 L 183.58736,490.34034 C 179.58201,490.8709 175.10889,488.0735 174.57834,484.06815 L 174.4475,410.43527 C 174.71744,406.42991 176.43842,399.92452 181.8973,397.29924 z " style$="opacity:0.9;fill:[[_getColour(colors,15)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000072;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1362" /> <path d="M 285.95838,361.60359 L 360.96446,334.70651 C 365.12991,333.05525 369.62303,334.33574 369.24914,340.30339 L 360.91246,412.00185 C 360.75399,416.52859 359.6914,419.42557 356.42915,421.21171 L 282.17164,450.93183 C 278.16628,451.46239 275.11822,448.78371 275.38816,444.61825 L 279.0313,374.05068 C 279.002,368.16011 281.95302,363.25486 285.95838,361.60359 z " style$="opacity:0.9;fill:[[_getColour(colors,16)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1364" /> <path d="M 382.51592,326.46271 L 444.08106,304.85333 C 449.36721,303.04197 451.11941,305.02438 450.52927,309.51004 L 439.5343,381.87298 C 438.19859,385.06646 437.80219,387.37091 434.11704,388.82322 L 372.4667,414.12159 C 367.74905,415.72695 367.13813,411.96423 367.47439,407.71637 L 375.65286,337.86408 C 376.08291,333.05823 378.78728,327.87381 382.51592,326.46271 z " style$="opacity:0.9;fill:[[_getColour(colors,17)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1366" /> </g> <!-- Right Face --> <g id="front"> <path d="M 13.305428,51.54059 L 40.343717,72.760901 C 43.734039,75.464962 45.23736,82.490187 45.76791,86.495547 L 49.07166,165.66735 C 49.289247,172.15029 47.781718,176.55716 44.096549,172.92511 L 14.319497,148.46078 C 12.537448,146.84845 11.649146,144.48061 11.278686,142.07627 L 6.6840438,55.738325 C 5.9144538,51.334595 9.1485329,49.897364 13.305428,51.54059 z " style$="opacity:0.9;fill:[[_getColour(colors,0)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000179;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1396" /> <path d="M 60.925762,84.484801 L 94.440727,110.17338 C 98.48416,113.28713 98.117046,115.7533 98.906924,122.40075 L 99.906265,206.01621 C 100.08229,212.18599 98.954748,216.91716 94.922195,215.05864 L 59.491492,185.32239 C 55.399174,181.44872 54.141798,179.02461 53.773149,173.56204 L 51.281758,92.445638 C 50.97761,83.275467 56.920401,82.791038 60.925762,84.484801 z " style$="opacity:0.9;fill:[[_getColour(colors,1)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000107;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1370" /> <path d="M 114.95394,121.04521 L 159.77156,153.23382 C 163.55918,156.47083 165.57932,161.4536 165.85146,169.72903 L 165.12324,258.38488 C 165.14318,269.27049 163.08196,270.8706 159.69501,268.5017 L 113.59759,227.8182 C 108.06233,222.32225 108.21804,221.40881 107.69789,213.179 L 106.78044,131.95583 C 106.25303,119.34354 109.79684,118.29452 114.95394,121.04521 z " style$="opacity:0.9;fill:[[_getColour(colors,2)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1372" /> <path d="M 15.880212,156.13397 L 45.353913,181.28943 C 50.303506,186.19687 51.122928,188.03109 51.146692,194.6036 L 55.126981,267.33731 C 55.038091,274.16079 54.210515,276.03873 50.685456,273.36728 L 20.772099,242.78852 C 18.215174,239.75578 17.772229,237.41182 17.401769,232.92617 L 12.455448,161.17569 C 11.924888,156.52992 13.177442,153.86816 15.880212,156.13397 z " style$="opacity:0.9;fill:[[_getColour(colors,3)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1374" /> <path d="M 63.560739,196.66859 L 95.849604,224.21548 C 99.860002,227.90036 101.42068,227.84883 102.24829,236.16862 L 105.16115,322.88131 C 105.32961,328.83472 100.6354,326.98289 97.27045,323.99124 L 64.004863,289.91488 C 60.376668,285.92234 60.812901,283.0865 60.282344,279.08114 L 56.974857,203.97033 C 56.534832,197.33461 59.555379,193.98372 63.560739,196.66859 z " style$="opacity:0.9;fill:[[_getColour(colors,4)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000036;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1368" /> <path d="M 115.16535,240.1369 L 157.39073,278.01718 C 163.35353,283.61754 164.20113,287.75376 164.33713,292.73915 L 164.46483,372.92651 C 164.8371,382.72559 163.11873,386.7217 158.31831,383.06065 L 116.21628,341.59277 C 113.14436,337.41881 111.77219,331.79454 111.56545,326.25228 L 108.05931,249.4705 C 107.8343,242.18566 110.33141,236.36305 115.16535,240.1369 z " style$="opacity:0.9;fill:[[_getColour(colors,5)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1376" /> <path d="M 21.801396,250.84788 L 53.362682,285.05081 C 55.478478,286.94737 55.860452,293.07504 56.230911,297.08039 L 59.037291,362.09942 C 59.567851,365.30428 57.391745,365.05795 55.670483,362.85491 L 26.987682,329.12149 C 24.403644,326.58 22.851374,322.17207 22.801115,318.16672 L 18.702227,254.06349 C 18.171667,250.05813 18.78043,246.99613 21.801396,250.84788 z " style$="opacity:0.9;fill:[[_getColour(colors,6)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1380" /> <path d="M 63.584727,297.86482 L 100.09771,336.25875 C 103.85532,339.94877 105.54225,346.52461 105.61997,350.86959 L 106.70076,413.69991 C 106.89661,418.85427 106.32415,421.59383 102.84852,417.56611 L 67.414737,377.50434 C 64.50888,374.54093 64.45614,374.60496 63.999005,369.27086 L 60.47761,304.56961 C 60.281747,300.54009 59.899568,294.23277 63.584727,297.86482 z " style$="opacity:0.9;fill:[[_getColour(colors,7)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1378" /> <path d="M 118.86081,353.35871 L 159.48013,395.6238 C 162.51764,399.1338 164.4245,404.65178 165.1061,412.62636 L 166.13587,476.20108 C 166.97938,485.11815 165.13028,489.47654 161.92361,484.85852 L 118.27286,435.65951 C 114.34971,431.59494 113.96682,428.88285 114.07666,422.63608 L 112.71221,363.08469 C 112.07473,354.59964 115.24041,350.55098 118.86081,353.35871 z " style$="opacity:0.9;fill:[[_getColour(colors,8)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000179;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1382" /> </g> <!-- Top Face --> <g id="top"> <path d="M 23.348625,43.167759 L 91.061974,32.897828 C 95.009786,32.418498 99.005619,31.91632 101.35705,33.680264 L 132.52336,50.748834 C 137.3639,53.755196 135.57759,56.641768 131.57224,57.172328 L 56.551277,69.765807 C 51.992688,70.353383 48.930844,70.408699 46.049907,68.279732 L 15.629868,47.347863 C 12.365004,45.277954 20.409636,43.572566 23.348625,43.167759 z " style$="opacity:0.9;fill:[[_getColour(colors,18)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000107;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1386" /> <path d="M 116.96704,29.014065 L 190.19371,18.227759 C 193.07674,17.920153 196.60675,18.927933 197.95065,19.968175 L 231.6175,34.951899 C 234.87404,36.701617 234.4189,38.896015 231.53423,39.586675 L 157.7355,51.255524 C 153.2397,51.961389 146.98973,51.849221 143.96153,49.794623 L 112.96777,33.044845 C 109.39612,31.009309 112.96169,29.864816 116.96704,29.014065 z " style$="opacity:0.9;fill:[[_getColour(colors,19)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000179;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1388" /> <path d="M 208.0159,16.168793 L 269.75334,6.0600534 C 273.7587,5.5294934 275.21465,4.9171898 278.80142,6.7939983 L 322.61024,24.147523 C 325.35884,25.591285 326.14101,26.455624 322.13564,27.626585 L 261.39636,37.422514 C 257.04309,37.934465 249.37571,37.324805 245.62489,35.579744 L 207.69802,19.306437 C 204.2424,18.022573 205.12432,16.29493 208.0159,16.168793 z " style$="opacity:0.9;fill:[[_getColour(colors,20)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000179;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1390" /> <path d="M 67.927185,70.656234 L 142.84719,58.31329 C 146.85254,57.78273 155.16986,58.670511 158.90242,60.754655 L 197.74124,82.476005 C 200.35311,84.72026 199.14053,86.204014 195.61549,87.535076 L 113.38232,104.5835 C 109.37696,105.59436 103.1984,105.49496 99.946129,103.25071 L 63.593588,77.511289 C 61.301923,75.267034 63.921825,71.506995 67.927185,70.656234 z " style$="opacity:0.9;fill:[[_getColour(colors,21)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000215;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1384" /> <path d="M 170.48279,53.739436 L 241.65115,41.973692 C 245.65651,41.443135 251.71764,41.2487 255.13001,43.49295 L 298.7151,63.776222 C 302.28756,65.700282 303.16938,68.298399 299.16402,68.828956 L 221.42396,83.385817 C 218.05899,83.916375 210.91385,82.856747 207.82168,81.09279 L 166.35015,58.667629 C 162.77769,56.103179 166.47742,54.269994 170.48279,53.739436 z " style$="opacity:0.9;fill:[[_getColour(colors,22)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1392" /> <path d="M 270.31191,40.717976 L 328.46622,30.954512 C 331.51097,29.783553 335.4718,29.045434 339.48937,31.094387 L 389.78175,51.331875 C 394.04242,53.506556 393.0239,54.981242 389.49721,55.365944 L 326.93439,66.86135 C 322.76893,67.712108 315.78067,66.433592 312.68851,64.669634 L 269.27213,44.479849 C 266.461,43.031581 266.62675,41.728835 270.31191,40.717976 z " style$="opacity:0.9;fill:[[_getColour(colors,23)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1394" /> <path d="M 123.16204,107.41734 L 203.88051,90.359284 C 207.88588,89.828726 217.64116,90.981557 220.73332,93.385916 L 270.90183,120.44184 C 273.99399,122.84619 276.26486,128.62938 272.0994,130.28064 L 183.26511,149.71779 C 178.61934,151.16482 171.27872,150.77234 167.22596,147.47591 L 119.63901,114.49559 C 116.06654,112.25133 119.31679,108.5883 123.16204,107.41734 z " style$="opacity:0.9;fill:[[_getColour(colors,24)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000143;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1398" /> <path d="M 234.17858,86.640558 L 308.0884,72.881494 C 312.09377,72.350935 318.62643,71.610297 322.8393,74.494959 L 380.23297,101.01614 C 382.84484,103.26038 383.27589,107.17731 379.27053,108.50837 L 300.24964,123.4242 C 296.24428,124.75525 290.32943,123.92592 285.47616,120.88116 L 232.46688,92.266536 C 229.37471,90.342477 230.17322,87.971619 234.17858,86.640558 z " style$="opacity:0.9;fill:[[_getColour(colors,25)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000215;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1400" /> <path d="M 336.56696,69.287076 L 397.63669,58.137148 C 401.08641,57.208951 404.77825,58.130822 410.42577,60.353676 L 464.50855,81.433424 C 470.52906,83.521457 473.46844,87.244831 469.46307,89.216293 L 411.53076,101.47045 C 408.14738,102.5029 397.18932,102.66256 394.09979,100.66772 L 336.10575,74.185386 C 332.76473,71.922386 332.66675,69.986992 336.56696,69.287076 z " style$="opacity:0.9;fill:[[_getColour(colors,26)]];fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1.25000215;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1" id="rect1402" /> </g> </g> </g> </svg> `; } static get properties() { return { stickers: { type: String, value: 'rrr rrr rrr | bbb bbb bbb | www www www', observer: '_stickersChanged' }, colors: { type: Array, value: [] }, scale: { type: Number, value: '1' }, width: { type: Number }, height: { type: Number }, payload: { type: Object } }; } _stickersChanged(stickers) { const newColors = stickers.split('') .filter(c => (c !== ' ' && c !== '|')) .join('') .padEnd(27, '.') .split('') .map(c => this._lookupColor(c)); this.set('colors', newColors); } _lookupColor(ch) { return (ch in COLORS ? COLORS[ch] : COLOR_BLACK) } _getColour(colors, position) { return colors[position]; } ready() { super.ready(); if (this.payload === undefined) { this.payload = { stickers: this.stickers }; } this.$.cube.addEventListener('click', e => this._tap(e)); } _tap(e) { const payload = this.payload; this.dispatchEvent(new CustomEvent('select', {detail: payload})); } }
JavaScript
class CustomGroupByItem extends DropdownMenuItem { constructor() { super(...arguments); this.canBeOpened = true; this.state.fieldName = this.props.fields[0].name; this.model = useModel('searchModel'); } //--------------------------------------------------------------------- // Handlers //--------------------------------------------------------------------- /** * @private */ _onApply() { const field = this.props.fields.find(f => f.name === this.state.fieldName); this.model.dispatch('createNewGroupBy', field); this.state.open = false; } }
JavaScript
class FontFamilyEditing extends Plugin { /** * @inheritDoc */ static get pluginName() { return 'FontFamilyEditing'; } /** * @inheritDoc */ constructor( editor ) { super( editor ); // Define default configuration using font families shortcuts. editor.config.define( FONT_FAMILY, { options: [ 'default', 'Arial, Helvetica, sans-serif', 'Courier New, Courier, monospace', 'Georgia, serif', 'Lucida Sans Unicode, Lucida Grande, sans-serif', 'Tahoma, Geneva, sans-serif', 'Times New Roman, Times, serif', 'Trebuchet MS, Helvetica, sans-serif', 'Verdana, Geneva, sans-serif' ], supportAllValues: false } ); } /** * @inheritDoc */ init() { const editor = this.editor; // Allow fontFamily attribute on text nodes. editor.model.schema.extend( '$text', { allowAttributes: FONT_FAMILY } ); editor.model.schema.setAttributeProperties( FONT_FAMILY, { isFormatting: true, copyOnEnter: true } ); // Get configured font family options without "default" option. const options = normalizeOptions( editor.config.get( 'fontFamily.options' ) ).filter( item => item.model ); const definition = buildDefinition( FONT_FAMILY, options ); // Set-up the two-way conversion. if ( editor.config.get( 'fontFamily.supportAllValues' ) ) { this._prepareAnyValueConverters(); } else { editor.conversion.attributeToElement( definition ); } editor.commands.add( FONT_FAMILY, new FontFamilyCommand( editor ) ); } /** * These converters enable keeping any value found as `style="font-family: *"` as a value of an attribute on a text even * if it is not defined in the plugin configuration. * * @private */ _prepareAnyValueConverters() { const editor = this.editor; editor.conversion.for( 'downcast' ).attributeToElement( { model: FONT_FAMILY, view: ( attributeValue, { writer } ) => { return writer.createAttributeElement( 'span', { style: 'font-family:' + attributeValue }, { priority: 7 } ); } } ); editor.conversion.for( 'upcast' ).attributeToAttribute( { model: { key: FONT_FAMILY, value: viewElement => viewElement.getStyle( 'font-family' ) }, view: { name: 'span', styles: { 'font-family': /.*/ } } } ); } }
JavaScript
class Module { /** * @param {Object} store - A Vuex store. * @param {Object} api - A public API object. * @param {Object} config - A module's configuration object */ constructor (store, api, config = {}) { if (!rootVi) { // Create a root Vue instance if not has been done already. // All properties registered here will be shared across all Vue instances (i.e. components). rootVi = new Vue({ store: store, // Install store into the instance provide: api // Public API of the modules for child components }) } this.config = Object.assign(this.constructor._configDefaults, config) this.isActivated = false } /** * Puts module into an activated state. * Must be implemented in the descendant if the latter has some special activation procedure. */ activate () { this.isActivated = true } /** * Puts module into an deactivated state. * Must be implemented in the descendant if the latter has some special deactivation procedure. */ deactivate () { this.isActivated = false } static get rootVi () { return rootVi } static get moduleName () { return this._configDefaults._moduleName } static get moduleType () { return this._configDefaults._moduleType } static get isDataModule () { return this._configDefaults._moduleType === Module.types.DATA } static get isUiModule () { return this._configDefaults._moduleType === Module.types.UI } /** * Checks whether a specified platform is supported by the module. * @param {Platform.deviceTypes} platform - A name of a deviceTypes. * @return {boolean} True if platform is supported, false otherwise. */ static isSupportedPlatform (platform) { if (this._configDefaults._supportedDeviceTypes.includes(Platform.deviceTypes.ANY)) { return true } else if (this._configDefaults._supportedDeviceTypes.includes(platform.deviceType)) { return true } return false } }
JavaScript
class Command { /** * Static property lettings us know what kind of class this is * * @type {string} * @private */ static __kind = "Command"; /** * Property lettings us know what kind of class this is * * @type {string} * @private */ __kind = "Command"; /** * Path to the command that will be attached while loading (this is automatically filled in) * * @type string */ static __path = ""; /** * Static signature key that will be callable name of our command. * * @type string */ static signature = ""; /** * User friendly description of the command that has to be static. * * @type string */ static description = ""; /** * User friendly example of your command usage. * * @type string */ static usage = ""; /** * Constructor of the command * * @param {any} payload * @param {boolean} cli Defines if the command has been called from CLI or application */ constructor(payload, cli = true) { this.payload = payload; this.cli = !!cli; } /** * Method that will be run once you call the command * * @return {Promise<any>} */ async handle() {} }
JavaScript
class AudioTarget extends Target { static get MAX_SIMULTANEOUS_NONBLOCKING_SOUNDS () { return 25; } constructor(runtime, id, audioInfo) { super(runtime, null); this.id = id; // Variables from RenderedTarget this.volume = 100; // Audio specific state this.totalSamples = 0; this.sampleRate = 48000; this.markers = []; this.trimStart = 0; this.trimEnd = 0; this.playbackRate = 100; this.nonblockingSoundsAvailable = AudioTarget.MAX_SIMULTANEOUS_NONBLOCKING_SOUNDS; if (!!audioInfo) { this.totalSamples = audioInfo.totalSamples || 0; this.sampleRate = audioInfo.sampleRate || 48000; this.markers = audioInfo.markers || []; this.trimStart = audioInfo.trimStart || 0; this.trimEnd = audioInfo.trimEnd || this.totalSamples; this.playbackRate = audioInfo.playbackRate || 100; } } setVolume (vol) { this.volume = MathUtil.clamp(vol, 0, 500); } setRate (rate) { // @TODO: Should we clamp this or is it fun to just go nuts with the rate? this.playbackRate = MathUtil.clamp(rate, 0, 1000); this.runtime.requestRedraw(); } toJSON () { return { id: this.id, volume: this.volume, totalSamples: this.totalSamples, sampleRate: this.sampleRate, blocks: { _blocks: this.blocks._blocks, _scripts: this.blocks._scripts, }, variables: this.variables, lists: this.lists, markers: this.markers, trimStart: this.trimStart, trimEnd: this.trimEnd, playbackRate: this.playbackRate } } duplicate () { var newTarget = new AudioTarget(this.runtime); // We purposefully don't provide an id here and // instead overwrite it after duplication so that // this method matches the signature of the standard // sprite duplication method newTarget.volume = this.volume; // Audio specific state newTarget.totalSamples = this.totalSamples; newTarget.sampleRate = this.sampleRate; newTarget.markers = JSON.parse(JSON.stringify(this.markers)) newTarget.trimStart = this.trimStart; newTarget.trimEnd = this.trimEnd; newTarget.playbackRate = this.playbackRate; // Copy blocks, vars, etc. newTarget.blocks = this.blocks.duplicate(); newTarget.variables = JSON.parse(JSON.stringify(this.variables)); newTarget.lists = JSON.parse(JSON.stringify(this.lists)); return newTarget; } }
JavaScript
class DeserializingCommand extends Command { /** * Creates an instance of DeserializingCommand. * @param {OdataRequest} request the current OData request * @param {FormatManager} formatManager The current used format manager * @param {RequestContentNegotiator} negotiator The current used request payload negotiator * @param {LoggerFacade} logger the logger */ constructor(request, formatManager, negotiator, logger) { super(); this._request = request; this._formatManager = formatManager; this._negotiator = negotiator; this._logger = logger; } /** * Executes the request-body parsing. The content negotiation creates a `RequestContract` object * as a result with a payload deserializer facade inside. The contract object is * attached to the odata request instance. The deserializer facade is executed and the result body * is attached to the request. This command is executed only if the incoming request has a body * to parse as determined by the negotiation. * * @param {Next} next The next callback to be called on finish */ execute(next) { this._logger.path('Entering DeserializingCommand.execute()...'); const contract = this._negotiator.negotiate(this._formatManager, this._request); const representationKind = contract.getRepresentationKind(); if (representationKind === RepresentationKinds.NO_CONTENT) { next(); } else { const deserializerFacade = contract.getDeserializerFunction(); if (deserializerFacade) { this._logger.path('Start request payload parsing...'); deserializerFacade(this._request, (err, body) => { this._request.setBody(body); next(err); }); } else { next(new DeserializationError( "No payload deserializer available for resource kind '" + representationKind + "' and mime type '" + contract.getContentTypeInfo().getMimeType() + "'")); } } } }
JavaScript
class Image extends Component { static defaultProps = { lazy: true }; state = { src: !this.props.lazy ? this.props.videoSrc || this.props.src : undefined }; handleIntersect = entry => { if (entry.isIntersecting) { this.setState({ src: this.props.videoSrc || this.props.src }); } }; render() { const { caption, width, height, isAmp, margin = 40, video = false, videoSrc, captionSpacing = null, renderImage, oversize = true, float, lazy, shadow, style, ...rest } = this.props; const aspectRatio = `${String((height / width) * 100)}%`; return ( <IObserver once onIntersect={this.handleIntersect} rootMargin="20%" disabled={!lazy}> <figure className={classNames({ oversize: width > 650 && oversize, float: float && width < 520 })} > <div className="container" style={{ width }}> <div style={isAmp ? undefined : { paddingBottom: aspectRatio, ...style }}> {isAmp ? ( videoSrc || video ? ( <> <Head> <script key="amp-video" async custom-element="amp-video" src="https://cdn.ampproject.org/v0/amp-video-0.1.js" /> </Head> <amp-video layout="responsive" src={rest.videoSrc || rest.src} width={width} height={height} muted="muted" autoPlay="autoplay" loop="loop" /> </> ) : ( <amp-img layout="responsive" src={rest.src} width={width} height={height} alt={rest.alt} /> ) ) : this.state.src ? ( videoSrc || video ? ( <video src={this.state.src} muted autoPlay loop playsInline /> ) : renderImage ? ( renderImage(rest) ) : ( <img src={this.state.src || null} alt={rest.alt} /> ) ) : null} </div> {caption && ( <figcaption style={captionSpacing ? { marginTop: captionSpacing } : {}}> {caption} </figcaption> )} </div> <style jsx> {` figure { display: block; text-align: center; margin: ${margin}px 0; } .container { margin: 0 auto; max-width: 100%; } div { transform: translate3d(0, 0, 0); /* Work around for Chrome bug */ position: relative; } figure :global(img), figure :global(video) { ${ isAmp ? 'position: inherit;' : ` height: 100%; left: 0; position: absolute; top: 0; width: 100%; ` }; ${shadow ? 'box-shadow: 0 8px 30px rgba(0,0,0,0.12)' : ''} } figcaption { color: #999; font-size: 12px; margin: 0; text-align: center; } @media (min-width: 1200px) { figure.oversize { width: ${width}px; margin: ${margin}px 0 ${margin}px calc(((${width}px - 650px) / 2) * -1); } figure.float { float: ${float}; margin: ${margin}px; margin-${float}: -150px; } } `} </style> </figure> </IObserver> ); } }
JavaScript
class Extensions { /** * @param {!Window} win */ constructor(win) { /** @const {!Window} */ this.win = win; /** @const @private */ this.ampdocService_ = Services.ampdocServiceFor(win); /** @private @const {!Object<string, !ExtensionHolderDef>} */ this.extensions_ = {}; /** @private {?string} */ this.currentExtensionId_ = null; } /** * Registers a new extension. This method is called by the extension's script * itself when it's loaded using the regular `AMP.push()` callback. * @param {string} extensionId * @param {function(!Object)} factory * @param {!Object} arg * @private * @restricted */ registerExtension_(extensionId, factory, arg) { const holder = this.getExtensionHolder_(extensionId, /* auto */ true); try { this.currentExtensionId_ = extensionId; factory(arg); if (getMode().localDev || getMode().test) { if (Object.freeze) { const m = holder.extension; m.elements = Object.freeze(m.elements); holder.extension = Object.freeze(m); } } holder.loaded = true; if (holder.resolve) { holder.resolve(holder.extension); } } catch (e) { holder.error = e; if (holder.reject) { holder.reject(e); } throw e; } finally { this.currentExtensionId_ = null; } } /** * Waits for the previously included extension to complete * loading/registration. * @param {string} extensionId * @return {!Promise<!ExtensionDef>} */ waitForExtension(extensionId) { return this.waitFor_(this.getExtensionHolder_( extensionId, /* auto */ false)); } /** * Returns the promise that will be resolved when the extension has been * loaded. If necessary, adds the extension script to the page. * @param {string} extensionId * @return {!Promise<!ExtensionDef>} */ preloadExtension(extensionId) { if (extensionId == 'amp-embed') { extensionId = 'amp-ad'; } const holder = this.getExtensionHolder_(extensionId, /* auto */ false); this.insertExtensionScriptIfNeeded_(extensionId, holder); return this.waitFor_(holder); } /** * Returns the promise that will be resolved when the extension has been * loaded. If necessary, adds the extension script to the page. * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {string} extensionId * @return {!Promise<!ExtensionDef>} */ installExtensionForDoc(ampdoc, extensionId) { const rootNode = ampdoc.getRootNode(); let extLoaders = rootNode[LOADER_PROP]; if (!extLoaders) { extLoaders = rootNode[LOADER_PROP] = map(); } if (extLoaders[extensionId]) { return extLoaders[extensionId]; } stubElementIfNotKnown(ampdoc.win, extensionId); return extLoaders[extensionId] = this.preloadExtension(extensionId) .then(() => this.installExtensionInDoc_(ampdoc, extensionId)); } /** * Reloads the new version of the extension. * @param {string} extensionId * @param {!Element} oldScriptElement * @return {!Promise<!ExtensionDef>} */ reloadExtension(extensionId, oldScriptElement) { // "Disconnect" the old script element and extension record. const holder = this.extensions_[extensionId]; if (holder) { dev().assert(!holder.loaded && !holder.error); delete this.extensions_[extensionId]; } oldScriptElement.removeAttribute('custom-element'); oldScriptElement.setAttribute('i-amphtml-loaded-new-version', extensionId); return this.preloadExtension(extensionId); } /** * Returns the promise that will be resolved with the extension element's * class when the extension has been loaded. If necessary, adds the extension * script to the page. * @param {string} elementName * @return {!Promise<function(new:../base-element.BaseElement, !Element)>} */ loadElementClass(elementName) { return this.preloadExtension(elementName).then(extension => { const element = dev().assert(extension.elements[elementName], 'Element not found: %s', elementName); return element.implementationClass; }); } /** * Registers the element implementation with the current extension. * @param {string} name * @param {!Function} implementationClass * @param {?string|undefined} css * @private * @restricted */ addElement_(name, implementationClass, css) { const holder = this.getCurrentExtensionHolder_(name); holder.extension.elements[name] = {implementationClass, css}; this.addDocFactory_(ampdoc => { this.installElement_(ampdoc, name, implementationClass, css); }); } /** * Installs the specified element implementation in the ampdoc. * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {string} name * @param {!Function} implementationClass * @param {?string|undefined} css * @private */ installElement_(ampdoc, name, implementationClass, css) { if (css) { installStylesForDoc(ampdoc, css, () => { this.registerElementInWindow_(ampdoc.win, name, implementationClass); }, /* isRuntimeCss */ false, name); } else { this.registerElementInWindow_(ampdoc.win, name, implementationClass); } } /** * @param {!Window} win * @param {string} name * @param {!Function} implementationClass * @private */ registerElementInWindow_(win, name, implementationClass) { // Register the element in the window. upgradeOrRegisterElement(win, name, implementationClass); // Register this extension to resolve its Service Promise. registerServiceBuilder(win, name, emptyService); } /** * Adds `name` to the list of services registered by the current extension. * @param {string} name * @param {function(new:Object, !./ampdoc-impl.AmpDoc)} implementationClass * @private */ addService_(name, implementationClass) { const holder = this.getCurrentExtensionHolder_(); holder.extension.services.push(name); this.addDocFactory_(ampdoc => { registerServiceBuilderForDoc( ampdoc, name, implementationClass, /* instantiate */ true); }); } /** * Registers an ampdoc factory. * @param {function(!./ampdoc-impl.AmpDoc)} factory * @param {string=} opt_forName * @private * @restricted */ addDocFactory_(factory, opt_forName) { const holder = this.getCurrentExtensionHolder_(opt_forName); holder.docFactories.push(factory); // If a single-doc mode, or is shadow-doc mode and has AmpDocShell, // run factory right away if it's included by the doc. if (this.currentExtensionId_ && (this.ampdocService_.isSingleDoc() || this.ampdocService_.hasAmpDocShell())) { const ampdoc = this.ampdocService_.getAmpDoc(this.win.document); const extensionId = dev().assertString(this.currentExtensionId_); if (ampdoc.declaresExtension(extensionId) || holder.auto) { factory(ampdoc); } } } /** * Installs all ampdoc factories previously registered with * `addDocFactory_`. * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {!Array<string>} extensionIds * @return {!Promise} * @private * @restricted */ installExtensionsInDoc_(ampdoc, extensionIds) { const promises = []; extensionIds.forEach(extensionId => { promises.push(this.installExtensionInDoc_(ampdoc, extensionId)); }); return Promise.all(promises); } /** * Installs all ampdoc factories for the specified extension. * @param {!./ampdoc-impl.AmpDoc} ampdoc * @param {string} extensionId * @return {!Promise} * @private */ installExtensionInDoc_(ampdoc, extensionId) { const holder = this.getExtensionHolder_(extensionId, /* auto */ false); return this.waitFor_(holder).then(() => { declareExtension(ampdoc, extensionId); holder.docFactories.forEach(factory => { try { factory(ampdoc); } catch (e) { rethrowAsync('Doc factory failed: ', e, extensionId); } }); }); } /** * Install extensions in the child window (friendly iframe). The pre-install * callback, if specified, is executed after polyfills have been configured * but before the first extension is installed. * @param {!Window} childWin * @param {!Array<string>} extensionIds * @param {function(!Window)=} opt_preinstallCallback * @return {!Promise} * @restricted */ installExtensionsInChildWindow(childWin, extensionIds, opt_preinstallCallback) { const topWin = this.win; const parentWin = childWin.frameElement.ownerDocument.defaultView; setParentWindow(childWin, parentWin); // Install necessary polyfills. installPolyfillsInChildWindow(childWin); // Install runtime styles. installStylesLegacy(childWin.document, cssText, /* callback */ null, /* opt_isRuntimeCss */ true, /* opt_ext */ 'amp-runtime'); // Run pre-install callback. if (opt_preinstallCallback) { opt_preinstallCallback(childWin); } // Adopt embeddable services. adoptStandardServicesForEmbed(childWin); // Install built-ins and legacy elements. copyBuiltinElementsToChildWindow(topWin, childWin); stubLegacyElements(childWin); const promises = []; extensionIds.forEach(extensionId => { // This will extend automatic upgrade of custom elements from top // window to the child window. if (!LEGACY_ELEMENTS.includes(extensionId)) { stubElementIfNotKnown(childWin, extensionId); } // Install CSS. const promise = this.preloadExtension(extensionId).then(extension => { // Adopt embeddable extension services. extension.services.forEach(service => { adoptServiceForEmbedIfEmbeddable(childWin, service); }); // Adopt the custom elements. let elementPromises = null; for (const elementName in extension.elements) { const elementDef = extension.elements[elementName]; const elementPromise = new Promise(resolve => { if (elementDef.css) { installStylesLegacy( childWin.document, elementDef.css, /* completeCallback */ resolve, /* isRuntime */ false, extensionId); } else { resolve(); } }).then(() => { upgradeOrRegisterElement( childWin, elementName, elementDef.implementationClass); }); if (elementPromises) { elementPromises.push(elementPromise); } else { elementPromises = [elementPromise]; } } if (elementPromises) { return Promise.all(elementPromises).then(() => extension); } return extension; }); promises.push(promise); }); return Promise.all(promises); } /** * Creates or returns an existing extension holder. * @param {string} extensionId * @param {boolean} auto * @return {!ExtensionHolderDef} * @private */ getExtensionHolder_(extensionId, auto) { let holder = this.extensions_[extensionId]; if (!holder) { const extension = /** @type {ExtensionDef} */ ({ elements: {}, services: [], }); holder = /** @type {ExtensionHolderDef} */ ({ extension, auto, docFactories: [], promise: undefined, resolve: undefined, reject: undefined, loaded: undefined, error: undefined, scriptPresent: undefined, }); this.extensions_[extensionId] = holder; } return holder; } /** * Returns the holder for the extension currently being registered. * @param {string=} opt_forName Used for logging only. * @return {!ExtensionHolderDef} * @private */ getCurrentExtensionHolder_(opt_forName) { if (!this.currentExtensionId_ && !getMode().test) { dev().error(TAG, 'unknown extension for ', opt_forName); } return this.getExtensionHolder_( this.currentExtensionId_ || UNKNOWN_EXTENSION, /* auto */ true); } /** * Creates or returns an existing promise that will yield as soon as the * extension has been loaded. * @param {!ExtensionHolderDef} holder * @return {!Promise<!ExtensionDef>} * @private */ waitFor_(holder) { if (!holder.promise) { if (holder.loaded) { holder.promise = Promise.resolve(holder.extension); } else if (holder.error) { holder.promise = Promise.reject(holder.error); } else { holder.promise = new Promise((resolve, reject) => { holder.resolve = resolve; holder.reject = reject; }); } } return holder.promise; } /** * Ensures that the script has already been injected in the page. * @param {string} extensionId * @param {!ExtensionHolderDef} holder * @private */ insertExtensionScriptIfNeeded_(extensionId, holder) { if (this.isExtensionScriptRequired_(extensionId, holder)) { const scriptElement = this.createExtensionScript_(extensionId); this.win.document.head.appendChild(scriptElement); holder.scriptPresent = true; } } /** * Determine the need to add amp extension script to document. * @param {string} extensionId * @param {!ExtensionHolderDef} holder * @return {boolean} * @private */ isExtensionScriptRequired_(extensionId, holder) { if (holder.loaded || holder.error) { return false; } if (holder.scriptPresent === undefined) { const scriptInHead = this.win.document.head./*OK*/querySelector( `[custom-element="${extensionId}"]`); holder.scriptPresent = !!scriptInHead; } return !holder.scriptPresent; } /** * Create the missing amp extension HTML script element. * @param {string} extensionId * @return {!Element} Script object * @private */ createExtensionScript_(extensionId) { const scriptElement = this.win.document.createElement('script'); scriptElement.async = true; scriptElement.setAttribute('custom-element', extensionId); scriptElement.setAttribute('data-script', extensionId); scriptElement.setAttribute('i-amphtml-inserted', ''); let loc = this.win.location; if (getMode().test && this.win.testLocation) { loc = this.win.testLocation; } const scriptSrc = calculateExtensionScriptUrl(loc, extensionId, getMode().localDev); scriptElement.src = scriptSrc; return scriptElement; } }
JavaScript
class CommandDictionary { /** * Creates a new (empty) CommandDictionary. */ constructor () { this._byOpcode = { } this._bySubsystem = { } } /** * Adds the given CommandDefinition to this CommandDictionary. */ add (defn) { if (defn instanceof CommandDefinition) { this[defn.name] = defn this._byOpcode[defn.opcode] = defn let subsys = null if (!defn.subsystem) { subsys = 'GENERAL' } else { subsys = defn.subsystem } let commands = this._bySubsystem[subsys] || [ ] commands.push(defn) this._bySubsystem[subsys] = commands } } get bySubsystem () { return this._bySubsystem } /** * Returns the CommandDefinition with the given opcode or the * given opcode if no definition exists for it. */ getByOpcode (opcode) { if (this._byOpcode[opcode]) { return this._byOpcode[opcode] } else { return opcode } } /** * Parses the given plain Javascript Object or JSON string and * returns a new CommandDictionary, mapping packet names to * PacketDefinitions. */ static parse (obj) { let dict = new CommandDictionary() if (typeof obj === 'string') { obj = JSON.parse(obj) } for (let name in obj) { dict.add( new CommandDefinition(obj[name]) ) } return dict } }
JavaScript
class DCache extends Events { #header = { locked: false }; #memory = new Map(); #meta; #proxy; /** * Creates a new dcache * @returns {Proxy} */ constructor() { super(); this.#meta = { header: this.header, body: this.body, memory: this.memory }; this.#proxy = new Proxy(this.#meta, { deleteProperty: (t, k) => t.body.delete(k), get: (t, k) => { if(k in t.body.constructor.prototype) { let p = t.body[k]; return typeof p === "function" ? p.bind(t.body) : p; }; return t.body.get(k); }, getPrototypeOf: t => t.body, has: (t, k) => t.body.has(k), isExtensible: t => t.header.locked, ownKeys: t => t.body.keys, preventExtensions: t => t.body.lock(), set: (t, k, v) => t.body.set(k, v), setPrototypeOf: () => { throw new TypeError("Please do not modify the prototype of DCache"); } }); this.#meta.proxy = this.#proxy; return this.#proxy; }; /** * Returns the body of this dcache * @readonly * @returns {DCache} */ get body() { return this; }; /** * Clears this dcache * @returns {boolean} */ clear() { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); this.#memory.clear(); super.emit("clear"); return true; }; /** * Clones this dcache * @param {boolean} d Whether or not to deep clone * @returns {DCache} */ clone(d) { let clone = new DCache(); for(let [ k, v ] of this.#memory.entries()) clone.set(k, d ? JSON.parse(JSON.stringify(v)) : v); return clone; }; /** * Decreases a value in this dcache * @param {any} k Key * @param {number} v Decrement * @returns {boolean} */ decrease(k, v = 1) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); if(isNaN(v)) throw new TypeError("Argument is not a number"); if(this.has(k) && isNaN(this.get(k))) throw new TypeError("Cannot increment a non-number value"); this.set(k, +(this.has(k) ? this.get(k) : 0) - v); super.emit("decrease"); return true; }; /** * Deletes a key from this dcache * @param {any} k Key * @returns {boolean} */ delete(k) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); if(!this.has(k)) return true; let v = this.get(k); this.#memory.delete(k); super.emit("delete", k, v); return true; }; /** * Sets a default value if the key doesn't exist in this dcache * @param {any} k Key * @param {any} v Value * @returns {boolean} */ ensure(k, v) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); if(this.has(k)) return true; this.set(k, v); super.emit("ensure", k, v); return true; }; /** * Returns all entries of this dcache * @readonly * @returns {[ any, any ][]} */ get entries() { return Array.from(this.#memory.entries()); }; /** * Returns if all entries in this dcache passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {boolean} */ every(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) if(!cb(v, k, this)) return false; return true; }; /** * Filters all values in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any[]} */ filter(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let r = []; for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) r.push(v); return r; }; /** * Filters all entries in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {[ any, any ][]} */ filterEntries(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let r = []; for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) r.push([ k, v ]); return r; }; /** * Filters all keys in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any[]} */ filterKeys(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let r = []; for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) r.push(k); return r; }; /** * Finds the first value in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any} */ find(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) return v; return null; }; /** * Finds the first entry in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {[ any, any ]} */ findEntry(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) return [ k, v ]; return null; }; /** * Finds the first key in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any[]} */ findKey(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) return k; return null; }; /** * Finds the last value in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any} */ findLast(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let e = this.#memory.entries(); for(let i = e.length - 1; i >= 0; i--) { let [ k, v ] = e[i]; if(cb(v, k, this)) return v; }; return null; }; /** * Finds the last entry in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {[ any, any ]} */ findLastEntry(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let e = this.#memory.entries(); for(let i = e.length - 1; i >= 0; i--) { let [ k, v ] = e[i]; if(cb(v, k, this)) return [ k, v ]; }; return null; }; /** * Finds the last key in this dcache that passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {any[]} */ findLastKey(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let e = this.#memory.entries(); for(let i = e.length - 1; i >= 0; i--) { let [ k, v ] = e[i]; if(cb(v, k, this)) return k; }; return null; }; /** * Loops through this dcache from the first to the last * @param {function(any, any, DCache)} cb Callback * @returns {boolean} */ forEach(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) cb(v, k, this); return true; }; /** * Loops through this dcache from the last to the first * @param {function(any, any, DCache)} cb Callback * @returns {boolean} */ forEachLast(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let e = this.#memory.entries(); for(let i = e.length - 1; i >= 0; i--) { let [ k, v ] = e[i]; cb(v, k, this); }; return null; }; /** * Returns the value from a key in this dcache * @param {any} k Key * @returns {any} */ get(k) { return this.#memory.get(k); }; /** * Returns if the key exists in this dcache * @param {any} k Key * @returns {boolean} */ has(k) { return this.#memory.has(k); }; /** * Returns the header of this dcache * @readonly * @returns {object} */ get header() { return JSON.parse(JSON.stringify(this.#header)); }; /** * Increases a value in this dcache * @param {any} k Key * @param {number} v Increment * @returns {boolean} */ increase(k, v = 1) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); if(isNaN(v)) throw new TypeError("Argument is not a number"); if(this.has(k) && isNaN(this.get(k))) throw new TypeError("Cannot increment a non-number value"); this.set(k, +(this.has(k) ? this.get(k) : 0) + v); super.emit("increase"); return true; }; /** * Returns whether or not this dcache is locked * @readonly * @returns {boolean} */ get isLocked() { return this.#header.locked; }; /** * Returns all keys of this dcache * @readonly * @returns {any[]} */ get keys() { return Array.from(this.#memory.keys()); }; /** * Locks this dcache * @returns {boolean} */ lock() { if(this.#header.locked) return true; this.#header.locked = true; super.emit("lock"); return true; }; /** * Maps through this dcache * @param {function(any, any, DCache)} cb Callback * @param {boolean} m Whether or not to merge (instead of making a clone) * @returns {boolean|DCache} */ map(cb, m) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); let t = m ? this : new DCache(); for(let [ k, v ] of this.#memory.entries()) t.set(k, cb(v, k, this)); return m ? true : t; }; /** * Returns the memory of this dcache * @readonly * @returns {Map} */ get memory() { return this.#memory; }; /** * Merges other dcaches with this dcache * @param {function(any, any, DCache)} cb Callback * @param {boolean} m Whether or not to merge (instead of making a clone) * @returns {boolean|DCache} */ merge(dcaches, m) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); if(!Array.isArray(dcaches)) throw new TypeError("Argument is not an array"); let t = m ? this : new DCache(); for(let dcache of m ? dcaches : [ this, ...dcaches ]) { if(!(dcache instanceof DCache)) continue; for(let entry of dcache.entries) t.set(entry[0], entry[1]); }; if(m) super.emit("merge", ...dcaches); return m ? true : t; }; /** * Returns the meta of this dcache * @readonly * @returns {object} */ get meta() { return { body: this.body, header: this.header, memory: this.memory, proxy: this.proxy }; }; /** * Returns the proxy of this dcache * @readonly * @returns {Proxy} */ get proxy() { return this.#proxy; }; /** * Reverses this dcache * @param {boolean} m Whether or not to merge (instead of making a clone) * @returns {boolean|DCache} */ reverse(m) { let e = this.entries, t = m ? this : new DCache(); t.clear(); for(let i = e.length - 1; i >= 0; i--) { let [ k, v ] = e[i]; t.set(k, v); }; if(m) super.emit("reverse", e); return m ? true : t; }; /** * Sets a value to this key in this dcache * @param {any} k Key * @param {any} v Value * @returns {boolean} */ set(k, v) { if(this.#header.locked) throw new Error("Cannot modify a locked dcache"); this.#memory.set(k, v); super.emit("set", k, v); return true; }; /** * Returns the size of this dcache * @readonly * @returns {number} */ get size() { return this.#memory.size; }; /** * Returns if at least one entry in this dcache passed the predicate * @param {function(any, any, DCache)} cb Callback * @returns {boolean} */ some(cb) { if(typeof cb !== "function") throw new TypeError("Argument is not a function"); for(let [ k, v ] of this.#memory.entries()) if(cb(v, k, this)) return true; return false; }; /** * Converts this dcache into a JSON * @returns {object} */ toObject() { return Object.fromEntries(this.#memory.entries()); }; /** * Converts this dcache into a string * @returns {string} */ toString() { return JSON.stringify(Object.fromEntries(this.#memory.entries())); }; /** * Returns all keys of this dcache * @readonly * @returns {any[]} */ get values() { return Array.from(this.#memory.values()); }; /** * Returns the value of this dcache * @returns {DCache} */ valueOf() { return this; }; *[Symbol.iterator]() { for(let v of this.#memory.values()) yield v; }; }
JavaScript
class CommandableLambdaFunction extends LambdaFunction_1.LambdaFunction { /** * Creates a new instance of this lambda function. * * @param name (optional) a container name (accessible via ContextInfo) * @param description (optional) a container description (accessible via ContextInfo) */ constructor(name, description) { super(name, description); this._dependencyResolver.put('controller', 'none'); } registerCommandSet(commandSet) { let commands = commandSet.getCommands(); for (let index = 0; index < commands.length; index++) { let command = commands[index]; this.registerAction(command.getName(), null, (params, callback) => { let correlationId = params.correlation_id; let args = pip_services3_commons_node_1.Parameters.fromValue(params); let timing = this.instrument(correlationId, this._info.name + '.' + command.getName()); command.execute(correlationId, args, (err, result) => { timing.endTiming(); callback(err, result); }); }); } } /** * Registers all actions in this lambda function. */ register() { let controller = this._dependencyResolver.getOneRequired('controller'); let commandSet = controller.getCommandSet(); this.registerCommandSet(commandSet); } }
JavaScript
class MemoryList extends React.Component { constructor(props) { super(props); this.initialState = { height: 400, width: 600, isLoaded: false, memory: null, filter: "", showDetail: false, detailUUID: null, }; this.state = this.initialState; this.outer_div = React.createRef(); this.resizeHandler = this.resizeHandler.bind(this); } resizeHandler() { if (this.outer_div != null && this.outer_div.current != null) { let { clientHeight, clientWidth } = this.outer_div.current; if ( (clientHeight !== undefined && clientHeight !== this.state.height) || (clientWidth !== undefined && clientWidth !== this.state.width) ) { this.setState({ height: clientHeight, width: clientWidth }); } } } componentDidMount() { if (this.props.stateManager) this.props.stateManager.connect(this); if (this.props.glContainer !== undefined) { // if this is inside a golden-layout container this.props.glContainer.on("resize", this.resizeHandler); } } componentDidUpdate(prevProps, prevState) { this.resizeHandler(); } render() { if (!this.state.isLoaded) return <p>Loading</p>; let { height, width, memory, isLoaded } = this.state; if (height === 0 && width === 0) { // return early for performance return ( <div ref={this.outer_div} style={{ height: "100%", width: "100%" }} /> ); } if (!isLoaded) { return ( <div ref={this.outer_div} style={{ height: "100%", width: "100%" }}> Loading... </div> ); } const darkTheme = createMuiTheme({ palette: { type: "dark", }, }); const memoryManager = new MemoryManager(memory, this.state.filter); const showMemoryDetail = (memoryUUID) => { this.setState({ detailUUID: memoryUUID, showDetail: true }); }; const paddedHeight = this.state.height - 24; const paddedWidth = this.state.width - 24; const closeDrawer = () => { this.setState({ showDetail: false }); }; // final render return ( <ThemeProvider theme={darkTheme}> <TextField style={{ borderBlockColor: "white", }} color="primary" id="outlined-uncontrolled" label="Search" margin="dense" variant="outlined" onChange={(event) => { this.setState({ filter: event.target.value }); }} /> <ReactVirtualizedTable height={paddedHeight} width={paddedWidth} memoryManager={memoryManager} onShowMemoryDetail={showMemoryDetail} /> <Drawer anchor="right" open={this.state.showDetail} onClose={() => { closeDrawer(); }} > <div style={{ width: 450 }}> <IconButton onClick={() => closeDrawer()}> <CloseIcon /> </IconButton> <Divider /> <MemoryDetail memoryManager={memoryManager} uuid={this.state.detailUUID} /> </div> </Drawer> </ThemeProvider> ); } }
JavaScript
class WebpackNodeDevelopmentConfiguration extends ConfigurationFile { /** * Class constructor. * @param {Logger} appLogger To send the plugin that executes * the bundle in order to log * information messages. * @param {Events} events To reduce the configuration. * @param {PathUtils} pathUtils Required by `ConfigurationFile` * in order to build the path to * the overwrite file. * @param {WebpackBaseConfiguration} webpackBaseConfiguration The configuration this one will * extend. */ constructor( appLogger, events, pathUtils, webpackBaseConfiguration ) { super( pathUtils, [ 'config/webpack/node.development.config.js', 'config/webpack/node.config.js', ], true, webpackBaseConfiguration ); /** * A local reference for the `appLogger` service. * @type {Logger} */ this.appLogger = appLogger; /** * A local reference for the `events` service. * @type {Events} */ this.events = events; } /** * Create the configuration with the `entry`, the `output` and the plugins specifics for a * Node target development build. * This method uses the reducer events `webpack-node-development-configuration` and * `webpack-node-configuration`. It sends the configuration, the received `params` and expects * a configuration on return. * @param {WebpackConfigurationParams} params A dictionary generated by the top service building * the configuration and that includes things like the * target information, its entry settings, output * paths, etc. * @return {object} */ createConfig(params) { const { entry, target, output, copy, additionalWatch, analyze, } = params; // By default it doesn't watch the source files. let watch = false; // Setup the basic plugins. const plugins = [ // To avoid pushing assets with errors. new NoEmitOnErrorsPlugin(), // To optimize the SCSS and remove repeated declarations. new OptimizeCssAssetsPlugin(), // Copy the files the target specified on its settings. new CopyWebpackPlugin(copy), // If there are additionals files to watch, add the plugin for it. ...( additionalWatch.length ? [new ExtraWatchWebpackPlugin({ files: additionalWatch })] : [] ), // If the the bundle should be analyzed, add the plugin for it. ...( analyze ? [new BundleAnalyzerPlugin()] : [] ), ]; // If the target needs to run on development... if (!analyze && target.runOnDevelopment) { // ...watch the source files. watch = true; // Push the plugin that executes the target bundle. plugins.push(new ProjextWebpackBundleRunner({ logger: this.appLogger, inspect: target.inspect, })); } else if (target.watch.development) { // Enable the watch mode if required. watch = true; } // Define the rest of the configuration. const config = { entry, output: { path: `./${target.folders.build}`, filename: output.js, chunkFilename: output.jsChunks, publicPath: '/', }, watch, plugins, target: 'node', node: { // Avoid getting an empty `__dirname`. __dirname: false, }, mode: 'development', }; // If the target has source maps enabled... if (target.sourceMap.development) { // ...configure the devtool config.devtool = 'source-map'; } // Reduce the configuration. return this.events.reduce( [ 'webpack-node-development-configuration', 'webpack-node-configuration', ], config, params ); } }
JavaScript
class ZcashTransaction { /** * Instantiate a new `ZcashTransaction`. * * See the class properties for expanded information on these parameters. * * @property {boolean} overwintered * @property {number} version * @property {number} versionGroupId * @property {Array.<ZcashTransactionIn>} vin * @property {Array.<ZcashTransactionIn>} vout * @property {number} lockTime * @property {number|null} expiryHeight * @property {BigInt|null} valueBalance * @property {Array.<ZcashSpendDescription>|null} shieldedSpend * @property {Array.<ZcashOutputDescription>|null} shieldedOutput * @property {Uint8Array|Buffer|null} joinSplitPubKey * @property {Array.<ZcashJoinSplitDescription>|null} joinSplits * @property {Uint8Array|Buffer|null} joinSplitSig * @property {Uint8Array|Buffer|null} bindingSig * @property {Uint8Array|Buffer} hash * @constructs ZcashTransaction */ constructor (overwintered, version, versionGroupId, vin, vout, lockTime, expiryHeight, valueBalance, shieldedSpend, shieldedOutput, joinSplits, joinSplitPubKey, joinSplitSig, bindingSig, hash) { this.overwintered = overwintered this.version = version this.versionGroupId = versionGroupId this.vin = vin this.vout = vout this.lockTime = lockTime this.expiryHeight = expiryHeight this.valueBalance = valueBalance this.shieldedSpend = shieldedSpend this.shieldedOutput = shieldedOutput this.joinSplitPubKey = joinSplitPubKey this.joinSplits = joinSplits this.joinSplitSig = joinSplitSig this.bindingSig = bindingSig this.hash = hash } /** * Convert to a serializable form that has nice stringified hashes and other simplified forms. May be * useful for simplified inspection. */ toJSON () { return Object.assign({}, this, { versionGroupId: this.versionGroupId.toString(16), valueBalance: Number(this.valueBalance) / COIN, hash: toHashHex(this.hash) }) } /** * Convert to a serializable form that has nice stringified hashes and other simplified forms. May be * useful for simplified inspection. */ toSerializable () { return this.toJSON() } }
JavaScript
class MatrixPresentation extends React.Component { constructor(props) { super(props); const query = new QueryString(this.props.context['@id']); const tagKey = query.getKeyValues(internalTagKey); const hasDeeplyProfiledTag = tagKey[0] === internalTagValue; this.state = { /** Categories the user has expanded */ expandedRowCategories: hasDeeplyProfiledTag ? props.context.matrix.y['replicates.library.biosample.biosample_ontology.term_name'].buckets.map((termName) => termName.key) : [], /** True if matrix scrolled all the way to the right; used for flashing arrow */ scrolledRight: false, }; this.expanderClickHandler = this.expanderClickHandler.bind(this); this.handleOnScroll = this.handleOnScroll.bind(this); this.handleScrollIndicator = this.handleScrollIndicator.bind(this); } componentDidMount() { this.handleScrollIndicator(this.scrollElement); } /* eslint-disable react/no-did-update-set-state */ componentDidUpdate(prevProps) { // If URI changed, we need close any expanded rowCategories in case the URI change results // in a huge increase in displayed data. Also update the scroll indicator if needed. if (prevProps.context['@id'] !== this.props.context['@id']) { this.handleScrollIndicator(this.scrollElement); this.setState({ expandedRowCategories: [] }); } } /* eslint-enable react/no-did-update-set-state */ /** * Called when the user scrolls the matrix horizontally within its div to handle scroll * indicators. * @param {object} e React synthetic scroll event */ handleOnScroll(e) { this.handleScrollIndicator(e.target); } /** * Show a scroll indicator depending on current scrolled position. * @param {object} element DOM element to apply shading to */ handleScrollIndicator(element) { // Have to use a "roughly equal to" test because of an MS Edge bug mentioned here: // https://stackoverflow.com/questions/30900154/workaround-for-issue-with-ie-scrollwidth const scrollDiff = Math.abs((element.scrollWidth - element.scrollLeft) - element.clientWidth); if (scrollDiff < 2 && !this.state.scrolledRight) { // Right edge of matrix scrolled into view. this.setState({ scrolledRight: true }); } else if (scrollDiff >= 2 && this.state.scrolledRight) { // Right edge of matrix scrolled out of view. this.setState({ scrolledRight: false }); } } /** * Called when the user clicks on the expander button on a category to collapse or expand it. * @param {string} category Key for the category */ expanderClickHandler(category) { this.setState((prevState) => { const matchingCategoryIndex = prevState.expandedRowCategories.indexOf(category); if (matchingCategoryIndex === -1) { // Category doesn't exist in array, so add it. return { expandedRowCategories: prevState.expandedRowCategories.concat(category) }; } // Category does exist in array // Move close to header const header = document.querySelector(`#${globals.sanitizeId(category)}`); const headerToPageTopDistance = header ? header.getBoundingClientRect().top : 0; const buffer = 20; // extra space between navbar and header const top = headerToPageTopDistance - (getNavbarHeight() + buffer); window.scrollBy({ top, left: 0, behavior: 'smooth', }); // Remove category. const expandedCategories = prevState.expandedRowCategories; return { expandedRowCategories: [...expandedCategories.slice(0, matchingCategoryIndex), ...expandedCategories.slice(matchingCategoryIndex + 1)] }; }); } render() { const { context, rowCategoryGetter, rowSubCategoryGetter, mapRowCategoryQueries, mapSubCategoryQueries } = this.props; const { scrolledRight } = this.state; // Convert encode matrix data to a DataTable object. const { dataTable, rowKeys } = convertDeeplyProfileDatatToDataTable(context, rowCategoryGetter, rowSubCategoryGetter, mapRowCategoryQueries, mapSubCategoryQueries, this.state.expandedRowCategories, this.expanderClickHandler); const matrixConfig = { rows: dataTable, rowKeys, tableCss: 'matrix', }; return ( <div className="matrix__presentation"> <div className={`matrix__label matrix__label--horz${!scrolledRight ? ' horz-scroll' : ''}`}> <span>{context.matrix.x.label}</span> {svgIcon('largeArrow')} </div> <div className="matrix__presentation-content"> <div className="matrix__label matrix__label--vert"><div>{svgIcon('largeArrow')}Cell Line (batch identifier)</div></div> <div className="matrix__data-wrapper"> <div className="matrix__data" onScroll={this.handleOnScroll} ref={(element) => { this.scrollElement = element; }}> <DataTable tableData={matrixConfig} /> </div> </div> </div> </div> ); } }
JavaScript
class DeeplyProfiledUniformBatchMatrix extends React.Component { constructor() { super(); this.getRowCategories = this.getRowCategories.bind(this); this.getRowSubCategories = this.getRowSubCategories.bind(this); } /** * Called to retrieve row category data for the deeply profiled matrix. */ getRowCategories() { const rowCategory = this.props.context.matrix.y.group_by[0]; const rowCategoryData = this.props.context.matrix.y[rowCategory].buckets.sort((a, b) => sortByDescending(a.key, b.key)); const rowCategoryColors = globals.DeeplyProfiledCellLineListColors.colorList(rowCategoryData.map((rowCategoryDatum) => rowCategoryDatum.key)); const rowCategoryNames = {}; rowCategoryData.forEach((datum) => { rowCategoryNames[datum.key] = datum.key; }); return { rowCategoryData, rowCategoryColors, rowCategoryNames, }; } /** * Called to retrieve subcategory data for the deeply profiled matrix. */ getRowSubCategories(rowCategoryBucket) { const subCategoryName = this.props.context.matrix.y.group_by[1]; return rowCategoryBucket[subCategoryName].buckets; } render() { const { context } = this.props; const itemClass = globals.itemClass(context, 'view-item'); if (context.total > 0) { return ( <Panel addClasses={itemClass}> <PanelBody> <MatrixHeader context={context} /> <MatrixAddCart context={context} fetch={this.context.fetch} pageName={matrixName} /> <MatrixContent context={context} rowCategoryGetter={this.getRowCategories} rowSubCategoryGetter={this.getRowSubCategories} mapRowCategoryQueries={mapRowCategoryQueriesExperiment} mapSubCategoryQueries={mapSubCategoryQueriesExperiment} /> </PanelBody> </Panel> ); } return <h4>No results found</h4>; } }
JavaScript
class _PowerUiBase { constructor() { // Hold temp scopes during templating this._tempScope = {}; } _createPowerTree() { this.powerTree = new PowerTree(this, _PowerUiBase); this.powerTree._callInit(); } }
JavaScript
class _PowerBasicElement { constructor(element) { // During startup (class constructor and compile method) we use the tempEl // After this the DOM changes so we get the element direct from DOM using this.$shared.element getter this.tempEl = element; this._$pwActive = false; } get id() { return this.element ? this.element.id || null : null; } set id(id) { this.element.id = id; } get element() { return this.$shared ? this.$shared.element : this.tempEl; } get $pwMain() { return this.$shared ? this.$shared.mainObj : null; } get $pwView() { return this.$shared ? this.$shared.viewObj : null; } get parent() { return this.$shared ? this.$shared.parentObj : null; } // Only powerCss objects are children, not pow or pwc attrs get children() { return this._cachedChildren || this._getChildren(); } _getChildren() { this._cachedChildren = []; const element = this.element; for (const child of element.children) { if (child.className.includes('power-')) { for (const datasetKey of Object.keys(this.$powerUi.powerTree.allPowerObjsById[child.id] || {})) { if (datasetKey.startsWith('power')) { this._cachedChildren.push(this.$powerUi.powerTree.allPowerObjsById[child.id][datasetKey]); } } } } return this._cachedChildren; } get innerPowerCss() { return this._cachedInnerPowerCss || this._getInnerPowerCss(); } _getInnerPowerCss() { this._cachedInnerPowerCss = this.$powerUi.powerTree._getAllInnerPowerCss(this.element); return this._cachedInnerPowerCss; } }
JavaScript
class AppSvc { #authenticatedDestinationName = Routes.Home.name /** * Checks if provided path is the current route * @param {Route} route * @returns {boolean} */ #isCurrentRoute ({ name }) { return router.currentRoute.name === name } goToHome () { if (this.#isCurrentRoute(Routes.Home)) return const { name } = Routes.Home router.push({ name }) } /** * @param {string} [authenticatedDestination] the destination the user will land at once they've recieved authorisation */ goToLogin ({ authenticatedDestinationName = Routes.Home.name } = {}) { if (this.#isCurrentRoute(Routes.Login)) return this.#authenticatedDestinationName = authenticatedDestinationName const { name } = Routes.Login router.push({ name }) } /** * Users without authorisation are forced to the * login page, but once they have logged in this * method will send them to their intended destination */ continueToInterceptedRoute () { if (this.#authenticatedDestinationName === Routes.Login.name) { this.goToHome() return } router.push({ name: this.#authenticatedDestinationName }) } goToDashboard () { if (this.#isCurrentRoute(Routes.Dashboard)) return const { name } = Routes.Dashboard router.push({ name }) } goToDashboardUpload () { if (this.#isCurrentRoute(Routes.DashboardUpload)) return const { name } = Routes.DashboardUpload router.push({ name }) } }
JavaScript
class Releases { /** * Creates a new `Releases` instance. * * @param {Object} [options] More options to pass to the CLI */ constructor(options) { this.options = options || {}; if (typeof this.options.configFile === 'string') { this.configFile = this.options.configFile; } delete this.options.configFile; } /** * Registers a new release with sentry. * * The given release name should be unique and deterministic. It can later be used to * upload artifacts, such as source maps. * * @param {string} release Unique name of the new release. * @param {object} options A set of options when creating a release. * @param {array} options.projects The list of project slugs for a release. * @returns {Promise} A promise that resolves when the release has been created. * @memberof SentryReleases */ new(release, options) { const args = ['releases', 'new', release].concat(helper.getProjectFlagsFromOptions(options)); return this.execute(args, null); } /** * Specifies the set of commits covered in this release. * * @param {string} release Unique name of the release * @param {object} options A set of options to configure the commits to include * @param {string} options.repo The full repo name as defined in Sentry * @param {boolean} options.auto Automatically choose the associated commit (uses * the current commit). Overrides other options. * @param {string} options.commit The current (last) commit in the release. * @param {string} options.previousCommit The commit before the beginning of this * release (in other words, the last commit of the previous release). If omitted, * this will default to the last commit of the previous release in Sentry. If there * was no previous release, the last 10 commits will be used. * @param {boolean} options.ignoreMissing When the flag is set and the previous release * commit was not found in the repository, will create a release with the default commits * count (or the one specified with `--initial-depth`) instead of failing the command. * @param {boolean} options.ignoreEmpty When the flag is set, command will not fail * and just exit silently if no new commits for a given release have been found. * @returns {Promise} A promise that resolves when the commits have been associated * @memberof SentryReleases */ setCommits(release, options) { if (!options || (!options.auto && (!options.repo || !options.commit))) { throw new Error('options.auto, or options.repo and options.commit must be specified'); } let commitFlags = []; if (options.auto) { commitFlags = ['--auto']; } else if (options.previousCommit) { commitFlags = ['--commit', `${options.repo}@${options.previousCommit}..${options.commit}`]; } else { commitFlags = ['--commit', `${options.repo}@${options.commit}`]; } if (options.ignoreMissing) { commitFlags.push('--ignore-missing'); } if (options.ignoreEmpty) { commitFlags.push('--ignore-empty'); } return this.execute(['releases', 'set-commits', release].concat(commitFlags)); } /** * Marks this release as complete. This should be called once all artifacts has been * uploaded. * * @param {string} release Unique name of the release. * @returns {Promise} A promise that resolves when the release has been finalized. * @memberof SentryReleases */ finalize(release) { return this.execute(['releases', 'finalize', release], null); } /** * Creates a unique, deterministic version identifier based on the project type and * source files. This identifier can be used as release name. * * @returns {Promise.<string>} A promise that resolves to the version string. * @memberof SentryReleases */ proposeVersion() { return this.execute(['releases', 'propose-version'], null).then( version => version && version.trim() ); } /** * Scans the given include folders for JavaScript source maps and uploads them to the * specified release for processing. * * The options require an `include` array, which is a list of directories to scan. * Additionally, it supports to ignore certain files, validate and preprocess source * maps and define a URL prefix. * * @example * await cli.releases.uploadSourceMaps(cli.releases.proposeVersion(), { * // required options: * include: ['build'], * * // default options: * ignore: ['node_modules'], // globs for files to ignore * ignoreFile: null, // path to a file with ignore rules * rewrite: false, // preprocess sourcemaps before uploading * sourceMapReference: true, // add a source map reference to source files * stripPrefix: [], // remove certain prefices from filenames * stripCommonPrefix: false, // guess common prefices to remove from filenames * validate: false, // validate source maps and cancel the upload on error * urlPrefix: '', // add a prefix source map urls after stripping them * urlSuffix: '', // add a suffix source map urls after stripping them * ext: ['js', 'map', 'jsbundle', 'bundle'], // override file extensions to scan for * projects: ['node'] // provide a list of projects * }); * * @param {string} release Unique name of the release. * @param {object} options Options to configure the source map upload. * @returns {Promise} A promise that resolves when the upload has completed successfully. * @memberof SentryReleases */ uploadSourceMaps(release, options) { if (!options || !options.include || !Array.isArray(options.include)) { throw new Error( '`options.include` must be a vaild array of paths and/or path descriptor objects.' ); } // Each entry in the `include` array will map to an array of promises, which // will in turn contain one promise per literal path value. Thus `uploads` // will be an array of Promise arrays, which we'll flatten later. const uploads = options.include.map(includeEntry => { let pathOptions; let uploadPaths; if (typeof includeEntry === 'object') { pathOptions = includeEntry; uploadPaths = includeEntry.paths; if (!Array.isArray(uploadPaths)) { throw new Error( `Path descriptor objects in \`options.include\` must contain a \`paths\` array. Got ${includeEntry}.` ); } } // `includeEntry` should be a string, which we can wrap in an array to // match the `paths` property in the descriptor object type else { pathOptions = {}; uploadPaths = [includeEntry]; } const newOptions = { ...options, ...pathOptions }; if (!newOptions.ignoreFile && !newOptions.ignore) { newOptions.ignore = DEFAULT_IGNORE; } // args which apply to the entire `include` entry (everything besides the path) const args = ['releases'] .concat(helper.getProjectFlagsFromOptions(options)) .concat(['files', release, 'upload-sourcemaps']); return uploadPaths.map(path => // `execute()` is async and thus we're returning a promise here this.execute(helper.prepareCommand([...args, path], SOURCEMAPS_SCHEMA, newOptions), true) ); }); // `uploads` is an array of Promise arrays, which needs to be flattened // before being passed to `Promise.all()`. (`Array.flat()` doesn't exist in // Node < 11; this polyfill takes advantage of the fact that `concat()` is // willing to accept an arbitrary number of items to add to and/or iterables // to unpack into the given array.) return Promise.all([].concat(...uploads)); } /** * List all deploys for a given release. * * @param {string} release Unique name of the release. * @returns {Promise} A promise that resolves when the list comes back from the server. * @memberof SentryReleases */ listDeploys(release) { return this.execute(['releases', 'deploys', release, 'list'], null); } /** * Creates a new release deployment. This should be called after the release has been * finalized, while deploying on a given environment. * * @example * await cli.releases.newDeploy(cli.releases.proposeVersion(), { * // required options: * env: 'production', // environment for this release. Values that make sense here would be 'production' or 'staging' * * // optional options: * started: 42, // unix timestamp when the deployment started * finished: 1337, // unix timestamp when the deployment finished * time: 1295, // deployment duration in seconds. This can be specified alternatively to `started` and `finished` * name: 'PickleRick', // human readable name for this deployment * url: 'https://example.com', // URL that points to the deployment * }); * * @param {string} release Unique name of the release. * @param {object} options Options to configure the new release deploy. * @returns {Promise} A promise that resolves when the deploy has been created. * @memberof SentryReleases */ newDeploy(release, options) { if (!options || !options.env) { throw new Error('options.env must be a vaild name'); } const args = ['releases', 'deploys', release, 'new']; return this.execute(helper.prepareCommand(args, DEPLOYS_SCHEMA, options), null); } /** * See {helper.execute} docs. * @param {string[]} args Command line arguments passed to `sentry-cli`. * @param {boolean} live We inherit stdio to display `sentry-cli` output directly. * @returns {Promise.<string>} A promise that resolves to the standard output. */ execute(args, live) { return helper.execute(args, live, this.options.silent, this.configFile, this.options); } }