language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class LDA extends Instruction { constructor(opCode, bytes, cycles, addressing, allowExtraCycles) { super(opCode, bytes, cycles, addressing, allowExtraCycles); } run(CPU) { CPU.REG_A = CPU.get8Bit(this.address); CPU.FLAG_N = Byte.isBitSetAtPosition(CPU.REG_A, 7); CPU.FLAG_Z = CPU.REG_A === 0x00; } }
JavaScript
class LDX extends Instruction { constructor(opCode, bytes, cycles, addressing, allowExtraCycles) { super(opCode, bytes, cycles, addressing, allowExtraCycles); } run(CPU) { CPU.REG_X = CPU.get8Bit(this.address); CPU.FLAG_N = Byte.isBitSetAtPosition(CPU.REG_X, 7); CPU.FLAG_Z = CPU.REG_X === 0x00; } }
JavaScript
class NMI extends Instruction { constructor(opCode, bytes, cycles, addressing) { super(opCode, bytes, cycles, addressing); this.disableLog = true; } run(CPU) { CPU.PROGRAM_COUNTER++; CPU.pushValueOnStack(CPU.PROGRAM_COUNTER >> 8); CPU.pushValueOnStack(CPU.PROGRAM_COUNTER & 0xFF); CPU.FLAG_B = false; CPU.pushValueOnStack(CPU.getStatusRegisterByte()); CPU.FLAG_I = true; CPU.PROGRAM_COUNTER = CPU.get16Bit(0xFFFA); window.output.push(`[NMI - Cycle: ${CPU.totalCycles - 1}]`); } }
JavaScript
class ModularConfiguration { /** * Create a new {@link ModularConfiguration}. * * @example * let config = new ModularConfiguration({...}); * * @param {Object|ModularConfiguration} options - Object representing the configuration options. * @param {string[]} options.dohEndpoints - A list of DNS over HTTPS endpoints to be used for bootstrapping. * @param {string[]} options.dnsServers - A list of DNS servers to be used for bootstrapping. * @param {string[]} options.dnsSeeds - A list of DNS seeds to be used for bootstrapping. * @param {string[]} options.httpsSeeds - A list of HTTPS seeds to be used for bootstrapping. * @param {string[]} options.staticSeeds - A list of nodes to be used for bootstrapping. * @param {number} options.networkModulus - The network modulus of the modular network. * @param {number} options.sectorMapSize - The sector map size of the primary sector map. * @param {number} options.logoSectorMapSize - The sector map size of the logo sector map. * @param {number} options.iconSectorMapSize - The sector map size of the icon sector map. * @param {number} options.defaultIgnorePeriod - The default duration to ignore bad-acting peers. * @param {number} options.queueTimeout - The time after which queued requests are terminated. * @param {number} options.maxPeerShare - The maximum number of peers to share. * @param {string} options.root.fingerprint - The fingerprint of the modular network trust root. * @param {string} options.root.publicKeyArmored - The ASCII-armored modular network trust root public key. * @param {string} options.networkIdentifier - The name of the modular network this configuration is for. * @param {number} options.version - The version of the standard that this configuration is for. * @param {number} options.minSectorCoverage - The minimal coverage that each node must achieve on every sector. * @param {number} options.minHomeModCoverage - The minimal coverage that each node must achieve on its home mod. * @param {number} options.maxConcurrentRequests - The default maximum number of concurrent requests that can be made. * @param {number} options.defaultNodePriority - The default priority that a node receives. * @param {number} options.pingPriorityThreshold - The RTT above which nodes should receive higher than default priority. * @param {number} options.defaultRequestPriority - The default request queue priority. * @param {number} options.discoveryRequestPriority - The request queue priority of peer discovery requests. * @param {number} options.bootstrapRequestPriority - The request queue priority of bootstrapping requests. * @param {number} options.recoveryDelay - The minimum delay between attempts to recover the network. * @param {number} options.requestTimeout - The number of milliseconds for which a signed request is valid. * @param {number} options.maxPostLength - The maximum number of characters in a post. * @param {number} options.maxProfileLength - The maximum number of characters in a user profile. * @param {number} options.maxPostCount - The maximum number of user posts to retain. * @param {number} options.maxFollowCount - The maximum number of other users a user can follow. * @author Modulo (https://github.com/modulo) <[email protected]> * @since 1.0.0 * @async */ static new (options) { const config = new ModularConfiguration() if (arguments.length !== 1) throw new RangeError('ModularConfiguration.new expects exactly one argument') if (typeof options !== 'object' || options === null) throw new TypeError('Options must be an object') if (!Number.isInteger(options.requestTimeout)) throw new TypeError('Request timeout must be an integer') if (options.requestTimeout <= 0) throw new RangeError('Request timeout must be positive') config.requestTimeout = options.requestTimeout if (!Number.isInteger(options.maxPostLength)) throw new TypeError('Max post length must be an integer') if (options.maxPostLength <= 0) throw new RangeError('Max post length must be positive') config.maxPostLength = options.maxPostLength if (!Number.isInteger(options.maxProfileLength)) throw new TypeError('Max profile length must be an integer') if (options.maxProfileLength <= 0) throw new RangeError('Max profile length must be positive') config.maxProfileLength = options.maxProfileLength if (!Number.isInteger(options.maxPostCount)) throw new TypeError('Max post count must be an integer') if (options.maxPostCount <= 0) throw new RangeError('Max post count must be positive') config.maxPostCount = options.maxPostCount if (!Number.isInteger(options.maxFollowCount)) throw new TypeError('Max follow count must be an integer') if (options.maxFollowCount <= 0) throw new RangeError('Max follow count must be positive') config.maxFollowCount = options.maxFollowCount if (!Number.isInteger(options.recoveryDelay)) throw new TypeError('Recovery delay must be an integer') if (options.recoveryDelay < 0) throw new RangeError('Recovery delay cannot be negative') config.recoveryDelay = options.recoveryDelay if (!Number.isInteger(options.maxConcurrentRequests)) throw new TypeError('Max concurrent requests must be an integer') if (options.maxConcurrentRequests <= 0) throw new RangeError('Max concurrent requests must be positive') config.maxConcurrentRequests = options.maxConcurrentRequests if (!Number.isInteger(options.defaultNodePriority)) throw new TypeError('Default node priority must be an integer') config.defaultNodePriority = options.defaultNodePriority if (!Number.isInteger(options.pingPriorityThreshold)) throw new TypeError('Ping priority threshold must be an integer') config.pingPriorityThreshold = options.pingPriorityThreshold if (!Number.isInteger(options.defaultRequestPriority)) throw new TypeError('Default request priority must be an integer') config.defaultRequestPriority = options.defaultRequestPriority if (!Number.isInteger(options.discoveryRequestPriority)) throw new TypeError('Discovery request priority must be an integer') config.discoveryRequestPriority = options.discoveryRequestPriority if (!Number.isInteger(options.bootstrapRequestPriority)) throw new TypeError('Bootstrap request priority must be an integer') config.bootstrapRequestPriority = options.bootstrapRequestPriority config.dohEndpoints = [] options.dohEndpoints.forEach((endpoint) => { const urlRegex = /^(https:\/\/)[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,}(:[0-9]{1,5})?(\/.*)?$/g if (!urlRegex.test(endpoint)) throw new TypeError('Invalid DNS over HTTPS (DoH) endpoint: ' + endpoint) config.dohEndpoints.push(endpoint) }) config.dnsSeeds = [] options.dnsSeeds.forEach((seed) => { const hostRegex = /^([a-z0-9]+[.-])+([a-z0-9]+)$/g if (!hostRegex.test(seed)) throw new TypeError('Invalid DNS seed: ' + seed) config.dnsSeeds.push(seed) }) config.dnsServers = [] options.dnsServers.forEach((server) => { const dnsServerRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/g if (!dnsServerRegex.test(server)) throw new TypeError('Invalid DNS server: ' + server) config.dnsServers.push(server) }) config.staticSeeds = [] options.staticSeeds.forEach((seed) => { const endpointRegex = /^https:\/\/([a-z0-9]+[.-])+([a-z0-9]+)$/g if (!endpointRegex.test(seed)) throw new TypeError('Invalid static seed: ' + seed) config.staticSeeds.push(seed) }) config.httpsSeeds = [] options.httpsSeeds.forEach((seed) => { const urlRegex = /^(https:\/\/)[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,}(:[0-9]{1,5})?(\/.*)?$/g if (!urlRegex.test(seed)) throw new TypeError('Invalid HTTPS seed: ' + seed) config.httpsSeeds.push(seed) }) if (!Number.isInteger(options.networkModulus)) throw new TypeError('Network modulus must be an integer') if (options.networkModulus <= 0) throw new RangeError('Network modulus must be positive') if (Math.log2(options.networkModulus) % 1 !== 0) throw new TypeError('Network modulus must be a power of 2') config.networkModulus = options.networkModulus if (!Number.isInteger(options.sectorMapSize)) throw new TypeError('Sector map size must be an integer') if (options.sectorMapSize <= 0) throw new RangeError('Sector map size must be positive') if ((Math.log(options.sectorMapSize) / Math.log(4)) % 1 !== 0) throw new RangeError('Sector map size must be a power of 4') config.sectorMapSize = options.sectorMapSize if (!Number.isInteger(options.logoSectorMapSize)) throw new TypeError('Logo sector map size must be an integer') if (options.logoSectorMapSize <= 0) throw new RangeError('Logo sector map size must be positive') if ((Math.log(options.logoSectorMapSize) / Math.log(4)) % 1 !== 0) throw new RangeError('Logo sector map size must be a power of 4') config.logoSectorMapSize = options.logoSectorMapSize if (!Number.isInteger(options.iconSectorMapSize)) throw new TypeError('Icon sector map size must be an integer') if (options.iconSectorMapSize <= 0) throw new RangeError('Icon sector map size must be positive') if ((Math.log(options.iconSectorMapSize) / Math.log(4)) % 1 !== 0) throw new RangeError('Icon sector map size must be a power of 4') config.iconSectorMapSize = options.iconSectorMapSize if (!Number.isInteger(options.version)) throw new TypeError('Version must be an integer') if (options.version <= 0) throw new RangeError('Version must be positive') config.version = options.version if (typeof options.networkIdentifier !== 'string') throw new TypeError('Network identifier must be a string') if (options.networkIdentifier.length === 0) throw new RangeError('Network identifier cannot be empty') config.networkIdentifier = options.networkIdentifier if (!Number.isInteger(options.minSectorCoverage)) throw new TypeError('Minimum sector coverage must be an integer') if (options.minSectorCoverage < 0) throw new RangeError('Minimum sector coverage cannot be negative') config.minSectorCoverage = options.minSectorCoverage if (!Number.isInteger(options.minHomeModCoverage)) throw new TypeError('Minimum home mod coverage must be an integer') if (options.minHomeModCoverage < 0) throw new RangeError('Minimum home mod coverage cannot be negative') config.minHomeModCoverage = options.minHomeModCoverage if (!Number.isInteger(options.defaultIgnorePeriod)) throw new TypeError('Default ignore period must be an integer') if (options.defaultIgnorePeriod < 0) throw new RangeError('Default ignore period cannot be negative') config.defaultIgnorePeriod = options.defaultIgnorePeriod if (!Number.isInteger(options.maxPeerShare)) throw new TypeError('Maximum peer share must be an integer') if (options.maxPeerShare <= 0) throw new RangeError('Maximum peer share must be positive') config.maxPeerShare = options.maxPeerShare if (!Number.isInteger(options.queueTimeout)) throw new TypeError('Queue timeout must be an integer') if (options.queueTimeout <= 0) throw new RangeError('Queue timeout must be positive') config.queueTimeout = options.queueTimeout if (options instanceof ModularConfiguration) { if (options.root === null) throw new TypeError('Options.root must be specified') config.root = options.root return config } else { return new Promise((resolve, reject) => { ModularTrustRoot.new(options.root.fingerprint, options.root.publicKeyArmored).then((root) => { config.root = root resolve(config) }) }) } } }
JavaScript
class App extends Component { render() { return ( <div className="wrapper"> {/* <Navigation /> <Header title="John Disla" subtext="Front-end developer from Florida" featTitle="Featured" /> */} <ResponsiveNav navLinks={navLinks} /> <Router> <Home strict path="/" /> <Portfolio strict path="/portfolio" /> <About strict path="/about" /> <Contact strict path="/contact" /> </Router> </div> ); } }
JavaScript
class Stack { /** * Instances an object structured as stack. * @constructor * @param {object} items List of iterable items to be added to the stack. */ constructor(...items) { this.items = undefined items.forEach(item => { this.push(item) }) } /** * Adds a new object to the stack. * @param {object} item Object to add to the top of the stack. */ push(item) { item._next = this.items this.items = item } /** * Removes the object int he top of the stack. * @returns {object} */ pop() { let item = {} for (let prop in this.items) if (prop != '_next') item[prop] = this.items[prop] this.items = this.items._next return item } /** * Returns the quantity of items in the stack. * @returns {number} */ size() { if (!this.items) return 0; let aux = this.items let count = 1 while (aux._next !== undefined) { aux = aux._next count++ } return count } /** * Returns the value in the (index+1)th position in the stack. * @param {number} index Index of the item in the structure (starting with 0) * @returns {object} */ getByIndex(index) { index = this.size() - ++index let aux = this.items let count = 0 while (count < index) { aux = aux._next count++ } let item = {} for (let prop in aux) if (prop != '_next') item[prop] = aux[prop] return aux } }
JavaScript
class Point { constructor(x, y) { this.x = x; this.y = y; }; get pair() { const { x, y } = this; return [ x, y ] }; get quadrant() { const sx = Math.sign(this.x); const sy = Math.sign(this.y); if (sx == 1) { if (sy == 1) return 1; return 4; } else { if (sy == 1) return 2; return 3; } }; decimalCorrection(shift) { // Shift forward the number let x = String(this.x * 10 ** shift); let y = String(this.y * 10 ** shift); // If the coordinates have decimals, split them. If not, '0' let [ ix ] = this.x % 1 != 0? x.split('.') : [ x, '0' ]; let [ iy ] = this.y % 1 != 0? y.split('.') : [ y, '0' ]; // Unshift the number return new Point(Number(`${ix / 10 ** shift}`), Number(`${iy / 10 ** shift}`)) }; static distance(a, b) { // Distance between two points formula return ( Math.sqrt ( (a.x - b.x) ** 2 + (a.y - b.y) ** 2 ) ); }; }
JavaScript
class Random { /** * Create Random. * - algorithm : "XORSHIFT" / "MLS" / "FAST" * @param {number|KRandomSettings} [init_data] - Seed number for random number generation. If not specified, create from time. */ constructor(init_data) { let seed_number = undefined; let algorithm = "fast"; /** * Random Number Generator. * @private * @type {RandomBase} */ this.rand = null; /** * have `NextNextGaussian` * @private * @type {boolean} */ this.haveNextNextGaussian = false; /** * Normally distributed random numbers. * @private * @type {number} */ this.nextNextGaussian = 0.0; if(typeof init_data === "number") { seed_number = init_data; } else if(typeof init_data === "object") { if(init_data.seed !== undefined) { seed_number = init_data.seed; } if(init_data.algorithm !== undefined) { algorithm = init_data.algorithm; } } if(/fast|xorshift/i.test(algorithm)) { // XORSHIFT this.rand = new Xorshift(seed_number); } else { // MLS this.rand = new MaximumLengthSequence(seed_number); } } /** * Create Random. * - algorithm : "XORSHIFT" / "MLS" / "FAST" * @param {number|KRandomSettings} [init_data] - Seed number for random number generation. If not specified, create from time. */ static create(init_data) { return new Random(init_data); } /** * Initialize random seed. * @param {number} seed */ setSeed(seed) { this.rand.setSeed(seed); } /** * 32-bit random number. * @returns {number} - 32-bit random number * @private * @ignore */ genrand_int32() { return this.rand.genrand_int32(); } /** * Random number of specified bit length. * @param {number} bits - Required number of bits (up to 64 possible). * @returns {number} */ next(bits) { if(bits === 0) { return 0; } else if(bits === 32) { return this.genrand_int32(); } else if(bits < 32) { // 線形合同法ではないため // 上位のビットを使用しなくてもいいがJavaっぽく。 return (this.genrand_int32() >>> (32 - bits)); } // double型のため、52ビットまでは、整数として出力可能 else if(bits === 63) { // 正の値を出力するように調節 return (this.genrand_int32() * 0x80000000 + this.genrand_int32()); } else if(bits === 64) { return (this.genrand_int32() * 0x100000000 + this.genrand_int32()); } else if(bits < 63) { return (this.genrand_int32() * (1 << (bits - 32)) + (this.genrand_int32() >>> (64 - bits))); } } /** * 8-bit random number array of specified length. * @param {number} size - 必要な長さ * @returns {Array<number>} */ nextBytes(size) { const y = new Array(size); // 配列yに乱数を入れる // 8ビットのために、32ビット乱数を1回回すのはもったいない for(let i = 0;i < y.length; i++) { y[i] = this.next(8); } return y; } /** * 32-bit random number. * @param {number} [x] - 指定した値未満の数値を作る * @returns {number} */ nextInt(x) { if((x !== undefined) && (typeof x === "number")) { let r, y; do { r = this.genrand_int32() >>> 0; y = r % x; } while((r - y + x) > 0x100000000 ); return y; } return (this.next(32) & 0xFFFFFFFF); } /** * Random boolean. * @returns {boolean} */ nextBoolean() { // 1ビットのために、32ビット乱数を1回回すのはもったいない return (this.next(1) !== 0); } /** * Double type random number in the range of [0, 1). * @returns {number} */ nextDouble() { const a1 = this.next(26) * 0x8000000 + this.next(27); const a2 = 0x8000000 * 0x4000000; return (a1 / a2); } /** * Random numbers from a Gaussian distribution. * This random number is a distribution with an average value of 0 and a standard deviation of 1. * @returns {number} */ nextGaussian() { if(this.haveNextNextGaussian) { this.haveNextNextGaussian = false; return this.nextNextGaussian; } // Box-Muller法 const a = Math.sqrt( -2 * Math.log( this.nextDouble() ) ); const b = 2 * Math.PI * this.nextDouble(); const y = a * Math.sin(b); this.nextNextGaussian = a * Math.cos(b); this.haveNextNextGaussian = true; return y; } }
JavaScript
class Stories { init(root) { this.root = root this.open = false; this.paused = false; this.pausedTime = false; this.itemIndex = 0; this.progress = 0; this.itemCount = null; this.story = null; this.storyBullets = []; this.rafID this.addEvents() } log() { //console.log(this.root) } addEvents() { this.root.querySelector(".story__cover").addEventListener('click', e => { //story = this.root if(!this.root.classList.contains('is-open')) { this.initStory(this.root) this.root.classList.add('is-open'); } }) this.root.querySelector(".story__box").addEventListener('mousedown', e => { this.pauseStart(e) }) this.root.querySelector(".story__box").addEventListener('mouseup', e => { this.pauseEnd() }) this.root.querySelector(".story__box").addEventListener('touchstart', e => { this.pauseStart(e) }) this.root.querySelector(".story__box").addEventListener('touchend', e => { this.pauseEnd() }) this.root.querySelector(".story__prev").addEventListener('click', e => { if(!this.pausedTime) { if(this.itemIndex == 0) { this.progress = 0; } else { this.storyBullets[this.itemIndex].style.width = '0%'; this.itemIndex = this.itemIndex - 1 this.progress = 0; this.pushFront(this.itemIndex) } } this.pausedTime = false }) this.root.querySelector(".story__next").addEventListener('click', e => { if(!this.pausedTime) { if(this.itemIndex == this.itemCount - 1) { this.close() this.root.querySelector('.story__cover').style.border = "2px solid #d3d3d3"; } else { this.storyBullets[this.itemIndex].style.width = '100%'; this.progress = 0; this.itemIndex = this.itemIndex + 1 this.pushFront(this.itemIndex) } } this.pausedTime = false }) this.root.querySelector(".story__close").addEventListener('click', e => { this.close() }) } pauseStart(e) { this.paused = e; cancelAnimationFrame(this.rafID) let currentItem = this.root.querySelectorAll(".story__item")[this.itemIndex] if(currentItem.classList.contains('story__item--video')) { currentItem.pause(); } setTimeout(function(){ if(this.paused && this.paused == e) { this.pausedTime = true; this.root.querySelector('.story__bullets').classList.add('is-paused') this.root.querySelector('.story__close').classList.add('is-paused') } }, 500); } pauseEnd() { if(this.paused) { this.paused = false; let currentItem = this.root.querySelectorAll(".story__item")[this.itemIndex] if(currentItem.classList.contains('story__item--video')) { currentItem.play(); } animate(this) } this.root.querySelector('.story__bullets').classList.remove('is-paused') this.root.querySelector('.story__close').classList.remove('is-paused') } close() { this.root.classList.remove('is-open'); this.root.querySelector(".story__bullets").innerHTML = ""; this.itemIndex = 0; this.progress = 0; this.open = false //document.querySelector('.menu').style.display = "block"; } initStory() { this.open = true this.itemCount = this.root.querySelectorAll(".story__item").length; this.addBullets(this.itemCount) this.storyBullets = this.root.querySelectorAll('.story__bullet span') this.pushFront(this.itemIndex) animate(this) //document.querySelector('.menu').style.display = "none"; } addBullets(items) { var i; for (i = 0; i < items; i++) { var newNode = document.createElement('div'); newNode.className = 'story__bullet story__bullet--' + i; newNode.innerHTML ="<span></span>"; this.root.querySelector(".story__bullets").appendChild(newNode); } } pushFront(index) { let items = this.root.querySelectorAll(".story__item"); items.forEach(item => { item.classList.remove('is-front') if(item.classList.contains('story__item--video')) { item.pause(); } }) items[index].classList.add('is-front') if(items[index].classList.contains('story__item--video')) { items[index].currentTime = 0; items[index].play(); } } /*animate() { console.log(this.progress) if(this.open) { this.progress = this.progress + 0.5 console.log(this.storyBullets[this.itemIndex]) this.storyBullets[this.itemIndex].style.width = this.progress + '%'; } //continue / switch img if(this.progress >= 100) { if(this.itemIndex == this.itemCount - 1) { this.close() this.root.querySelector('.story__cover').style.border = "2px solid #d3d3d3"; } else { this.itemIndex = this.itemIndex + 1 this.pushFront(this.itemIndex) this.progress = 0 //console.log('again / next') this.rafID = requestAnimationFrame(this.animate) } } else if(this.open && !this.paused) { //console.log('again') //request animation Frame not workin properly let self = this; this.rafID = requestAnimationFrame(self.animate) //this.rafID = window.webkitRequestAnimationFrame(() => this.animate()); } }*/ }
JavaScript
class VerticalGeneSetScoresView extends PureComponent { handleHoverOut = () => { this.props.onHover(null) }; handleHover = (event) => { this.props.onHover(getPointData(event, this.props)) }; handleClick = (event) => { this.props.onClick(getPointData(event, this.props)) }; render() { let {cohortIndex, geneData, labelHeight, width, associatedData, maxValue, pathways, selectedPathway} = this.props if (!associatedData) { return <div>Loading Cohort {getLabelForIndex(cohortIndex)}</div> } let pathwayIndex = getSelectedGeneSetIndex(selectedPathway,pathways) // need a size and vertical start for each let inputPathways = geneData.pathways ? [...pathways.slice(0,pathwayIndex+1),...geneData.pathways,...pathways.slice(pathwayIndex+1)] : pathways let layout = inputPathways.map((p, index) => { return {start: index * labelHeight, size: labelHeight, // if none are open, then show all, if selected is open, then show that one and the genes active: !selectedPathway.open ? true : index >= pathwayIndex && index <= (pathwayIndex + geneData.pathways.length) , } }) const totalHeight = layout.length * labelHeight if (associatedData.length === 0) { return <div>Loading...</div> } return ( <div> <CanvasDrawing {...this.props} associatedData={associatedData} cohortIndex={cohortIndex} draw={DrawFunctions.drawGeneSetView} height={totalHeight} labelHeight={labelHeight} layout={layout} maxValue={maxValue} onClick={this.handleClick} onHover={this.handleHover} onMouseOut={this.handleHoverOut} width={width} /> </div> ) } }
JavaScript
class PlasmaNode { constructor (options) { options = Object.assign({}, defaultOptions, options) this.core = new PlasmaCore(options) this.core.registerService(RPCServerService, { port: options.port }) this.client = new Plasma( new Plasma.providers.HttpProvider(`http://localhost:${options.port}`) ) } /** * Starts the node. */ async start () { this.started = true return this.core.start() } /** * Stops the node. */ async stop () { this.started = false return this.core.stop() } }
JavaScript
class MagazineColumnsEdit extends Component { render() { const { className, } = this.props; const blockClasses = classnames( className, 'tz-magazine-block' ); return ( <div className={ blockClasses }> <div className="tz-magazine-columns"> <InnerBlocks template={ [ [ 'themezee-magazine-blocks/column', {} ], [ 'themezee-magazine-blocks/column', {} ], ] } templateLock={ true } allowedBlocks={ [ 'themezee-magazine-blocks/column' ] } /> </div> </div> ); } }
JavaScript
class point{ constructor(x, y) { this.x = x; this.y = y; } static midpoint(a,b){ let newX= (a.x+b.x)/2; let newY= (a.y+b.y)/2; return new point(newX,newY); } toString(){ return("("+this.x+","+this.y+")"); } }
JavaScript
class LightPipeline extends Phaser.Renderer.WebGL.Pipelines.ForwardDiffuseLightPipeline { /** * @constructor * @override */ constructor( config ) { super( config ); LIGHT_COUNT = config.maxLights; /* eslint-disable */ config.fragShader = [ '#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS', '', 'precision mediump float;', '', 'struct Light', '{', ' vec2 position;', ' vec3 color;', ' float intensity;', ' float radius;', ' float hWidth;', ' float hHeight;', '};', '', 'const int kMaxLights = %LIGHT_COUNT%;', '', 'uniform vec4 uCamera; /* x, y, rotation, zoom */', 'uniform vec2 uResolution;', 'uniform sampler2D uMainSampler;', 'uniform sampler2D uNormSampler;', 'uniform vec3 uAmbientLightColor;', 'uniform Light uLights[kMaxLights];', '', 'varying vec2 outTexCoord;', 'varying vec4 outTint;', '', 'void main()', '{', ' vec3 finalColor = vec3(0.0, 0.0, 0.0);', ' vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);', ' vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;', ' vec3 normal = normalize(vec3(normalMap * 2.0 - 1.0));', ' vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;', '', ' for (int index = 0; index < kMaxLights; ++index)', ' {', ' Light light = uLights[index];', ' vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.2);', ' vec3 lightNormal = normalize(lightDir);', ' float distToSurf = length(lightDir) * uCamera.w;', ' float diffuseFactor = max(dot(normal, lightNormal), 0.0);', ' float radius = (light.radius / res.x * uCamera.w) * uCamera.w;', ' float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);', ' vec3 diffuse = light.color * diffuseFactor;', ' finalColor += (attenuation * diffuse) * light.intensity;', ' }', '', ' vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);', ' gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);', '', '}', '' ].join( '\n' ).replace( '%LIGHT_COUNT%', LIGHT_COUNT.toString() ); /* eslint-enable */ TextureTintPipeline.call( this, config ); } /** * @override */ onBind( gameObject ) { TextureTintPipeline.prototype.onBind.call( this ); const renderer = this.renderer; const program = this.program; this.mvpUpdate(); renderer.setInt1( program, 'uNormSampler', 1 ); renderer.setFloat2( program, 'uResolution', this.width, this.height ); if ( gameObject ) { this.setNormalMap( gameObject ); } return this; } /** * @override */ onRender( scene, camera ) { /** * Whether or not the pipeline is active * @type {boolean} */ this.active = false; const lightManager = scene.sys.lights; if ( !lightManager || lightManager.lights.length <= 0 || !lightManager.active ) { // Passthru return this; } const lights = lightManager.cull( camera ); const lightCount = Math.min( lights.length, LIGHT_COUNT ); if ( lightCount === 0 ) { return this; } this.active = true; const renderer = this.renderer; const program = this.program; const cameraMatrix = camera.matrix; const point = { x: 0, y: 0 }; const height = renderer.height; let index; for ( index = 0; index < LIGHT_COUNT; ++index ) { // Reset lights renderer.setFloat1( program, 'uLights[' + index + '].radius', 0 ); } renderer.setFloat4( program, 'uCamera', camera.x, camera.y, camera.rotation, camera.zoom ); renderer.setFloat3( program, 'uAmbientLightColor', lightManager.ambientColor.r, lightManager.ambientColor.g, lightManager.ambientColor.b ); for ( index = 0; index < lightCount; ++index ) { const light = lights[ index ]; const lightName = 'uLights[' + index + '].'; cameraMatrix.transformPoint( light.x, light.y, point ); renderer.setFloat2( program, lightName + 'position', point.x - ( camera.scrollX * light.scrollFactorX * camera.zoom ), height - ( point.y - ( camera.scrollY * light.scrollFactorY ) * camera.zoom ) ); renderer.setFloat3( program, lightName + 'color', light.r, light.g, light.b ); renderer.setFloat1( program, lightName + 'intensity', light.intensity ); renderer.setFloat1( program, lightName + 'radius', light.radius ); if ( light.hWidth && light.hHeight ) { renderer.setFloat1( program, lightName + 'hWidth', light.hWidth ); renderer.setFloat1( program, lightName + 'hHeight', light.hHeight ); } } return this; } /** * @override */ batchTexture( gameObject, texture, textureWidth, textureHeight, srcX, srcY, srcWidth, srcHeight, scaleX, scaleY, rotation, flipX, flipY, scrollFactorX, scrollFactorY, displayOriginX, displayOriginY, frameX, frameY, frameWidth, frameHeight, tintTL, tintTR, tintBL, tintBR, tintEffect, uOffset, vOffset, camera, parentTransformMatrix ) { if ( !this.active ) { return; } this.renderer.setPipeline( this ); let normalTexture; if ( gameObject.displayTexture ) { normalTexture = gameObject.displayTexture .dataSource[ gameObject.displayFrame.sourceIndex ]; } else if ( gameObject.texture ) { normalTexture = gameObject.texture .dataSource[ gameObject.frame.sourceIndex ]; } else if ( gameObject.tileset ) { // NOTE: PATCH HERE normalTexture = gameObject.tileset[ 0 ].image.dataSource[ 0 ]; } if ( !normalTexture ) { console.warn( 'Normal map missing or invalid' ); return; } this.setTexture2D( normalTexture.glTexture, 1 ); const camMatrix = this._tempMatrix1; const spriteMatrix = this._tempMatrix2; const calcMatrix = this._tempMatrix3; let u0 = ( frameX / textureWidth ) + uOffset; let v0 = ( frameY / textureHeight ) + vOffset; let u1 = ( frameX + frameWidth ) / textureWidth + uOffset; let v1 = ( frameY + frameHeight ) / textureHeight + vOffset; let width = srcWidth; let height = srcHeight; // var x = -displayOriginX + frameX; // var y = -displayOriginY + frameY; let x = -displayOriginX; let y = -displayOriginY; if ( gameObject.isCropped ) { const crop = gameObject._crop; width = crop.width; height = crop.height; srcWidth = crop.width; srcHeight = crop.height; frameX = crop.x; frameY = crop.y; let ox = frameX; let oy = frameY; if ( flipX ) { ox = ( frameWidth - crop.x - crop.width ); } if ( flipY && !texture.isRenderTexture ) { oy = ( frameHeight - crop.y - crop.height ); } u0 = ( ox / textureWidth ) + uOffset; v0 = ( oy / textureHeight ) + vOffset; u1 = ( ox + crop.width ) / textureWidth + uOffset; v1 = ( oy + crop.height ) / textureHeight + vOffset; x = -displayOriginX + frameX; y = -displayOriginY + frameY; } // Invert the flipY if this is a RenderTexture flipY = flipY ^ ( texture.isRenderTexture ? 1 : 0 ); if ( flipX ) { width *= -1; x += srcWidth; } if ( flipY ) { height *= -1; y += srcHeight; } const xw = x + width; const yh = y + height; spriteMatrix.applyITRS( srcX, srcY, rotation, scaleX, scaleY ); camMatrix.copyFrom( camera.matrix ); if ( parentTransformMatrix ) { // Multiply the camera by the parent matrix camMatrix.multiplyWithOffset( parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY ); // Undo the camera scroll spriteMatrix.e = srcX; spriteMatrix.f = srcY; // Multiply by the Sprite matrix, store result in calcMatrix camMatrix.multiply( spriteMatrix, calcMatrix ); } else { spriteMatrix.e -= camera.scrollX * scrollFactorX; spriteMatrix.f -= camera.scrollY * scrollFactorY; // Multiply by the Sprite matrix, store result in calcMatrix camMatrix.multiply( spriteMatrix, calcMatrix ); } let tx0 = calcMatrix.getX( x, y ); let ty0 = calcMatrix.getY( x, y ); let tx1 = calcMatrix.getX( x, yh ); let ty1 = calcMatrix.getY( x, yh ); let tx2 = calcMatrix.getX( xw, yh ); let ty2 = calcMatrix.getY( xw, yh ); let tx3 = calcMatrix.getX( xw, y ); let ty3 = calcMatrix.getY( xw, y ); if ( camera.roundPixels ) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0; } this.setTexture2D( texture, 0 ); this.batchQuad( tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect ); } }
JavaScript
class ModalProvider extends Component { constructor(props) { super(props); const { cookies } = props; this.state = { visited: cookies.get("visited"), handleVisitedFlag: () => cookies.set("visited", true, { path: "/" }), showModal: () => this.setState({ visited: false }), hideModal: () => this.setState({ visited: true }) }; } render() { return <ModalContext.Provider value={this.state}>{this.props.children}</ModalContext.Provider>; } }
JavaScript
class EmailTaskVM { /** * Constructs a new <code>EmailTaskVM</code>. * @alias module:models/EmailTaskVM * @implements module:models/TransportTaskBaseVM */ constructor() { TransportTaskBaseVM.initialize(this); EmailTaskVM.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>EmailTaskVM</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:models/EmailTaskVM} obj Optional instance to populate. * @return {module:models/EmailTaskVM} The populated <code>EmailTaskVM</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new EmailTaskVM(); TransportTaskBaseVM.constructFromObject(data, obj); if (data.hasOwnProperty('body')) { obj['body'] = ApiClient.convertToType(data['body'], 'String'); } if (data.hasOwnProperty('isBodyHtml')) { obj['isBodyHtml'] = ApiClient.convertToType(data['isBodyHtml'], 'Boolean'); } if (data.hasOwnProperty('subject')) { obj['subject'] = ApiClient.convertToType(data['subject'], 'String'); } if (data.hasOwnProperty('to')) { obj['to'] = ApiClient.convertToType(data['to'], ['String']); } if (data.hasOwnProperty('from')) { obj['from'] = ApiClient.convertToType(data['from'], 'String'); } if (data.hasOwnProperty('username')) { obj['username'] = ApiClient.convertToType(data['username'], 'String'); } if (data.hasOwnProperty('server')) { obj['server'] = ApiClient.convertToType(data['server'], 'String'); } if (data.hasOwnProperty('port')) { obj['port'] = ApiClient.convertToType(data['port'], 'Number'); } if (data.hasOwnProperty('enableSsl')) { obj['enableSsl'] = ApiClient.convertToType(data['enableSsl'], 'Boolean'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('subscriptionId')) { obj['subscriptionId'] = ApiClient.convertToType(data['subscriptionId'], 'String'); } if (data.hasOwnProperty('type')) { obj['type'] = TaskType.constructFromObject(data['type']); } } return obj; } }
JavaScript
class PromiseMock extends Mock { /** * @param {Object} instance The object instance on which the method will be * mocked. * @param {String} methodName The name of the method on the object that * needs to be mocked. If the specified method does not exist, a * placeholder method will be injected into the instance which will * then be mocked. */ constructor(instance, methodName) { let callIndex = 0; super(instance, methodName, () => { const wrapper = this._getPromiseWrapper(callIndex); callIndex++; return wrapper.promise; }); this._wrappers = []; } /** * Returns a wrapper that contains a reference to a promise object, and the * reject and resolve methods of the promise object. This can be used to * reject or resolve the promise from outside the mock. * * If a wrapper for a specific invocation has already been created, it will * be returned, if not a new wrapper will be created for the specified * index. * * @private * @param {Number} callIndex The invocation index for which to get the * wrapper. * * @return {Object} A simple object with references to the promise, reject * and resolve methods. */ _getPromiseWrapper(callIndex) { let wrapper = this._wrappers[callIndex]; if (!wrapper) { wrapper = {}; wrapper.promise = new Promise((resolve, reject) => { wrapper.resolve = resolve; wrapper.reject = reject; }); this._wrappers[callIndex] = wrapper; } return wrapper; } /** * Returns the promise associated with a specific invocation of the mock, * identified by the call index. This value could reference a future * invocation (meaning that the specific invocation of the mock has not yet * occurred). * * Promises for all completed invocations of the mock can be obtained by * inspecting the [responses]{@link Mock#responses} method. * * <p> * The value of this method is that actions can be be assigned to the * <code>then(...)</code> callback of the mock even before the mock has * been invoked. The use of the [responses]{@link Mock#responses} array * is retroactive in nature, and cannot be accessed until after the method * has been invoked, which does not always work in asynchronous scenarios. * </p> * * @param {Number} [callIndex=0] The index of the invocation, with the * first invocation starting at index 0. Defaults to 0. * * @return {Promise} The promise associated with the specified call index. */ promise(callIndex) { if (typeof callIndex !== 'number' || callIndex <= 0) { callIndex = 0; } return this._getPromiseWrapper(callIndex).promise; } /** * Rejects the promise associated with a specific invocation of the mock, * identified by the call index. This value could reference a future * invocation (meaning that the specific invocation of the mock has not yet * occurred). * * <p> * The value of this method is that a rejection can be set on a specific * invocation prior to it actually occurring. * </p> * * @param {*} [error=undefined] The rejection response for the promise. * This is typically an error, but can be any value. * * @param {Number} [callIndex=0] The index of the invocation, with the * first invocation starting at index 0. Defaults to 0. * * @return {Promise} The promise associated with the specified call index. */ reject(error, callIndex) { if (typeof callIndex !== 'number' || callIndex <= 0) { callIndex = 0; } const wrapper = this._getPromiseWrapper(callIndex); wrapper.reject(error); return wrapper.promise; } /** * Resolves the promise associated with a specific invocation of the mock, * identified by the call index. This value could reference a future * invocation (meaning that the specific invocation of the mock has not yet * occurred). * * <p> * The value of this method is that a resolution can be set on a specific * invocation prior to it actually occurring. * </p> * * @param {*} [response=undefined] The resolution response for the promise. * This is typically an error, but can be any value. * * @param {Number} [callIndex=0] The index of the invocation, with the * first invocation starting at index 0. Defaults to 0. * * @return {Promise} The promise associated with the specified call index. */ resolve(response, callIndex) { if (typeof callIndex !== 'number' || callIndex <= 0) { callIndex = 0; } const wrapper = this._getPromiseWrapper(callIndex); wrapper.resolve(response); return wrapper.promise; } }
JavaScript
class OVH { #app; #consumer; #url; constructor({ key, secret }, consumer) { this.#app = { key, secret }; this.#consumer = consumer; this.#url = "https://api.us.ovhcloud.com/1.0"; } /* Get the current Unix epoch time. */ static get now() { return Math.round(Date.now() / 1000); } /* Get the client's consumer token. */ get consumer() { return this.#consumer; } /* Set the client's consumer token. */ set consumer(token) { this.#consumer = token; } /** Make a Fetch request to the specified endpoint of the OVH API. * @memberOf OVH * * @async * @method request * * @param {string} endpoint - The OVH API endpoint to request. * @param {string} method - The HTTP method of the request. * @param {object} [body] - A JavaScript object to be converted to JSON, and sent as the request body. * * @return {object} The HTTP response returned by the API. */ async request(endpoint, method, body) { const resource = this.#url + endpoint; const time = this.now; const headers = { "Content-Type": "application/json", "X-Ovh-Application": this.#app.key, "X-Ovh-Timestamp": time }; body = body ? JSON.stringify(body) : ""; if (this.#consumer) { headers["X-Ovh-Consumer"] = this.#consumer, headers["X-Ovh-Signature"] = "$1$" + sha1([ this.#app.secret, this.#consumer, method, resource, body, time ].join("+"), "utf8", "hex"); } const response = await fetch(resource, { method, headers, body }); return [ response.ok, await response.json() ]; } /** Make a POST request. * @memberOf OVH * * @async * @method post * * @param {string} endpoint - The OVH API endpoint to request. * @param {object} [body] - A JavaScript object to be converted to JSON, and sent as the request body. * * @return {object} The HTTP response returned by the API. */ async post(path, body) { return await this.request(path, "POST", body); } /** Make a GET request. * @memberOf OVH * * @async * @method get * * @param {string} endpoint - The OVH API endpoint to request. * @param {object} [body] - A JavaScript object to be converted to JSON, and sent as the request body. * * @return {object} The HTTP response returned by the API. */ async get(path, body) { return await this.request(path, "GET", body); } /** Make a PUT request. * @memberOf OVH * * @async * @method put * * @param {string} endpoint - The OVH API endpoint to request. * @param {object} [body] - A JavaScript object to be converted to JSON, and sent as the request body. * * @return {object} The HTTP response returned by the API. */ async put(path, body) { return await this.request(path, "PUT", body); } /** Make a DELETE request. * @memberOf OVH * * @async * @method del * * @param {string} endpoint - The OVH API endpoint to request. * @param {object} [body] - A JavaScript object to be converted to JSON, and sent as the request body. * * @return {object} The HTTP response returned by the API. */ async del(path, body) { return await this.request(path, "DELETE", body); } }
JavaScript
class CompletionConnector extends coreutils_1.DataConnector { /** * Create a new connector for completion requests. * * @param options - The instatiation options for the connector. */ constructor(options) { super(); this._kernel = new kernelconnector_1.KernelConnector(options); this._context = new contextconnector_1.ContextConnector(options); } /** * Fetch completion requests. * * @param request - The completion request text and details. */ fetch(request) { return Promise.all([ this._kernel.fetch(request), this._context.fetch(request) ]).then(([kernelReply, contextReply]) => { return Private.mergeReplies(kernelReply, contextReply); }); } }
JavaScript
class XwDoms { /** * Show the target element * @param {HTMLElement} element Element to be shown * @param {string} [displayType] Display type to be shown, default to 'block' */ show(element, displayType) { element.style.display = xw.defaultable(displayType, 'block'); } /** * Hide the target element * @param {HTMLElement} element Element to be shown */ hide(element) { element.style.display = 'none'; } /** * If target element is shown * @param {HTMLElement} element Target element * @return {boolean} */ isShown(element) { return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length); } /** * Run animation * @param {HTMLElement} element Element to be animated * @param {object} propSpecs CSS properties to be animated * @param {object} [options] Animation options * @return {Promise<void>} */ async animate(element, propSpecs, options) { // Fallback to CSS animation solutions if element.animate() not found if (typeof element.animate !== 'function') { return _cssAnimate(element, propSpecs, options); } // Get variables const _element = xw.requires(element); const _propSpecs = xw.requires(propSpecs); const _options = xw.defaultable(options, {}); return new Promise((resolve, reject) => { // Initialize states and keyframes const fromState = {}; const toState = {}; for (const prop in _propSpecs) { const valueSpec = _propSpecs[prop]; const fromValue = valueSpec[0]; const toValue = valueSpec[1]; fromState[prop] = fromValue; toState[prop] = toValue; } const keyframes = [ fromState, toState, ]; // Setup options const outOptions = {}; const translateOptions = (inKey, outKey) => { const _inKey = xw.requires(inKey); const _outKey = xw.defaultable(outKey, _inKey); const _value = xw.defaultable(_options[_inKey], null); if (_value === null) return; outOptions[_outKey] = _value; }; translateOptions('delay'); translateOptions('direction'); translateOptions('duration'); translateOptions('easing'); translateOptions('iterations'); // Start animation const anim = _element.animate(keyframes, outOptions); anim.oncancel = (ev) => { reject(new Error(_l('Animation cancelled'))); }; anim.onfinish = (ev) => { for (const prop in toState) { _element.style[prop] = toState[prop]; } resolve(); }; // Handle pre-animation for (const prop in fromState) { _element.style[prop] = fromState[prop]; } const _optionBeforeAnimation = xw.defaultable(_options.beforeAnimation, null); if (_optionBeforeAnimation !== null) _optionBeforeAnimation(); // Run the animation anim.play(); }); } /** * Bind an element's click action to cause clipboard interaction * @param {HTMLElement} element Element to be binded * @param {object} [options] Clipboard options * @param {HTMLElement} [options.target] Target element to be copied from * @param {string} [options.text] Text to be copied * @param {function(Event):void} [options.onClipboard] Handler for clipboard action */ clickToClipboard(element, options) { const _element = xw.requires(element); const _options = xw.defaultable(options, {}); const _optionsOnClipboard = xw.defaultable(_options.onClipboard); const _data = {}; // Text provider if (xw.isDefined(_options.text)) { _data.text = (trigger) => { return _options.text; } } // Target provider if (xw.isDefined(_options.target)) { _data.target = (trigger) => { return _options.target; } } // Create object const cb = new ClipboardJS(_element, _data); // Bind event handlers const _onClipboard = (isSuccess, ev) => { if (_optionsOnClipboard === null) return; const newEv = new CustomEvent('clipboard'); newEv.isSuccess = isSuccess; newEv.srcEv = ev; _optionsOnClipboard(newEv); }; cb.on('success', (ev) => { _onClipboard(true, ev); }); cb.on('error', (ev) => { _onClipboard(false, ev); }); } }
JavaScript
class Movable extends Component { constructor(owner) { super(owner); this.position = {x:0,y:0}; this.speed = {x:0,y:0}; this.acceleration = {x:0,y:0}; } /** * translales the object to the given position * @param {int} x - x position to move. * @param {int} y - y position to move. * @returns {} */ translate(x,y){ this.position = {x:x,y:y}; return this; } /** * moves the object by the given amount * @param {int} x - x amount to move. * @param {int} y - y amount to move. */ move(x,y){ this.position.x += x; this.position.y += y; return this; } /** * sets the velocity of the object * @param {int} x - horizontal velocity component. * @param {int} y- vertical velocity component. * @returns {Sprite} itself */ velocity(x,y){ this.speed = {x:x,y:y}; return this; } /** * increases the acceleration of the object * @param {int} x - horizontal acceleration component. * @param {int} y- vertical acceleration component. * @returns {Sprite} itself */ accelerate(x,y){ this.acceleration.x += x; this.acceleration.y += y; return this; } /** * applies a force to the object * @param {int} x - horizontal force component. * @param {int} y- vertical force component. * @returns {Sprite} itself */ force(x,y){ this.acceleration.x += (x/(this.mass || 1)); this.acceleration.y += (y/(this.mass || 1)); return this; } /* * defines how the movable component change state on one update */ process(){ this.velocity(this.speed.x + this.acceleration.x, this.speed.y + this.acceleration.y ); this.move(this.speed.x,this.speed.y); } }
JavaScript
class Home extends PureComponent { state = { email: '', password: '', doesntMatch: false, noUser: false, checkBoxe: false, zone: '', loading: false }; // componentWillReceiveProps (nextProps) { // const changedProps = _.reduce(this.props, function (result, value, key) { // return _.isEqual(value, nextProps[key]) // ? result // : result.concat(key) // }, []) // console.log('changedProps: ', changedProps) // } // shouldComponentUpdate=(nextProps, nextState) =>{ // console.log(nextProps,nextState) // return false; // } componentDidMount = () => { if (localStorage.getItem('UserEmail', this.state.email) !== null) { this.setState({ email: localStorage.getItem('UserEmail'), }); }; }; toggleCheck = () => { if (this.state.checkBoxe === false) { this.setState({ checkBoxe: true }); } else if (this.state.checkBoxe === true) { this.setState({ checkBoxe: false }); }; }; onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); }; onSubmit = async () => { this.setState({ loading: true, noUser: false, doesntMatch: false }); if (this.state.checkBoxe === true) { localStorage.setItem('UserEmail', this.state.email) }; let lowerCaseEmail = this.state.email.toLowerCase() let res = await usersAPI.signIn(lowerCaseEmail, this.state.password) const self = this; if (res.data === 'noMatch') { self.setState({ doesntMatch: true, noUser: false, loading: false }); } else if (res.data === 'noUser') { self.setState({ noUser: true, doesntMatch: false, loading: false }); } else { console.log("Authenticated user: " + res.data); localStorage.setItem('auth', res.data) window.location = '/dashboard'; }; }; componentDidCatch = (error, info) => { console.log('hi i am catching Sign In'); console.log(error, 'hi im errors at sign in'); console.log(info, 'hi im info at sign in'); }; render() { return ( <div> <h4>Master User</h4> <p> email [email protected]</p> <p> password projectgreen</p> <p> User Id: 538f6eb2-f522-4cbd-9a3a-dc4e9433ec5d</p> <br /> <h4>David's User Id</h4> <p>9b4c41ef-9e1d-492b-acce-a9bd9eca46a9</p> <br /> <h4>Alex's User Id</h4> <p>16abfe25-8869-4693-977f-49dd48e74815</p> <h4>Lee's User Id </h4> <p>05e64ad4-d91b-4295-87a0-0220133e1c7a</p> todo build admin screen <div id='home'> <Grid container spacing={24}> <Grid item md={12}> <img src={Images.companyLogo} id="logo" alt='logo' /> </Grid> <Grid item md={12}> <TextField autoFocus margin="dense" label="Username" id="email" name='email' type="email" value={this.state.email} onChange={this.onChange} onKeyPress={(ev) => { if (ev.key === 'Enter') { this.onSubmit(); ev.preventDefault(); }; }} /> </Grid> <Grid item md={12}> <TextField autoFocus margin="dense" label="Password" name='password' type="password" value={this.state.password} onChange={this.onChange} onKeyPress={(ev) => { if (ev.key === 'Enter') { this.onSubmit(); ev.preventDefault(); }; }} /> </Grid> <Grid item md={6} > <div id="remember-me"> <input onClick={this.toggleCheck} type="checkbox" onKeyPress={(ev) => { if (ev.key === 'Enter') { this.onSubmit(); ev.preventDefault(); }; }} /> <span>Remember Me</span> </div> </Grid> <Grid item md={6}> <a href="/password/reset" id="forgot-pass">Forgot Password</a> </Grid> <Grid item md={12}> {this.state.loading ? <img src={Images.loadingGif} alt='loading' width={30} height={40} /> : <Button variant="contained" onClick={this.onSubmit} color="primary" > Log in </Button>} {this.state.noUser && <p>There is no account associated with that email</p>} {this.state.doesntMatch && <p>Email or password dont match. Please try again.</p> } </Grid> </Grid> </div> </div> ); }; }
JavaScript
class NetCordaCoreTransactionsSignedTransaction { /** * Constructs a new <code>NetCordaCoreTransactionsSignedTransaction</code>. * @alias module:io.generated.model/NetCordaCoreTransactionsSignedTransaction * @param sigs {Array.<module:io.generated.model/NetCordaCoreCryptoTransactionSignature>} * @param id {String} Base 58 Encoded Secure Hash * @param inputs {Array.<module:io.generated.model/NetCordaCoreContractsStateRef>} * @param references {Array.<module:io.generated.model/NetCordaCoreContractsStateRef>} * @param notaryChangeTransaction {Boolean} * @param missingSigners {Array.<String>} */ constructor(sigs, id, inputs, references, notaryChangeTransaction, missingSigners) { NetCordaCoreTransactionsSignedTransaction.initialize(this, sigs, id, inputs, references, notaryChangeTransaction, missingSigners); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, sigs, id, inputs, references, notaryChangeTransaction, missingSigners) { obj['sigs'] = sigs; obj['id'] = id; obj['inputs'] = inputs; obj['references'] = references; obj['notaryChangeTransaction'] = notaryChangeTransaction; obj['missingSigners'] = missingSigners; } /** * Constructs a <code>NetCordaCoreTransactionsSignedTransaction</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:io.generated.model/NetCordaCoreTransactionsSignedTransaction} obj Optional instance to populate. * @return {module:io.generated.model/NetCordaCoreTransactionsSignedTransaction} The populated <code>NetCordaCoreTransactionsSignedTransaction</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new NetCordaCoreTransactionsSignedTransaction(); if (data.hasOwnProperty('txBits')) { obj['txBits'] = NetCordaCoreSerializationSerializedBytesNetCordaCoreTransactionsCoreTransaction.constructFromObject(data['txBits']); } if (data.hasOwnProperty('sigs')) { obj['sigs'] = ApiClient.convertToType(data['sigs'], [NetCordaCoreCryptoTransactionSignature]); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('tx')) { obj['tx'] = NetCordaCoreTransactionsWireTransaction.constructFromObject(data['tx']); } if (data.hasOwnProperty('coreTransaction')) { obj['coreTransaction'] = NetCordaCoreTransactionsCoreTransaction.constructFromObject(data['coreTransaction']); } if (data.hasOwnProperty('inputs')) { obj['inputs'] = ApiClient.convertToType(data['inputs'], [NetCordaCoreContractsStateRef]); } if (data.hasOwnProperty('references')) { obj['references'] = ApiClient.convertToType(data['references'], [NetCordaCoreContractsStateRef]); } if (data.hasOwnProperty('notary')) { obj['notary'] = NetCordaCoreIdentityParty.constructFromObject(data['notary']); } if (data.hasOwnProperty('networkParametersHash')) { obj['networkParametersHash'] = ApiClient.convertToType(data['networkParametersHash'], 'String'); } if (data.hasOwnProperty('notaryChangeTransaction')) { obj['notaryChangeTransaction'] = ApiClient.convertToType(data['notaryChangeTransaction'], 'Boolean'); } if (data.hasOwnProperty('missingSigners')) { obj['missingSigners'] = ApiClient.convertToType(data['missingSigners'], ['String']); } } return obj; } }
JavaScript
class AnimationCore { /** * Create new Animation Core element. * * @class * @param {Pixel.AnimatedSprite} parent - Parent of Animation Core. */ constructor(parent) { /** * Stores parent of this core. * * @private * @name Pixel.EXPORTS.AnimationCore#parent * @type {Pixel.AnimatedSprite} */ this.parent = parent; /** * Current frame this core is on. * * @name Pixel.EXPORTS.AnimationCore#frame * @type {number} */ this.frame = 0; /** * Stores spritesheet. * * @name Pixel.EXPORTS.AnimationCore#cache * @type {Pixel.Sprite} */ this.cache = []; /** * All tracks created that can be played. * * @name Pixel.EXPORTS.AnimationCore#tracks * @type {object} */ this.tracks = {}; /** * Current track being played. * * @name Pixel.EXPORTS.AnimationCore#current * @type {boolean|Pixel.Sprite[]} */ this.current = false; /** * Current name of the track being played. * * @name Pixel.EXPORTS.AnimationCore#track * @type {string} */ this.track = ""; } /** * Stops the current animation and plays 1 item in the cache on continous loop. * * @function Pixel.EXPORTS.AnimationCore#stop * @param {number} num - ID of image being played continously. */ stop(num) { let dummy = new Sprite({ renderable: true, image: this.cache[num - 1].image }); this.current = [dummy]; this.frame = 0; } /** * Plays an animation saved in the cache. * * @function Pixel.EXPORTS.AnimationCore#play * @param {string} name - Name of track to be played. */ play(name) { if (this.track !== name) {this.frame = 0;} this.current = this.tracks[name]; this.track = name; } /** * Add track when cached spritesheet is defined through a json file. * * @function Pixel.EXPORTS.AnimationCore#add * @param {string} name - Name of track. * @param {string} prefix - Name every item in track begins with. * @param {number} [delay=0] - How many items to skip before they are added. */ add(name, prefix, delay = 0) { var cur_delay = delay; var frames = this.cache; var storage = []; for (var frame in frames) { var fram = frames[frame]; if (fram.name.startsWith(prefix) && cur_delay === 0) { var dummy = new Sprite({renderable: true, image: fram.image}); storage.push(dummy); } else if (cur_delay > 0) {cur_delay--;} } if (storage.length > 0) {this.tracks[name] = storage;} } /** * Create a new track if there is no json file. * * @function Pixel.EXPORTS.AnimationCore#create * @param {object} data - Data for the creation. * @param {string} data.name - Name of track. * @param {number[]} data.positions - Array of start and end id of animation. */ create(data) { let name = data.name; let start = data.positions[0]; let end = data.positions[1]; let frames = this.cache; let storage = []; for (var i = start - 1; i < end; i++) { var dummy = new Sprite({renderable: true, image: frames[i].image}); storage.push(dummy); } this.tracks[name] = storage; } /** * Add multiple animation tracks at once (with json file). * * @function Pixel.EXPORTS.AnimationCore#multiAdd * @param {object[]} groups - Data of every group to be added. * * @example * // Example of creating an animation, where sprite is Pixel.AnimatedSprite * data = { name: 'name', filter: 'prefix', offset: 'delay' } * sprite.animation.multiAdd([data]) // Adds just one, but you get the idea */ multiAdd(groups) { for (var g in groups) { let group = groups[g]; let name = group.name; let prefix = group.filter; let delay = group.offset; this.add(name, prefix, delay); } } }
JavaScript
class App { /** * Create a new web application * * @param {object} _config - Application config */ constructor(_config = config) { this.config = _config; /* Setup database */ this.database = new Database(config.database); this.database.migrateUp(); this.database.seed(); /* Setup express. Add middlewares/… here */ this.express = express(); /* Setup passport authentication. Add strategies/… here */ passport.use(new AnonymousStrategy()); passport.use(new BearerStrategy((token, done) => { try { const decodedToken = jwt.verify(token, this.config.secret); this.database.User .findById(decodedToken.userId) .then(done.bind(this, null)); } catch (e) { done(e); } })); /* Attach HTTP routes */ routes(this); } /** * Start listening via HTTP */ listen() { this.express.listen(this.config.listen.port, this.config.listen.hostname, () => console.log(`Now listening on ${this.config.listen.hostname}:${this.config.listen.port}`), ); } }
JavaScript
class Alerts extends Component { state = { showFilters: false, isEditForm: false, }; static propTypes = { loading: PropTypes.bool.isRequired, posting: PropTypes.bool.isRequired, alerts: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string })) .isRequired, alert: PropTypes.shape({ name: PropTypes.string }), page: PropTypes.number.isRequired, showForm: PropTypes.bool.isRequired, searchQuery: PropTypes.string, total: PropTypes.number.isRequired, }; static defaultProps = { alert: null, searchQuery: undefined, }; componentDidMount() { getAlerts(); } /** * @function * @name openFiltersModal * @description open filters modal by setting it's visible property to false via state * * @version 0.1.0 * @since 0.1.0 */ openFiltersModal = () => { this.setState({ showFilters: true }); }; /** * @function * @name closeFiltersModal * @description Close filters modal by setting it's visible property to false via state * * @version 0.1.0 * @since 0.1.0 */ closeFiltersModal = () => { this.setState({ showFilters: false }); }; /** * @function * @name openAlertForm * @description Open alert form * * @version 0.1.0 * @since 0.1.0 */ openAlertForm = () => { openAlertForm(); }; /** * @function * @name openAlertForm * @description close alert form * * @version 0.1.0 * @since 0.1.0 */ closeAlertForm = () => { closeAlertForm(); this.setState({ isEditForm: false }); }; /** * @function * @name searchAlerts * @description Search Alerts List based on supplied filter word * * @param {object} event - Event instance * * @version 0.1.0 * @since 0.1.0 */ searchAlerts = event => { searchAlerts(event.target.value); }; /** * @function * @name handleEdit * @description Handle on Edit action for list item * * @param {object} alert alert to be edited * * @version 0.1.0 * @since 0.1.0 */ handleEdit = alert => { selectAlert(alert); this.setState({ isEditForm: true }); openAlertForm(); }; /** * @function * @name handleAfterCloseForm * @description Perform post close form cleanups * * @version 0.1.0 * @since 0.1.0 */ handleAfterCloseForm = () => { this.setState({ isEditForm: false }); }; render() { const { alerts, alert, loading, posting, page, showForm, searchQuery, total, } = this.props; const { showFilters, isEditForm } = this.state; return ( <div className="Alerts"> <Row> <Col xxl={12} xl={12} lg={12} md={12} sm={24} xs={24}> {/* search input component */} <Search size="large" placeholder="Search for alerts here ..." onChange={this.searchAlerts} allowClear value={searchQuery} className="searchBox" /> {/* end search input component */} </Col> {/* primary actions */} <Col xxl={12} xl={12} lg={12} md={12} sm={24} xs={24}> <Row type="flex" justify="end"> <Col xxl={6} xl={6} lg={6} md={8} sm={24} xs={24}> <Button type="primary" icon="plus" size="large" title="Add New Alert" onClick={this.openAlertForm} block > New Alert </Button> </Col> </Row> </Col> {/* end primary actions */} </Row> {/* list starts */} <AlertList total={total} page={page} alerts={alerts} loading={loading} onEdit={this.handleEdit} onFilter={this.openFiltersModal} onNotify={this.openNotificationForm} onShare={this.handleShare} onBulkShare={this.handleBulkShare} /> {/* end list */} {/* filter modal */} <Modal title="Filter Alerts" visible={showFilters} onCancel={this.closeFiltersModal} width="50%" footer={null} destroyOnClose maskClosable={false} > <AlertFilters onCancel={this.closeFiltersModal} /> </Modal> {/* end filter modal */} {/* create/edit form modal */} <Modal title={isEditForm ? 'Edit Alert' : 'Add New Alert'} visible={showForm} width="50%" footer={null} onCancel={this.closeAlertForm} destroyOnClose maskClosable={false} afterClose={this.handleAfterCloseForm} > <AlertForm posting={posting} isEditForm={isEditForm} alert={alert} onCancel={this.closeAlertForm} /> </Modal> {/* end create/edit form modal */} </div> ); } }
JavaScript
class NotFound extends React.Component { render() { return ( <div className="page page-not-found-page bg-primary"> <div className="flex-vt flex-stretch flex-space-between"> <div className="home-header"> <Header class='headerGame position-relative flex-hz flex-space-between'> <p>Not Found</p> </Header> </div> <div className="text-center padding-large"> <p>Yo cracker!</p> <p>This page doesn't exist.</p> <p>Get back to the game son!</p> </div> <Link to="/game" className="page-footer flex-vt-normal flex-center"> <Button bsSize="sm" bsStyle="primary"> <p className="text-secondary text-light">Back</p> </Button> </Link> </div> </div> ); } }
JavaScript
class FilterEffect extends Effect { /** The vertex format expected by <code>uploadVertexData</code>: * <code>'position:float2, texCoords:float2'</code> */ static VERTEX_FORMAT = Effect.VERTEX_FORMAT.extend('texCoords:float2') static STD_VERTEX_SHADER = `#version 300 es layout(location = 0) in vec2 aPosition; layout(location = 1) in vec2 aTexCoords; uniform mat4 uMVPMatrix; out vec2 vTexCoords; void main() { // Transform to clipspace gl_Position = uMVPMatrix * vec4(aPosition, 0.0, 1.0); vTexCoords = aTexCoords; } ` _texture _textureSmoothing _textureRepeat /** Creates a new FilterEffect instance. */ constructor() { super() this._textureSmoothing = TextureSmoothing.BILINEAR } /** Override this method if the effect requires a different program depending on the * current settings. Ideally, you do this by creating a bit mask encoding all the options. * This method is called often, so do not allocate any temporary objects when overriding. * * <p>Reserve 4 bits for the variant name of the base class.</p> */ get programVariantName() { return RenderUtil.getTextureVariantBits(this._texture) // todo: implement } /** @private */ createProgram() { if (this._texture) { const vertexShader = FilterEffect.STD_VERTEX_SHADER const fragmentShader = `#version 300 es precision highp float; uniform sampler2D sTexture; in vec2 vTexCoords; out vec4 color; void main() { color = texture(sTexture, vTexCoords); } ` return Program.fromSource(vertexShader, fragmentShader) } else { return super.createProgram() } } /** This method is called by <code>render</code>, directly before * <code>context.drawTriangles</code>. It activates the program and sets up * the context with the following constants and attributes: * * <ul> * <li><code>vc0-vc3</code> — MVP matrix</li> * <li><code>va0</code> — vertex position (xy)</li> * <li><code>va1</code> — texture coordinates (uv)</li> * <li><code>fs0</code> — texture</li> * </ul> */ beforeDraw(gl) { super.beforeDraw(gl) const { _texture, _textureSmoothing, _textureRepeat } = this if (_texture) { gl.bindTexture(gl.TEXTURE_2D, _texture.base) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, _textureSmoothing) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, _textureSmoothing) gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, _textureRepeat ? gl.REPEAT : gl.CLAMP_TO_EDGE ) gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, _textureRepeat ? gl.REPEAT : gl.CLAMP_TO_EDGE ) } } /** This method is called by <code>render</code>, directly after * <code>context.drawTriangles</code>. Resets texture and vertex buffer attributes. */ afterDraw(gl) { gl.bindTexture(gl.TEXTURE_2D, null) super.afterDraw(gl) } /** The data format that this effect requires from the VertexData that it renders: * <code>'position:float2, texCoords:float2'</code> */ get vertexFormat() { // eslint-disable-line return FilterEffect.VERTEX_FORMAT } /** The texture to be mapped onto the vertices. */ get texture() { return this._texture } set texture(value) { this._texture = value } /** The smoothing filter that is used for the texture. @default bilinear */ get textureSmoothing() { return this._textureSmoothing } set textureSmoothing(value) { this._textureSmoothing = value } /** Indicates if pixels at the edges will be repeated or clamped. * Only works for power-of-two textures. @default false */ get textureRepeat() { return this._textureRepeat } set textureRepeat(value) { this._textureRepeat = value } }
JavaScript
class Endpoint { constructor(path) { const self = this; self._path = path; self._pathSegments = path .replace(LEADING_PATH_SEPARATOR_REGEX, "") .split(PATH_SEPARATOR) ; self._operations = []; // Validate endpoint if(!LEADING_PATH_SEPARATOR_REGEX.test(self._path)) { throw new Error("Failed to create Endpoint: path should have a leading " + PATH_SEPARATOR); } self._pathSegments.forEach(function(pathSegment) { if(pathSegment.length === 0 || WHITESPACE.test(pathSegment)) { throw new Error("Failed to create Endpoint: path contains whitespace or empty segments"); } }); } // Public instance methods handle(request) { const self = this; let requestParameters = self._requestParametersFromPath(request.getPath()); if(!requestParameters) { return Result.noResourceFound; } request.setParameters(requestParameters); // Perform first matching operation let result = null; self._operations.some(function(operation) { let operationResult = operation.perform(request); result = Result.mostSpecific(result, operationResult); return result.isOk(); }); return result; } getPath() { const self = this; return self._path; } addOperation(operation) { const self = this; self._operations.push(operation); } // Private instance methods _requestParametersFromPath(requestPath) { const self = this; // Match receiver's path against provided request path // Answer a parameter object if the request path matches the receiver (may be empty object in case no parameters are present on path) // If no match is found answers false. // For example: // Existing paths: // "/api/projects" // "/api/projects/:projectId" // "/api/projects/:projectId/members/:memberId" // // _requestParametersFromPath("/api/projects/123/members/2") => // { "projectId": 123, "memberId": 2 } // _requestParametersFromPath("/api/projects") => // {} // _requestParametersFromPath("/api/users") => // false // Pedantic check for leading separator if(!LEADING_PATH_SEPARATOR_REGEX.test(requestPath)) { return false; } // Iterate over path segments let apiPathSegments = self._pathSegments; let requestPathSegments = requestPath .replace(LEADING_PATH_SEPARATOR_REGEX, "") .split(PATH_SEPARATOR) ; // Paths should have same number of segments if(apiPathSegments.length !== requestPathSegments.length) { return false; } // Process the path segments one by one let parameters = {}; let success = apiPathSegments.every(function(apiPathSegment, index) { let requestPathSegment = requestPathSegments[index]; // Check for parameter or path segment if(apiPathSegment.startsWith(":")) { // Store parameter let name = apiPathSegment.slice(1); // Remove leading ":" let value = decodeURIComponent(requestPathSegment); parameters[name] = value; // Check for matching segment } else if(apiPathSegment !== requestPathSegment) { return false; } return true; }); // Answer false if match is unsuccessful if(!success) { return false; } return parameters; } }
JavaScript
class QuestionMiddleware { /** * Validates user's question. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static validate(req, res, next) { const message = validateQuestionSchema(req.body); if (message === true) return next(); errorResponse(res, { code: 400, message }); } /** * Checks that the id in the path belongs to an existing question. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static async validateId(req, res, next) { const { id } = req.params; try { const question = await fetchById(id); if (!question) { return errorResponse(res, { code: 404, message: 'A question with the id provided was not found' }); } req.question = question; next(); } catch (e) { const regex = /Cast to ObjectId/i; if (regex.test(e.message)) { return errorResponse(res, { code: 400, message: 'Invalid question Id' }); } errorResponse(res, {}); } } /** * It checks if a question that a user requests to be * upvoted has already been downvoted by the user and * removes the downvote on the question by that user if found. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static async syncUpVoteWithDownVote(req, res, next) { const { question } = req; const { id } = req.data; const isDownVotedIndex = question.downVote.by.findIndex( userId => userId.toString() === id.toString() ); if (isDownVotedIndex !== -1) { question.downVote.by.splice(isDownVotedIndex, 1); question.downVote.total = question.downVote.by.length; } next(); } /** * It checks if a question that a user requests to be * downvote was previously upvoted by the user and * removes the upvote on the question by that user if found. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static async syncDownVoteWithUpVote(req, res, next) { const { question } = req; const { id } = req.data; const isUpVotedIndex = question.upVote.by.findIndex( userId => userId.toString() === id.toString() ); if (isUpVotedIndex !== -1) { question.upVote.by.splice(isUpVotedIndex, 1); question.upVote.total = question.upVote.by.length; } next(); } /** * Checks if a user who has requested to upvote a question * has already upvoted the question with a previous request and removes * the upvote for the user if that's the case otherwise, it adds * an upvote to the question for that user. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static async syncUpVote(req, res, next) { const { question } = req; const { id } = req.data; const isUpVotedIndex = question.upVote.by.findIndex( userId => userId.toString() === id.toString() ); if (isUpVotedIndex !== -1) question.upVote.by.splice(isUpVotedIndex, 1); else question.upVote.by.push(id); question.upVote.total = question.upVote.by.length; next(); } /** * Checks if a user who has requested to upvote a question * has already upvoted the question with a previous request and removes * the upvote for the user if that's the case otherwise, it adds * an upvote to the question for that user. * @param {object} req - The request from the endpoint. * @param {object} res - The response returned by the method. * @param {function} next - Call the next operation. *@returns {object} - Returns an object (error or response). * @memberof QuestionMiddleware * */ static async syncDownVote(req, res, next) { const { question } = req; const { id } = req.data; const isDownVotedIndex = question.downVote.by.findIndex( userId => userId.toString() === id.toString() ); if (isDownVotedIndex !== -1) question.downVote.by.splice(isDownVotedIndex, 1); else question.downVote.by.push(id); question.downVote.total = question.downVote.by.length; next(); } }
JavaScript
class XBrowserExtension extends yeoman.Base { constructor(...args) { super(...args); this.spinner = ora('starting'); this.supportedBrowsers = [ { name: 'Chrome', checked: true, }, { name: 'Firefox', checked: true, }, { name: 'Opera', checked: true, }, { name: 'Safari', checked: true, }, ]; this.npmDependencies = [ 'axios', 'normalize.css', 'react', 'react-dom', ]; this.npmDevDependencies = [ 'autoprefixer', 'babel', 'babel-cli', 'babel-core', 'babel-eslint', 'babel-loader', 'babel-plugin-typecheck', 'babel-preset-es2015', 'babel-preset-react', 'babel-preset-react-hmre', 'babel-preset-stage-0', 'babel-register', 'body-parser', 'css-loader', 'eslint', 'eslint-plugin-babel', 'eslint-plugin-react', 'express', 'jade', 'node-sass', 'postcss-loader', 'react-addons-test-utils', 'redux-devtools', 'sass-loader', 'sleep', 'style-loader', 'webpack', 'webpack-dev-middleware', 'webpack-hot-middleware', 'chai', 'jsdom', 'mocha', 'mocha-jsdom', 'sinon', ]; this.say = { arr: '----> ', tab: ' ', info(msg) { console.log('\n\n' + chalk.yellow(this.arr + msg) + '\n'); }, status(item, status) { console.log(`${this.tab}${chalk.green(status)} ${item}`); }, cmd(cmd) { console.log('\n' + chalk.green('$' + cmd)); }, done(status, msg) { console.log(`\n\n${this.tab}${chalk.green(status)} $ ${msg}\n`); }, }; this.getDeps = deps => deps.map(dep => dep + '@latest'); this.copy = function(src, dest, show) { shell.cp('-Rf', this.templatePath(src), this.destinationPath(dest)); this.say.status(show || dest, '✓ '); }; this.render = function(src, dest, params = {}) { const output = ejs.render(this.read(this.templatePath(src)), params); fs.writeFileSync(this.destinationPath(dest), output); this.say.status(dest, '✓ '); }; this.shellExec = function(cmd) { this.say.cmd(cmd); shell.exec(cmd); console.log('Completed.'); }; this.allDone = function() { this.say.done('All done!', `cd ${this.appName}/ && npm start`); }; } /** * Initialize the yeoman generator */ initializing () { this.log('---------------------------------------'); this.log(' _ _____'); this.log(' | |/_/ _ )_______ _ _____ ___ ____'); this.log(' _> </ _ / __/ _ \\ |/|/ (_-</ -_) __/'); this.log('/_/|_/____/_/_ \\___/__,__/___/\\__/_/'); this.log(' / __/_ __/ /____ ___ ___ (_)__ ___'); this.log(' / _/ \\ \\ / __/ -_) _ \\(_-</ / _ \\/ _ \\'); this.log('/___//_\\_\\\\__/\\__/_//_/___/_/\\___/_//_/'); this.log(''); this.log('---------------------------------------'); this.log(''); this.appName = shift.param('Synopsis'); } prompting () { const cb = this.async(); let isChecked = (choices, value) => { return choices.indexOf(value) > -1; }; let defaultAppName = shift.param(this.options.argv.original[0]) || null; let prompts = [{ type : 'input', name : 'appName', message: 'Extension name:', default: defaultAppName, }, { type : 'checkbox', name : 'browsers', message: 'What browsers do you want to support?', choices: this.supportedBrowsers, validate: (answer) => { if (answer.length < 1) { return 'You must choose at least one browser to support.'; } return true; } }]; this.prompt(prompts, props => { //this.appName = shift.param(props.appName); //this.browsers = props.browsers; //this.log('IDK????'); cb(); }); } copyFiles () { this.spinner.text = 'Copying files...'; this.spinner.start(); this.log(''); shell.mkdir(this.appName); this.destinationRoot(this.appName); this.copy('app/', 'app/'); this.copy('config/', 'config/'); this.copy('dev/', 'dev/'); this.copy('.babelrc', '.', '.babelrc'); this.copy('.editorconfig', '.', '.editorconfig'); this.copy('.eslintignore', '.', '.eslintignore'); this.copy('.eslintrc', '.', '.eslintrc'); this.copy('.scss-lint.yml', '.', '.scss-lint.yml'); this.render('_package.json', 'package.json', { appName: this.appName }); this.copy('server.js', '.', 'server.js'); this.spinner.stop(); } /* install () { const deps = this.getDeps(this.npmDependencies); const devDeps = this.getDeps(this.npmDevDependencies); this.spinner.start(); this.spinner.text = 'Installing dependencies...'; const done = this.async(); this.npmInstall(deps, { save: true }); this.npmInstall(devDeps, { saveDev: true }, () => { this.shellExec('npm shrinkwrap --loglevel error'); this.done(); }); } */ end () { this.spinner.stop() this.log('All done!'); this.log(''); } }
JavaScript
class StateTransformer { setUp() {} tearDown() {} handleEvent(event) {} update(time, deltaTime) {} render() {} }
JavaScript
class Result { constructor(path, operationType, db, opts) { const isRead = operationType === 'read'; opts = opts || {}; if (!isRead && !opts.newDatabase) { throw new Error('The resulting database should be provided.'); } this.path = path; this.auth = isRead ? db.auth : opts.newDatabase.auth; this.type = operationType; this[logsKey] = []; this.permitted = false; this.validated = true; this.database = db; this.newDatabase = opts.newDatabase; this.newValue = opts.newValue; } get logs() { if (this[logsKey].some(r => r.kind === this.permissionType)) { return this[logsKey]; } return [{path: paths.trim(this.path), hasNoRules: true}].concat(this[logsKey]); } get allowed() { return this.permitted && this.validated; } get permissionType() { return this.type === 'read' ? 'read' : 'write'; } get info() { const info = [ this.description, this.evaluations ]; if (this.allowed) { info.push(`${this.type} was allowed.`); return info.join('\n'); } if (!this.permitted) { info.push(`No .${this.permissionType} rule allowed the operation.`); } if (!this.validated) { info.push('One or more .validate rules disallowed the operation.'); } info.push(`${this.type} was denied.`); return info.join('\n'); } get description() { const op = `Attempt to ${this.type} ${this.path} as ${JSON.stringify(this.auth)}.\n`; switch (this.type) { case 'write': return `${op}New Value: "${JSON.stringify(this.newValue, undefined, 2)}".\n`; case 'patch': return `${op}Patch: "${JSON.stringify(this.newValue, undefined, 2)}".\n`; default: return op; } } get evaluations() { return this.logs.map(r => { if (r.hasNoRules === true) { return `/${r.path}: ${this.permissionType} <no rules>\n`; } const header = `/${r.path}: ${r.kind} "${r.rule}"`; const result = r.error == null ? r.value : r.error; if (r.detailed == null) { return `${header} => ${result}\n`; } return `${header} => ${result}\n${pad.lines(r.detailed)}\n`; }).join('\n'); } get root() { return this.database.snapshot('/'); } get newRoot() { return this.newDatabase.snapshot('/'); } get data() { return this.database.snapshot(this.path); } get newData() { return this.newDatabase.snapshot(this.path); } /** * Logs the evaluation result. * * @param {string} path The rule path * @param {string} kind The rule kind * @param {NodeRule} rule The rule * @param {{value: boolean, error: Error, detailed: string}} result The evaluation result */ add(path, kind, rule, result) { this[logsKey].push({ path, kind, rule: rule.toString(), value: result.value == null ? false : result.value, error: result.error, detailed: result.detailed }); switch (kind) { case 'validate': this.validated = this.validated && result.value === true; break; case 'write': case 'read': this.permitted = this.permitted || result.value === true; break; /* istanbul ignore next */ default: throw new Error(`Unknown type: ${kind}`); } } }
JavaScript
class Node { constructor(value) { this.value = value; this.next = null; } }
JavaScript
class LayerPanelActionDuplicate extends Component { incrementTitle(dupeLayer) { const { map } = this.props const originalTitle = dupeLayer.get('title').trim() const layers = map.getLayers().getArray().filter(layer => layer instanceof VectorLayer || layer.isVectorLayer) const strippedTitle = originalTitle.replace(/\d+$/, '').trim() const count = layers.filter((layer) => { const includes = originalTitle.includes(layer.get('title').replace(/\d+$/, '').trim()) return includes }).length const exactCount = layers.filter(layer => layer.get('title').trim() === strippedTitle ).length if ((strippedTitle !== originalTitle)) { return (count == 1 || exactCount == 0 || (exactCount == 1 && isNaN(strippedTitle.substr(-1)) && isNaN(originalTitle.substr(-1))) ? originalTitle : strippedTitle) + ' ' + count.toString() } return strippedTitle + ' ' + count.toString() } duplicateLayer = (layer) => { const { map, onLayerDuplicated, handleMenuClose } = this.props if (layer.isGeoserverLayer) { onLayerDuplicated(layer) handleMenuClose() } else { const newTitle = this.incrementTitle(layer) const dupeFeatures = layer.getSource().getFeatures().map(feature => feature.clone()) const source = new VectorSource({ features: dupeFeatures }) const properties = Object.assign(layer.getProperties(), { source, title: newTitle}) const dupeLayer = new VectorLayer({...properties}) map.addLayer(dupeLayer) onLayerDuplicated(dupeLayer) handleMenuClose() } } render () { const { layer, translations } = this.props return ( <MenuItem data-testid='LayerPanelAction.duplicate' key={'zoom'} onClick={() => this.duplicateLayer(layer)}> {translations['_ol_kit.actions.duplicate']} </MenuItem> ) } }
JavaScript
class Rect extends React.Component { constructor() { super() } render() { return ( <rect style={defaultStyle} {...this.props}> {this.props.children} </rect> ) } }
JavaScript
class TabBar extends React.PureComponent { //--------------------------------------------------------------------// // Constructor //--------------------------------------------------------------------// constructor(props) { super(props); } //--------------------------------------------------------------------// // Render Methods //--------------------------------------------------------------------// _renderTab(text, screen, props) { return ( <RN.TouchableOpacity onPress={() => this.props.navigateTo(screen, props)} style={styles.button}> <RN.Text allowFontScaling={false} numberOfLines={1} style={[UTILITY_STYLES.lightBlackText16, { marginBottom: 5 }, this.props.currentScreen === screen && UTILITY_STYLES.textHighlighted]}> {text} </RN.Text> </RN.TouchableOpacity> ) } render() { let currentScreen = this.props.screen; return ( <RN.View style={styles.tabs}> {this._renderTab('Posts', 'AuthoredScreen', { userId: this.props.userId })} {this._renderTab('Liked', 'LikedScreen', { userId: this.props.userId })} </RN.View> ) } }
JavaScript
class Resolver extends DefaultResolver { constructor(name, directives) { super(directives); this.name = name; } resolve(keyword) { let [deviceName, commandName] = unwrapKeyword(keyword); // This requires synchronization between multiple devices - some device can // issue an error, but some may not. TODO if (deviceName !== this.name) { // Create no-op return NOOP; } return this.directives[commandName]; } }
JavaScript
class Cell { /** * Neighbors are ordered according to this clock-based convention: * [ 12:00, 2:00, 4:00, 6:00, 8:00, 10:00 ] * Center is a float that represents the coordinate center of the cell. * Preact will handle scaling on-screen. * Just keep scaling consistent among the cell objects. */ constructor() { this.id = ID_COUNTER++; this.center = null; this.neighbors = [null, null, null, null, null, null]; this.occupation = CellState.NO_USER; this.wasProtected = false; } /** * Conveniently sets antibiotic protection to false */ resetProtection() { this.wasProtected = false; } isSurrounded() { return this.neighbors.filter(x => x === null).length == 0; } setRelativeCenter(neighbor, positionToNeighbor) { let nX = neighbor.center[0]; let nY = neighbor.center[1]; let angle = (Math.PI / 2) + (positionToNeighbor * Math.PI / 3); let x = nX + Math.cos(angle); let y = nY + Math.sin(angle); this.center = [x, y]; } /** * Links cell to its neighbor at the given position. * Note: this is only a single link! * Don't forget to do the backwards link to keep double-linkedness! * @param {Number} position * @param {Cell} neighbor */ link(position, neighbor) { if (this.center === null && neighbor.center === null) { console.log('Major error! At least one of the neighbors must have a center!'); } if (this.isSurrounded() || neighbor.isSurrounded() || this.isAdjacent(neighbor)) { return false; } let positionFromNeighbor = (position + 3) % 6; this.neighbors[position] = neighbor; neighbor.neighbors[positionFromNeighbor] = this; if (this.center === null) { this.setRelativeCenter(neighbor, position); } else if (neighbor.center === null) { neighbor.setRelativeCenter(this, positionFromNeighbor); } return true; } /** * Returns whether the neighbor is a neighbor or not. * @param {Cell} neighbor */ isAdjacent(neighbor) { return this.neighbors.filter(x => (x !== null && x.id === neighbor.id)).length > 0; } /** * Returns the position (-1 if neighbor is not found) of neighbor in the list of neighbors. * @param {Cell} neighbor */ getPosition(neighbor) { let position = -1; for (let i = 0; i < 6; ++i) { if (this.neighbors[i] !== null && this.neighbors[i].id === neighbor.id) { position = i; break; } } return position; } getNumberOfAdjacentHigherIDConnections() { return this.neighbors.filter( (n) => (n !== null && (n.id > this.id && n.occupation == this.occupation)) ).length; } hasNeighbor(neighborID) { return this.neighbors.filter(n=>(n!==null && n.occupation === neighborID)).length > 0; } hasUnoccupiedNeighbor() { for (let i = 0; i < 6; ++i) { if (this.neighbors[i] !== null && this.neighbors[i].occupation == CellState.NO_USER) { return true; } } return false; } getUnoccupiedNeighbors() { return this.neighbors.filter(n=>(n !== null && n.occupation == CellState.NO_USER)); } }
JavaScript
class SaveFavoriteOpt { constructor( opts ) { this.saveOpt = saveFavoriteOpt.call( this ); this.currentFavorites = this.sortAll( null, opts ); } render() { let metadata = { title: 'Save Favorite Adv. Opts', form: this.saveOpt, button: { text: 'Add', location: 'right', id: 'addSubmitBtn', onClick: () => this.handleSubmit() } }; this.container = new FormFactory().generateForm( 'body', 'save-favorite-opts', metadata ); this.folderNameInput = this.container.select( '#addFolderName' ); this.folderVisibilityInput = this.container.select( '#addFolderVisibility' ); this.submitButton = this.container.select( '#addSubmitBtn' ); return this; } validateTextInput( d ) { let target = d3.select( `#${ d.id }` ), node = target.node(), str = node.value, reservedWords = [ 'root', 'dataset', 'folder' ]; this.currentFavorites.map( name => reservedWords.push(name)); let unallowedPattern = new RegExp( /[~`#$%\^&*+=\-\[\]\\';\./!,/{}|\\":<>\?|]/g ), valid = true; if ( !str.length || reservedWords.indexOf( str.toLowerCase() ) > -1 || unallowedPattern.test( str ) ) { valid = false; } target.classed( 'invalid', !valid ); this.formValid = valid; this.updateButtonState(); } /** * Enable/disable button based on form validity */ updateButtonState() { let folderName = this.folderNameInput.node().value, self = this; this.container.selectAll( '.text-input' ) .each( function() { let classes = d3.select( this ).attr( 'class' ).split( ' ' ); if ( classes.indexOf( 'invalid' ) > -1 || !folderName.length ) { self.formValid = false; } } ); this.submitButton.node().disabled = !this.formValid; } sortAll( defaultTypes, userFavorites ) { let favorites = []; Object.keys( userFavorites ).map( fav => favorites.push( fav ) ); favorites.sort(); if ( defaultTypes ) { favorites.forEach( opt => defaultTypes.push( opt ) ); return defaultTypes; } else { return favorites; } } populateCombobox( input ) { let newCombo = new FormFactory(); let element = d3.select( '#conflateType' ); element.datum().data = input; newCombo.populateCombobox( element ); } handleSubmit() { let favoriteName = this.folderNameInput.property( 'value' ); let confType = d3.select('#conflateType').property('value'); let opts = { name: favoriteName, members: { members: this.saveOpt[0].data, name: favoriteName, label: favoriteName, conflateType: confType } }; this.processRequest = Hoot.api.saveFavoriteOpts( opts ) .then( () => Hoot.getAllUsers() ) .then( async () => { let getTypes = await Hoot.api.getConflateTypes(true); let getFavorites = Hoot.config.users[Hoot.user().id].members; let allConfTypes = this.sortAll( getTypes, getFavorites ); this.populateCombobox( allConfTypes ); } ) .catch( err => { let alert = { message: err, type: 'warn' }; Hoot.message.alert( alert ); } ) .finally( () => { this.container.remove(); Hoot.events.emit( 'modal-closed' ); Hoot.message.alert( { message: 'Fav. Opts Saved Successfully', type: 'success' } ); } ); } }
JavaScript
class Game { constructor() { this.missed = 0; this.phrases = [ {phrase: "Mirror Mirror on the Wall"}, {phrase: "Life is like a box of chocolates"}, {phrase: "Singing in the rain"}, {phrase: "The eye of the tiger"}, {phrase: "A stitch in time saves nine"} ]; this.activePhrase = null; } startGame () { const overlay = document.getElementById("overlay"); // Remove game start menu overlay.style.display = "none"; // Grab a random phrase and set/display const phrase = new Phrase(this.getRandomPhrase()); this.activePhrase = phrase; phrase.addPhraseToDisplay(); } // Returns a random phrase from the phrases array getRandomPhrase () { const phrases = this.phrases; const randIndex = Math.floor(Math.random() * phrases.length); return phrases[randIndex]; } handleInteraction (event) { // Handle button click if the onscreen keyboard is clicked if (event.type === "click") { // Disable the onscreen keyboard button event.target.disabled = true; // Add appropriate classes and reveal letter if the selected letter is in the random phrase if (this.activePhrase.checkLetter(event.target.textContent)) { event.target.classList.add("chosen"); this.activePhrase.showMatchedLetter(event.target.textContent); // Check if player won if (this.checkForWin()) { this.gameOver(true); } } else { // Add appropriate classes and remove a life if player guessed wrong event.target.classList.add("wrong"); this.removeLife(); } } // Handle button click if the user's physical keyboard is pressed if (event.type === "keyup"){ const keyboardBtns = document.getElementsByClassName("key"); for (let i=0; i<keyboardBtns.length; i++){ // Check if the keyboard letter matches the pressed key and is not already selected // (to avoid losing additional lives if a wrong key is pressed more than once) if (keyboardBtns[i].textContent === event.key && !keyboardBtns[i].classList.contains("wrong")) { // Disable the onscreen keyboard button keyboardBtns[i].disabled = true; // Add appropriate classes and reveal letter if the selected letter is in the random phrase if (this.activePhrase.checkLetter(event.key)) { keyboardBtns[i].classList.add("chosen"); this.activePhrase.showMatchedLetter(event.key); // Check if player won if (this.checkForWin()) { this.gameOver(true); } } else { // Add appropriate classes and remove a life if player guessed wrong keyboardBtns[i].classList.add("wrong"); this.removeLife(); } } } } } // Increment missed counter and alter heart image if life is lost removeLife () { const lives = document.getElementsByClassName("tries"); this.missed++; for (let i=0; i<this.missed; i++){ lives[i].innerHTML = `<img src="images/lostHeart.png" alt="Lost Heart Icon" height="35" width="30">`; } // Lose the game if user runs out of lives if (this.missed === 5){ this.gameOver(false); } } checkForWin () { let wonGame = false; const displayLetters = document.querySelectorAll("#phrase .letter"); // Loop through phrase display, and any contain the "hide" class, then the game // is not over. wonGame is true when no letter in the display has the "hide" class. for (let i=0; i<displayLetters.length; i++){ if (displayLetters[i].classList.contains("hide")){ wonGame = false; break; } wonGame = true; } return wonGame; } gameOver (gameWon) { const overlay = document.getElementById("overlay"); const gameOverMessage = document.getElementById("game-over-message"); // Display overlay on game win or lose overlay.style.display = "flex"; startBtn.textContent = "Play Again"; // Adjust overlay content according to win or loss if (gameWon) { overlay.className = "win"; gameOverMessage.textContent = "You Won!" } else { overlay.className = "lose"; gameOverMessage.textContent = "Better Luck Next Time"; } // Reset Gameboard const phraseUL = document.querySelector("#phrase ul"); const keyboardButtons = document.querySelectorAll("button.key"); const lives = document.getElementsByClassName("tries"); // Reset missed counter this.missed = 0; this.phrases = []; this.activePhrase = null; // Reset phrase display phraseUL.innerHTML = ""; // Reset keyboard for (let i=0; i<keyboardButtons.length; i++){ keyboardButtons[i].disabled = false; keyboardButtons[i].className = "key"; } // Reset lives for (let i=0; i<lives.length; i++){ lives[i].innerHTML = `<img src="images/liveHeart.png" alt="Heart Icon" height="35" width="30">`; } } }
JavaScript
class MusicSubscription { voiceConnection; audioPlayer; queue; queueLock = false; readyLock = false; constructor(voiceConnection, textChannel) { this.voiceConnection = voiceConnection; this.textChannel = textChannel this.audioPlayer = createAudioPlayer(); this.queue = []; this.voiceConnection.on('stateChange', async (_, newState) => { if (newState.status === VoiceConnectionStatus.Disconnected) { if (newState.reason === VoiceConnectionDisconnectReason.WebSocketClose && newState.closeCode === 4014) { /* If the WebSocket closed with a 4014 code, this means that we should not manually attempt to reconnect, but there is a chance the connection will recover itself if the reason of the disconnect was due to switching voice channels. This is also the same code for the bot being kicked from the voice channel, so we allow 5 seconds to figure out which scenario it is. If the bot has been kicked, we should destroy the voice connection. */ try { await entersState(this.voiceConnection, VoiceConnectionStatus.Connecting, 5_000); // Probably moved voice channel } catch { this.voiceConnection.destroy(); // Probably removed from voice channel } } else if (this.voiceConnection.rejoinAttempts < 5) { /* The disconnect in this case is recoverable, and we also have <5 repeated attempts so we will reconnect. */ await wait((this.voiceConnection.rejoinAttempts + 1) * 5_000); this.voiceConnection.rejoin(); } else { /* The disconnect in this case may be recoverable, but we have no more remaining attempts - destroy. */ this.voiceConnection.destroy(); } } else if (newState.status === VoiceConnectionStatus.Destroyed) { /* Once destroyed, stop the subscription */ this.stop(); } else if ( !this.readyLock && (newState.status === VoiceConnectionStatus.Connecting || newState.status === VoiceConnectionStatus.Signalling) ) { /* In the Signalling or Connecting states, we set a 20 second time limit for the connection to become ready before destroying the voice connection. This stops the voice connection permanently existing in one of these states. */ this.readyLock = true; try { await entersState(this.voiceConnection, VoiceConnectionStatus.Ready, 20_000); } catch { if (this.voiceConnection.state.status !== VoiceConnectionStatus.Destroyed) this.voiceConnection.destroy(); } finally { this.readyLock = false; } } }); // Configure audio player this.audioPlayer.on('stateChange', (oldState, newState) => { if (newState.status === AudioPlayerStatus.Idle && oldState.status !== AudioPlayerStatus.Idle) { // If the Idle state is entered from a non-Idle state, it means that an audio resource has finished playing. // The queue is then processed to start playing the next track, if one is available. oldState.resource.metadata.onFinish() void this.processQueue() } else if (newState.status === AudioPlayerStatus.Playing){ newState.resource.metadata.onStart() } }); this.audioPlayer.on('error', (error) => error.resource.metadata.onError(error)); voiceConnection.subscribe(this.audioPlayer); } /** * Adds a new Track to the queue. * * @param track The track to add to the queue */ enqueue(track) { this.queue.push(track); void this.processQueue(); } /** * Stops audio playback and empties the queue */ stop() { this.queueLock = true; this.queue = []; this.audioPlayer.stop(true); } /** * Attempts to play a Track from the queue */ async processQueue() { if (this.queueLock || this.audioPlayer.state.status !== AudioPlayerStatus.Idle || this.queue.length === 0) return; this.queueLock = true const nextTrack = this.queue.shift(); try { const resource = await nextTrack.createAudioResource(); this.audioPlayer.play(resource); this.queueLock = false } catch (error) { console.log(error) nextTrack.onError(error); this.queueLock = false this.processQueue(); } } }
JavaScript
class Route { /** * @param {Object} data All of the data returned from the API */ constructor(data) { this.id = data.Route; this.provider_id = data.ProviderID; this.description = data.Description; } }
JavaScript
class dbReader { // empty constructor call as this would be added automatically. constructor() { }; // Functions to view various elements viewAll() { let query = "SELECT employee.id, CONCAT(employee.first_name,' ',employee.last_name) AS name, role.title, department.name AS department, role.salary, CONCAT(manager.first_name,' ',manager.last_name) AS manager FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id LEFT JOIN employee manager ON manager.id = employee.manager_id"; return connection.query(query); }; viewByDepartments() { let query = "SELECT department.name AS department, CONCAT(employee.first_name,' ',employee.last_name) AS name, role.title FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id ORDER BY department"; return connection.query(query); }; viewByManager() { let query = "SELECT CONCAT(manager.first_name,' ',manager.last_name) AS manager, CONCAT(employee.first_name,' ',employee.last_name) AS name, role.title, department.name AS department FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id LEFT JOIN employee manager ON manager.id = employee.manager_id ORDER BY manager"; return connection.query(query); }; viewRoles() { let query = "SELECT * FROM role"; return connection.query(query); } viewDepartments() { let query = "SELECT * FROM department"; return connection.query(query); }; // Functions to Add elements to tables insertNewEmployee(employeeData) { return connection.query("INSERT INTO employee SET ?", employeeData); }; insertNewRole(roleData) { return connection.query("INSERT INTO role SET ?", roleData); }; insertNewDepartment(departmentData) { return connection.query("INSERT INTO department SET ?", departmentData); }; // functions to return values for display in inquirer calls getRoles() { let query = "SELECT id, title FROM role"; return connection.query(query); }; getManagers() { let query = "SELECT DISTINCT manager.id, CONCAT(manager.first_name,' ',manager.last_name) AS manager FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id LEFT JOIN employee manager ON manager.id = employee.manager_id"; return connection.query(query); }; getDepartments() { let query = "SELECT * FROM department"; return connection.query(query); } // Functions to delete specific elements deleteDepartment(deptID) { return connection.query("DELETE FROM department WHERE id = ?", deptID.id); }; deleteEmployee(empdel) { return connection.query("DELETE FROM employee WHERE id = ?", empdel.id); }; deleteRole(role) { return connection.query("DELETE FROM role WHERE id = ?", role.id); }; // Updated functions updateRole(role, id) { return connection.query("UPDATE employee SET role_id = ? WHERE id = ?", [role, id]); }; updateManager(manager, id) { return connection.query("UPDATE employee SET manager_id = ? WHERE id = ?", [manager, id]); }; // Quit Function quit() { console.log("\nGoodbye!"); process.exit(0); } }
JavaScript
class Machine extends Object { /** * @param {WorldManager} worldManager */ constructor(worldManager) { super(worldManager); this.running = false; } static defaultMass = 2; }
JavaScript
class PostAdhocQuerySearchRequest { /** * Constructs a new <code>PostAdhocQuerySearchRequest</code>. * PostAdhocQuerySearchRequest * @alias module:model/PostAdhocQuerySearchRequest */ constructor() { PostAdhocQuerySearchRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PostAdhocQuerySearchRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PostAdhocQuerySearchRequest} obj Optional instance to populate. * @return {module:model/PostAdhocQuerySearchRequest} The populated <code>PostAdhocQuerySearchRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PostAdhocQuerySearchRequest(); if (data.hasOwnProperty('locale')) { obj['locale'] = ApiClient.convertToType(data['locale'], 'String'); } if (data.hasOwnProperty('dateFormat')) { obj['dateFormat'] = ApiClient.convertToType(data['dateFormat'], 'String'); } if (data.hasOwnProperty('loanDateOption')) { obj['loanDateOption'] = ApiClient.convertToType(data['loanDateOption'], 'String'); } if (data.hasOwnProperty('loanFromDate')) { obj['loanFromDate'] = ApiClient.convertToType(data['loanFromDate'], 'Date'); } if (data.hasOwnProperty('loanToDate')) { obj['loanToDate'] = ApiClient.convertToType(data['loanToDate'], 'Date'); } if (data.hasOwnProperty('includeOutStandingAmountPercentage')) { obj['includeOutStandingAmountPercentage'] = ApiClient.convertToType(data['includeOutStandingAmountPercentage'], 'Boolean'); } if (data.hasOwnProperty('outStandingAmountPercentageCondition')) { obj['outStandingAmountPercentageCondition'] = ApiClient.convertToType(data['outStandingAmountPercentageCondition'], 'String'); } if (data.hasOwnProperty('outStandingAmountPercentage')) { obj['outStandingAmountPercentage'] = ApiClient.convertToType(data['outStandingAmountPercentage'], 'Number'); } if (data.hasOwnProperty('includeOutstandingAmount')) { obj['includeOutstandingAmount'] = ApiClient.convertToType(data['includeOutstandingAmount'], 'Boolean'); } if (data.hasOwnProperty('outstandingAmountCondition')) { obj['outstandingAmountCondition'] = ApiClient.convertToType(data['outstandingAmountCondition'], 'String'); } if (data.hasOwnProperty('minOutstandingAmount')) { obj['minOutstandingAmount'] = ApiClient.convertToType(data['minOutstandingAmount'], 'Number'); } if (data.hasOwnProperty('maxOutstandingAmount')) { obj['maxOutstandingAmount'] = ApiClient.convertToType(data['maxOutstandingAmount'], 'Number'); } } return obj; } }
JavaScript
class LegendreTable { /** * @param maxN * The maximum n- and m-values to support * @param thetaRad * Returned functions will be Gauss-normalized * P_n^m(cos(thetaRad)), with thetaRad in radians. */ constructor(maxN, thetaRad) { // These are the Gauss-normalized associated Legendre functions -- that // is, they are normal Legendre functions multiplied by // (n-m)!/(2n-1)!! (where (2n-1)!! = 1*3*5*...*2n-1) this.mP = []; // Derivative of mP, with respect to theta. this.mPDeriv = []; // Compute the table of Gauss-normalized associated Legendre // functions using standard recursion relations. Also compute the // table of derivatives using the derivative of the recursion // relations. const cos = Math.cos(thetaRad); const sin = Math.sin(thetaRad); this.mP = Array(maxN + 1); this.mPDeriv = Array(maxN + 1); this.mP[0] = [ 1.0 ]; this.mPDeriv[0] = [ 0.0 ]; for (let n = 1; n <= maxN; n++) { this.mP[n] = new Array(n + 1); this.mPDeriv[n] = new Array(n + 1); for (let m = 0; m <= n; m++) { if (n == m) { this.mP[n][m] = sin * this.mP[n - 1][m - 1]; this.mPDeriv[n][m] = cos * this.mP[n - 1][m - 1] + sin * this.mPDeriv[n - 1][m - 1]; } else if (n == 1 || m == n - 1) { this.mP[n][m] = cos * this.mP[n - 1][m]; this.mPDeriv[n][m] = -sin * this.mP[n - 1][m] + cos * this.mPDeriv[n - 1][m]; } else { const k = ((n - 1) * (n - 1) - m * m) / ((2 * n - 1) * (2 * n - 3)); this.mP[n][m] = cos * this.mP[n - 1][m] - k * this.mP[n - 2][m]; this.mPDeriv[n][m] = -sin * this.mP[n - 1][m] + cos * this.mPDeriv[n - 1][m] - k * this.mPDeriv[n - 2][m]; } } } } }
JavaScript
class GeomagneticField { /** * Estimate the magnetic field at a given point and time. * * @param gdLatitudeDeg * Latitude in WGS84 geodetic coordinates -- positive is east. * @param gdLongitudeDeg * Longitude in WGS84 geodetic coordinates -- positive is north. * @param altitudeMeters * Altitude in WGS84 geodetic coordinates, in meters. * @param timeMillis * Time at which to evaluate the declination, in milliseconds * since January 1, 1970. (approximate is fine -- the declination * changes very slowly). */ constructor(gdLatitudeDeg, gdLongitudeDeg, altitudeMeters, timeMillis) { // The magnetic field at a given point, in nonoteslas in geodetic // coordinates. this.mX; this.mY; this.mZ; // Geocentric coordinates -- set by computeGeocentricCoordinates. this.mGcLatitudeRad = null; this.mGcLongitudeRad = null; this.mGcRadiusKm = null; const EARTH_REFERENCE_RADIUS_KM = 6371.2; // These coefficients and the formulae used below are from: // NOAA Technical Report: The US/UK World Magnetic Model for 2010-2015 const G_COEFF = [ [ 0.0 ], [ -29496.6, -1586.3 ], [ -2396.6, 3026.1, 1668.6 ], [ 1340.1, -2326.2, 1231.9, 634.0 ], [ 912.6, 808.9, 166.7, -357.1, 89.4 ], [ -230.9, 357.2, 200.3, -141.1, -163.0, -7.8 ], [ 72.8, 68.6, 76.0, -141.4, -22.8, 13.2, -77.9 ], [ 80.5, -75.1, -4.7, 45.3, 13.9, 10.4, 1.7, 4.9 ], [ 24.4, 8.1, -14.5, -5.6, -19.3, 11.5, 10.9, -14.1, -3.7 ], [ 5.4, 9.4, 3.4, -5.2, 3.1, -12.4, -0.7, 8.4, -8.5, -10.1 ], [ -2.0, -6.3, 0.9, -1.1, -0.2, 2.5, -0.3, 2.2, 3.1, -1.0, -2.8 ], [ 3.0, -1.5, -2.1, 1.7, -0.5, 0.5, -0.8, 0.4, 1.8, 0.1, 0.7, 3.8 ], [ -2.2, -0.2, 0.3, 1.0, -0.6, 0.9, -0.1, 0.5, -0.4, -0.4, 0.2, -0.8, 0.0 ] ]; const H_COEFF = [ [ 0.0 ], [ 0.0, 4944.4 ], [ 0.0, -2707.7, -576.1 ], [ 0.0, -160.2, 251.9, -536.6 ], [ 0.0, 286.4, -211.2, 164.3, -309.1 ], [ 0.0, 44.6, 188.9, -118.2, 0.0, 100.9 ], [ 0.0, -20.8, 44.1, 61.5, -66.3, 3.1, 55.0 ], [ 0.0, -57.9, -21.1, 6.5, 24.9, 7.0, -27.7, -3.3 ], [ 0.0, 11.0, -20.0, 11.9, -17.4, 16.7, 7.0, -10.8, 1.7 ], [ 0.0, -20.5, 11.5, 12.8, -7.2, -7.4, 8.0, 2.1, -6.1, 7.0 ], [ 0.0, 2.8, -0.1, 4.7, 4.4, -7.2, -1.0, -3.9, -2.0, -2.0, -8.3 ], [ 0.0, 0.2, 1.7, -0.6, -1.8, 0.9, -0.4, -2.5, -1.3, -2.1, -1.9, -1.8 ], [ 0.0, -0.9, 0.3, 2.1, -2.5, 0.5, 0.6, 0.0, 0.1, 0.3, -0.9, -0.2, 0.9 ] ]; const DELTA_G = [ [ 0.0 ], [ 11.6, 16.5 ], [ -12.1, -4.4, 1.9 ], [ 0.4, -4.1, -2.9, -7.7 ], [ -1.8, 2.3, -8.7, 4.6, -2.1 ], [ -1.0, 0.6, -1.8, -1.0, 0.9, 1.0 ], [ -0.2, -0.2, -0.1, 2.0, -1.7, -0.3, 1.7 ], [ 0.1, -0.1, -0.6, 1.3, 0.4, 0.3, -0.7, 0.6 ], [ -0.1, 0.1, -0.6, 0.2, -0.2, 0.3, 0.3, -0.6, 0.2 ], [ 0.0, -0.1, 0.0, 0.3, -0.4, -0.3, 0.1, -0.1, -0.4, -0.2 ], [ 0.0, 0.0, -0.1, 0.2, 0.0, -0.1, -0.2, 0.0, -0.1, -0.2, -0.2 ], [ 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.1, 0.0 ], [ 0.0, 0.0, 0.1, 0.1, -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.1, 0.1 ] ]; const DELTA_H = [ [ 0.0 ], [ 0.0, -25.9 ], [ 0.0, -22.5, -11.8 ], [ 0.0, 7.3, -3.9, -2.6 ], [ 0.0, 1.1, 2.7, 3.9, -0.8 ], [ 0.0, 0.4, 1.8, 1.2, 4.0, -0.6 ], [ 0.0, -0.2, -2.1, -0.4, -0.6, 0.5, 0.9 ], [ 0.0, 0.7, 0.3, -0.1, -0.1, -0.8, -0.3, 0.3 ], [ 0.0, -0.1, 0.2, 0.4, 0.4, 0.1, -0.1, 0.4, 0.3 ], [ 0.0, 0.0, -0.2, 0.0, -0.1, 0.1, 0.0, -0.2, 0.3, 0.2 ], [ 0.0, 0.1, -0.1, 0.0, -0.1, -0.1, 0.0, -0.1, -0.2, 0.0, -0.1 ], [ 0.0, 0.0, 0.1, 0.0, 0.1, 0.0, 0.1, 0.0, -0.1, -0.1, 0.0, -0.1 ], [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] ]; const BASE_TIME = (new Date(2010, 1, 1)).getTime(); const MAX_N = G_COEFF.length; // Maximum degree of the coefficients. // The ratio between the Gauss-normalized associated Legendre functions and // the Schmid quasi-normalized ones. Compute these once staticly since they // don't depend on input variables at all. const SCHMIDT_QUASI_NORM_FACTORS = GeomagneticField.computeSchmidtQuasiNormFactors(MAX_N); // We don't handle the north and south poles correctly -- pretend that // we're not quite at them to avoid crashing. gdLatitudeDeg = Math.min(90.0 - 1e-5, Math.max(-90.0 + 1e-5, gdLatitudeDeg)); this.computeGeocentricCoordinates(gdLatitudeDeg, gdLongitudeDeg, altitudeMeters); // Note: LegendreTable computes associated Legendre functions for // cos(theta). We want the associated Legendre functions for // sin(latitude), which is the same as cos(PI/2 - latitude), except the // derivate will be negated. const legendre = new LegendreTable(MAX_N - 1, Math.PI / 2.0 - this.mGcLatitudeRad); // Compute a table of (EARTH_REFERENCE_RADIUS_KM / radius)^n for i in // 0..MAX_N-2 (this is much faster than calling Math.pow MAX_N+1 times). let relativeRadiusPower = new Array(MAX_N + 2); relativeRadiusPower[0] = 1.0; relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS_KM / this.mGcRadiusKm; for (let i = 2; i < relativeRadiusPower.length; ++i) { relativeRadiusPower[i] = relativeRadiusPower[i - 1] * relativeRadiusPower[1]; } // Compute tables of sin(lon * m) and cos(lon * m) for m = 0..MAX_N -- // this is much faster than calling Math.sin and Math.com MAX_N+1 times. let sinMLon = new Array(MAX_N); let cosMLon = new Array(MAX_N); sinMLon[0] = 0.0; cosMLon[0] = 1.0; sinMLon[1] = Math.sin(this.mGcLongitudeRad); cosMLon[1] = Math.cos(this.mGcLongitudeRad); for (let m = 2; m < MAX_N; ++m) { // Standard expansions for sin((m-x)*theta + x*theta) and // cos((m-x)*theta + x*theta). let x = m >> 1; sinMLon[m] = sinMLon[m-x] * cosMLon[x] + cosMLon[m-x] * sinMLon[x]; cosMLon[m] = cosMLon[m-x] * cosMLon[x] - sinMLon[m-x] * sinMLon[x]; } let inverseCosLatitude = 1.0 / Math.cos(this.mGcLatitudeRad); let yearsSinceBase = (timeMillis - BASE_TIME) / (365 * 24 * 60 * 60 * 1000); // We now compute the magnetic field strength given the geocentric // location. The magnetic field is the derivative of the potential // function defined by the model. See NOAA Technical Report: The US/UK // World Magnetic Model for 2010-2015 for the derivation. let gcX = 0.0; // Geocentric northwards component. let gcY = 0.0; // Geocentric eastwards component. let gcZ = 0.0; // Geocentric downwards component. for (let n = 1; n < MAX_N; n++) { for (let m = 0; m <= n; m++) { // Adjust the coefficients for the current date. let g = G_COEFF[n][m] + yearsSinceBase * DELTA_G[n][m]; let h = H_COEFF[n][m] + yearsSinceBase * DELTA_H[n][m]; // Negative derivative with respect to latitude, divided by // radius. This looks like the negation of the version in the // NOAA Techincal report because that report used // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the // derivative with respect to theta is negated. gcX += relativeRadiusPower[n+2] * (g * cosMLon[m] + h * sinMLon[m]) * legendre.mPDeriv[n][m] * SCHMIDT_QUASI_NORM_FACTORS[n][m]; // Negative derivative with respect to longitude, divided by // radius. gcY += relativeRadiusPower[n+2] * m * (g * sinMLon[m] - h * cosMLon[m]) * legendre.mP[n][m] * SCHMIDT_QUASI_NORM_FACTORS[n][m] * inverseCosLatitude; // Negative derivative with respect to radius. gcZ -= (n + 1) * relativeRadiusPower[n+2] * (g * cosMLon[m] + h * sinMLon[m]) * legendre.mP[n][m] * SCHMIDT_QUASI_NORM_FACTORS[n][m]; } } // Convert back to geodetic coordinates. This is basically just a // rotation around the Y-axis by the difference in latitudes between the // geocentric frame and the geodetic frame. let latDiffRad = (gdLatitudeDeg * Math.PI / 180) - this.mGcLatitudeRad; this.mX = gcX * Math.cos(latDiffRad) + gcZ * Math.sin(latDiffRad); this.mY = gcY; this.mZ = - gcX * Math.sin(latDiffRad) + gcZ * Math.cos(latDiffRad); } /** * @return The X (northward) component of the magnetic field in nanoteslas. */ get x() { return this.mX; } /** * @return The Y (eastward) component of the magnetic field in nanoteslas. */ get y() { return this.mY; } /** * @return The Z (downward) component of the magnetic field in nanoteslas. */ get z() { return this.mZ; } /** * @return The declination of the horizontal component of the magnetic * field from true north, in radians (i.e. positive means the * magnetic field is rotated east that much from true north). */ get declinationRad() { return Math.atan2(this.mY, this.mX); } /** * @return The inclination of the magnetic field in radians -- positive * means the magnetic field is rotated downwards. */ get inclinationRad() { return Math.atan2(this.mZ, this.horizontalStrength); } /** * @return Horizontal component of the field strength in nonoteslas. */ get horizontalStrength() { return Math.hypot(this.mX, this.mY); } /** * @return Total field strength in nanoteslas. */ get fieldStrength() { return Math.sqrt(this.mX ** 2 + this.mY ** 2 + this.mZ ** 2); } /** * @param gdLatitudeDeg * Latitude in WGS84 geodetic coordinates. * @param gdLongitudeDeg * Longitude in WGS84 geodetic coordinates. * @param altitudeMeters * Altitude above sea level in WGS84 geodetic coordinates. * @return Geocentric latitude (i.e. angle between closest point on the * equator and this point, at the center of the earth. */ computeGeocentricCoordinates(gdLatitudeDeg, gdLongitudeDeg, altitudeMeters) { // Constants from WGS84 (the coordinate system used by GPS) const EARTH_SEMI_MAJOR_AXIS_KM = 6378.137; const EARTH_SEMI_MINOR_AXIS_KM = 6356.7523142; let altitudeKm = altitudeMeters / 1000.0; let a2 = EARTH_SEMI_MAJOR_AXIS_KM * EARTH_SEMI_MAJOR_AXIS_KM; let b2 = EARTH_SEMI_MINOR_AXIS_KM * EARTH_SEMI_MINOR_AXIS_KM; let gdLatRad = gdLatitudeDeg * Math.PI / 180; let clat = Math.cos(gdLatRad); let slat = Math.sin(gdLatRad); let tlat = slat / clat; let latRad = Math.sqrt(a2 * clat * clat + b2 * slat * slat); this.mGcLatitudeRad = Math.atan(tlat * (latRad * altitudeKm + b2) / (latRad * altitudeKm + a2)); this.mGcLongitudeRad = gdLongitudeDeg * Math.PI / 180; let radSq = altitudeKm * altitudeKm + 2 * altitudeKm * Math.sqrt(a2 * clat * clat + b2 * slat * slat) + (a2 * a2 * clat * clat + b2 * b2 * slat * slat) / (a2 * clat * clat + b2 * slat * slat); this.mGcRadiusKm = Math.sqrt(radSq); } /** * Compute the ration between the Gauss-normalized associated Legendre * functions and the Schmidt quasi-normalized version. This is equivalent to * sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)! */ static computeSchmidtQuasiNormFactors(maxN) { let schmidtQuasiNorm = new Array(maxN + 1); schmidtQuasiNorm[0] = [ 1.0 ]; for (let n = 1; n <= maxN; n++) { schmidtQuasiNorm[n] = new Array(n + 1); schmidtQuasiNorm[n][0] = schmidtQuasiNorm[n - 1][0] * (2 * n - 1) / n; for (let m = 1; m <= n; m++) { schmidtQuasiNorm[n][m] = schmidtQuasiNorm[n][m - 1] * Math.sqrt((n - m + 1) * (m == 1 ? 2 : 1) / (n + m)); } } return schmidtQuasiNorm; } }
JavaScript
class Portal extends Component { static propTypes = { /** * The children to be rendered in the passed in `container`. */ children: PropTypes.node, /** * The `container` will have the children appended to itself during mount. * Default value is the `document.body`. */ container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), /** * Disable the React portal behavior. * Only the children are rendered. */ disable: PropTypes.bool, /** * Callback fired upon the children being rendered in the `container`. */ onMount: PropTypes.func, }; static defaultProps = { children: null, container: null, disable: false, onMount: () => {}, }; // Define an empty container container = null; componentDidMount() { // Set the container and force render if needed. this.setContainerAndRender(this.props); } componentDidUpdate(prevProps, prevState) { const { container, disable } = this.props; if (prevProps.container !== container || prevProps.disable !== disable) { // Set the container and force render if needed. this.setContainerAndRender(this.props); } } componentWillUnmount() { // Remove the current container this.container = null; } setContainerAndRender = props => { const { container, disable, onMount } = props; // Set the container this.setContainer(container); // Force the render when needed. // This skips the `shouldComponentUpdate` method call. if (!disable) { this.forceUpdate(onMount); } }; setContainer = container => { const { disable } = this.props; // If the Portal is `disable`d, then set the current DOM node's parent as the container. if (disable) { this.container = findDOMNode(this).parentElement; return; } // Otherwise, find the current passed in `container`'s parent and set it to the `container`. this.container = getContainer(container, getDocumentOwner(this).body); }; render() { const { children, disable } = this.props; // If the Portal is disabled, render just the children. if (disable) { return children; } // Create the portal for the current children, and the chosen container. return this.container ? createPortal(children, this.container) : null; } }
JavaScript
class LineChartComponent extends Component { constructor(props) { super(props); } render() { return ( <div className="textCenter"> <Header>System Load Since Page Load</Header> <div className="lineChart"> <LineChart width={800} height={300} data={this.props.value} margin={{top: 5, right: 30, left: 20, bottom: 5}}> <XAxis dataKey="count" /> <YAxis /> <CartesianGrid strokeDasharray="3 3"/> <Tooltip/> <Legend /> <Line type="monotone" dataKey="CPUload" stroke="#8884d8" activeDot={{r: 8}}/> <Line type="monotone" stroke="#82ca9d" /> </LineChart></div> </div> ); } }
JavaScript
class SwapElementsPlugin extends PureComponent { state = { activeTab: null, activeModeler: null, disabled: true, modelers: [] } constructor(props) { super(props); const { subscribe } = props; subscribe('bpmn.modeler.configure', (event) => { const { middlewares } = event; middlewares.push(addModule(SwapElements)); }); subscribe('app.activeTabChanged', (event) => { const { activeTab } = event; this.setState({ activeTab }); }); subscribe('bpmn.modeler.created', (event) => { const { tab, modeler } = event; this.setState({ modelers: { ...this.state.modelers, [tab.id]: modeler } }); const eventBus = modeler.get('eventBus'); eventBus.on('selection.changed', this.handleSelectionChange); }); } handleSelectionChange = (context) => { const { newSelection: selectedElements } = context; const { activeTab } = this.state; const modeler = this.getModeler(activeTab); const swapElements = modeler.get('swapElements'); const canBeSwapped = swapElements.canBeSwapped(selectedElements); this.setState({ disabled: !canBeSwapped }); } swapSelectedElements = () => { const { activeTab, disabled } = this.state; if (disabled) { return; } const modeler = this.getModeler(activeTab); const swapElements = modeler.get('swapElements'); const selection = modeler.get('selection'); const currentSelection = selection.get(); swapElements.trigger(currentSelection); } getModeler(tab) { const { modelers } = this.state; return modelers[tab.id]; } render() { const { disabled } = this.state; return <Fragment> <Fill slot="toolbar" group="9_swapElements"> <ExchangeSvg className={ 'swap-elements-icon ' + (disabled ? 'disabled' : '') } onClick={ this.swapSelectedElements } /> </Fill> </Fragment>; } }
JavaScript
class SelectMenuComponent extends Component { /** * The placeholder for this select menu * @type {?string} * @readonly */ get placeholder() { return this.data.placeholder ?? null; } /** * The maximum amount of options that can be selected * @type {?number} * @readonly */ get maxValues() { return this.data.max_values ?? null; } /** * The minimum amount of options that must be selected * @type {?number} * @readonly */ get minValues() { return this.data.min_values ?? null; } /** * The custom id of this select menu * @type {string} * @readonly */ get customId() { return this.data.custom_id; } /** * Whether this select menu is disabled * @type {?boolean} * @readonly */ get disabled() { return this.data.disabled ?? null; } /** * The options in this select menu * @type {APISelectMenuOption[]} * @readonly */ get options() { return this.data.options; } }
JavaScript
class GetShipmentItemsResult { /** * Constructs a new <code>GetShipmentItemsResult</code>. * @alias module:client/models/GetShipmentItemsResult * @class */ constructor() { } /** * Constructs a <code>GetShipmentItemsResult</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:client/models/GetShipmentItemsResult} obj Optional instance to populate. * @return {module:client/models/GetShipmentItemsResult} The populated <code>GetShipmentItemsResult</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new GetShipmentItemsResult(); if (data.hasOwnProperty('ItemData')) { obj['ItemData'] = InboundShipmentItemList.constructFromObject(data['ItemData']); } if (data.hasOwnProperty('NextToken')) { obj['NextToken'] = ApiClient.convertToType(data['NextToken'], 'String'); } } return obj; } /** * @member {module:client/models/InboundShipmentItemList} ItemData */ 'ItemData' = undefined; /** * When present and not empty, pass this string token in the next request to return the next response page. * @member {String} NextToken */ 'NextToken' = undefined; }
JavaScript
class MatchmakerWrapper { /** * instantiate wrapper * @param {matchmaker} main */ constructor(main) { // capture main app this.app = main; // add a series of shutdown handlers this.shutdownHandlers = new Set(); // deconstruct relevant configs const { http, matchmaker, cirrusServers, config: { metricsPort } } = main; // deconstruct env const { DEBUG, NAMESPACE, STREAM_SERVICE_NAME } = process.env; const streamSvc = STREAM_SERVICE_NAME + (NAMESPACE ? `.${NAMESPACE}.svc.cluster.local` : ''); // instantiate the custom gateway, and metrics this.metrics = new MetricsAdapter({ port: metricsPort, prefix: 'matchmaker_' }); this.gateway = new PlayerConnectionGateway({ lastPingMax: LAST_PING_MAX, // threshold for identifying dead connections server: http, // reuse the http server matchmaker, // attach to matchmaker net.server pool: cirrusServers, // forward the pool connection map metrics: this.metrics, // provide metrics hooks streamSvc, // dns name for internal (headless) stream service debug: !!DEBUG, // debug }); this.registerSocketShutdown(this.gateway.wss); // initialize wrapper features this.init(); } _info(...args) { console.log(`${this.constructor.name} INFO:`, ...args); } _error(...args) { console.error(`${this.constructor.name} ERROR:`, ...args); } init() { this .setupInstrumentation() .setupExtensions() .setupGracefulShutdown(); } /** * start any necessary services * @returns {this} */ run() { // start metrics service this.metrics.listen(() => this._info('metrics service up')); return this; } /** * process shutdown * @param {*} event */ async shutdown(event) { this._info('processing shutdown handlers for signal', event); await Promise.all([...this.shutdownHandlers.values()] .map(cb => Promise.resolve(cb()))) .catch(e => this._error('graceful shutdown error:', e)); this._info('shutdown complete. exiting'); process.exit(0); } /** * register a shutdown handler * @param {(): Promise<void>|void} cb * @returns {this} */ registerShutdown(cb) { this.shutdownHandlers.add(cb); return this; } /** * catch the process termination signals * @returns {this} */ setupGracefulShutdown() { process.once('SIGTERM', this.shutdown.bind(this)); const { http, matchmaker, cirrusServers } = this.app; // add shutdown handlers this.registerShutdown(() => { this._info('close metrics server'); return new Promise(resolve => this.metrics.server ? this.metrics.server.close(resolve) : resolve()) .then(() => this._info('metrics server closed')); }) .registerShutdown(promisify(http.close).bind(http)) .registerShutdown(promisify(matchmaker.close).bind(matchmaker)) .registerShutdown(() => cirrusServers.forEach((_, conn) => conn.destroy())); return this; } /** * perform any extra/custom instrumentation * @returns {this} */ setupInstrumentation() { const { http, matchmaker, // matchmaker net.server } = this.app; this.metrics.gauge('streamer_connections', { async collect() { this.set(await promisify(matchmaker.getConnections).call(matchmaker)); } }); return this; } /** * perform any necessary extensions on the main app objects */ setupExtensions() { const { app, // matchmaker express app matchmaker, // matchmaker net.server cirrusServers, // cirrus pool map } = this.app; // add basic healthcheck app.get('/healthz', (req, res) => res.send('ok')); // add basic list api app.get('/list', (req, res) => res.json([...cirrusServers.values()])); // setup pool monitor to detect lost pings (cirrus pings every 30s) setInterval(() => [...cirrusServers.values()] .filter(c => (c.lastPingReceived < (Date.now() - LAST_PING_MAX))) .forEach(c => cirrusServers.delete(c)) , LAST_PING_MAX / 2); // handle cirrus connections (after main matchmaker.js) matchmaker.on('connection', connection => { // must capture the remote address of this connection. // It is the connection path back to cirrus const address = connection.remoteAddress.split(':').pop(); connection.on('data', msg => { try { msg = JSON.parse(msg); if (msg.type === 'connect') { const c = cirrusServers.get(connection); // lookup if (c) { this._info('extend streamer configuration'); Object.assign(c, { id: uuid(), // create an identifier address, // overload address as the internal connection (pod ip) restPort: msg.restPort || null, // the stream api port }); } else { this._error('could not locate cirrus on connection'); } } } catch (e) { this._error('unrecognized cirrus data', msg); } }); }); return this; } /** * gracefully handle socket shutdowns * @param {WebSocket.Server} wss */ registerSocketShutdown(wss) { this.registerShutdown(async () => { this._info('websocket server shutdown'); // fire close wss.clients.forEach(ws => ws.close()); wss.close(); // wait and kill if necessary await new Promise(resolve => { setTimeout(() => resolve(wss.clients.forEach((socket) => { if ([WebSocket.OPEN, WebSocket.CLOSING].includes(socket.readyState)) { socket.terminate(); } })), 2e3); }); this._info('websocket server shutdown complete'); }); } }
JavaScript
class PostResponseInfo { /** * Constructs a new <code>PostResponseInfo</code>. * Response that a user will receive on successful report creation * @alias module:model/PostResponseInfo */ constructor() { PostResponseInfo.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PostResponseInfo</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PostResponseInfo} obj Optional instance to populate. * @return {module:model/PostResponseInfo} The populated <code>PostResponseInfo</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PostResponseInfo(); if (data.hasOwnProperty('status')) { obj['status'] = ApiClient.convertToType(data['status'], 'String'); } if (data.hasOwnProperty('report_id')) { obj['report_id'] = ApiClient.convertToType(data['report_id'], 'String'); } } return obj; } }
JavaScript
class InlineResponse2003InstrumentCategorization { /** * Constructs a new <code>InlineResponse2003InstrumentCategorization</code>. * Debt instrument categorization. See endpoint &#x60;/category/listBySystem&#x60; with &#x60;id&#x3D;18&#x60; for valid values. * @alias module:model/InlineResponse2003InstrumentCategorization */ constructor() { InlineResponse2003InstrumentCategorization.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>InlineResponse2003InstrumentCategorization</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineResponse2003InstrumentCategorization} obj Optional instance to populate. * @return {module:model/InlineResponse2003InstrumentCategorization} The populated <code>InlineResponse2003InstrumentCategorization</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse2003InstrumentCategorization(); if (data.hasOwnProperty('level1')) { obj['level1'] = InlineResponse2003InstrumentCategorizationLevel1.constructFromObject(data['level1']); } if (data.hasOwnProperty('level2')) { obj['level2'] = InlineResponse2003InstrumentCategorizationLevel2.constructFromObject(data['level2']); } if (data.hasOwnProperty('level3')) { obj['level3'] = InlineResponse2003InstrumentCategorizationLevel3.constructFromObject(data['level3']); } } return obj; } }
JavaScript
class NavSocialList extends Component { render() { const navSocials = this.props.links.map( link => ( <a key={link.title} className="nav-social" href={link.href}> <img src={link.imgSrc} /> </a> ) ); return <div className="nav-social-list">{navSocials}</div>; } }
JavaScript
class Game extends Phaser.Game { constructor() { // Add the config file to the game super(config) // Add all the scenes // << ADD ALL SCENES HERE >> // Add all the scenes this.scene.add('BgScene', BgScene) this.scene.add('FgScene', FgScene) this.scene.add('MainScene', MainScene) this.scene.add('StartScene', StartScene) this.scene.add('LobbyScene', LobbyScene) // Start the game with the mainscene this.scene.start('StartScene', StartScene) // << START GAME WITH MAIN SCENE HERE >> } }
JavaScript
class Texture { // helper objects static sDefaultOptions = new TextureOptions() static sRectangle = new Rectangle() static sMatrix = new Matrix() static sPoint = new Point() /** Disposes the underlying texture data. Note that not all textures need to be disposed: * SubTextures (created with 'Texture.fromTexture') just reference other textures and * and do not take up resources themselves; this is also true for textures from an * atlas. */ dispose() { // override in subclasses } /** Sets up a VertexData instance with the correct positions for 4 vertices so that * the texture can be mapped onto it unscaled. If the texture has a <code>frame</code>, * the vertices will be offset accordingly. * * @param vertexData the VertexData instance to which the positions will be written. * @param vertexID the start position within the VertexData instance. * @param attrName the attribute name referencing the vertex positions. * @param bounds useful only for textures with a frame. This will position the * vertices at the correct position within the given bounds, * distorted appropriately. */ setupVertexPositions( vertexData, vertexID = 0, attrName = 'position', bounds = null ) { const { sRectangle, sMatrix } = Texture const frame = this.frame const width = this.width const height = this.height if (frame) sRectangle.setTo(-frame.x, -frame.y, width, height) else sRectangle.setTo(0, 0, width, height) vertexData.setPoint(vertexID, attrName, sRectangle.left, sRectangle.top) vertexData.setPoint( vertexID + 1, attrName, sRectangle.right, sRectangle.top ) vertexData.setPoint( vertexID + 2, attrName, sRectangle.left, sRectangle.bottom ) vertexData.setPoint( vertexID + 3, attrName, sRectangle.right, sRectangle.bottom ) if (bounds) { const scaleX = bounds.width / this.frameWidth const scaleY = bounds.height / this.frameHeight if ( scaleX !== 1.0 || scaleY !== 1.0 || bounds.x !== 0 || bounds.y !== 0 ) { sMatrix.identity() sMatrix.scale(scaleX, scaleY) sMatrix.translate(bounds.x, bounds.y) vertexData.transformPoints(attrName, sMatrix, vertexID, 4) } } } /** Sets up a VertexData instance with the correct texture coordinates for * 4 vertices so that the texture is mapped to the complete quad. * * @param vertexData the vertex data to which the texture coordinates will be written. * @param vertexID the start position within the VertexData instance. * @param attrName the attribute name referencing the vertex positions. */ setupTextureCoordinates( vertexData, vertexID = 0, attrName = 'texCoords', fbo = false ) { this.setTexCoords(vertexData, vertexID, attrName, 0.0, 0.0, fbo) this.setTexCoords(vertexData, vertexID + 1, attrName, 1.0, 0.0, fbo) this.setTexCoords(vertexData, vertexID + 2, attrName, 0.0, 1.0, fbo) this.setTexCoords(vertexData, vertexID + 3, attrName, 1.0, 1.0, fbo) } /** Transforms the given texture coordinates from the local coordinate system * into the root texture's coordinate system. */ localToGlobal(u, v, out = null) { if (!out) out = new Point() if (this === this.root) out.setTo(u, v) else MatrixUtil.transformCoords(this.transformationMatrixToRoot, u, v, out) return out } /** Transforms the given texture coordinates from the root texture's coordinate system * to the local coordinate system. */ globalToLocal(u, v, out = null) { if (!out) out = new Point() if (this === this.root) out.setTo(u, v) else { Texture.sMatrix.identity() Texture.sMatrix.copyFrom(this.transformationMatrixToRoot) Texture.sMatrix.invert() MatrixUtil.transformCoords(Texture.sMatrix, u, v, out) } return out } /** Writes the given texture coordinates to a VertexData instance after transforming * them into the root texture's coordinate system. That way, the texture coordinates * can be used directly to sample the texture in the fragment shader. */ setTexCoords(vertexData, vertexID, attrName, u, v, fbo = false) { const { sPoint } = Texture this.localToGlobal(u, v, sPoint) vertexData.setPoint( vertexID, attrName, sPoint.x, fbo || this.fbo ? 1 - sPoint.y : sPoint.y ) } /** Reads a pair of texture coordinates from the given VertexData instance and transforms * them into the current texture's coordinate system. (Remember, the VertexData instance * will always contain the coordinates in the root texture's coordinate system!) */ getTexCoords(vertexData, vertexID, attrName = 'texCoords', out = null) { if (!out) out = new Point() vertexData.getPoint(vertexID, attrName, out) return this.globalToLocal(out.x, out.y, out) } // properties /** The texture frame if it has one (see class description), otherwise <code>null</code>. * <p>CAUTION: not a copy, but the actual object! Do not modify!</p> */ get frame() { return null } /** The height of the texture in points, taking into account the frame rectangle * (if there is one). */ get frameWidth() { return this.frame ? this.frame.width : this.width } /** The width of the texture in points, taking into account the frame rectangle * (if there is one). */ get frameHeight() { return this.frame ? this.frame.height : this.height } /** The width of the texture in points. */ get width() { return 0 } /** The height of the texture in points. */ get height() { return 0 } /** The width of the texture in pixels (without scale adjustment). */ get nativeWidth() { return 0 } /** The height of the texture in pixels (without scale adjustment). */ get nativeHeight() { return 0 } /** The scale factor, which influences width and height properties. */ get scale() { return 1.0 } /** The Stage3D texture object the texture is based on. */ get base() { return null } /** The concrete texture the texture is based on. */ get root() { return null } /** The <code>Context3DTextureFormat</code> of the underlying texture data. */ //get format() { return Context3DTextureFormat.BGRA; } /** Indicates if the texture contains mip maps. */ get mipMapping() { return false } /** Indicates if the alpha values are premultiplied into the RGB values. */ get premultipliedAlpha() { return false } /** The matrix that is used to transform the texture coordinates into the coordinate * space of the parent texture, if there is one. @default null * * <p>CAUTION: not a copy, but the actual object! Never modify this matrix!</p> */ get transformationMatrix() { return null } /** The matrix that is used to transform the texture coordinates into the coordinate * space of the root texture, if this instance is not the root. @default null * * <p>CAUTION: not a copy, but the actual object! Never modify this matrix!</p> */ get transformationMatrixToRoot() { return null } /** Returns the maximum size constraint (for both width and height) for textures in the * current Context3D profile. */ //static get maxSize() //{ // var target:Starling = Starling.current; // var profile = target ? target.profile : "baseline"; // // if (profile == "baseline" || profile == "baselineConstrained") // return 2048; // else // return 4096; //} /** Indicates if it should be attempted to upload bitmaps asynchronously when the <code>async</code> parameter * is supplied to supported methods. Since this feature is still not 100% reliable in AIR 26 (especially on * Android), it defaults to 'false' for now. * * <p>If the feature is disabled or not available in the current AIR/Flash runtime, the async callback will * still be executed; however, the upload itself will be made synchronously.</p> */ //static get asyncBitmapUploadEnabled() //{ // return ConcreteRectangleTexture.asyncUploadEnabled; //} // //static set asyncBitmapUploadEnabled(value) //{ // ConcreteRectangleTexture.asyncUploadEnabled = value; // ConcretePotTexture.asyncUploadEnabled = value; //} }
JavaScript
class DominoSpecFileTreeItem { constructor(specDescriptor, showShortName) { this._specDescriptor = specDescriptor; this._showShortName = showShortName; } /** * Returns a URI for the spec file that can be opened in the text editor. */ uri() { // The files we get back from the language server need to have // the schema appened to them in order VSCode to understand them. return vscode_1.Uri.parse("file:///" + this._specDescriptor.fileName); } /** * Returns a "tree item" representing a BuildXL spec file for the project browser. */ getTreeItem() { return { command: { arguments: [this, undefined], title: "Open", tooltip: "Open", command: 'dscript.openSpecData' }, contextValue: "dscript.spec", label: this._showShortName ? path.basename(this._specDescriptor.fileName) : this._specDescriptor.fileName, collapsibleState: vscode_1.TreeItemCollapsibleState.None }; } /** * BuildXL spec files currently have no childern. */ getChildren() { return []; } }
JavaScript
class DirectoryTreeItem { constructor(directoryName) { this._directoryName = directoryName; this._retrieveSpecs = true; } // Creates or retrieves a DirectoryTreeItem that represents // the passed in single directory name (path-atom) getOrAddSingleChild(directoryName) { assert.equal(directoryName.includes(path.sep), false); // If this is the first time through, allocate the children if (this._childDirectories === undefined) { this._childDirectories = new Map(); } const directoryNameForMap = directoryName.toLowerCase(); // Create a new item if one does not exist for this directory. if (!this._childDirectories.has(directoryNameForMap)) { const newDirectoryTreeItem = new DirectoryTreeItem(directoryName); this._childDirectories.set(directoryNameForMap, newDirectoryTreeItem); // Let the tree view know that we've added a child. // This will cause the tree-view to re-acquire the childern. dominoDirectoryTreeEventEmitter.fire(this); return newDirectoryTreeItem; } return this._childDirectories.get(directoryNameForMap); } /** * Creates a hierarchy of DirectoryTreeItem's based on the specified path. * @returns A directory tree item representing the last portion of the passed in path. * @param directoryName The path to split apart and create a hierarchy of DirectoryTreeItems */ getOrAddChild(directoryName) { const paths = directoryName.split(path.sep); let nextDirectoryTreeItem = this; paths.forEach((singlePath, index) => { nextDirectoryTreeItem = nextDirectoryTreeItem.getOrAddSingleChild(singlePath); }); return nextDirectoryTreeItem; } /** * Associates a module descriptor with this directory tree item. * @param mod The module to associate with this directory item. */ addModule(mod) { if (this._modules === undefined) { this._modules = []; } this._modules.push(mod); // Let the tree view know that we've added a child. // This will cause the tree-view to re-acquire the childern. dominoDirectoryTreeEventEmitter.fire(this); } /** * Associates the spcified project spec file with this directory item. * @param projectSpec The project spec file to associate with this directory item. */ addProjectSpec(projectSpec) { if (this._projectSpecs === undefined) { this._projectSpecs = []; } this._projectSpecs.push(projectSpec); dominoDirectoryTreeEventEmitter.fire(this); } /** * Returns the tree item to the tree-view for this directory tree item. */ getTreeItem() { return { // Set a context value used by the context menu contribution so // it knows this is a project directory. contextValue: "dscript.projectDirectory", // The label is simply the directory name label: this._directoryName, // The collapisble state has to check multiple things as it can have // multiple children. It needs to check for directories, project specs // and modules. collapsibleState: ((this._childDirectories && this._childDirectories.size !== 0) || (this._projectSpecs && this._projectSpecs.length !== 0) || (this._modules && this._modules.length !== 0)) ? vscode_1.TreeItemCollapsibleState.Collapsed : vscode_1.TreeItemCollapsibleState.None }; } /** * Returns the children known to this directory. */ getChildren() { const directoryChildren = []; // Add our child directories, sorted by name. if (this._childDirectories && this._childDirectories.size !== 0) { directoryChildren.push(...this._childDirectories.values()); directoryChildren.sort((a, b) => { return a._directoryName.localeCompare(b._directoryName); }); } // Add our modules, sorted by module name. const moduleChildren = []; if (this._modules && this._modules.length !== 0) { this._modules.forEach((mod) => { moduleChildren.push(new DominoModuleTreeItem(mod, dominoDirectoryTreeEventEmitter)); }); moduleChildren.sort((a, b) => { return a.descriptor().name.localeCompare(b.descriptor().name); }); } // Add our project specs. const specChildren = []; // If we have not asked the language server for the specs, then do so know. if (this._modules && this._modules.length !== 0 && this._retrieveSpecs) { this._retrieveSpecs = false; this._modules.forEach((mod) => { languageClient.sendRequest(specsForModuleParams_1.SpecsForModulesRequest, { moduleDescriptor: mod }).then((specs) => { specs.specs.forEach((spec, index) => { const directoryTreeItem = directoryTreeItems.getOrAddChild(path.dirname(spec.fileName)); directoryTreeItem.addProjectSpec(spec); }); }); }); } else { if (this._projectSpecs && this._projectSpecs.length !== 0) { this._projectSpecs.forEach((spec) => { specChildren.push(new DominoSpecFileTreeItem(spec, true)); }); specChildren.sort((a, b) => { return a.uri().fsPath.localeCompare(b.uri().fsPath); }); } } // Finally return the child array which is a combination of all three types. return [...directoryChildren, ...moduleChildren, ...specChildren]; } }
JavaScript
class DominoModuleTreeItem { constructor(moduleDescriptor, eventEmiiter) { this._moduleDescriptor = moduleDescriptor; this._collapseState = vscode_1.TreeItemCollapsibleState.Collapsed; this._eventEmiiter = eventEmiiter; } /** * Returns a "tree item" representing a module for the project browser. */ getTreeItem() { return { contextValue: "dscript.module", label: this._moduleDescriptor.name, collapsibleState: this._collapseState }; } expand() { // Note that this does not actually work due to // https://github.com/Microsoft/vscode/issues/40179 this._collapseState = vscode_1.TreeItemCollapsibleState.Expanded; this._eventEmiiter.fire(this); } collapse() { this._collapseState = vscode_1.TreeItemCollapsibleState.Collapsed; this._eventEmiiter.fire(this); } /** * Returns the children of the BuildXL module, which, are currently spec files. */ getChildren() { if (this._children === undefined) { this._children = []; // Capture the this pointer in a block variable so it can // be used after the sendRequest completes. let moduleData = this; languageClient.sendRequest(specsForModuleParams_1.SpecsForModulesRequest, { moduleDescriptor: this._moduleDescriptor }).then((specs) => { specs.specs.forEach((spec, index) => { moduleData._children.push(new DominoSpecFileTreeItem(spec, false)); }); // Now, fire the change event to the tree so that it calls the getChildren again moduleData._eventEmiiter.fire(moduleData); }); } return this._children; } /** * Returns the module descriptor for the item. */ descriptor() { return this._moduleDescriptor; } }
JavaScript
class Dialog { constructor() { this.View = document.getElementById("Dialog"); this.PathSection = document.getElementById("DirPath"); this.PathContent = []; this.Path = undefined; this.ContentList = document.getElementById("ContentList"); this.Content = []; this.Select = document.getElementById("DialogSelect"); this.Cancel = document.getElementById("DialogCancel"); this.Extension = undefined; this.Hint = document.getElementById("FileTypeHint"); this.Action = undefined; this.Cancel.addEventListener("click", evt => this.Hide(evt)); this.Select.addEventListener("click", evt => this.Selected(evt)); } // Hiding the Dialog Hide() { if (this.View.classList.contains("dialog-show")) { this.View.classList.remove("dialog-show"); } this.Reset(); } // Setting the datas in the Dialog Hydrate(data) { this.Reset(); this.SetExtension(data.Extension); this.SetPath(data.Path); this.SetContent(data.Files); dialog.Show(); } // Trigger when the dialog's Select button is clicked Selected() { // Checking for each element wich one is selected for (let index = 0; index < this.Content.length; index++) { // Checking if the element is checked if (this.Content[index].Selected) { // Checking if the selected element as the right extension if (this.Content[index].Extension == this.Extension) { console.log("User select file: " + this.Content[index].Name); // Send message to Go with selected file data.Identifier = this.Action; data.Content = { "File": this.Path + "\\" + this.Content[index].Name, }; astilectron.sendMessage(data); this.Hide(); } return; } } // If the user didn't select anything but the target is a directory, than the file is the current directory if (this.Extension == "none") { // Send message to Go with selected file data.Identifier = this.Action; data.Content = { "File": this.Path + "\\", }; astilectron.sendMessage(data); this.Hide(); } } // Setting the content of the files scrollview SetContent(files) { // Checking if there is files to show if (files != null) { for (let index = 0; index < files.length; index++) { // Creating the new file class var file = new File(files[index]); this.Content.push(file); // Creating the new file elements var fileElement = file.Create(); this.ContentList.appendChild(fileElement); } } } // Setting the dialog needed extension & setting the text of the dialog hint SetExtension(extension) { this.Extension = extension; // Checking if the required type is a directory or a file if (this.Extension == "none") { this.Hint.innerHTML = "Select a directory"; } else { this.Hint.innerHTML = "Select a " + this.Extension + " file"; } } // Filling the Ariane's string with the required path SetPath(fullPath) { this.Path = fullPath; var paths = this.Path.split("\\"); for (let index = 0; index < paths.length; index++) { if (paths[index] != "") { // Creating the Path element & getting his class & his elements var path = new Path(fullPath, paths[index]); this.PathContent.push(path); var pathElement = path.Create(); this.PathSection.appendChild(pathElement); // Creating the "/" after each path directory var slash = document.createElement("li"); slash.innerHTML = "/"; this.PathSection.appendChild(slash); } } } // Showing the Dialog Show() { if (!this.View.classList.contains("dialog-show")) { this.View.classList.add("dialog-show"); } } // Reset the dialog's vars & contents Reset() { this.ContentList.innerHTML = ""; this.PathSection.innerHTML = ""; // Reseting the Files Content of the Dialog for (let index = 0; index < this.Content.length; index++) { delete this.Content[index]; } this.Content = []; // Reseting the Path Content of the Dialog for (let index = 0; index < this.PathContent.length; index++) { delete this.PathContent[index]; } this.PathContent = []; } }
JavaScript
class File { constructor(data) { this.Element = document.createElement("li"); this.Button = document.createElement("button"); this.IsDir = data.IsDir; this.Name = data.Name; this.Selected = false; if (this.IsDir) { this.Extension = "none"; } else { this.Extension = data.Extension; } this.Button.addEventListener("click", evt => this.Select(evt)); if (this.IsDir) { this.Button.addEventListener("dblclick", evt => this.GoTrough(evt)); } return this; } // Create the new file Create() { if (this.IsDir) { this.Button.classList.add("directory"); }else { this.Button.classList.add("file"); } this.Button.innerHTML = this.Name; this.Element.appendChild(this.Button); return this.Element; } // Unselect the file Unselect() { this.Button.classList.remove("selected-content"); this.Selected = false; } // Select the file Select() { // Checking if another file is selected for (let index = 0; index < dialog.Content.length; index++) { if (dialog.Content[index].Selected) { // Unselect the file if it is not this if (dialog.Content[index].Name != this.Name) { dialog.Content[index].Unselect(); } break; } } // Set selected if not already selectd if (!this.Selected) { this.Button.classList.add("selected-content"); this.Selected = true; } else { // Unselect if already selected this.Unselect(); } } // Action when the directory is dblclicked GoTrough() { console.log("Going trough " + dialog.Path + "\\" + this.Name); // Send message to Go with the path to follow data.Identifier = "GoTroughFolder"; data.Content = { "Path": dialog.Path + "\\" + this.Name, "Extension": dialog.Extension, "Action": dialog.Action }; astilectron.sendMessage(data); } }
JavaScript
class Path { constructor(fullpath, name) { this.Element = document.createElement("li"); this.Button = document.createElement("button"); this.Name = name; var path = fullpath.split(name); this.Path = path[0] + name + "\\"; this.Button.addEventListener("click", evt => this.Select(evt)); return this; } // Create the path element & return it Create() { this.Button.innerHTML = this.Name; this.Element.appendChild(this.Button); return this.Element; } // Select when the user click on this path Select() { // Send message to Go with the path to follow data.Identifier = "GoTroughFolder"; data.Content = { "Path": this.Path, "Extension": dialog.Extension, "Action": dialog.Action }; astilectron.sendMessage(data); } }
JavaScript
class SyncbackTaskFactory { static create(account, syncbackRequest) { let Task = null; switch (syncbackRequest.type) { case "MoveThreadToFolder": Task = require('./syncback-tasks/move-thread-to-folder.imap'); break; case "SetThreadLabels": Task = require('./syncback-tasks/set-thread-labels.imap'); break; case "SetThreadFolderAndLabels": Task = require('./syncback-tasks/set-thread-folder-and-labels.imap'); break; case "MarkThreadAsRead": Task = require('./syncback-tasks/mark-thread-as-read.imap'); break; case "MarkThreadAsUnread": Task = require('./syncback-tasks/mark-thread-as-unread.imap'); break; case "StarThread": Task = require('./syncback-tasks/star-thread.imap'); break; case "UnstarThread": Task = require('./syncback-tasks/unstar-thread.imap'); break; case "CreateCategory": Task = require('./syncback-tasks/create-category.imap'); break; case "RenameFolder": Task = require('./syncback-tasks/rename-folder.imap'); break; case "RenameLabel": Task = require('./syncback-tasks/rename-label.imap'); break; case "DeleteFolder": Task = require('./syncback-tasks/delete-folder.imap'); break; case "DeleteLabel": Task = require('./syncback-tasks/delete-label.imap'); break; case "EnsureMessageInSentFolder": Task = require('./syncback-tasks/ensure-message-in-sent-folder.imap'); break; case "SyncUnknownUIDs": Task = require('./syncback-tasks/sync-unknown-uids.imap'); break; default: throw new Error(`Task type not defined in syncback-task-factory: ${syncbackRequest.type}`) } return new Task(account, syncbackRequest) } }
JavaScript
class MovieDBClient extends BaseClient{ /** * @param {string} apiKey The movie db api key ([Ref]{@link https://developers.themoviedb.org/3/getting-started/introduction}) * @param {string} baseUrl Base url for movie db api */ constructor(apiKey, baseUrl) { super(apiKey, baseUrl); } /** * Get a movie db client instance. * @param {string} apiKey The movie db api key * @returns {MovieDBClient} */ static getInstance(apiKey) { return new MovieDBClient(apiKey, 'https://api.themoviedb.org/3/'); } get authParam() { return 'api_key'; } get requestKeyMap() { return { title: 'query', query: 'query', page: 'page', year: 'primary_release_year' }; } /** * Get a media(movie/series) by looking up using different params (e.g. title, imdb id, year etc.) * @param {object} options The options based on which the movie will be fetched. * @example * get({title: 'Saw', year: 2004, type: 'movie'}) * @example * get({imdbID: 'tt12444'}) * @returns {Promise} * @fulfil {object} - The movie/series object. * @reject {Error} - The error with an appropriate `message`. */ get(options) { if (!options.imdbID) { if (!options.title || !options.year || !options.type) { throw new Error('Either one of the format of data must be provided: imdbID | (title, year, type)'); } } let url, responseTransformer, reqOptions = {}; if (options.imdbID) { url = this._getURL('imdbID') + '/' + options.imdbID; reqOptions['external_source'] = 'imdb_id'; responseTransformer = (data) => { let nonEmptyResultsKey = Object.keys(data).filter((k) => { return data[k].length > 0; }); if (nonEmptyResultsKey.length > 0) { return data[nonEmptyResultsKey[0]]; } else { return []; } }; } else { options.type = options.type || 'movie'; reqOptions = this._translateIncomingRequestOptions(options); reqOptions['include_adult'] = false; reqOptions['page'] = 1; url = this._getURL(options.type); if (options.type === 'series') { reqOptions['first_air_date_year'] = options.year; delete reqOptions['primary_release_year']; } let mediaType = options.type === 'series' ? 'tv' : 'movie'; responseTransformer = (data) => { return this._findMatchByTitleAndYear( data.results, options.title, options.year, mediaType, true ); }; } return this._makeHTTPGET( url, reqOptions, null, responseTransformer ).then((resp) => { if (resp.data.length) { // fetch the details return this.getDetails(resp.data[0].id, this._guessMediaType(resp.data[0])); } else { return {}; } }); } /** * Search for a movie/series. * @param {object} options The options based on which the search will be conducted. * @example * search({query: 'Saw', year: 2004, type: 'movie'}) * @returns {Promise} * @fulfil {object} - The movie/series object. * @reject {Error} - The error with an appropriate `message`. */ search(options) { if (!options.query) { throw new Error('Query must be given'); } options.type = options.type || 'movie'; let reqOptions = this._translateIncomingRequestOptions(options); reqOptions['include_adult'] = false; let url = this._getURL('search'); let responseTransformer = (data) => { return { currentPage: options.page, totalPages: data['total_pages'], numFound: data['total_results'], results: data.results.map((result) => { return this._translateResponseObject(result, result['media_type']) }) }; }; return this._makeHTTPGET( url, reqOptions, null, responseTransformer ).then((resp) => { return resp.data; }); } /** * Get a media(movie/series) by title and year * @param {string} title Title of the media (movie/series) * @param {number} year The year media type(movie/series) was released (Optional). * @param {string} [type='movie'] Type of the media; movie/series (Optional). * @returns {Promise} * @fulfil {object} - The movie/series object. * @reject {Error} - The error with an appropriate `message`. */ getByTitleAndYear(title, year, type = 'movie') { return this.get({title: title, year: year, type: type}); } /** * Get a media(movie/series) by IMDB ID * @param {string} imdbID IMDB ID of the media * @returns {Promise} * @fulfil {object} - The movie/series object. * @reject {Error} - The error with an appropriate `message`. */ getByIMDBId(imdbID) { return this.get({imdbID: imdbID}); } /** * Get details of a movie or series with given tmdb id * @param {string} tmdbID The Movie DB ID of the media * @param {string} type The media type; movie/series * @returns {Promise} * @fulfil {object} - The movie/series object. * @reject {Error} - The error with an appropriate `message`. */ getDetails(tmdbID, type) { let mediaType = type === 'series' ? 'tv' : 'movie'; let detailsUrl = this._getURL(type + 'Details') + '/' + tmdbID; return this._makeHTTPGET(detailsUrl, null, null, null) .then((resp) => { return this._translateResponseObject(resp.data, mediaType); }); } _getURL(identifier) { return { movie: 'search/movie', series: 'search/tv', search: 'search/multi', movieDetails: 'movie', seriesDetails: 'tv', genreList: 'genre/movie/list', imdbID: 'find' }[identifier]; } _findMatchByTitleAndYear(movieResults, qTitle, qYear, mediaType, exact=false) { return movieResults.filter((movieResult) => { let titleKey = mediaType === 'tv' ? 'name' : 'title'; let dateKey = mediaType === 'tv' ? 'first_air_date' : 'release_date'; let title = movieResult[titleKey]; let year = movieResult[dateKey].match(/(\d{4})-\d{2}-\d{2}/)[1]; let normalizedTitle = title.toLowerCase().replace(/_|-|\.|:/, ' '); let normalizedQueryTitle = qTitle.toLowerCase(); return exact ? (normalizedQueryTitle === normalizedTitle && year === qYear) : (normalizedTitle.includes(normalizedQueryTitle) || (qYear && year == qYear)); }); } _guessMediaType(response) { return response.name ? 'series' : (response.title ? 'movie' : ''); } _translateResponseObject(responseObj, mediaType) { let response = {}; let titleKey = mediaType === 'tv' ? 'name' : 'title'; let dateKey = mediaType === 'tv' ? 'first_air_date' : 'release_date'; response['id'] = responseObj['id']; response['imdbID'] = responseObj['imdb_id']; response['title'] = responseObj[titleKey]; response['year'] = responseObj[dateKey].match(/(\d{4})-\d{2}-\d{2}/)[1]; response['summary'] = responseObj['overview']; response['poster'] = 'http://image.tmdb.org/t/p/original' + responseObj['poster_path']; response['genres'] = responseObj['genres'] || responseObj['genre_ids']; response['rating'] = responseObj['vote_average']; return response; } }
JavaScript
class RecentItem { testID = { recentItemPrefix: 'search.recent_item.', } getRecentItem = (searchTerms) => { return element(by.id(`${this.testID.recentItemPrefix}${searchTerms}`)); } }
JavaScript
class Dialog extends LightningElement { /** * Dialog name. * * @type {string} * @public */ @api dialogName; /** * The title can include text, and is displayed in the header. To include additional markup or another component, use the title slot. * * @type {string} * @public */ @api title; /** * Message displayed while the modal box is in the loading state. * * @type {string} * @public */ @api loadingStateAlternativeText; _size = DIALOG_SIZES.default; _isLoading; _showDialog = false; showFooter = true; showHeader = true; connectedCallback() { this.setAttribute('dialog-name', this.dialogName); } renderedCallback() { if (this.titleSlot) { this.showTitleSlot = this.titleSlot.assignedElements().length !== 0; this.showHeader = this.title || this.showTitleSlot; } if (this.footerSlot) { this.showFooter = this.footerSlot.assignedElements().length !== 0; } } /** * Title Slot DOM element * * @type {HTMLElement} */ get titleSlot() { return this.template.querySelector('slot[name=title]'); } /** * Footer Slot DOM element * * @type {HTMLElement} */ get footerSlot() { return this.template.querySelector('slot[name=footer]'); } /** * Width of the modal. Accepted sizes include small, medium, large. * * @type {string} * @public * @default medium */ @api get size() { return this._size; } set size(size) { this._size = normalizeString(size, { fallbackValue: DIALOG_SIZES.default, validValues: DIALOG_SIZES.valid }); } /** * If present, the modal box is in a loading state and shows a spinner. * * @public * @type {boolean} * @default false */ @api get isLoading() { return this._isLoading; } set isLoading(value) { this._isLoading = normalizeBoolean(value); } /** * If present, the dialog is open by default. * * @type {boolean} * @default false * @public */ @api get showDialog() { return this._showDialog; } set showDialog(value) { this._showDialog = normalizeBoolean(value); } /** * Verify if Title string present. * * @type {boolean} */ get hasStringTitle() { return !!this.title; } /** * Open the modal box. * * @public */ @api show() { this._showDialog = true; } /** * Close the modal box. * * @public */ @api hide() { this._showDialog = false; /** * The event fired when the dialog closes. * * @event * @name closedialog */ this.dispatchEvent(new CustomEvent('closedialog')); } /** * Set the focus on the close button. * * @public */ @api focusOnCloseButton() { const button = this.template.querySelector('.slds-modal__close'); if (button) button.focus(); } /** * Computed Header class styling. * * @type {string} */ get computedHeaderClass() { return classSet('slds-modal__header') .add({ 'slds-modal__header_empty': !this.showHeader }) .toString(); } /** * Computed Modal class styling * * @type {string} */ get computedModalClass() { return classSet('slds-modal slds-fade-in-open') .add(`slds-modal_${this._size}`) .toString(); } }
JavaScript
class DBHelper { constructor({ host='localhost', port=1338, name='restaurant-reviews', pendingCallback } = {}) { this._host = host; this._port = port; this._name = name; this._pendingCallback = pendingCallback; if (!('serviceWorker' in navigator)) { this._dbPromise = null; return; } this._dbPromise = idb.open(name, 4, upgradeDB => { /* eslint no-undef: 0 */ switch (upgradeDB.oldVersion) { case 0: upgradeDB.createObjectStore('restaurants', { keyPath: 'id' }); upgradeDB.createObjectStore('reviews', { keyPath: 'id' }). createIndex('by-restaurant', 'restaurant_id'); case 1: /* eslint no-fallthrough: 0 */ upgradeDB.createObjectStore('pendingFavorites', { keyPath: 'id' }); case 2: /* eslint no-fallthrough: 0 */ upgradeDB.createObjectStore('pendingReviews', { keyPath: 'restaurant_id' }); case 3: /* eslint no-fallthrough: 0 */ upgradeDB.createObjectStore('pendingDeletions', { keyPath: 'id' }); } }); if (this._pendingCallback) this._isPending().then(pending => void this._pendingCallback({pending})); } get name() { return this._name; } get host() { return this._host; } get port() { return this._port; } get protocol() { if (this.host === 'localhost' || this.host === '127.0.0.1') return 'http'; return 'https'; } get origin() { return `${this.protocol}://${this.host}:${this.port}`; } queryUrl({id=''} = {}) { return `http://localhost:1338/restaurants/${id}`; } networkFetch({id=''} = {}) { return fetch(this.queryUrl({id})); } /** * ============ Generic database methods ============= */ async open({storeName, write=false} = {}) { if (!storeName) return {}; const db = await this._dbPromise; const mode = write ? 'readwrite' : 'readonly'; let index; if (storeName === 'by-restaurant') { index = true; storeName = 'reviews'; } const tx = db.transaction(storeName, mode); let store = tx.objectStore(storeName); if (index) store = store.index('by-restaurant'); return {db, tx, store}; } async get({storeName, id} = {}) { const {store} = await this.open({storeName}); if (id) { if (storeName === 'by-restaurant') { return await store.getAll(id); } return await store.get(id); } return await store.getAll(); } async put({storeName, records}) { if (!Array.isArray(records)) records = [records]; if (storeName === 'by-restaurant') storeName = 'reviews'; const {tx, store} = await this.open({storeName, write: true}); records.forEach(record => store.put(record)); return await tx.complete; } /** * Main fetch method. Pulls data from database for speed/offline first and * then goes to network to check for updates. * * The callback will be called twice: once on the local data and then again on * the network response (if it succeeds). * * The return value is a promise which resolves to the local response, or the * network response if no local response exists. * * After a successful network fetch, at attempt is made to reconcile any * pending local transactions. This serves two purposes: * - syncing with remote server as soon as network is available * - ensuring pending changes are preserved in the local database and are not * overwritten by stale data from the network * This reconciliation is performed before the second callback, to ensure that * the final UI update uses the authoritative state. */ async fetch({storeName, restaurant_id, id, callback}) { let queryUrl = `${this.origin}/${storeName}/`; let localResult; if (id) { queryUrl += id; } else if (restaurant_id) { id = restaurant_id; queryUrl += `?restaurant_id=${restaurant_id}`; storeName = 'by-restaurant'; // get locally stored (pending) reviews const {tx, store} = await this.open({storeName: 'pendingReviews'}); localResult = await store.get(id); await tx.complete; } const result = await this.get({storeName, id}); if (localResult) result.push(localResult); if (callback) callback(result); const networkResult = fetch(queryUrl).then(async response => { if (response.status === 200) { this.put({ storeName, records: await response.json() }); await this._tryPending(); const result = await this.get({storeName, id}); if (callback) callback(result); return result; } }).catch(err => { console.log(`Fetch for ${queryUrl} failed:`, err); }); return result || await networkResult; } getReview({id, callback}) { return this.fetch({storeName: 'reviews', id, callback}); } getReviewsForRestaurant({restaurant_id, callback}) { if (!restaurant_id) return []; return this.fetch({storeName: 'reviews', restaurant_id, callback}); } getReviews({callback} = {}) { return this.fetch({storeName: 'reviews', callback}); } getRestaurant({id, callback}) { return this.fetch({storeName: 'restaurants', id, callback}); } getRestaurants({callback} = {}) { return this.fetch({storeName: 'restaurants', callback}); } async searchRestaurants({cuisine, neighborhood, callback}) { const filterByCuisine = filterOnProp('cuisine_type', cuisine); const filterByNeighborhood = filterOnProp('neighborhood', neighborhood); const search = restaurants => { let results = restaurants; if (cuisine && cuisine != 'all') results = filterByCuisine(results); if (neighborhood && neighborhood != 'all') results = filterByNeighborhood(results); return results; }; const restaurants = await this.getRestaurants({ callback: callback && (ls => callback(search(ls))) }); return search(restaurants); } async getPropertyValues({property, callback}) { const restaurants = await this.getRestaurants({ callback: callback && (ls => callback(extractProp(property)(ls))) }); return extractProp(property)(restaurants); } getNeighborhoods({callback} = {}) { return this.getPropertyValues({property: 'neighborhood', callback}); } getCuisines({callback} = {}) { return this.getPropertyValues({property: 'cuisine_type', callback}); } async deleteReview({id, restaurant_id}) { // if the review has an ID then it's already on the server // if not, it's local only. in this case, deletion is simple if (!id) { if (!restaurant_id) return; const {tx, store} = await this.open({storeName: 'pendingReviews', write: true}); store.delete(restaurant_id); return tx.complete; } else { localStorage.removeItem(`user-owns-review-${id}`); const alreadyPending = await this._isPending(); const {tx, store} = await this.open({storeName: 'reviews', write: true}); store.delete(id); await tx.complete; if (! await this._deleteReviewNetworkFetch(id)) { const {tx, store} = await this.open({storeName: 'pendingDeletions', write: true}); store.put({id, type: 'review'}); if (this._pendingCallback && !alreadyPending) this._pendingCallback({pending: true}); await tx.complete; } } } async _deleteReviewNetworkFetch(id) { const method = 'DELETE'; const url = `${this.origin}/reviews/${id}`; try { const response = await fetch(url, {method}); if (response.status === 200) return true; } catch (err) { console.log('Fetch failed:', err); } return false; } async _applyPendingNetworkDeletions() { const {store} = await this.open({storeName: 'pendingDeletions'}); const pendingDeletions = await store.getAll(); const result = (await Promise.all(pendingDeletions.map( ({id}) => this._deleteReviewNetworkFetch(id) ))).every(x => x); return result; } async saveReview({review, callback}) { await this._tryPending(); const response = await this._saveReviewNetworkFetch(review); if (response) { localStorage.setItem(`user-owns-review-${response.id}`, true); this.put({storeName: 'reviews', records: response}); callback(response); } else { const alreadyPending = await this._isPending(); const {tx, store} = await this.open({storeName: 'pendingReviews', write: true}); store.put(review); if (this._pendingCallback && !alreadyPending) { this._pendingCallback({pending: true}); } callback(review); await tx.complete; } return response; } async _saveReviewNetworkFetch({id, restaurant_id, name, rating, comments}) { let method = id ? 'PUT' : 'POST'; const okCode = id ? 200 : 201; let url = `${this.origin}/reviews`; const body = { name, rating, comments }; if (id) { url += `/${id}`; } else { body.restaurant_id = restaurant_id; } try { const response = await fetch(url, {method, body: JSON.stringify(body)}); if (response.status === okCode) { return await response.json(); } } catch (err) { console.log(err); } return null; } async setFavorite({id, is_favorite}) { // we do not use our network wrapping functions here: // unlike reviews, we cannot PUT restaurants and so the network database // cannot be generically kept in sync with the local database // // instead we make changes directly to the IDB store while also queueing a // fetch to update the favorite status on the server const {tx, store} = await this.open({storeName: 'restaurants', write: true}); const restaurant = await store.get(id); restaurant.is_favorite = is_favorite; store.put(restaurant); this._setFavoriteNetwork({id, is_favorite}); return tx.complete; } async _setFavoriteNetwork({id, is_favorite}) { // Try to resolve pending transactions over the network (no need to worry // about latency ― the local database was already updated). await this._tryPending(); // Now try to apply current transaction. const success = await this._setFavoriteNetworkFetch({id, is_favorite}); // If remote save failed, we are probably offline so let's queue it for later. if (!success) { // 1. Check if there are already pending transactions: we need this to // decide whether to notify client via `this._pendingCallback`. const alreadyPending = await this._isPending(); // 2. Open store and write transaction. const {tx, store} = await this.open({storeName: 'pendingFavorites', write: true}); store.put({id, is_favorite}); // 3. Notify client if necessary. if (this._pendingCallback && !alreadyPending) { this._pendingCallback({pending: true}); } return await tx.complete; } } async _setFavoriteNetworkFetch({id, is_favorite}) { const url = `${this.origin}/restaurants/${id}/?is_favorite=${is_favorite}`; try { const response = await fetch(url, {method: 'PUT'}); if (response.status !== 200) throw new Error(`Failed to set is_favorite=${is_favorite} for restaurant ${id} on remote server.`); } catch (err) { console.log('Error setting favorite over network:', err); return false; } return true; } async _applyPendingNetworkFavorites() { const {tx, store} = await this.open({storeName: 'pendingFavorites'}); const networkPromises = []; const changes = []; store.iterateCursor(cursor => { if (!cursor) return; networkPromises.push(this._setFavoriteNetworkFetch(cursor.value)); changes.push(cursor.value); cursor.continue(); }); await tx.complete; const success = (await Promise.all(networkPromises)).every(x => x === true); await this._applyPendingLocalFavorites(changes); return success; } async _applyPendingLocalFavorites(changes) { const {tx, store} = await this.open({ storeName: 'restaurants', write: true }); changes.forEach(async ({id, is_favorite}) => { const restaurant = await store.get(id); restaurant.is_favorite = is_favorite; store.put(restaurant); }); return await tx.complete; } async _applyPendingNetworkReviews() { const {store} = await this.open({storeName: 'pendingReviews'}); const pendingReviews = await store.getAll(); const changes = await Promise.all(pendingReviews.map( this._saveReviewNetworkFetch.bind(this) )); const success = changes.every(x => x); await this._applyPendingLocalReviews(changes.filter(x => x)); return success; } async _applyPendingLocalReviews(changes) { const {tx, store} = await this.open({storeName: 'reviews', write: true}); changes.forEach(review => { store.put(review); localStorage.setItem(`user-owns-review-${review.id}`, true); }); return tx.complete; } async _erasePending(storeName) { if (!storeName) { await applyToPendingStores(this._erasePending.bind(this)); // now reset warning status ― user will be warned next time there is no // connection localStorage.removeItem('user_warned'); return; } const {tx, store} = await this.open({storeName, write: true}); store.clear(); return await tx.complete; } async _tryPending() { if (!await this._isPending()) return; const success = (await Promise.all([ this._applyPendingNetworkFavorites(), this._applyPendingNetworkReviews(), this._applyPendingNetworkDeletions() ])).every(x => x); if (success) { // if we successfully reconciled with network, wipe pending transactions // from IDB await this._erasePending(); if (this._pendingCallback) this._pendingCallback({pending: false}); } } async _isPending(storeName) { if (!storeName) { return (await applyToPendingStores(x => this._isPending(x))). some(x => x); } const {tx, store} = await this.open({storeName}); let pending = (await store.count()) > 0; await tx.complete; return pending; } }
JavaScript
class PseudoWeakRef { constructor(ref) { this._ref = ref; } /** * Disassociates the ref with the backing instance. */ disconnect() { this._ref = undefined; } /** * Reassociates the ref with the backing instance. */ reconnect(ref) { this._ref = ref; } /** * Retrieves the backing instance (will be undefined when disconnected) */ deref() { return this._ref; } }
JavaScript
class Pauser { constructor() { this._promise = undefined; this._resolve = undefined; } /** * When paused, returns a promise to be awaited; when unpaused, returns * undefined. Note that in the microtask between the pauser being resumed * an an await of this promise resolving, the pauser could be paused again, * hence callers should check the promise in a loop when awaiting. * @returns A promise to be awaited when paused or undefined */ get() { return this._promise; } /** * Creates a promise to be awaited */ pause() { var _a; (_a = this._promise) !== null && _a !== void 0 ? _a : (this._promise = new Promise((resolve) => (this._resolve = resolve))); } /** * Resolves the promise which may be awaited */ resume() { var _a; (_a = this._resolve) === null || _a === void 0 ? void 0 : _a.call(this); this._promise = this._resolve = undefined; } }
JavaScript
class SingleOrder extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.loadSingleOrder(this.props.match.params.userId, this.props.match.params.orderId); } render() { let orderArr = this.props.order; console.log(orderArr) // TODO: Convert order time if (orderArr.length) { return ( <div> <h1>Order Number: {this.props.match.params.orderId}</h1> <h2>Order Details</h2> <h3>Order Date: { orderArr[0].cart.updatedAt }</h3> { orderArr.map((elem, index) => { return ( <div key = {index}> <h4>{ elem.coffeeInfo.name }</h4> <p> Description: { elem.coffeeInfo.description } </p> <p> Price: { elem.coffeeInfo.price } </p> <p> Quantity: { elem.quantity } </p> </div> ) }) } <h4> Total: { orderArr.total } </h4> </div> ) } else { return ( <p>Order Does Not Exist: Please contact our customer support!</p> ) } } }
JavaScript
class PostTemplate extends Component { render() { const post = this.props.data.wordpressPost return ( <Container> <Row> <Col xs="9"> <h1 dangerouslySetInnerHTML={{ __html: post.title }} /> <Alert color="primary"> This is a primary alert — check it out! </Alert> <div dangerouslySetInnerHTML={{ __html: post.content }} /> {post.acf && post.acf.page_builder_post && post.acf.page_builder_post.map((layout, i) => { if (layout.__typename === `WordPressAcf_image_gallery`) { return ( <div key={`${i} image-gallery`}> <h2>ACF Image Gallery</h2> {layout.pictures.map(({ picture }) => { const img = picture.localFile.childImageSharp.sizes return <Img key={img.src} sizes={img} /> })} </div> ) } if (layout.__typename === `WordPressAcf_post_photo`) { const img = layout.photo.localFile.childImageSharp.sizes return ( <div key={`${i}-photo`}> <h2>ACF Post Photo</h2> <Img css={{ marginBottom: rhythm(1) }} src={img.src} sizes={img} /> </div> ) } return null })} </Col> <Col xs="3"> <h2>Side bar</h2> </Col> </Row> </Container> ) } }
JavaScript
class Emitter { constructor(obj) { if (obj) return mixin(obj); } /** * Mixin methods from Emitter. * * ```js * const Emitter = require('emitter'); * const obj = {}; * Emitter.mixin(obj); * obj.on('status', console.log); * obj.emit('status', 'I emit!'); * ``` * @name Emitter#mixin * @param {Object} `obj` * @return {Object} * @api public */ static mixin(obj) { return new Emitter(obj); } /** * Return the array of registered listeners for `event`. * * ```js * // all listeners for event "status" * console.log(emitter.listeners('status')); * // all listeners * console.log(emitter.listeners()); * ``` * @name .listeners * @param {String} `event` * @return {Array} * @api public */ listeners(event) { if (!this._listeners) define(this, '_listeners', {}); if (!this._only) define(this, '_only', {}); if (!event) return this._listeners; return this._listeners['$' + event] || (this._listeners['$' + event] = []); } /** * Listen on the given `event` with `fn`. * * ```js * emitter.on('foo', () => 'do stuff'); * ``` * @name .on * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ on(event, fn) { if (this._only && this._only[event]) { return this.only(event, fn); } this.listeners(event).push(fn); return this; } /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * ```js * emitter.only('once', () => 'do stuff'); * ``` * @name .once * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ once(event, fn) { const on = function() { this.off(event, on); fn.apply(this, arguments); }; on.fn = fn; this.on(event, on); return this; } /** * Ensures that listeners for `event` are only **_registered_** once * and are disabled correctly when specified. This is different from * `.once`, which only **emits** once. * * ```js * emitter.only('foo', () => 'do stuff'); * ``` * @name .only * @param {String} `event` * @param {Object} `options` * @param {Function} `fn` * @return {Emitter} * @api public */ only(event, options, fn) { this.listeners(); if (typeof options === 'function') { fn = options; options = null; } if (options && options.first === true) { define(this, '_first', true); } if (!fn || !event || !this._only[event]) { this.off(event); if (!fn) return this; } const existing = this._only[event]; if (existing) { if (this._first === true) return this; this.off(event, existing); } this._only[event] = fn; this.listeners(event).push(fn); return this; } /** * Remove the given listener for `event`, or remove all * registered listeners if `event` is undefined. * * ```js * emitter.off(); * emitter.off('foo'); * emitter.off('foo', fn); * ``` * @name .off * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ off(event, fn) { this.listeners(); // remove all listeners if (!event) { this._listeners = {}; this._only = {}; return this; } // remove all listeners for "event" if (!fn) { this._listeners['$' + event] = []; this._only['$' + event] = []; return this; } // remove all instances of "fn" from "event" removeListeners(fn, this.listeners(event)); return this; } /** * Emit `event` with the given args. * * ```js * emitter.emit('foo', 'bar'); * ``` * @name .emit * @param {String} `event` * @param {Mixed} ... * @return {Emitter} */ emit(event) { const listeners = this.listeners(event).slice(); const args = [].slice.call(arguments, 1); for (const fn of listeners) { fn.apply(this, args); } return this; } /** * Returns true if the emitter has registered listeners for `event`. * * ```js * emitter.on('foo', 'do stuff'); * console.log(emitter.has('foo')); // true * console.log(emitter.has('bar')); // false * ``` * @name .has * @param {String} `event` * @return {Boolean} * @api public */ has(event) { return this.listeners(event).length > 0; } }
JavaScript
class Experiment{ // 그냥 쓰면 public, 앞에 #을 쓰면 private publicField = 2; #privateField = 0; }
JavaScript
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } }
JavaScript
class DeprecatedTasks { constructor() { /** * **Deprecated** Filter Onboarding tasks. * * @filter woocommerce_admin_onboarding_task_list * @deprecated * @param {Array} tasks Array of tasks. * @param {Array} query Url query parameters. */ this.filteredTasks = applyFilters( 'woocommerce_admin_onboarding_task_list', [], getQuery() ); if ( this.filteredTasks && this.filteredTasks.length > 0 ) { deprecated( 'woocommerce_admin_onboarding_task_list', { version: '2.10.0', alternative: 'TaskLists::add_task()', plugin: '@woocommerce/data', } ); } this.tasks = this.filteredTasks.reduce( ( org, task ) => { return { ...org, [ task.key ]: task, }; }, {} ); } hasDeprecatedTasks() { return this.filteredTasks.length > 0; } getPostData() { return this.hasDeprecatedTasks() ? { extended_tasks: this.filteredTasks.map( ( task ) => ( { title: task.title, content: task.content, additional_info: task.additionalInfo, time: task.time, level: task.level ? parseInt( task.level, 10 ) : 3, list_id: task.type || 'extended', can_view: task.visible, id: task.key, is_snoozeable: task.allowRemindMeLater, is_dismissable: task.isDismissable, is_complete: task.completed, } ) ), } : null; } mergeDeprecatedCallbackFunctions( taskLists ) { if ( this.filteredTasks.length > 0 ) { for ( const taskList of taskLists ) { // Merge any extended task list items, to keep the callback functions around. taskList.tasks = taskList.tasks.map( ( task ) => { if ( this.tasks && this.tasks[ task.id ] ) { return { ...this.tasks[ task.id ], ...task, isDeprecated: true, }; } return task; } ); } } return taskLists; } /** * Used to keep backwards compatibility with the extended task list filter on the client. * This can be removed after version WC Admin 2.10 (see deprecated notice in resolvers.js). * * @param {Object} task the returned task object. * @param {Array} keys to keep in the task object. * @return {Object} task with the keys specified. */ static possiblyPruneTaskData( task, keys ) { if ( ! task.time && ! task.title ) { // client side task return keys.reduce( ( simplifiedTask, key ) => { return { ...simplifiedTask, [ key ]: task[ key ], }; }, { id: task.id } ); } return task; } }
JavaScript
class core { constructor (...args) { mockConstructor(...args) global._bundler__arguments = args } run () { mockBundle() } watch () { mockServe() } }
JavaScript
class KpiChart extends PureComponent { static Header = Header; static Body = Body; static Footer = Footer; static Title = Title; render() { const { children, className } = this.props; return <div className={className}>{children}</div>; } }
JavaScript
class PrivateGameController extends GameController { roomManager turnTimeout difficulty wildcardsEnable constructor(room, roomManager, turnTimeout, difficulty, categories, wildcardsEnable, srvsock) { super(room, srvsock); this.roomManager = roomManager; this.turnTimeout = turnTimeout; this.difficulty = difficulty; this.categories = categories this.wildcardsEnable = wildcardsEnable; } restartGame() { } }
JavaScript
class ContactinformationsRequestCompoundAllOf { /** * Constructs a new <code>ContactinformationsRequestCompoundAllOf</code>. * @alias module:eZmaxAPI/model/ContactinformationsRequestCompoundAllOf * @param a_objAddress {Array.<module:eZmaxAPI/model/AddressRequestCompound>} * @param a_objPhone {Array.<module:eZmaxAPI/model/PhoneRequestCompound>} * @param a_objEmail {Array.<module:eZmaxAPI/model/EmailRequestCompound>} * @param a_objWebsite {Array.<module:eZmaxAPI/model/WebsiteRequestCompound>} */ constructor(a_objAddress, a_objPhone, a_objEmail, a_objWebsite) { ContactinformationsRequestCompoundAllOf.initialize(this, a_objAddress, a_objPhone, a_objEmail, a_objWebsite); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, a_objAddress, a_objPhone, a_objEmail, a_objWebsite) { obj['a_objAddress'] = a_objAddress; obj['a_objPhone'] = a_objPhone; obj['a_objEmail'] = a_objEmail; obj['a_objWebsite'] = a_objWebsite; } /** * Constructs a <code>ContactinformationsRequestCompoundAllOf</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:eZmaxAPI/model/ContactinformationsRequestCompoundAllOf} obj Optional instance to populate. * @return {module:eZmaxAPI/model/ContactinformationsRequestCompoundAllOf} The populated <code>ContactinformationsRequestCompoundAllOf</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ContactinformationsRequestCompoundAllOf(); if (data.hasOwnProperty('a_objAddress')) { obj['a_objAddress'] = ApiClient.convertToType(data['a_objAddress'], [AddressRequestCompound]); } if (data.hasOwnProperty('a_objPhone')) { obj['a_objPhone'] = ApiClient.convertToType(data['a_objPhone'], [PhoneRequestCompound]); } if (data.hasOwnProperty('a_objEmail')) { obj['a_objEmail'] = ApiClient.convertToType(data['a_objEmail'], [EmailRequestCompound]); } if (data.hasOwnProperty('a_objWebsite')) { obj['a_objWebsite'] = ApiClient.convertToType(data['a_objWebsite'], [WebsiteRequestCompound]); } } return obj; } /** * @return {Array.<module:eZmaxAPI/model/AddressRequestCompound>} */ getAObjAddress() { return this.a_objAddress; } /** * @param {Array.<module:eZmaxAPI/model/AddressRequestCompound>} a_objAddress */ setAObjAddress(a_objAddress) { this['a_objAddress'] = a_objAddress; } /** * @return {Array.<module:eZmaxAPI/model/PhoneRequestCompound>} */ getAObjPhone() { return this.a_objPhone; } /** * @param {Array.<module:eZmaxAPI/model/PhoneRequestCompound>} a_objPhone */ setAObjPhone(a_objPhone) { this['a_objPhone'] = a_objPhone; } /** * @return {Array.<module:eZmaxAPI/model/EmailRequestCompound>} */ getAObjEmail() { return this.a_objEmail; } /** * @param {Array.<module:eZmaxAPI/model/EmailRequestCompound>} a_objEmail */ setAObjEmail(a_objEmail) { this['a_objEmail'] = a_objEmail; } /** * @return {Array.<module:eZmaxAPI/model/WebsiteRequestCompound>} */ getAObjWebsite() { return this.a_objWebsite; } /** * @param {Array.<module:eZmaxAPI/model/WebsiteRequestCompound>} a_objWebsite */ setAObjWebsite(a_objWebsite) { this['a_objWebsite'] = a_objWebsite; } }
JavaScript
class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }
JavaScript
class BaseSender extends link_1.Link { constructor(session, sender, options) { super(link_1.LinkType.sender, session, sender, options); } setDrained(drained) { this._link.set_drained(drained); } /** * Determines whether the message is sendable. * @returns {boolean} `true` Sendable. `false` Not Sendable. */ sendable() { return this._link.sendable(); } }
JavaScript
class Sender extends BaseSender { constructor(session, sender, options) { super(session, sender, options); } /** * Sends the message * @param {Message | Buffer} msg The message to be sent. For default AMQP format msg parameter * should be of type Message interface. For a custom format, the msg parameter should be a Buffer * and a valid value should be passed to the `format` argument. * @param {SenderSendOptions} [options] Options to configure the tag and message format of the message. * @returns {Delivery} Delivery The delivery information about the sent message. */ send(msg, options = {}) { return this._link.send(msg, options.tag, options.format); } }
JavaScript
class Scope { /** * Read permission to the Clients registry * @member {String} ENTITY_CLIENTS_READ */ static ENTITY_CLIENTS_READ = 'entity.clients:r' /** * Write permission to the Clients registry * @member {String} ENTITY_CLIENTS_ALL */ static ENTITY_CLIENTS_ALL = 'entity.clients:a' /** * Read permission to the Suppliers registry * @member {String} ENTITY_SUPPLIERS_READ */ static ENTITY_SUPPLIERS_READ = 'entity.suppliers:r' /** * Write permission to the Suppliers registry * @member {String} ENTITY_SUPPLIERS_ALL */ static ENTITY_SUPPLIERS_ALL = 'entity.suppliers:a' /** * Read permission to the Products * @member {String} PRODUCTS_READ */ static PRODUCTS_READ = 'products:r' /** * Write permission to the Products * @member {String} PRODUCTS_ALL */ static PRODUCTS_ALL = 'products:a' /** * Read permission to the issued Invoices * @member {String} ISSUED_DOCUMENTS_INVOICES_READ */ static ISSUED_DOCUMENTS_INVOICES_READ = 'issued_documents.invoices:r' /** * Read permission to the issued Credit Notes * @member {String} ISSUED_DOCUMENTS_CREDIT_NOTES_READ */ static ISSUED_DOCUMENTS_CREDIT_NOTES_READ = 'issued_documents.credit_notes:r' /** * Read permission to the issued Receipts * @member {String} ISSUED_DOCUMENTS_RECEIPTS_READ */ static ISSUED_DOCUMENTS_RECEIPTS_READ = 'issued_documents.receipts:r' /** * Read permission to the issued Orders * @member {String} ISSUED_DOCUMENTS_ORDERS_READ */ static ISSUED_DOCUMENTS_ORDERS_READ = 'issued_documents.orders:r' /** * Read permission to the issued Quotes * @member {String} ISSUED_DOCUMENTS_QUOTES_READ */ static ISSUED_DOCUMENTS_QUOTES_READ = 'issued_documents.quotes:r' /** * Read permission to the issued Proformas * @member {String} ISSUED_DOCUMENTS_PROFORMAS_READ */ static ISSUED_DOCUMENTS_PROFORMAS_READ = 'issued_documents.proformas:r' /** * Read permission to the issued Delivery Notes * @member {String} ISSUED_DOCUMENTS_DELIVERY_NOTES_READ */ static ISSUED_DOCUMENTS_DELIVERY_NOTES_READ = 'issued_documents.delivery_notes:r' /** * Write permission to the issued Invoices * @member {String} ISSUED_DOCUMENTS_INVOICES_ALL */ static ISSUED_DOCUMENTS_INVOICES_ALL = 'issued_documents.invoices:a' /** * Write permission to the issued Credit Notes * @member {String} ISSUED_DOCUMENTS_CREDIT_NOTES_ALL */ static ISSUED_DOCUMENTS_CREDIT_NOTES_ALL = 'issued_documents.credit_notes:a' /** * Write permission to the issued issued Receipts * @member {String} ISSUED_DOCUMENTS_RECEIPTS_ALL */ static ISSUED_DOCUMENTS_RECEIPTS_ALL = 'issued_documents.receipts:a' /** * Write permission to the issued Orders * @member {String} ISSUED_DOCUMENTS_ORDERS_ALL */ static ISSUED_DOCUMENTS_ORDERS_ALL = 'issued_documents.orders:a' /** * Write permission to the issued Quotes * @member {String} ISSUED_DOCUMENTS_QUOTES_ALL */ static ISSUED_DOCUMENTS_QUOTES_ALL = 'issued_documents.quotes:a' /** * Write permission to the issued Proformas * @member {String} ISSUED_DOCUMENTS_PROFORMAS_ALL */ static ISSUED_DOCUMENTS_PROFORMAS_ALL = 'issued_documents.proformas:a' /** * Write permission to the issued Delivery Notes * @member {String} ISSUED_DOCUMENTS_DELIVERY_NOTES_ALL */ static ISSUED_DOCUMENTS_DELIVERY_NOTES_ALL = 'issued_documents.delivery_notes:a' /** * Read permission to the Received Documents * @member {String} RECEIVED_DOCUMENTS_READ */ static RECEIVED_DOCUMENTS_READ = 'received_documents:r' /** * Write permission to the Received Documents * @member {String} RECEIVED_DOCUMENTS_ALL */ static RECEIVED_DOCUMENTS_ALL = 'received_documents:a' /** * Read permission to the Stock movements * @member {String} STOCK_READ */ static STOCK_READ = 'stock:r' /** * Write permission to the Stock movements * @member {String} STOCK_ALL */ static STOCK_ALL = 'stock:a' /** * Read permission to the Receipts * @member {String} RECEIPTS_READ */ static RECEIPTS_READ = 'receipts:r' /** * Write permission to the Receipts * @member {String} RECEIPTS_ALL */ static RECEIPTS_ALL = 'receipts:a' /** * Read permission to the Taxes * @member {String} TAXES_READ */ static TAXES_READ = 'taxes:r' /** * Write permission to the Taxes * @member {String} TAXES_ALL */ static TAXES_ALL = 'taxes:a' /** * Read permission to the Archive Documents * @member {String} ARCHIVE_READ */ static ARCHIVE_READ = 'archive:r' /** * Read permission to the Archive Documents * @member {String} ARCHIVE_ALL */ static ARCHIVE_ALL = 'archive:a' /** * Read permission to the Cashbook * @member {String} CASHBOOK_READ */ static CASHBOOK_READ = 'cashbook:r' /** * Write permission to the Cashbook * @member {String} CASHBOOK_ALL */ static CASHBOOK_ALL = 'cashbook:a' /** * Read permission to the Settings * @member {String} SETTINGS_READ */ static SETTINGS_READ = 'settings:r' /** * Write permission to the Settings * @member {String} SETTINGS_ALL */ static SETTINGS_ALL = 'settings:a' /** * Read permission to the company Situation * @member {String} SITUATION_READ */ static SITUATION_READ = 'situation:r' }
JavaScript
class AnimatedParticle extends Particle { /** * Texture array used as each frame of animation, similarly to how MovieClip works. */ textures; /** * Duration of the animation, in seconds. */ duration; /** * Animation framerate, in frames per second. */ framerate; /** * Animation time elapsed, in seconds. */ elapsed; /** * If this particle animation should loop. */ loop; /** * @param emitter {Emitter} The emitter that controls this AnimatedParticle. */ constructor(emitter) { super(emitter); this.textures = null; this.duration = 0; this.framerate = 0; this.elapsed = 0; this.loop = false; } /** * Initializes the particle for use, based on the properties that have to * have been set already on the particle. */ init() { this.Particle_init(); this.elapsed = 0; //if the animation needs to match the particle's life, then cacluate variables if(this.framerate < 0) { this.duration = this.maxLife; this.framerate = this.textures.length / this.duration; } } /** * Sets the textures for the particle. * @param art {ParsedAnimatedParticleArt} An array of PIXI.Texture objects for this animated particle. */ applyArt(art) { this.textures = art.textures; this.framerate = art.framerate; this.duration = art.duration; this.loop = art.loop; } /** * Updates the particle. * @param delta {number} Time elapsed since the previous frame, in __seconds__. */ update(delta) { const lerp = this.Particle_update(delta); //only animate the particle if it is still alive if(lerp >= 0) { this.elapsed += delta; if(this.elapsed > this.duration) { //loop elapsed back around if(this.loop) this.elapsed = this.elapsed % this.duration; //subtract a small amount to prevent attempting to go past the end of the animation else this.elapsed = this.duration - 0.000001; } // add a very small number to the frame and then floor it to avoid // the frame being one short due to floating point errors. let frame = (this.elapsed * this.framerate + 0.0000001) | 0; this.texture = this.textures[frame] || Texture.EMPTY; } return lerp; } /** * Destroys the particle, removing references and preventing future use. */ destroy() { this.Particle_destroy(); this.textures = null; } /** * Checks over the art that was passed to the Emitter's init() function, to do any special * modifications to prepare it ahead of time. * @param art {AnimatedParticleArt[]} The array of art data, properly formatted for AnimatedParticle. * @return The art, after any needed modifications. */ static parseArt(art) { let data, output, textures, tex, outTextures; let outArr = []; for(let i = 0; i < art.length; ++i) { data = art[i]; outArr[i] = output = {}; output.textures = outTextures = []; textures = data.textures; for(let j = 0; j < textures.length; ++j) { tex = textures[j]; if(typeof tex == "string") outTextures.push(GetTextureFromString(tex)); else if(tex instanceof Texture) outTextures.push(tex); //assume an object with extra data determining duplicate frame data else { let dupe = tex.count || 1; if(typeof tex.texture == "string") tex = GetTextureFromString(tex.texture); else// if(tex.texture instanceof Texture) tex = tex.texture; for(; dupe > 0; --dupe) { outTextures.push(tex); } } } //use these values to signify that the animation should match the particle life time. if(data.framerate == "matchLife") { //-1 means that it should be calculated output.framerate = -1; output.duration = 0; output.loop = false; } else { //determine if the animation should loop output.loop = !!data.loop; //get the framerate, default to 60 output.framerate = data.framerate > 0 ? data.framerate : 60; //determine the duration output.duration = outTextures.length / output.framerate; } } return outArr; } }
JavaScript
class FilterDate extends Component { // init constructor(props) { super(props); this.state = { start: this.props.start, end: this.props.end }; this.onStartChanged = this.onStartChanged.bind(this); this.onEndChanged = this.onEndChanged.bind(this); this.reset = this.reset.bind(this); this.convertDateToISO = this.convertDateToISOString.bind(this); } // update the state on prop changes componentWillReceiveProps(nextProps) { this.setState({ start: this.convertDateToISOString(nextProps.start), end: this.convertDateToISOString(nextProps.end) }) } // handler for the start value change onStartChanged (value) { this.setState({ start: value }); } // handler for the end value change onEndChanged (value) { this.setState({ end: value }); } // convert the date format to ISO convertDateToISOString(date) { if (date) return moment(date, defaultDateFormat).toISOString(); return date; } // method to apply a filter apply() { const start = (this.state.start !== null) ? moment(this.state.start).format(defaultDateFormat) : null; const end = (this.state.end !== null) ? moment(this.state.end).format(defaultDateFormat) : null; return { start, end }; } // method to reset a filter reset() { this.setState({ start: new Date(), end: new Date(), }); } // main render method render() { const startPicker = ( <KeyboardDatePicker id="startDate" margin="normal" className="dayPickerInput" label={this.props.startLabel} value={this.state.start} onChange={this.onStartChanged} KeyboardButtonProps={{ 'aria-label': 'Change Start Date', }} /> ); const endPicker = ( <KeyboardDatePicker id="endDate" margin="normal" className="dayPickerInput" label={this.props.endLabel} value={this.state.end} onChange={this.onEndChanged} KeyboardButtonProps={{ 'aria-label': 'Change End Date', }} /> ); return ( <div className="filter-date"> <MuiPickersUtilsProvider utils={LuxonUtils}> {startPicker} {endPicker} </MuiPickersUtilsProvider> </div> ) } }
JavaScript
class Grid extends Molecule { /** * Creates a new Grid having the specified number of columns, number of rows, * and famo.us-style size. * * @constructor * @param {Number} columns The integer number of columns. * @param {Number} rows The integer number of rows. * @param {Array} size A famo.us-style width/height size array. */ constructor(columns, rows, size) { super({size: size}); this.columns = columns; this.rows = rows; this.cellNodes = []; if (typeof this.options.size === 'undefined') { this.setOptions({size: [undefined, undefined]}); } forLength(this.columns*this.rows, this._createGridCell.bind(this)); } /** * Creates a grid cell at the given index. * * @private * @param {Number} index The integer index of the grid cell. */ _createGridCell(index) { const column = index % this.columns; const row = Math.floor(index / this.columns); let cellSize = null; if (typeof this.options.size[0] != 'undefined' && typeof this.options.size[1] != 'undefined') { cellSize = []; cellSize[0] = this.options.size[0]/this.columns; cellSize[1] = this.options.size[1]/this.rows; } const mod = new Modifier({ align: [0,0], origin: [0,0], size: cellSize? [cellSize[0], cellSize[1]]: [undefined, undefined], transform: Transform.translate(column*cellSize[0],row*cellSize[1],0) }); const mod2 = new Modifier({ //transform: Transform.rotateY(Math.PI/10), align: [0.5,0.5], origin: [0.5,0.5] }); // FIXME: ^^^ Why do I need an extra Modifier to align stuff in the middle of the grid cells????? this.cellNodes.push(this.add(mod).add(mod2)); } /** * Sets the items to be layed out in the grid. * * @param {Array} children An array of [famous/src/core/RenderNode](#famous/src/core/RenderNode)-compatible items. */ setChildren(children) { forLength(this.columns*this.rows, function(index) { //this.cellNodes[index].set(null); // TODO: how do we erase previous children? this.cellNodes[index].add(children[index]); }.bind(this)); return this; } }
JavaScript
class ChatService { constructor(client, utils) { this._chat = client.chatService(); this._utils = utils; } // 获取会话列表 getChatList(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getChatList(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } setMessageRead(param){ this._chat.setMessageRead(param); } //添加最近联系人 addRecontact(param, cb) { return new Promise((resolve, reject)=>{ this._chat.addRecontact(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //移除会话 removeChat(param, cb) { return new Promise((resolve, reject)=>{ this._chat.removeChat(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //注册最近会话头像更新 regChatHeadImgUpdateCb(param, cb) { this._chat.regChatHeadImgUpdateCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //注册会话列表更新 regRecontactCb(param, cb) { this._chat.regRecontactCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //获取所有消息数目 getAllMsgCount(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getAllMsgCount(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取@我的消息 或者 我@别人的消息 getAtMessage(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getAtMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取消息 getMessages(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getMessages(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取对象聊天时间数组 getMsgDays(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getMsgDays(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //根据日期获取消息 getMsgFromDay(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getMsgFromDay(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取图片消息 getImgMsg(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getImgMsg(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取群议题 getIssueById(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getIssueById(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //拉取议题内历史消息 getIssueMessages(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getIssueMessages(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取敏感词 getBadWordList(param) { return this._chat.getBadWordList(param); } //获取敏感词 getBadWordListAsync(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getBadWordList(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取联系人最大已读ID getContractMaxReadId(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getContractMaxReadId(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取群内消息的读取状态 getGroupMsgReadState(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getGroupMsgReadState(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取一批消息的未读数计数器 getGroupMsgUnreadCounter(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getGroupMsgUnreadCounter(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //统计消息已读、未读数量详细信息 getGroupMsgUnreadInfo(param, cb) { return new Promise((resolve, reject)=>{ this._chat.getGroupMsgUnreadInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取不同类型的未读消息数量[同步接口] getUnReadMsgCountByType(param) { return this._chat.getUnReadMsgCountByType(param); } //获取不同类型的未读消息数量[异步接口] getUnReadMsgCountByTypeAsync(param) { return new Promise((resolve, reject)=>{ let result = this._chat.getUnReadMsgCountByType(param); resolve(result); }) } //获取URL的详细信息 getUrlInfo(param,cb) { return new Promise((resolve, reject)=>{ this._chat.getUrlInfo(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取群置顶消息 getGroupTopMsgById(param,cb) { return new Promise((resolve, reject)=>{ this._chat.getGroupTopMsgById(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取群中潜水者ID集合 getGroupDivers(param,cb) { return new Promise((resolve, reject)=>{ this._chat.getGroupDivers(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //分页获取提醒消息 getReminderMsgByPage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.getReminderMsgByPage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //发送消息 sendMessage(param,cb) { return this._chat.sendMessage(param, resp => { this._utils.makeCallBack(resp, cb); }) } /* * 发送消息 * cb 用于接收localId的回调函数 */ sendMessageAsync(param,cb) { return new Promise((resolve, reject)=>{ let localId = this._chat.sendMessage(param, resp => { this._utils.makeCallBack(resp, null, resolve, reject); }); if(cb){ cb(localId); } }) } //发送短信 sendShortMessage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.sendShortMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //发送附件消息 sendAppendixMessage(param,cb,pro) { return new Promise((resolve, reject)=>{ this._chat.sendAppendixMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); },proResp=>{ this._utils.makeCallBack(proResp, pro); }); }) } //发送消息输入状态 sendMsgInputState(param,cb) { return new Promise((resolve, reject)=>{ this._chat.sendMsgInputState(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //透传发送消息 transferMessage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.transferMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //插入消息 insertMessage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.insertMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //转发消息 forwardMessage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.forwardMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //通过消息ID解密消息 decryptMsg(param,cb) { return new Promise((resolve, reject)=>{ this._chat.decryptMsg(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //删除所有消息 deleteAllMessage(param,cb) { return new Promise((resolve, reject)=>{ this._chat.deleteAllMessage(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //通过msgId删除消息 deleteMessageById(param,cb) { return new Promise((resolve, reject)=>{ this._chat.deleteMessageById(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //删除时间段消息 deleteMessageByTime(param,cb) { return new Promise((resolve, reject)=>{ this._chat.deleteMessageByTime(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //更新对应targetId的消息 updateMsg(param,cb) { return new Promise((resolve, reject)=>{ this._chat.updateMsg(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //本地查找群议题 searchIssueLocal(param,cb) { return new Promise((resolve, reject)=>{ this._chat.searchIssueLocal(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //上传消息计数 upMsgCount(param,cb) { return new Promise((resolve, reject)=>{ this._chat.upMsgCount(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //获取是否有群置顶消息[同步] isGroupTopMsgSync(param) { return this._chat.isGroupTopMsgSync(param); } //获取是否有群置顶消息[异步] isGroupTopMsgAsync(param) { return new Promise((resolve, reject)=>{ let result = this._chat.isGroupTopMsgSync(param); resolve(result); }) } //删除提醒消息 deleteReminderMsg(param,cb) { return new Promise((resolve, reject)=>{ this._chat.deleteReminderMsg(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //会话置顶 chatTop(param,cb) { return new Promise((resolve, reject)=>{ this._chat.chatTop(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //设置消息未读 setMessageUnRead(param,cb) { return new Promise((resolve, reject)=>{ this._chat.setMessageUnRead(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //批量设置已读 setMsgReads(param,cb) { return new Promise((resolve, reject)=>{ this._chat.setMsgReads(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //设置私信秘钥 setPrivateKey(param,cb) { return new Promise((resolve, reject)=>{ this._chat.setPrivateKey(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //设置群置顶消息 setGroupTopMsg(param,cb) { return this._chat.setGroupTopMsg(param, resp => { this._utils.makeCallBack(resp, cb); }) } /* * 设置群置顶消息 * cb 用于接收localId的回调函数 */ setGroupTopMsgAsync(param,cb) { return new Promise((resolve, reject)=>{ let localId = this._chat.setGroupTopMsg(param, resp => { this._utils.makeCallBack(resp, null, resolve, reject); }); cb(localId); }) } //创建提醒消息 createReminderMsg(param,cb) { return new Promise((resolve, reject)=>{ this._chat.createReminderMsg(param, resp => { this._utils.makeCallBack(resp, cb, resolve, reject); }); }) } //消息游标推送 regMessageCursorCb(param,cb) { this._chat.regMessageCursorCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //设置监听消息输入状态的回调 regMessageInputStateCb(param,cb) { this._chat.regMessageInputStateCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //注册聊天消息的回调 regMsgNoticeCb(param,cb) { this._chat.regMsgNoticeCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //设置监听离线消息的回调 regOfflineMsgCb(param,cb) { this._chat.regOfflineMsgCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //设置监听新透传消息的回调 regTransMsgNoticeCb(param,cb) { this._chat.regTransMsgNoticeCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } //注册敏感词更新回调 regBadWordUpdateCb(param,cb) { this._chat.regBadWordUpdateCb(param, resp => { this._utils.makeCallBack(resp, cb); }); } }
JavaScript
class UiColorButton extends UiControl { /** * Create a new UiColorButton object. * @return {UiColorButton} */ constructor() { super(ColorButton.create()); } /** * Set or return the ColorButton color value. * @return {Color} */ get color() { this._ensureType(UiColorButton); return ColorButton.getColor(this.handle); } set color(value) { this._ensureType(UiColorButton); ColorButton.setColor(this.handle, value.r, value.g, value.b, value.a); } /** * Add a listener to the `changed` event. Emitted whenever the user * changed the selected color. * * @param {Function} callback - callback to execute when the event is * fired. */ onChanged(callback) { this._ensureType(UiColorButton); ColorButton.onChanged(this.handle, callback); } }
JavaScript
class SlidersArrows extends Component{ render(){ return ( <div className="arrows" > <span className="arrow arrow-left" onClick={()=>this.props.turn(-1)} > &lsaquo; </span> <span className="arrow arrow-right" onClick={()=>this.props.turn(1)} > &rsaquo; </span> </div> ) } }
JavaScript
class ContentTypeContract extends models['Resource'] { /** * Create a ContentTypeContract. * @property {string} [contentTypeContractId] Content type identifier * @property {string} [contentTypeContractName] Content type name. Must be 1 * to 250 characters long. * @property {string} [description] Content type description. * @property {object} [schema] Content type schema. * @property {string} [version] Content type version. */ constructor() { super(); } /** * Defines the metadata of ContentTypeContract * * @returns {object} metadata of ContentTypeContract * */ mapper() { return { required: false, serializedName: 'ContentTypeContract', type: { name: 'Composite', className: 'ContentTypeContract', 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' } }, contentTypeContractId: { required: false, serializedName: 'properties.id', type: { name: 'String' } }, contentTypeContractName: { required: false, serializedName: 'properties.name', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, schema: { required: false, serializedName: 'properties.schema', type: { name: 'Object' } }, version: { required: false, serializedName: 'properties.version', type: { name: 'String' } } } } }; } }
JavaScript
class RemoteLogger { constructor() {} sendMessage(message, value) { console.log( '\nLogging Remote Message -->> ', [new Date().getTime(), message, value]); } }
JavaScript
class ExpandDetailsDirective { constructor(grid) { this.grid = grid; /** * Fires when the expandedDetailKeys are changed. */ this.expandedDetailKeysChange = new EventEmitter(); /** * Defines the collection that will store the expanded keys. */ this.expandedDetailKeys = []; /** * Specifies if the items should be initially expanded. * @default false */ this.initiallyExpanded = false; this.subscriptions = new Subscription(); this.grid.isDetailExpanded = this.isExpanded.bind(this); this.subscriptions.add(merge(this.grid.detailExpand.pipe(map(e => (Object.assign({ expand: true }, e)))), this.grid.detailCollapse.pipe(map(e => (Object.assign({ expand: false }, e))))).subscribe(this.toggleState.bind(this))); } /** * Defines the item key that will be stored in the `expandedDetailKeys` collection. */ get expandDetailBy() { return this._expandBy; } set expandDetailBy(key) { if (isString(key)) { this._expandBy = getter(key); } else { this._expandBy = key; } } ngOnDestroy() { this.subscriptions.unsubscribe(); } get keyGetter() { return this._expandBy || getter(undefined); } /** * @hidden */ isExpanded(args) { const key = this.keyGetter(args.dataItem); return this.expandedDetailKeys.indexOf(key) > -1 ? !this.initiallyExpanded : this.initiallyExpanded; } toggleState(args) { const key = this.keyGetter(args.dataItem); if (Boolean(this.initiallyExpanded) !== args.expand) { this.expandedDetailKeys.push(key); } else { const index = this.expandedDetailKeys.indexOf(key); this.expandedDetailKeys.splice(index, 1); } this.expandedDetailKeysChange.emit(this.expandedDetailKeys); } }
JavaScript
class PagePropertyBuilder { constructor() { this.title = ""; this.url = ""; this.path = ""; this.referrer = ""; this.search = ""; this.keywords = ""; } // Build the core constituents of the payload build() { if (!this.url || this.url.length === 0) { throw new Error("Page url cannot be null or empty"); } const pageProperty = new RudderProperty(); pageProperty.setProperty("title", this.title); pageProperty.setProperty("url", this.url); pageProperty.setProperty("path", this.path); pageProperty.setProperty("referrer", this.referrer); pageProperty.setProperty("search", this.search); pageProperty.setProperty("keywords", this.keywords); return pageProperty; } // Setter methods to align with Builder pattern setTitle(title) { this.title = title; return this; } setUrl(url) { this.url = url; return this; } setPath(path) { this.path = path; return this; } setReferrer(referrer) { this.referrer = referrer; return this; } setSearch(search) { this.search = search; return search; } setKeywords(keywords) { this.keywords = keywords; return this; } }
JavaScript
class mxRectangle extends mxPoint { constructor(x, y, width, height) { super(x, y) this.width = (width != null) ? width : 0 this.height = (height != null) ? height : 0 } /** * Variable: width * * Holds the width of the rectangle. Default is 0. */ width = null /** * Variable: height * * Holds the height of the rectangle. Default is 0. */ height = null /** * Function: setRect * * Sets this rectangle to the specified values */ setRect(x, y, w, h) { this.x = x this.y = y this.width = w this.height = h } /** * Function: getCenterX * * Returns the x-coordinate of the center point. */ getCenterX() { return this.x + this.width / 2 } /** * Function: getCenterY * * Returns the y-coordinate of the center point. */ getCenterY() { return this.y + this.height / 2 } /** * Function: add * * Adds the given rectangle to this rectangle. */ add(rect) { if (rect != null) { var minX = Math.min(this.x, rect.x) var minY = Math.min(this.y, rect.y) var maxX = Math.max(this.x + this.width, rect.x + rect.width) var maxY = Math.max(this.y + this.height, rect.y + rect.height) this.x = minX this.y = minY this.width = maxX - minX this.height = maxY - minY } } /** * Function: intersect * * Changes this rectangle to where it overlaps with the given rectangle. */ intersect(rect) { if (rect != null) { var r1 = this.x + this.width var r2 = rect.x + rect.width var b1 = this.y + this.height var b2 = rect.y + rect.height this.x = Math.max(this.x, rect.x) this.y = Math.max(this.y, rect.y) this.width = Math.min(r1, r2) - this.x this.height = Math.min(b1, b2) - this.y } } /** * Function: grow * * Grows the rectangle by the given amount, that is, this method subtracts * the given amount from the x- and y-coordinates and adds twice the amount * to the width and height. */ grow(amount) { this.x -= amount this.y -= amount this.width += 2 * amount this.height += 2 * amount } /** * Function: getPoint * * Returns the top, left corner as a new <mxPoint>. */ getPoint() { return new mxPoint(this.x, this.y) } /** * Function: rotate90 * * Rotates this rectangle by 90 degree around its center point. */ rotate90() { var t = (this.width - this.height) / 2 this.x += t this.y -= t var tmp = this.width this.width = this.height this.height = tmp } /** * Function: equals * * Returns true if the given object equals this rectangle. */ equals(obj) { return obj != null && obj.x == this.x && obj.y == this.y && obj.width == this.width && obj.height == this.height } /** * Function: fromRectangle * * Returns a new <mxRectangle> which is a copy of the given rectangle. */ static fromRectangle(rect) { return new mxRectangle(rect.x, rect.y, rect.width, rect.height) } }
JavaScript
class NMF { // https://abicky.net/2010/03/25/101719/ // https://qiita.com/nozma/items/d8dafe4e938c43fb7ad1 // http://lucille.sourceforge.net/blog/archives/000282.html constructor() {} /** * Initialize model. * @param {Array<Array<number>>} x * @param {number} rd */ init(x, rd = 0) { this._x = Matrix.fromArray(x).t if (this._x.value.some(v => v < 0)) { throw 'Non-negative Matrix Fractorization only can process non negative matrix.' } this._r = rd this._W = Matrix.random(this._x.rows, this._r) this._H = Matrix.random(this._r, this._x.cols) } /** * Fit model. */ fit() { const n = this._W.rows const m = this._H.cols let WH = this._W.dot(this._H) for (let j = 0; j < m; j++) { for (let i = 0; i < this._r; i++) { let s = 0 for (let k = 0; k < n; k++) { s += (this._W.at(k, i) * this._x.at(k, j)) / WH.at(k, j) } this._H.multAt(i, j, s) } } for (let j = 0; j < this._r; j++) { for (let i = 0; i < n; i++) { let s = 0 for (let k = 0; k < m; k++) { s += (this._x.at(i, k) / WH.at(i, k)) * this._H.at(j, k) } this._W.multAt(i, j, s) } } this._W.div(this._W.sum(0)) } /** * Returns reduced datas. * @returns {Array<Array<number>>} */ predict() { return this._H.t.toArray() } }
JavaScript
class PtlRemoteVariable extends PtlVariable { /** * Creates remote variable instance from Projectile sync result * @param {String} layerName Name of host layer * @param {Object} syncData Sync operation result * @param {PtlClient} client Client instance * @throws {ReferenceError} If syncData.T does not reference known type constructor */ constructor(layerName, syncData, client) { const T = client.typesRegistry[syncData.T]; if (!T) { throw new ReferenceError( `Unknown type for variable ${syncData.name}: "${syncData.T}". Did you register it with PtlClient::registerType?` ); } super(syncData._value, T); this.name = syncData.name; this.parentName = []; this._nullable = syncData._nullable; this._allow = syncData._allow; this.layerName = layerName; this.client = client; } makeGetSetSync() { const sync = () => { return this.client.getPropertyValue(this.layerName + '/' + this.fullName()) .then(value => { this._value = value; return value; }); }; let get; if (this._allow.r) { get = () => this._value; } else { get = () => { throw new IllegalAccessError(`Property ${this.fullName()} is not readable`); }; } let set; if (this._allow.w) { set = value => { if (!this.typecheck(value)) { return Promise.reject( new TypeError(`Attempting to set ${this} with value "${value}" of incorrect type`) ); } return this.client.setPropertyValue(this.layerName + '/' + this.fullName(), value) .then(remoteValue => { console.log(remoteValue); this._value = remoteValue; }); }; } else { set = () => Promise.reject(new IllegalAccessError(`Property "${this.fullName()}" is not writable`)); } return { get, set, sync }; } /** * Define this variable on dest. See examples on how it behaves * @param {Object} dest Target object * @example * const name = plained.name(); // get value from cache * const x = plained.point.x(); // for nested objects * @example * // you probably will use such constructions with * // PtlClient request buffering: * plained.name = 'John'; // will asyncly set value * plained.point.x = 68; * @example * // use this without buffering if you need a * // Promise of operation result * plained.x.set(68); * // sync variable value with remote layer * plained.x.sync(); */ plain(dest) { const { get, set, sync } = this.makeGetSetSync(); get.get = get; get.set = set; get.sync = sync; Object.defineProperty(dest, this.name, { enumerable: true, get: () => get, set // writable: false, // value: { // sync, // get, // set, // valueOf: get // } }); } /** * Apply patch value to this variable * @param {any} patch Value to patch this with */ applyPatch(patch) { this._value = patch; } fullName() { return this.parentName.concat([this.name]).join('.'); } }
JavaScript
class AbstractVectorStyle extends AbstractStyle { /** * Constructor. * @param {string} layerId * @param {T} value * @param {T=} opt_oldValue */ constructor(layerId, value, opt_oldValue) { super(layerId, value, opt_oldValue); this.updateOldValue(); } /** * @inheritDoc */ getLayerConfig(layer) { return layer ? StyleManager.getInstance().getLayerConfig(layer.getId()) : null; } /** * @inheritDoc */ applyValue(config, value) { var source = /** @type {VectorSource} */ (DataManager.getInstance().getSource(this.layerId)); asserts.assert(source, 'source must be defined'); // update feature styles. don't use forEachFeature or the rbush will throw an error due to feature changes // while iterating osStyle.setFeaturesStyle(source.getFeatures()); // if we are using the timeline with fade enabled, we need to reset objects with this style change source.refreshAnimationFade(); } /** * @inheritDoc */ finish(config) { var layer = /** @type {VectorLayer} */ (getMapContainer().getLayer(this.layerId)); asserts.assert(layer); osStyle.notifyStyleChange(layer); } }