language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ComplexTool { /** * Create data for complex numbers from strings. * @param {string} text - Target strings. * @returns {{real : number, imag : number}} */ static ToComplexFromString(text) { let str = text.replace(/\s/g, "").toLowerCase(); str = str.replace(/infinity|inf/g, "1e100000"); // 複素数の宣言がない場合 if(!(/[ij]/.test(str))) { return { real : parseFloat(str), imag : 0.0 }; } // この時点で複素数である。 // 以下真面目に調査 let re = 0; let im = 0; let buff; // 最後が$なら右側が実数、最後が[+-]なら左側が実数 buff = str.match(/[+-]?(([0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?)|(nan))($|[+-])/); if(buff) { re = parseFloat(buff[0]); } // 複素数は数値が省略される場合がある buff = str.match(/[+-]?(([0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?)|(nan))?[ij]/); if(buff) { buff = buff[0].substring(0, buff[0].length - 1); // i, +i, -j のように実数部がなく、数値もない場合 if((/^[-+]$/.test(buff)) || buff.length === 0) { im = buff === "-" ? -1 : 1; } else { im = parseFloat(buff); } } return { real : re, imag : im }; } }
JavaScript
class Complex extends KonpeitoFloat { /** * Create a complex number. * * Initialization can be performed as follows. * - 1200, "1200", "12e2", "1.2e3" * - "3 + 4i", "4j + 3", [3, 4]. * @param {KComplexInputData} number - Complex number. See how to use the function. */ constructor(number) { super(); // 行列で使うためイミュータブルは必ず守ること。 if(arguments.length === 1) { const obj = number; if(obj instanceof Complex) { /** * The real part of this Comlex. * @private * @type {number} */ this._re = obj._re; /** * The imaginary part of this Comlex. * @private * @type {number} */ this._im = obj._im; } else if(typeof obj === "number") { this._re = obj; this._im = 0.0; } else if(typeof obj === "string") { const x = ComplexTool.ToComplexFromString(obj); this._re = x.real; this._im = x.imag; } else if(obj instanceof Array) { if(obj.length === 2) { this._re = obj[0]; this._im = obj[1]; } else { throw "Complex Unsupported argument " + arguments; } } else if(typeof obj === "boolean") { this._re = obj ? 1 : 0; this._im = 0.0; } else if("doubleValue" in obj) { this._re = obj.doubleValue; this._im = 0.0; } else if(("_re" in obj) && ("_im" in obj)) { this._re = obj._re; this._im = obj._im; } else if(obj instanceof Object) { const x = ComplexTool.ToComplexFromString(obj.toString()); this._re = x.real; this._im = x.imag; } else { throw "Complex Unsupported argument " + arguments; } } else { throw "Complex Many arguments : " + arguments.length; } } /** * Create an entity object of this class. * @param {KComplexInputData} number * @returns {Complex} */ static create(number) { if(number instanceof Complex) { return number; } else { return new Complex(number); } } /** * Convert number to Complex type. * @param {KComplexInputData} number * @returns {Complex} */ static valueOf(number) { return Complex.create(number); } /** * Convert to Complex. * If type conversion is unnecessary, return the value as it is. * @param {KComplexInputData} number * @returns {Complex} * @ignore */ static _toComplex(number) { if(number instanceof Complex) { return number; } else if(number instanceof Matrix) { return Matrix._toComplex(number); } else { return new Complex(number); } } /** * Convert to real number. * @param {KComplexInputData} number * @returns {number} * @ignore */ static _toDouble(number) { if(typeof number === "number") { return number; } const complex_number = Complex._toComplex(number); if(complex_number.isReal()) { return complex_number.real; } else { throw "not support complex numbers.[" + number + "]"; } } /** * Convert to integer. * @param {KComplexInputData} number * @returns {number} * @ignore */ static _toInteger(number) { return Math.trunc(Complex._toDouble(number)); } /** * Deep copy. * @returns {Complex} */ clone() { return this; } /** * Convert to string. * @returns {string} */ toString() { /** * @type {function(number): string } */ const formatG = function(x) { let numstr = x.toPrecision(6); if(numstr.indexOf(".") !== -1) { numstr = numstr.replace(/\.?0+$/, ""); // 1.00 , 1.10 numstr = numstr.replace(/\.?0+e/, "e"); // 1.0e , 1.10e } else if(/inf/i.test(numstr)) { if(x === Number.POSITIVE_INFINITY) { return "Inf"; } else { return "-Inf"; } } else if(/nan/i.test(numstr)) { return "NaN"; } return numstr; }; if(!this.isReal()) { if(this._re === 0) { return formatG(this._im) + "i"; } else if((this._im >= 0) || (Number.isNaN(this._im))) { return formatG(this._re) + " + " + formatG(this._im) + "i"; } else { return formatG(this._re) + " - " + formatG(-this._im) + "i"; } } else { return formatG(this._re); } } /** * Convert to JSON. * @returns {string} */ toJSON() { if(!this.isReal()) { if(this._re === 0) { return this._im.toString() + "i"; } else if((this._im >= 0) || (Number.isNaN(this._im))) { return this._re.toString() + "+" + this._im.toString() + "i"; } else { return this._re.toString() + this._im.toString() + "i"; } } else { return this._re.toString(); } } /** * The real part of this Comlex. * @returns {number} real(A) */ get real() { return this._re; } /** * The imaginary part of this Comlex. * @returns {number} imag(A) */ get imag() { return this._im; } /** * norm. * @returns {number} |A| */ get norm() { if(this._im === 0) { return Math.abs(this._re); } else if(this._re === 0) { return Math.abs(this._im); } else { return Math.sqrt(this._re * this._re + this._im * this._im); } } /** * The argument of this complex number. * @returns {number} arg(A) */ get arg() { if(this._im === 0) { return this._re >= 0 ? 0 : Math.PI; } else if(this._re === 0) { return Math.PI * (this._im >= 0.0 ? 0.5 : -0.5); } else { return Math.atan2(this._im, this._re); } } /** * Return number of decimal places for real and imaginary parts. * - Used to make a string. * @returns {number} Number of decimal places. */ getDecimalPosition() { /** * @type {function(number): number } */ const getDecimal = function(x) { if(!Number.isFinite(x)) { return 0; } let a = x; let point = 0; for(let i = 0; i < 20; i++) { if(Math.abs(a - Math.round(a)) <= Number.EPSILON) { break; } a *= 10; point++; } return point; }; return Math.max( getDecimal(this.real), getDecimal(this.imag) ); } /** * The positive or negative sign of this number. * - +1 if positive, -1 if negative, 0 if 0. * @returns {Complex} */ sign() { if(!this.isFinite()) { if(this.isNaN() || this._im === Infinity || this._im === -Infinity) { return Complex.NaN; } if(this._re === Infinity) { return Complex.ONE; } else { return Complex.MINUS_ONE; } } if(this._im === 0) { if(this._re === 0) { return Complex.ZERO; } else { return new Complex(this._re > 0 ? 1 : -1); } } return this.div(this.norm); } // ---------------------- // 四則演算 // ---------------------- /** * Add. * @param {KComplexInputData} number * @returns {Complex} A + B */ add(number) { const A = this; const B = new Complex(number); B._re = A._re + B._re; B._im = A._im + B._im; return B; } /** * Subtract. * @param {KComplexInputData} number * @returns {Complex} A - B */ sub(number) { const A = this; const B = new Complex(number); B._re = A._re - B._re; B._im = A._im - B._im; return B; } /** * Multiply. * @param {KComplexInputData} number * @returns {Complex} A * B */ mul(number) { const A = this; const B = new Complex(number); if((A._im === 0) && (B._im === 0)) { B._re = A._re * B._re; return B; } else if((A._re === 0) && (B._re === 0)) { B._re = - A._im * B._im; B._im = 0; return B; } else { const re = A._re * B._re - A._im * B._im; const im = A._im * B._re + A._re * B._im; B._re = re; B._im = im; return B; } } /** * Inner product/Dot product. * @param {KComplexInputData} number * @returns {Complex} A * conj(B) */ dot(number) { const A = this; const B = new Complex(number); if((A._im === 0) && (B._im === 0)) { B._re = A._re * B._re; return B; } else if((A._re === 0) && (B._re === 0)) { B._re = A._im * B._im; B._im = 0; return B; } else { const re = A._re * B._re + A._im * B._im; const im = - A._im * B._re + A._re * B._im; B._re = re; B._im = im; return B; } } /** * Divide. * @param {KComplexInputData} number * @returns {Complex} A / B */ div(number) { const A = this; const B = new Complex(number); if((A._im === 0) && (B._im === 0)) { B._re = A._re / B._re; return B; } else if((A._re === 0) && (B._re === 0)) { B._re = A._im / B._im; B._im = 0; return B; } else { const re = A._re * B._re + A._im * B._im; const im = A._im * B._re - A._re * B._im; const denominator = 1.0 / (B._re * B._re + B._im * B._im); B._re = re * denominator; B._im = im * denominator; return B; } } /** * Modulo, positive remainder of division. * - Result has same sign as the Dividend. * @param {KComplexInputData} number - Divided value (real number only). * @returns {Complex} A rem B */ rem(number) { const A = this; const B = new Complex(number); if((A._im !== 0) || (B._im !== 0)) { throw "calculation method is undefined."; } if(!A.isFinite() || !B.isFinite() || B.isZero()) { return Complex.NaN; } B._re = A._re - B._re * (Math.trunc(A._re / B._re)); return B; } /** * Modulo, positive remainder of division. * - Result has same sign as the Divisor. * @param {KComplexInputData} number - Divided value (real number only). * @returns {Complex} A mod B */ mod(number) { const A = this; const B = new Complex(number); if((A._im !== 0) || (B._im !== 0)) { throw "calculation method is undefined."; } if(B.isZero()) { return A; } const ret = A.rem(B); if(!A.equalsState(B)) { return ret.add(B); } else { return ret; } } /** * Inverse number of this value. * @returns {Complex} 1 / A */ inv() { if(this._im === 0) { return new Complex(1.0 / this._re); } else if(this._re === 0) { return new Complex([0, - 1.0 / this._im]); } return Complex.ONE.div(this); } // ---------------------- // 他の型に変換用 // ---------------------- /** * boolean value. * @returns {boolean} */ get booleanValue() { return !this.isZero() && !this.isNaN(); } /** * integer value. * @returns {number} */ get intValue() { if(!this.isFinite()) { return this.isNaN() ? NaN : (this.isPositiveInfinity() ? Infinity : -Infinity); } const value = this._re; const delta = Math.abs(value - Math.trunc(value)); if(delta < Number.EPSILON) { return Math.round(value); } else { return Math.trunc(value); } } /** * floating point. * @returns {number} */ get doubleValue() { if(!this.isFinite()) { return this.isNaN() ? NaN : (this.isPositiveInfinity() ? Infinity : -Infinity); } const value = this._re; const delta = Math.abs(value - Math.trunc(value)); if(delta < Number.EPSILON) { return Math.round(value); } else { return value; } } // ---------------------- // konpeito で扱う数値型へ変換 // ---------------------- /** * return BigInteger. * @returns {BigInteger} */ toBigInteger() { return new BigInteger(this.intValue); } /** * return BigDecimal. * @param {MathContext} [mc] - MathContext setting after calculation. * @returns {BigDecimal} */ toBigDecimal(mc) { if(mc) { return new BigDecimal([this.doubleValue, mc]); } else { return new BigDecimal(this.doubleValue); } } /** * return Fraction. * @returns {Fraction} */ toFraction() { return new Fraction(this.doubleValue); } /** * return Complex. * @returns {Complex} */ toComplex() { return this; } /** * return Matrix. * @returns {Matrix} */ toMatrix() { return new Matrix(this); } // ---------------------- // 比較 // ---------------------- /** * Equals. * @param {KComplexInputData} number * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} A === B */ equals(number, tolerance) { const A = this; const B = Complex._toComplex(number); // 無限大、非数の値も含めて一度確認 if(A.isNaN() || B.isNaN()) { return false; } if((A._re === B._re) && (A._im === B._im)) { return true; } // 誤差を含んだ値の比較 const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return (Math.abs(A._re - B._re) < tolerance_) && (Math.abs(A._im - B._im) < tolerance_); } /** * Numeric type match. * @param {KComplexInputData} number * @returns {boolean} */ equalsState(number) { const A = this; const B = Complex._toComplex(number); /** * @param {Complex} num * @returns {number} */ const getState = function(num) { if(num.isZero()) { return 0; } if(!num.isFinite()) { if(num.isPositiveInfinity()) { return 4; } else if(num.isNegativeInfinity()) { return 5; } else { return 3; } } return num.isPositive() ? 1 : 2; }; const A_type = getState(A); const B_type = getState(B); return A_type === B_type; } /** * Compare values. * @param {KComplexInputData} number * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {number} A > B ? 1 : (A === B ? 0 : -1) */ compareTo(number, tolerance) { const A = this; const B = Complex._toComplex(number); if(!A.isFinite() || !B.isFinite()) { if(A.equals(B)) { return 0; } else if( A.isNaN() || B.isNaN() || (A.real === Infinity && A.imag === -Infinity) || (A.real === -Infinity && A.imag === Infinity) || (B.real === Infinity && B.imag === -Infinity) || (B.real === -Infinity && B.imag === Infinity) ) { return NaN; } else if(A.isFinite()) { return B.real + B.imag < 0 ? 1 : -1; } else if(B.isFinite()) { return A.real + A.imag > 0 ? 1 : -1; } else { return NaN; } } const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; const a = A.real + A.imag; const b = B.real + B.imag; if((Math.abs(a - b) <= tolerance_)) { return 0; } return a > b ? 1 : -1; } /** * Maximum number. * @param {KComplexInputData} number * @returns {Complex} max([A, B]) */ max(number) { const x = Complex._toComplex(number); if(this.compareTo(x) >= 0) { return this; } else { return x; } } /** * Minimum number. * @param {KComplexInputData} number * @returns {Complex} min([A, B]) */ min(number) { const x = Complex._toComplex(number); if(this.compareTo(x) <= 0) { return this; } else { return x; } } /** * Clip number within range. * @param {KComplexInputData} min * @param {KComplexInputData} max * @returns {Complex} min(max(x, min), max) */ clip(min, max) { const min_ = Complex._toComplex(min); const max_ = Complex._toComplex(max); const arg_check = min_.compareTo(max_); if(arg_check === 1) { throw "clip(min, max) error. (min > max)->(" + min_ + " > " + max_ + ")"; } else if(arg_check === 0) { return min_; } if(this.compareTo(max_) === 1) { return max_; } else if(this.compareTo(min_) === -1) { return min_; } return this; } // ---------------------- // 丸め // ---------------------- /** * Floor. * @returns {Complex} floor(A) */ floor() { return new Complex([Math.floor(this._re), Math.floor(this._im)]); } /** * Ceil. * @returns {Complex} ceil(A) */ ceil() { return new Complex([Math.ceil(this._re), Math.ceil(this._im)]); } /** * Rounding to the nearest integer. * @returns {Complex} round(A) */ round() { return new Complex([Math.round(this._re), Math.round(this._im)]); } /** * To integer rounded down to the nearest. * @returns {Complex} fix(A), trunc(A) */ fix() { return new Complex([Math.trunc(this._re), Math.trunc(this._im)]); } /** * Fraction. * @returns {Complex} fract(A) */ fract() { return new Complex([this._re - Math.floor(this._re), this._im - Math.floor(this._im)]); } // ---------------------- // 複素数 // ---------------------- /** * Absolute value. * @returns {Complex} abs(A) */ abs() { return new Complex(this.norm); } /** * Complex conjugate. * @returns {Complex} real(A) - imag(A)j */ conj() { if(this._im === 0) { return this; } // 共役複素数 return new Complex([this._re, -this._im]); } /** * this * -1 * @returns {Complex} -A */ negate() { return new Complex([-this._re, -this._im]); } // ---------------------- // 指数 // ---------------------- /** * Power function. * @param {KComplexInputData} number * @returns {Complex} pow(A, B) */ pow(number) { const A = this; const B = new Complex(number); // -2 ^ 0.5 ... 複素数 // -2 ^ 1 ... 実数 // 2 ^ 0.5 ... 実数 if(B.isReal()) { if(A.isReal() && (A.isNotNegative() || B.isInteger())) { B._re = Math.pow(A._re, B._re); return B; } else { const r = Math.pow(A.norm, B._re); const s = A.arg * B._re; B._re = r * Math.cos(s); B._im = r * Math.sin(s); return B; } } else { return B.mul(A.log()).exp(); } } /** * Square. * @returns {Complex} pow(A, 2) */ square() { if(this._im === 0.0) { return new Complex(this._re * this._re); } return this.mul(this); } /** * Square root. * @returns {Complex} sqrt(A) */ sqrt() { if(this.isReal()) { if(this.isNotNegative()) { return new Complex(Math.sqrt(this._re)); } else { return new Complex([0, Math.sqrt(-this._re)]); } } const r = Math.sqrt(this.norm); const s = this.arg * 0.5; return new Complex([r * Math.cos(s), r * Math.sin(s)]); } /** * Cube root. * @param {KComplexInputData} [n=0] - Value type(0,1,2) * @returns {Complex} cbrt(A) */ cbrt(n) { const type = Complex._toInteger(n !== undefined ? n : 0); const x = this.log().div(3).exp(); if(type === 0) { return x; } else if(type === 1) { return x.mul([-0.5, Math.sqrt(3) * 0.5]); } else { return x.mul([-0.5, - Math.sqrt(3) * 0.5]); } } /** * Reciprocal square root. * @returns {Complex} rsqrt(A) */ rsqrt() { if(this.isReal()) { if(this.isNotNegative()) { return new Complex(1.0 / Math.sqrt(this._re)); } else { return new Complex([0, - 1.0 / Math.sqrt(-this._re)]); } } return this.sqrt().inv(); } /** * Logarithmic function. * @returns {Complex} log(A) */ log() { if(this.isReal() && this.isNotNegative()) { return new Complex(Math.log(this._re)); } // 負の値が入っているか、もともと複素数が入っている場合は、複素対数関数 return new Complex([Math.log(this.norm), this.arg]); } /** * Exponential function. * @returns {Complex} exp(A) */ exp() { if(this.isReal()) { return new Complex(Math.exp(this._re)); } // 複素指数関数 const r = Math.exp(this._re); return new Complex([r * Math.cos(this._im), r * Math.sin(this._im)]); } /** * e^x - 1 * @returns {Complex} expm1(A) */ expm1() { return this.exp().sub(1); } /** * ln(1 + x) * @returns {Complex} log1p(A) */ log1p() { return this.add(1).log(); } /** * log_2(x) * @returns {Complex} log2(A) */ log2() { return this.log().div(Complex.LN2); } /** * log_10(x) * @returns {Complex} log10(A) */ log10() { return this.log().div(Complex.LN10); } // ---------------------- // 三角関数 // ---------------------- /** * Sine function. * @returns {Complex} sin(A) */ sin() { if(this.isReal()) { return new Complex(Math.sin(this._re)); } // オイラーの公式より // sin x = (e^ix - e^-ex) / 2i const a = this.mul(Complex.I).exp(); const b = this.mul(Complex.I.negate()).exp(); return a.sub(b).div([0, 2]); } /** * Cosine function. * @returns {Complex} cos(A) */ cos() { if(this.isReal()) { return new Complex(Math.cos(this._re)); } // オイラーの公式より // cos x = (e^ix + e^-ex) / 2 const a = this.mul(Complex.I).exp(); const b = this.mul(Complex.I.negate()).exp(); return a.add(b).div(2); } /** * Tangent function. * @returns {Complex} tan(A) */ tan() { if(this.isReal()) { return new Complex(Math.tan(this._re)); } // 三角関数の相互関係 tan x = sin x / cos x return this.sin().div(this.cos()); } /** * Atan (arc tangent) function. * - Return the values of [-PI/2, PI/2]. * @returns {Complex} atan(A) */ atan() { if(this.isReal()) { return new Complex(Math.atan(this._re)); } // 逆正接 tan-1 x = i/2 log( i+x / i-x ) return Complex.I.div(Complex.TWO).mul(Complex.I.add(this).div(Complex.I.sub(this)).log()); } /** * Atan (arc tangent) function. * Return the values of [-PI, PI] . * Supports only real numbers. * @param {KComplexInputData} [number] - X * @returns {Complex} atan2(Y, X) */ atan2(number) { if(arguments.length === 0) { return new Complex(this.arg); } // y.atan2(x) とする。 const y = this; const x = Complex._toComplex(number); if(y.isReal() && x.isReal()) { return new Complex(Math.atan2(y._re, x._re)); } // 複素数のatan2は未定義である(実装不可能) throw "calculation method is undefined."; } // ---------------------- // 双曲線関数 // ---------------------- /** * Arc sine function. * @returns {Complex} asin(A) */ asin() { // 逆正弦 return this.mul(Complex.I).add(Complex.ONE.sub(this.square()).sqrt()).log().mul(Complex.MINUS_I); } /** * Arc cosine function. * @returns {Complex} acos(A) */ acos() { // 逆余弦 return this.add(Complex.I.mul(Complex.ONE.sub(this.square()).sqrt())).log().mul(Complex.MINUS_I); } /** * Hyperbolic sine function. * @returns {Complex} sinh(A) */ sinh() { // 双曲線正弦 const y = this.exp(); return y.sub(y.inv()).mul(0.5); } /** * Inverse hyperbolic sine function. * @returns {Complex} asinh(A) */ asinh() { // 逆双曲線正弦 Math.log(x + Math.sqrt(x * x + 1)); if(this.isInfinite()) { return this; } return this.add(this.mul(this).add(1).sqrt()).log(); } /** * Hyperbolic cosine function. * @returns {Complex} cosh(A) */ cosh() { // 双曲線余弦 return this.exp().add(this.negate().exp()).mul(0.5); } /** * Inverse hyperbolic cosine function. * @returns {Complex} acosh(A) */ acosh() { // 逆双曲線余弦 Math.log(x + Math.sqrt(x * x - 1)); // Octave だと log(0.5+(0.5*0.5-1)^0.5) !== acosh(0.5) になる。 // おそらく log(0.5-(0.5*0.5-1)^0.5) の式に切り替わるようになっている // これは2つの値を持っているためだと思われるので合わせてみる if(this.isZero()) { return new Complex([0, Math.PI * 0.5]); } if(this.compareTo(Complex.ONE) >= 1) { return this.add(this.square().sub(1).sqrt()).log(); } else { return this.sub(this.square().sub(1).sqrt()).log(); } } /** * Hyperbolic tangent function. * @returns {Complex} tanh(A) */ tanh() { // 双曲線正接 if(this.isNaN()) { return Complex.NaN; } const y = this.mul(2).exp(); if(y.isZero()) { return Complex.MINUS_ONE; } else if(y.isPositiveInfinity()) { return Complex.ONE; } return y.sub(1).div(y.add(1)); } /** * Inverse hyperbolic tangent function. * @returns {Complex} atanh(A) */ atanh() { // 逆双曲線正接 if(this.isInfinite() && this.isReal()) { return new Complex([0, Math.PI * 0.5]); } return this.add(1).div(this.negate().add(1)).log().mul(0.5); } /** * Secant function. * @returns {Complex} sec(A) */ sec() { // 正割 return this.cos().inv(); } /** * Reverse secant function. * @returns {Complex} asec(A) */ asec() { // 逆正割 return this.inv().acos(); } /** * Hyperbolic secant function. * @returns {Complex} sech(A) */ sech() { // 双曲線正割 return this.exp().add(this.negate().exp()).inv().mul(2); } /** * Inverse hyperbolic secant function. * @returns {Complex} asech(A) */ asech() { // 逆双曲線正割 if(this.isInfinite() && this.isReal()) { return new Complex([0, Math.PI * 0.5]); } if(this.isPositive() || (this.compareTo(Complex.MINUS_ONE) == -1)) { return this.inv().add(this.square().inv().sub(1).sqrt()).log(); } else { return this.inv().sub(this.square().inv().sub(1).sqrt()).log(); } } /** * Cotangent function. * @returns {Complex} cot(A) */ cot() { // 余接 return this.tan().inv(); } /** * Inverse cotangent function. * @returns {Complex} acot(A) */ acot() { // 逆余接 return this.inv().atan(); } /** * Hyperbolic cotangent function. * @returns {Complex} coth(A) */ coth() { // 双曲線余接 if(this.isZero()) { return Complex.POSITIVE_INFINITY; } return this.tanh().inv(); } /** * Inverse hyperbolic cotangent function. * @returns {Complex} acoth(A) */ acoth() { // 逆双曲線余接 if(this.isInfinite()) { return Complex.ZERO; } return this.add(1).div(this.sub(1)).log().mul(0.5); } /** * Cosecant function. * @returns {Complex} csc(A) */ csc() { // 余割 return this.sin().inv(); } /** * Inverse cosecant function. * @returns {Complex} acsc(A) */ acsc() { // 逆余割 return this.inv().asin(); } /** * Hyperbolic cosecant function. * @returns {Complex} csch(A) */ csch() { // 双曲線余割 return this.exp().sub(this.negate().exp()).inv().mul(2); } /** * Inverse hyperbolic cosecant function. * @returns {Complex} acsch(A) */ acsch() { // 逆双曲線余割 return this.inv().add(this.square().inv().add(1).sqrt()).log(); } // ---------------------- // 確率・統計系 // ---------------------- /** * Logit function. * @returns {Complex} logit(A) */ logit() { return this.log().sub(Complex.ONE.sub(this).log()); } // ---------------------- // 信号処理系 // ---------------------- /** * Normalized sinc function. * @returns {Complex} sinc(A) */ sinc() { if(this.isReal()) { if(this._re === 0) { return(Complex.ONE); } const x = Math.PI * this._re; return new Complex(Math.sin(x) / x); } const x = this.mul(Complex.PI); return new Complex( x.sin().div(x) ); } // ---------------------- // 乱数 // ---------------------- /** * Create random values [0, 1) with uniform random numbers. * @param {Random} [random] - Class for creating random numbers. * @returns {Complex} */ static rand(random) { const rand = (random !== undefined && random instanceof Random) ? random : random_class; return new Complex(rand.nextDouble()); } /** * Create random values with normal distribution. * @param {Random} [random] - Class for creating random numbers. * @returns {Complex} */ static randn(random) { const rand = (random !== undefined && random instanceof Random) ? random : random_class; return new Complex(rand.nextGaussian()); } // ---------------------- // テスト系 // ---------------------- /** * Return true if the value is integer. * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} */ isInteger(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return this.isReal() && (Math.abs(this._re - Math.trunc(this._re)) < tolerance_); } /** * Returns true if the vallue is complex integer (including normal integer). * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} real(A) === integer && imag(A) === integer */ isComplexInteger(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; // 複素整数 return (Math.abs(this._re - Math.trunc(this._re)) < tolerance_) && (Math.abs(this._im - Math.trunc(this._im)) < tolerance_); } /** * this === 0 * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} A === 0 */ isZero(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return (Math.abs(this._re) < tolerance_) && (Math.abs(this._im) < tolerance_); } /** * this === 1 * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} A === 1 */ isOne(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return (Math.abs(this._re - 1.0) < tolerance_) && (Math.abs(this._im) < tolerance_); } /** * Returns true if the vallue is complex number (imaginary part is not 0). * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} imag(A) !== 0 */ isComplex(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return (Math.abs(this._im) >= tolerance_); } /** * Return true if the value is real number. * @param {KComplexInputData} [tolerance=Number.EPSILON] - Calculation tolerance of calculation. * @returns {boolean} imag(A) === 0 */ isReal(tolerance) { const tolerance_ = tolerance ? Complex._toDouble(tolerance) : Number.EPSILON; return (Math.abs(this._im) < tolerance_); } /** * this === NaN * @returns {boolean} isNaN(A) */ isNaN() { return isNaN(this._re) || isNaN(this._im); } /** * Return true if this real part of the complex positive. * @returns {boolean} real(x) > 0 */ isPositive() { // Number.EPSILONは使用しない。どちらにぶれるか不明な点及び // わずかな負の数だった場合に、sqrtでエラーが発生するため return 0.0 < this._re; } /** * real(this) < 0 * @returns {boolean} real(x) < 0 */ isNegative() { return 0.0 > this._re; } /** * real(this) >= 0 * @returns {boolean} real(x) >= 0 */ isNotNegative() { return 0.0 <= this._re; } /** * this === Infinity * @returns {boolean} isPositiveInfinity(A) */ isPositiveInfinity() { return this._re === Number.POSITIVE_INFINITY || this._im === Number.POSITIVE_INFINITY; } /** * this === -Infinity * @returns {boolean} isNegativeInfinity(A) */ isNegativeInfinity() { return this._re === Number.NEGATIVE_INFINITY || this._im === Number.NEGATIVE_INFINITY; } /** * this === Infinity or -Infinity * @returns {boolean} isPositiveInfinity(A) || isNegativeInfinity(A) */ isInfinite() { return this.isPositiveInfinity() || this.isNegativeInfinity(); } /** * Return true if the value is finite number. * @returns {boolean} !isNaN(A) && !isInfinite(A) */ isFinite() { return !this.isNaN() && !this.isInfinite(); } // ---------------------- // 確率 // ---------------------- /** * Log-gamma function. * - Calculate from real values. * @returns {Complex} */ gammaln() { return new Complex(Probability.gammaln(this._re)); } /** * Gamma function. * - Calculate from real values. * @returns {Complex} */ gamma() { return new Complex(Probability.gamma(this._re)); } /** * Incomplete gamma function. * - Calculate from real values. * @param {KComplexInputData} a * @param {string} [tail="lower"] - lower (default) , "upper" * @returns {Complex} */ gammainc(a, tail) { const a_ = Complex._toDouble(a); return new Complex(Probability.gammainc(this._re, a_, tail)); } /** * Probability density function (PDF) of the gamma distribution. * - Calculate from real values. * @param {KComplexInputData} k - Shape parameter. * @param {KComplexInputData} s - Scale parameter. * @returns {Complex} */ gampdf(k, s) { const k_ = Complex._toDouble(k); const s_ = Complex._toDouble(s); return new Complex(Probability.gampdf(this._re, k_, s_)); } /** * Cumulative distribution function (CDF) of gamma distribution. * - Calculate from real values. * @param {KComplexInputData} k - Shape parameter. * @param {KComplexInputData} s - Scale parameter. * @returns {Complex} */ gamcdf(k, s) { const k_ = Complex._toDouble(k); const s_ = Complex._toDouble(s); return new Complex(Probability.gamcdf(this._re, k_, s_)); } /** * Inverse function of cumulative distribution function (CDF) of gamma distribution. * - Calculate from real values. * @param {KComplexInputData} k - Shape parameter. * @param {KComplexInputData} s - Scale parameter. * @returns {Complex} */ gaminv(k, s) { const k_ = Complex._toDouble(k); const s_ = Complex._toDouble(s); return new Complex(Probability.gaminv(this._re, k_, s_)); } /** * Beta function. * - Calculate from real values. * @param {KComplexInputData} y * @returns {Complex} */ beta(y) { const y_ = Complex._toDouble(y); return new Complex(Probability.beta(this._re, y_)); } /** * Incomplete beta function. * - Calculate from real values. * @param {KComplexInputData} a * @param {KComplexInputData} b * @param {string} [tail="lower"] - lower (default) , "upper" * @returns {Complex} */ betainc(a, b, tail) { const a_ = Complex._toDouble(a); const b_ = Complex._toDouble(b); return new Complex(Probability.betainc(this._re, a_, b_, tail)); } /** * Probability density function (PDF) of beta distribution. * - Calculate from real values. * @param {KComplexInputData} a * @param {KComplexInputData} b * @returns {Complex} */ betapdf(a, b) { const a_ = Complex._toDouble(a); const b_ = Complex._toDouble(b); return new Complex(Probability.betapdf(this._re, a_, b_)); } /** * Cumulative distribution function (CDF) of beta distribution. * - Calculate from real values. * @param {KComplexInputData} a * @param {KComplexInputData} b * @returns {Complex} */ betacdf(a, b) { const a_ = Complex._toDouble(a); const b_ = Complex._toDouble(b); return new Complex(Probability.betacdf(this._re, a_, b_)); } /** * Inverse function of cumulative distribution function (CDF) of beta distribution. * - Calculate from real values. * @param {KComplexInputData} a * @param {KComplexInputData} b * @returns {Complex} */ betainv(a, b) { const a_ = Complex._toDouble(a); const b_ = Complex._toDouble(b); return new Complex(Probability.betainv(this._re, a_, b_)); } /** * Factorial function, x!. * - Calculate from real values. * @returns {Complex} */ factorial() { return new Complex(Probability.factorial(this._re)); } /** * Binomial coefficient, number of all combinations, nCk. * - Calculate from real values. * @param {KComplexInputData} k * @returns {Complex} */ nchoosek(k) { const k_ = Complex._toDouble(k); return new Complex(Probability.nchoosek(this._re, k_)); } /** * Error function. * - Calculate from real values. * @returns {Complex} */ erf() { return new Complex(Probability.erf(this._re)); } /** * Complementary error function. * - Calculate from real values. * @returns {Complex} */ erfc() { return new Complex(Probability.erfc(this._re)); } /** * Inverse function of Error function. * - Calculate from real values. * @returns {Complex} */ erfinv() { return new Complex(Probability.erfinv(this._re)); } /** * Inverse function of Complementary error function. * - Calculate from real values. * @returns {Complex} */ erfcinv() { return new Complex(Probability.erfcinv(this._re)); } /** * Probability density function (PDF) of normal distribution. * - Calculate from real values. * @param {KComplexInputData} [u=0.0] - Average value. * @param {KComplexInputData} [s=1.0] - Variance value. * @returns {Complex} */ normpdf(u, s) { const u_ = u !== undefined ? Complex._toDouble(u) : 0.0; const s_ = s !== undefined ? Complex._toDouble(s) : 1.0; return new Complex(Probability.normpdf(this._re, u_, s_)); } /** * Cumulative distribution function (CDF) of normal distribution. * - Calculate from real values. * @param {KComplexInputData} [u=0.0] - Average value. * @param {KComplexInputData} [s=1.0] - Variance value. * @returns {Complex} */ normcdf(u, s) { const u_ = u !== undefined ? Complex._toDouble(u) : 0.0; const s_ = s !== undefined ? Complex._toDouble(s) : 1.0; return new Complex(Probability.normcdf(this._re, u_, s_)); } /** * Inverse function of cumulative distribution function (CDF) of normal distribution. * - Calculate from real values. * @param {KComplexInputData} [u=0.0] - Average value. * @param {KComplexInputData} [s=1.0] - Variance value. * @returns {Complex} */ norminv(u, s) { const u_ = u !== undefined ? Complex._toDouble(u) : 0.0; const s_ = s !== undefined ? Complex._toDouble(s) : 1.0; return new Complex(Probability.norminv(this._re, u_, s_)); } /** * Probability density function (PDF) of binomial distribution. * - Calculate from real values. * @param {KComplexInputData} n * @param {KComplexInputData} p * @returns {Complex} */ binopdf(n, p) { const n_ = Complex._toDouble(n); const p_ = Complex._toDouble(p); return new Complex(Probability.binopdf(this._re, n_, p_)); } /** * Cumulative distribution function (CDF) of binomial distribution. * - Calculate from real values. * @param {KComplexInputData} n * @param {KComplexInputData} p * @param {string} [tail="lower"] - lower (default) , "upper" * @returns {Complex} */ binocdf(n, p, tail) { const n_ = Complex._toDouble(n); const p_ = Complex._toDouble(p); return new Complex(Probability.binocdf(this._re, n_, p_, tail)); } /** * Inverse function of cumulative distribution function (CDF) of binomial distribution. * - Calculate from real values. * @param {KComplexInputData} n * @param {KComplexInputData} p * @returns {Complex} */ binoinv(n, p) { const n_ = Complex._toDouble(n); const p_ = Complex._toDouble(p); return new Complex(Probability.binoinv(this._re, n_, p_)); } /** * Probability density function (PDF) of Poisson distribution. * - Calculate from real values. * @param {KComplexInputData} lambda * @returns {Complex} */ poisspdf(lambda) { const lambda_ = Complex._toDouble(lambda); return new Complex(Probability.poisspdf(this._re, lambda_)); } /** * Cumulative distribution function (CDF) of Poisson distribution. * - Calculate from real values. * @param {KComplexInputData} lambda * @returns {Complex} */ poisscdf(lambda) { const lambda_ = Complex._toDouble(lambda); return new Complex(Probability.poisscdf(this._re, lambda_)); } /** * Inverse function of cumulative distribution function (CDF) of Poisson distribution. * - Calculate from real values. * @param {KComplexInputData} lambda * @returns {Complex} */ poissinv(lambda) { const lambda_ = Complex._toDouble(lambda); return new Complex(Probability.poissinv(this._re, lambda_)); } /** * Probability density function (PDF) of Student's t-distribution. * - Calculate from real values. * @param {KComplexInputData} v - The degrees of freedom. (DF) * @returns {Complex} */ tpdf(v) { const v_ = Complex._toDouble(v); return new Complex(Probability.tpdf(this._re, v_)); } /** * Cumulative distribution function (CDF) of Student's t-distribution. * - Calculate from real values. * @param {KComplexInputData} v - The degrees of freedom. (DF) * @returns {Complex} */ tcdf(v) { const v_ = Complex._toDouble(v); return new Complex(Probability.tcdf(this._re, v_)); } /** * Inverse of cumulative distribution function (CDF) of Student's t-distribution. * - Calculate from real values. * @param {KComplexInputData} v - The degrees of freedom. (DF) * @returns {Complex} */ tinv(v) { const v_ = Complex._toDouble(v); return new Complex(Probability.tinv(this._re, v_)); } /** * Cumulative distribution function (CDF) of Student's t-distribution that can specify tail. * - Calculate from real values. * @param {KComplexInputData} v - The degrees of freedom. (DF) * @param {KComplexInputData} tails - Tail. (1 = the one-tailed distribution, 2 = the two-tailed distribution.) * @returns {Complex} */ tdist(v, tails) { const v_ = Complex._toDouble(v); const tails_ = Complex._toInteger(tails); return new Complex(Probability.tdist(this._re, v_, tails_)); } /** * Inverse of cumulative distribution function (CDF) of Student's t-distribution in two-sided test. * - Calculate from real values. * @param {KComplexInputData} v - The degrees of freedom. (DF) * @returns {Complex} */ tinv2(v) { const v_ = Complex._toDouble(v); return new Complex(Probability.tinv2(this._re, v_)); } /** * Probability density function (PDF) of chi-square distribution. * - Calculate from real values. * @param {KComplexInputData} k - The degrees of freedom. (DF) * @returns {Complex} */ chi2pdf(k) { const k_ = Complex._toDouble(k); return new Complex(Probability.chi2pdf(this._re, k_)); } /** * Cumulative distribution function (CDF) of chi-square distribution. * - Calculate from real values. * @param {KComplexInputData} k - The degrees of freedom. (DF) * @returns {Complex} */ chi2cdf(k) { const k_ = Complex._toDouble(k); return new Complex(Probability.chi2cdf(this._re, k_)); } /** * Inverse function of cumulative distribution function (CDF) of chi-square distribution. * - Calculate from real values. * @param {KComplexInputData} k - The degrees of freedom. (DF) * @returns {Complex} */ chi2inv(k) { const k_ = Complex._toDouble(k); return new Complex(Probability.chi2inv(this._re, k_)); } /** * Probability density function (PDF) of F-distribution. * - Calculate from real values. * @param {KComplexInputData} d1 - The degree of freedom of the molecules. * @param {KComplexInputData} d2 - The degree of freedom of the denominator * @returns {Complex} */ fpdf(d1, d2) { const d1_ = Complex._toDouble(d1); const d2_ = Complex._toDouble(d2); return new Complex(Probability.fpdf(this._re, d1_, d2_)); } /** * Cumulative distribution function (CDF) of F-distribution. * - Calculate from real values. * @param {KComplexInputData} d1 - The degree of freedom of the molecules. * @param {KComplexInputData} d2 - The degree of freedom of the denominator * @returns {Complex} */ fcdf(d1, d2) { const d1_ = Complex._toDouble(d1); const d2_ = Complex._toDouble(d2); return new Complex(Probability.fcdf(this._re, d1_, d2_)); } /** * Inverse function of cumulative distribution function (CDF) of F-distribution. * - Calculate from real values. * @param {KComplexInputData} d1 - The degree of freedom of the molecules. * @param {KComplexInputData} d2 - The degree of freedom of the denominator * @returns {Complex} */ finv(d1, d2) { const d1_ = Complex._toDouble(d1); const d2_ = Complex._toDouble(d2); return new Complex(Probability.finv(this._re, d1_, d2_)); } // ---------------------- // ビット演算系 // ---------------------- /** * Logical AND. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Complex} A & B */ and(number) { const n_src = Math.round(this.real); const n_tgt = Math.round(Complex._toDouble(number)); return new Complex(n_src & n_tgt); } /** * Logical OR. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Complex} A | B */ or(number) { const n_src = Math.round(this.real); const n_tgt = Math.round(Complex._toDouble(number)); return new Complex(n_src | n_tgt); } /** * Logical Exclusive-OR. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Complex} A ^ B */ xor(number) { const n_src = Math.round(this.real); const n_tgt = Math.round(Complex._toDouble(number)); return new Complex(n_src ^ n_tgt); } /** * Logical Not. (mutable) * - Calculated as an integer. * @returns {Complex} !A */ not() { const n_src = Math.round(this.real); return new Complex(!n_src); } /** * this << n * - Calculated as an integer. * @param {KComplexInputData} n * @returns {Complex} A << n */ shift(n) { const src = Math.round(this.real); const number = Math.round(Complex._toDouble(n)); return new Complex(src << number); } // ---------------------- // factor // ---------------------- /** * Factorization. * - Calculated as an integer. * - Calculate up to `9007199254740991`. * @returns {Complex[]} factor */ factor() { const x = this.round().toBigInteger().factor(); const y = []; for(let i = 0; i < x.length; i++) { y.push(new Complex(x[i])); } return y; } // ---------------------- // gcd, lcm // ---------------------- /** * Euclidean algorithm. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Complex} gcd(x, y) */ gcd(number) { const x = Math.round(this.real); const y = Math.round(Complex._toDouble(number)); const result = new BigInteger(x).gcd(y); return new Complex(result); } /** * Extended Euclidean algorithm. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Array<Complex>} [a, b, gcd(x, y)], Result of calculating a*x + b*y = gcd(x, y). */ extgcd(number) { const x = Math.round(this.real); const y = Math.round(Complex._toDouble(number)); const result = new BigInteger(x).extgcd(y); return [new Complex(result[0]), new Complex(result[1]), new Complex(result[2])]; } /** * Least common multiple. * - Calculated as an integer. * @param {KComplexInputData} number * @returns {Complex} lcm(x, y) */ lcm(number) { const x = Math.round(this.real); const y = Math.round(Complex._toDouble(number)); const result = new BigInteger(x).lcm(y); return new Complex(result); } // ---------------------- // mod // ---------------------- /** * Modular exponentiation. * - Calculated as an integer. * @param {KComplexInputData} exponent * @param {KComplexInputData} m * @returns {Complex} A^B mod m */ modPow(exponent, m) { const A = Math.round(this.real); const B = Math.round(Complex._toDouble(exponent)); const m_ = Math.round(Complex._toDouble(m)); const result = new BigInteger(A).modPow(B, m_); return new Complex(result); } /** * Modular multiplicative inverse. * - Calculated as an integer. * @param {KComplexInputData} m * @returns {Complex} A^(-1) mod m */ modInverse(m) { const A = Math.round(this.real); const m_ = Math.round(Complex._toDouble(m)); const result = new BigInteger(A).modInverse(m_); return new Complex(result); } // ---------------------- // その他の演算 // ---------------------- /** * Multiply a multiple of ten. * @param {KComplexInputData} n * @returns {Complex} x * 10^n */ scaleByPowerOfTen(n) { return this.mul(Complex.TEN.pow(n)); } // ---------------------- // 素数 // ---------------------- /** * Return true if the value is prime number. * - Calculated as an integer. * - Calculate up to `9007199254740991`. * @returns {boolean} - If the calculation range is exceeded, null is returned. */ isPrime() { const src = new BigInteger(Math.round(this.real)); return src.isPrime(); } /** * Return true if the value is prime number by Miller-Labin prime number determination method. * * Attention : it takes a very long time to process. * - Calculated as an integer. * @param {KComplexInputData} [certainty=100] - Repeat count (prime precision). * @returns {boolean} */ isProbablePrime(certainty) { const src = new BigInteger(Math.round(this.real)); return src.isProbablePrime(certainty !== undefined ? Math.round(Complex._toDouble(certainty)) : undefined); } /** * Next prime. * @param {KComplexInputData} [certainty=100] - Repeat count (prime precision). * @param {KComplexInputData} [search_max=100000] - Search range of next prime. * @returns {Complex} */ nextProbablePrime(certainty, search_max) { const src = new BigInteger(Math.round(this.real)); const p1 = certainty !== undefined ? Math.round(Complex._toDouble(certainty)) : undefined; const p2 = search_max !== undefined ? Math.round(Complex._toDouble(search_max)) : undefined; return new Complex(src.nextProbablePrime(p1, p2)); } // ---------------------- // 定数 // ---------------------- /** * 1 * @returns {Complex} 1 */ static get ONE() { return DEFINE.ONE; } /** * 2 * @returns {Complex} 2 */ static get TWO() { return DEFINE.TWO; } /** * 10 * @returns {Complex} 10 */ static get TEN() { return DEFINE.TEN; } /** * 0 * @returns {Complex} 0 */ static get ZERO() { return DEFINE.ZERO; } /** * -1 * @returns {Complex} -1 */ static get MINUS_ONE() { return DEFINE.MINUS_ONE; } /** * i, j * @returns {Complex} i */ static get I() { return DEFINE.I; } /** * - i, - j * @returns {Complex} - i */ static get MINUS_I() { return DEFINE.MINUS_I; } /** * PI. * @returns {Complex} 3.14... */ static get PI() { return DEFINE.PI; } /** * 0.25 * PI. * @returns {Complex} 0.78... */ static get QUARTER_PI() { return DEFINE.QUARTER_PI; } /** * 0.5 * PI. * @returns {Complex} 1.57... */ static get HALF_PI() { return DEFINE.HALF_PI; } /** * 2 * PI. * @returns {Complex} 6.28... */ static get TWO_PI() { return DEFINE.TWO_PI; } /** * E, Napier's constant. * @returns {Complex} 2.71... */ static get E() { return DEFINE.E; } /** * log_e(2) * @returns {Complex} ln(2) */ static get LN2() { return DEFINE.LN2; } /** * log_e(10) * @returns {Complex} ln(10) */ static get LN10() { return DEFINE.LN10; } /** * log_2(e) * @returns {Complex} log_2(e) */ static get LOG2E() { return DEFINE.LOG2E; } /** * log_10(e) * @returns {Complex} log_10(e) */ static get LOG10E() { return DEFINE.LOG10E; } /** * sqrt(2) * @returns {Complex} sqrt(2) */ static get SQRT2() { return DEFINE.SQRT2; } /** * sqrt(0.5) * @returns {Complex} sqrt(0.5) */ static get SQRT1_2() { return DEFINE.SQRT1_2; } /** * 0.5 * @returns {Complex} 0.5 */ static get HALF() { return DEFINE.HALF; } /** * Positive infinity. * @returns {Complex} Infinity */ static get POSITIVE_INFINITY() { return DEFINE.POSITIVE_INFINITY; } /** * Negative Infinity. * @returns {Complex} -Infinity */ static get NEGATIVE_INFINITY() { return DEFINE.NEGATIVE_INFINITY; } /** * Not a Number. * @returns {Complex} NaN */ static get NaN() { return DEFINE.NaN; } // ---------------------- // 互換性 // ---------------------- /** * The positive or negative sign of this number. * - +1 if positive, -1 if negative, 0 if 0. * @returns {Complex} */ signum() { return this.sign(); } /** * Subtract. * @param {KComplexInputData} number * @returns {Complex} A - B */ subtract(number) { return this.sub(number); } /** * Multiply. * @param {KComplexInputData} number * @returns {Complex} A * B */ multiply(number) { return this.mul(number); } /** * Divide. * @param {KComplexInputData} number * @returns {Complex} fix(A / B) */ divide(number) { return this.div(number); } /** * Remainder of division. * - Result has same sign as the Dividend. * @param {KComplexInputData} number * @returns {Complex} A % B */ remainder(number) { return this.rem(number); } /** * To integer rounded down to the nearest. * @returns {Complex} fix(A), trunc(A) */ trunc() { return this.fix(); } }
JavaScript
class Deploy extends Command { constructor(client) { super(client, { name: "deploy", description: "This will deploy all slash commands.", category: "Dev", permLevel: 10, usage: "deploy", aliases: ["d"], enabled: true }); } async run(Bot, message) { if (!message?.guild) return super.error(message, "This command can only be run in a server"); const outLog = []; try { // Filter the slash commands to find guild only ones. const guildCmds = message.client.slashcmds.filter(c => c.guildOnly).map(c => c.commandData); // The currently deployed commands const currentGuildCommands = await message.client.guilds.cache.get(message.guild.id)?.commands.fetch(); const { newComs: newGuildComs, changedComs: changedGuildComs } = checkCmds(guildCmds, currentGuildCommands); // Give the user a notification the commands are deploying. await message.channel.send("Deploying commands!"); // We'll use set but please keep in mind that `set` is overkill for a singular command. // Set the guild commands like this. if (newGuildComs.length) { for (const newGuildCom of newGuildComs) { console.log(`Adding ${newGuildCom.name} to Guild commands`); await message.client.guilds.cache.get(message.guild.id)?.commands.create(newGuildCom); } } if (changedGuildComs.length) { for (const diffGuildCom of changedGuildComs) { console.log(`Updating ${diffGuildCom.com.name} in Guild commands`); await message.client.guilds.cache.get(message.guild.id)?.commands.edit(diffGuildCom.id, diffGuildCom.com); } } // The new guild commands outLog.push({ name: "**Added Guild**", value: newGuildComs?.length ? newGuildComs.map(newCom => ` * ${newCom.name}`).join("\n") : "N/A" }); // The edited guild commands outLog.push({ name: "**Changed Guild**", value: changedGuildComs?.length ? changedGuildComs.map(diffCom => ` * ${diffCom.com.name}`).join("\n") : "N/A" }); if (Bot.config.enableGlobalCmds) { // Then filter out global commands by inverting the filter const globalCmds = message.client.slashcmds.filter(c => !c.guildOnly).map(c => c.commandData); // Get the currently deployed global commands const currentGlobalCommands = await message.client.application?.commands?.fetch(); const { newComs: newGlobalComs, changedComs: changedGlobalComs } = checkCmds(globalCmds, currentGlobalCommands); if (newGlobalComs.length) { for (const newGlobalCom of newGlobalComs) { console.log(`Adding ${newGlobalCom.name} to Global commands`); await message.client.application?.commands.create(newGlobalCom); } } if (changedGlobalComs.length) { for (const diffGlobalCom of changedGlobalComs) { console.log(`Updating ${diffGlobalCom.com.name} in Global commands`); await message.client.application?.commands.edit(diffGlobalCom.id, diffGlobalCom.com); } } // The new global commands outLog.push({ name: "**Added Global**", value: newGlobalComs?.length ? newGlobalComs.map(newCom => ` * ${newCom.name}`).join("\n") : "N/A" }); // The edited global commands outLog.push({ name: "**Changed Global**", value: changedGlobalComs?.length ? changedGlobalComs.map(diffCom => ` * ${diffCom.com.name}`).join("\n") : "N/A" }); } return message.channel.send({ content: null, embeds: [ { title: "Deployed Commands", fields: outLog } ] }); } catch (err) { Bot.logger.error(inspect(err, {depth: 5})); } function checkCmds(newCmdList, oldCmdList) { const changedComs = []; const newComs = []; // Work through all the commands that are already deployed, and see which ones have changed newCmdList.forEach(cmd => { const thisCom = oldCmdList.find(c => c.name === cmd.name); let isDiff = false; // If there's no match, it definitely goes in if (!thisCom) { console.log("Need to add " + cmd.name); return newComs.push(cmd); } else { // Fill in various options info, just in case debugLog("\nChecking " + cmd.name); for (const ix in cmd.options) { if (!cmd.options[ix]) cmd.options[ix] = {}; if (!cmd.options[ix].required) cmd.options[ix].required = false; if (!cmd.options[ix].autocomplete) cmd.options[ix].autocomplete = undefined; if (!cmd.options[ix].choices) cmd.options[ix].choices = undefined; if (!cmd.options[ix].options || !cmd.options[ix].options?.length) cmd.options[ix].options = undefined; if (!cmd.options[ix].channelTypes) cmd.options[ix].channelTypes = undefined; debugLog("> checking " + cmd.options[ix]?.name); for (const op of Object.keys(cmd.options[ix])) { debugLog(" * Checking: " + op); if (op === "choices") { if (cmd.options[ix]?.choices?.length && thisCom.options[ix]?.choices?.length) { // Make sure they both have some number of choices if (cmd.options[ix]?.choices?.length !== thisCom.options[ix]?.choices?.length) { // One of em is different than the other, so definitely needs an update console.log("ChoiceLen is different"); isDiff = true; } else { // If they have the same option count, make sure that the choices are the same inside cmd.options[ix].choices.forEach((c, jx) => { const thisChoice = thisCom.options[ix].choices[jx]; if (c.name !== thisChoice.name || c.value !== thisChoice.value) { // They have a different choice here, needs updating console.log("Diff choices"); console.log(c, thisChoice); isDiff = true; return; } }); } } else { // One or both have no choices if (cmd.options[ix]?.choices?.length && thisCom.options[ix]?.choices?.length) { // At least one of em has an entry, so it needs updating console.log("choiceLen2 is diff"); isDiff = true; } else { // Neither of em have any, so nothing to do here continue; } } if (isDiff) { debugLog(` [NEW] - ${cmd.options[ix] ? inspect(cmd.options[ix]?.choices) : null}\n [OLD] - ${thisCom.options[ix] ? inspect(thisCom.options[ix]?.choices) : null}`); break; } } else { const newOpt = cmd.options[ix]; const thisOpt = thisCom.options[ix]; if (!thisOpt) { debugLog("Missing opt for: newOpt"); break; } if (!newOpt) { debugLog("Missing opt for: newOpt"); break; } if ((newOpt.required !== thisOpt.required && (newOpt.required || thisOpt.required)) || (newOpt.name !== thisOpt.name && (newOpt.name || thisOpt.name)) || (newOpt.description !== thisOpt.description && (newOpt.description || thisOpt.description)) || (newOpt.min_value !== thisOpt.min_value && (newOpt.min_value || thisOpt.min_value)) || (newOpt.max_value !== thisOpt.max_value && (newOpt.max_value || thisOpt.max_value)) || (newOpt.choices?.length !== thisOpt.choices?.length && (newOpt.choices || thisOpt.choices)) || (newOpt.options?.length !== thisOpt.options?.length && (newOpt.options || thisOpt.options)) ) { isDiff = true; debugLog(` [NEW] - ${newOpt ? inspect(newOpt) : null}\n [OLD] - ${thisOpt ? inspect(thisOpt) : null}`); break; } } } } if (!cmd.defaultPermission) cmd.defaultPermission = true; if (cmd?.description !== thisCom?.description) { isDiff = true; } if (cmd?.defaultPermission !== thisCom?.defaultPermission) { isDiff = true; } } // If something has changed, stick it in there if (isDiff) { console.log("Need to update " + thisCom.name); changedComs.push({id: thisCom.id, com: cmd}); } }); return {changedComs, newComs}; } } }
JavaScript
class ItemDelivery { /** * Constructs a new <code>ItemDelivery</code>. * Delivery information for the item. * @alias module:client/models/ItemDelivery * @class */ constructor() { } /** * Constructs a <code>ItemDelivery</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/ItemDelivery} obj Optional instance to populate. * @return {module:client/models/ItemDelivery} The populated <code>ItemDelivery</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ItemDelivery(); if (data.hasOwnProperty('estimatedDeliveryDate')) { obj['estimatedDeliveryDate'] = ApiClient.convertToType(data['estimatedDeliveryDate'], 'Date'); } if (data.hasOwnProperty('itemDeliveryPromise')) { obj['itemDeliveryPromise'] = ItemDeliveryPromise.constructFromObject(data['itemDeliveryPromise']); } } return obj; } /** * The date and time of the latest Estimated Delivery Date (EDD) of all the items with an EDD. In ISO 8601 format. * @member {Date} estimatedDeliveryDate */ 'estimatedDeliveryDate' = undefined; /** * @member {module:client/models/ItemDeliveryPromise} itemDeliveryPromise */ 'itemDeliveryPromise' = undefined; }
JavaScript
class Profiler { /** * Instantiate new profiler and start time. * * @param {string} [name] - Profiler name (default: "unknown") */ constructor(name) { this.name = name || 'unknown'; this._startTime = process.hrtime(); this._duration = null; this._children = []; } /** * Stop time tracking. */ end() { this._duration = process.hrtime(this._startTime); } /** * Create a child profiler. * * Its data is aggregated into ours. * * @param {string} [name] - Name of the child profiler * @returns {Profiler} */ child(name) { const child = new Profiler(name); this._children.push(child); return child; } /** * Return the duration since instantiation until end(). * * @returns {number} Duration in milliseconds */ getDuration() { return calcTime(this._duration); } /** * Return a report object. * * @param {number} [startTime] - All times are resolved relative to this startTime * @return {Array.<Object>} Array of objects with profiling information. */ report(startTime) { startTime = startTime || calcTime(this._startTime); let report = [ { name: this.name, startTime: calcTime(this._startTime, -startTime), duration: this._duration !== null ? calcTime(this._duration) : null } ]; this._children.forEach((child) => { report = report.concat(child.report(startTime)); }); return report; } }
JavaScript
class DefaultStdInHandlerJs extends DefaultStdInHandler { constructor() { super(); this.rl = readline.createInterface({ input: process.stdin, output: process.stdout }); this.rl.on('line', line => this.online(line)); event_1.events.serverClose.on(this.onclose); } close() { if (stdInHandler === null) return; console.assert(stdInHandler !== null); stdInHandler = null; this.rl.close(); this.rl.removeAllListeners(); bedrockServer.close.remove(this.onclose); } }
JavaScript
class Merger { constructor(source) { const opts = { recurse: false, sources: [], exclusions: [] } this[scope] = { opts } // Push the source into the sources array this.and(source) } /** * @summary Add another source object to be merged * * @param {Object} source The object to be merged * @return {this} */ and(source) { // Only allow objects as sources if (!(source instanceof Object)) { throw new TypeError(`Object or array source is required for merging, ${typeof source} given`) } this[scope].opts.sources.push(source) return this } /** * @summary Set the target object to merge into and perform the actual merge * * @desc This should be the last method called. * * @param {Object} target The object to start merging into * @return {Object} Returns the merged object */ into(target) { // Only allow objects as targets if (!(target instanceof Object)) { throw new TypeError(`Object or array target is required for merging, ${typeof target} given`) } // There may be multiple source objects to be merged into the target - start with the object // which has been added to the sources as last while (this[scope].opts.sources.length) { doMerge(this[scope].opts.sources.pop(), target, this[scope].opts) } return target } /** * @summary While merging, ignore properties with this name * * @tutorial ignoring-properties * @param {String|Array} properties A single property or array of properties to be ignored. * This will be used on all recursive levels of merging. * @return {this} */ excluding(properties) { if (!(properties instanceof Array)) { properties = [properties] } for (const property of properties) { this[scope].opts.exclusions.push(property) } return this } /** * @summary Alias of {@link module:semantic-merge~Merger#excluding excluding()} * * @tutorial ignoring-properties * @method module:semantic-merge~Merger#except * @param {String|Array} properties Property names which should be ignored when merging * @return {this} */ except(properties) { return this.excluding(properties) } /** * @summary Semantic getter to enable recursive merge * * @desc By default, only shallow merge is performed. That means, if an object's property is * also an object, it will be copied by reference. To avoid this, call this getter * somewhere in your call chain (before you call * {@link module:semantic-merge~Merger#into into()}) * @tutorial recursive-merge * @member module:semantic-merge~Merger#recursively * @default this */ get recursively() { this[scope].opts.recurse = true return this } }
JavaScript
class DashboardController extends RunningJobsController { constructor(params) { super(params, 'Dashboard') } /** * This collects and renders all of the data to be displayed * in the Dashboard. The data includes information about currently * running jobs, recently defined jobs, and information fetched * from any remote repositories DART can connect to. * */ show() { // Get a list of RemoteRepository clients that have enough information // to attempt a connection with the remote repo. let clients = this._getViableRepoClients(); // Get a list of available reports. let repoReports = this._getRepoReportDescriptions(clients); // Each of these clients can provide one or more reports. We want to // display the reports in rows, with two reports per row. let reportRows = this._getRepoRows(repoReports); // Assemble the HTML let html = Templates.dashboard({ alertMessage: this.params.get('alertMessage'), reportRows: reportRows, runningJobs: Object.values(Context.childProcesses), recentJobs: this._getRecentJobSummaries() }); // Call the reports. These are asynchronous, since they have to // query remote repositories. The callbacks describe which HTML // element on the rendered page will contain the HTML output of // the reports. repoReports.forEach((report) => { let elementId = '#' + report.id report.method().then( result => { $(elementId).removeClass('text-danger'); $(elementId).html(result) }, error => { $(elementId).addClass('text-danger'); $(elementId).html(error) } ); }); return this.containerContent(html); } /** * This returns summary info about the ten most recent jobs. * The return value is an array of objects, each of which has three * string properties. Object.name is the job name. Object.outcome * is the name and outcome of the last attempted action. * Object.date is the date at which the job last completed. * * @returns {Array<object>} */ _getRecentJobSummaries() { let jobSummaries = []; // This sort can approximate the 20 most recent jobs, // but the sort below, based on a calculated value, is more accurate. let opts = {limit: 20, offset: 0, orderBy: 'createdAt', sortDir: 'desc'}; // TODO: Override list() in Job to do its own inflation? let jobs = Job.list(null, opts).map((data) => { return Job.inflateFrom(data) }); for (let job of jobs) { let [outcome, timestamp] = this._getJobOutcomeAndTimestamp(job); jobSummaries.push({ name: job.title, outcome: outcome, date: timestamp }); } let sortFn = Util.getSortFunction('date', 'desc'); return jobSummaries.sort(sortFn); } /** * This returns formatted information about the outcome of a job * and when that outcome occurred. The return value is a two-element * array of strings. The first element describes the outcome. The * second is the date on which the outcome occurred. * * @returns {Array<string>} * */ _getJobOutcomeAndTimestamp(job) { // TODO: This code has some overlap with JobController#colorCodeJobs. let outcome = "Job has not been run."; let timestamp = null; if(job.uploadAttempted()) { outcome = job.uploadSucceeded() ? 'Uploaded' : 'Upload failed'; timestamp = dateFormat(job.uploadedAt(), 'yyyy-mm-dd'); } else if (job.validationAttempted) { outcome = job.validationSucceeded() ? 'Validated' : 'Validation failed'; timestamp = dateFormat(job.validatedAt(), 'yyyy-mm-dd'); } else if (job.packageAttempted()) { outcome = job.packageSucceeded() ? 'Packaged' : 'Packaging failed'; timestamp = dateFormat(job.packagedAt(), 'yyyy-mm-dd'); } return [outcome, timestamp] } /** * This returns a list of repository clients that look like they * can return data from remote repository. To find a list of viable * repository clients, DART first gets a list of all * {@link RemoteRepository} objects. If the RemoteRepository object * includes a {@link RemoteRepository#pluginId}, this function creates * an instance of the plugin and calls the plugin's {@link * RepositoryBase#hasRequiredConnectionInfo} method. If the method * returns true, the instantiated client will be returned in the list * of viable repo clients. * * @returns {Array<RepositoryBase>} * */ _getViableRepoClients() { let repoClients = []; let repos = RemoteRepository.list((r) => { return !Util.isEmpty(r.pluginId) }); for (let _repoData of repos) { // TODO: This object inflation should be pushed down into the // RemoteRepository class. let repo = new RemoteRepository(); Object.assign(repo, _repoData); let clientClass = PluginManager.findById(repo.pluginId); let clientInstance = new clientClass(repo); if (clientInstance.hasRequiredConnectionInfo()) { repoClients.push(clientInstance); } } return repoClients; } /** * This returns a list of report rows to be displayed in the dashboard. * Each row has up to two reports. (Because we're using the brain dead * Handlebars templating library, we have to format our data structures * precisely before rendering them. And, by the way, templates *should* * be brain dead, because when they start thinking, they become evil, * like PHP and React.) * * @param {} repoReports - A list of repo report summary objects, which * can be obtained from * {@link DashboardController#_getRepoReportDescriptions}. * * @returns {Array<Array<object>>} */ _getRepoRows(repoReports) { let reportRows = []; let i = 0; while (i < repoReports.length) { let report1 = repoReports[i]; let report2 = i + 1 < repoReports.length ? repoReports[i + 1] : null; reportRows.push([report1, report2]); i += 2; } return reportRows; } /** * This returns an array of objects describing all of the * reports available from all of the viable repository clients. * * Internally, this calls {@link RepositoryBase#provides} to * get the title, description, and function to call for each report. * * This adds an id to each description record, so the Dashboard * controller can map each report to the HTML element that will * display its output. * * Each item in the returned array will have properies id, title, * description, and method. * * @returns {Array<object>} * */ _getRepoReportDescriptions(clients) { let reports = []; let clientNumber = 0; clients.forEach((client) => { clientNumber++; let className = client.constructor.name; let reportIndex = 0; client.provides().forEach((report) => { reportIndex++; reports.push({ id: `${className}_${clientNumber}_${reportIndex}`, title: report.title, description: report.description, method: report.method }); } )}); return reports; } postRenderCallback(fnName) { for(let dartProcess of Object.values(Context.childProcesses)) { this.initRunningJobDisplay(dartProcess); } } }
JavaScript
class Node { /** * Constructs a new Node object from a "plain node", i.e. an object that has * all properties documented for this class, apart from all the ...*Edges * properties and the .meta property. * @param {Object} plainNode A "plain node" object as described above * @param {Object} defaultMeta (optional) an object containing keys with default * values that will be assigned to the .meta property. */ constructor(plainNode, defaultMeta = null) { this.id = plainNode.id; this.name = plainNode.name || '(unnamed SMARTS)'; this.pattern = plainNode.pattern || ''; this.library = plainNode.library || '(no library)'; this.outgoingEdges = []; this.incomingEdges = []; this.incidentEdges = []; // Validation of input if(!this.pattern || (typeof this.pattern) !== 'string') { throw new Error( `Node must be given a nonempty pattern but was given '${this.pattern}'!` ); } this.meta = {}; Object.assign(this.meta, _.cloneDeep(defaultMeta)); } }
JavaScript
class Edge { /** * Constructs a new Edge object from a "plain edge", i.e., an object that has * all properties documented for this class, apart from the .meta property. * * Can attach arbitrary metadata to the .meta property by passing default values * as an object `defaultMeta`. * * If the `getNodeFn` function parameter is passed, it will be called with the source * and target IDs to replace the .source and .target properties on the returned Edge, * by whatever values that function returns. * @param {Object} plainEdge A "plain edge" object as described above * @param {Object} defaultMeta (optional) an object containing keys with default * values that will be assigned to the .meta property. * @param {Function} getNodeFn (optional) A function that will be used to retrieve * matching Node object for the source and target IDs. * If not passed, .source and .target will be stored unchanged, i.e. as their IDs. */ constructor(plainEdge, defaultMeta = null, getNodeFn = null) { getNodeFn = getNodeFn || _.identity; this.id = plainEdge.id; this.mcssim = plainEdge.mcssim; this.spsim = plainEdge.spsim; this.type = plainEdge.type || 'subset'; this.source = getNodeFn(plainEdge.source); this.target = getNodeFn(plainEdge.target); // Validation of input if(!(this.type === 'equal' || this.type === 'subset')) { throw new Error(`Edge type must be 'equal' or 'subset', but '${this.type}' was given!`); } if(!(typeof this.mcssim === 'number') || this.mcssim < 0 || this.mcssim > 1) { throw new Error( `MCS similarity of edge must be a number between 0 and 1, but is '${this.mcssim}'!`); } if(!(typeof this.spsim === 'number') || this.spsim < 0 || this.spsim > 1) { throw new Error( `SP similarity of edge must be a number between 0 and 1, but is '${this.mcssim}'!`); } this.meta = {}; Object.assign(this.meta, _.cloneDeep(defaultMeta)); } }
JavaScript
class Graph { /** * Constructs a new Graph object from arrays 'nodes' and 'edges'. Allows the attachment of * metadata to every node and edge using a dictionary of default values for both. * @param {Array} nodes An array of plain-object nodes. See Node class for details. * @param {Array} edges An array of plain-object edges. See Edge class for details. * @param {Object} defaultNodeMeta (optional) an object containing default values for * arbitrary keys, to be attached as metadata to every *node*. * @param {Object} defaultEdgeMeta (optional) an object containing default values for * arbitrary keys, to be attached as metadata to every *edge*. * @param {Boolean} markEqualEdges (optional) If true (default), automatically detect equal * edges, i.e., a pair of edges (l,r) and (r,l), and mark them as having .type == 'equal'. * Will also remove one of each pair's edges, and sort the stored edges so that equal edges * come last (useful for rendering order). */ constructor(nodes, edges, defaultNodeMeta=null, defaultEdgeMeta=null, markEqualEdges=true) { // Store used "plain" nodes and edges (used by plainClone) this._plainNodes = nodes; this._plainEdges = edges; // Store default meta definitions (used by _createNode, _createEdge) this._defaultNodeMeta = defaultNodeMeta; this._defaultEdgeMeta = defaultEdgeMeta; // Store lookup dicts for nodeid->node, edgeid->edge lookups this._idsToNodes = {}; this._idsToEdges = {}; // Copy and initialize nodes & edges this.nodes = _.map(nodes, (node) => this._createNode(node)); this.edges = _.map(edges, (edge) => this._createEdge(edge)); if(markEqualEdges) { this._findMarkAndSortEqualEdges(); } } /** * Returns a clone of this graph simply by reusing the plain nodes, plain edges, * and their default meta values. * * Accordingly, will *not* copy any data updated after creation of this graph. */ plainClone() { return new Graph( this._plainNodes, this._plainEdges, this._defaultNodeMeta, this._defaultEdgeMeta); } /** * Returns a Node by ID if present, undefined otherwise. * @param {any} id The ID of the Node to be returned. */ getNodeById(id) { return this._idsToNodes[id]; } /** * Returns an Edge by ID if present, undefined otherwise. * @param {any} id The ID of the Edge to be returned. */ getEdgeById(id) { return this._idsToEdges[id]; } /** * Adds a new Node to this graph. * @param {Node} node The Node object to add. Must have a newly unique ID, or the * behavior of this Graph is undefined. */ addNode(node) { this.nodes.push(this._createNode(node)); } /** * Adds a new Edge to this graph. * @param {Edge} edge The Edge object to add. Must have a newly unique ID, or the * behavior of this Graph is undefined. */ addEdge(edge) { this.edges.push(this._createEdge(edge)); } /** * Runs a depth-first search through this graph starting from some Node, * calling arbitrary callback functions at each visited node and edge. * @param {Array} startNodes The Node object(s) to start the DFS from. Must be part of * this Graph. Can pass a list of Nodes or a single Node. * @param {String} direction The direction(s) to traverse edges in. * Can be 'outgoing', 'incoming', or 'all'. * @param {Number} maxDepth The maximum depth of the DFS. Convention: If maxDepth == 1, * then exactly all directly adjacent nodes of `selectedNode` are visited. * @param {Function} visitedNodeCallback (optional) A callback that will be called for * every visited node, with arguments: (visited node {Node}, current DFS depth {Number}). * @param {Function} visitedEdgeCallback (optional) A callback that will be called for * every traversed edge, with arguments: (traversed edge {Edge}, edge outgoing? {Boolean}) * TODO document new params */ runDFS(startNodes, direction, maxDepth, visitedNodeCallback=null, visitedEdgeCallback=null, beforeVisitCallback=null, edgeFilter=null, nodeFilter=null) { if(!(startNodes instanceof Array)) { startNodes = [startNodes]; } _.each(startNodes, (startNode) => { if(!(startNode instanceof Node)) { throw new Error("At least one start node is not a Node object!"); } if(!(startNode.id in this._idsToNodes)) { throw new Error("At least one start node ID was not found inside this Graph!"); } }); const lookup = { 'outgoing': 'outgoingEdges', 'incoming': 'incomingEdges', 'all': 'incidentEdges' }; const edgeProp = lookup[direction]; let visited = {}; function visitNode(node, depth) { if(nodeFilter && !nodeFilter(node)) return; if(visited[node.id] || depth > maxDepth) return; visited[node.id] = true; if(visitedNodeCallback) visitedNodeCallback(node, depth); _.each(node[edgeProp], function(edge) { if(edgeFilter && !edgeFilter(edge)) return; let isOutgoing = edge.source == node; let otherNode = isOutgoing ? edge.target : edge.source; if( ( isOutgoing && direction == 'outgoing') || (!isOutgoing && direction == 'incoming') || (direction == 'all') ) { if(visitedEdgeCallback) visitedEdgeCallback(edge, isOutgoing); visitNode(otherNode, depth+1); } }); } _.each(startNodes, (startNode) => { if(nodeFilter && !nodeFilter(startNode)) return; if(beforeVisitCallback) beforeVisitCallback(startNode, visited[startNode.id]); visitNode(startNode, 0); }); } /** * Calculates the connected components of this graph. Returns a 2-tuple of: * * - a dict mapping (CC id) -> (list of nodes in CC) * - a dict mapping (node id) -> (id of CC that contains this node) * @param {Function} edgeFilter (optional) a predicate to filter which edges will be traversed * @param {Function} nodeFilter (optional) a predicate to filter which nodes will be visited */ getCCs(edgeFilter=null, nodeFilter=null) { const nodes = this.nodes; let nofCC = 0; let nodeToCC = {}; let ccs = {}; this.runDFS(nodes, 'all', Infinity, (node) => { // node callback nodeToCC[node.id] = nofCC; ccs[nofCC].push(node); }, null, // edge callback (node, previouslyVisited) => { // before node visit callback if(!previouslyVisited) { nofCC++; ccs[nofCC] = []; return true; } return false; }, edgeFilter, nodeFilter ); ccs = _.map(ccs, (cc) => { return _.sortBy(cc, 'id'); }); return [ccs, nodeToCC]; } /** * Sets node positions (x, y) to a grid, based on the connected components. * * - Every node in one CC will be assigned the same position. * - Nodes in CCs with at least 2 nodes are put into one--roughly quadratic--regular grid, * ordered by corresponding CC size * - Nodes in CCs with only one node (isolated nodes) are put into another * --roughly quadratic--regular grid, separate from the first one. * @param {Function} edgeFilter (optional) a predicate to filter which edges will be traversed * @param {Function} nodeFilter (optional) a predicate to filter which nodes will be visited */ setPositionsFromCCs(edgeFilter, nodeFilter) { // TODO: more flexibility in layout (especially offsets) let [ccs, nodeToCC] = this.getCCs(edgeFilter, nodeFilter); ccs = _.sortBy(Object.values(ccs), cc => -cc.length); // TODO also consider identical edges? let [ccsMultiple, ccsSingle] = _.partition(ccs, cc => cc.length >= 2); // Multiple nodes per CC let perRow = Math.ceil(Math.sqrt(ccsMultiple.length)); let offset = 500; let mid = (offset * (perRow - 1)) / 2; let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; _.each(ccsMultiple, function(cc, ccIdx) { let x = offset * (ccIdx % perRow) - mid; let y = offset * Math.floor(ccIdx / perRow) - mid; minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); let perCCRow = Math.ceil(Math.sqrt(cc.length)); _.each(cc, function(node, i) { node.x = x + 0.5 * (i % perCCRow); node.y = y + 0.5 * Math.floor(i / perCCRow); }); }); if(!ccsMultiple.length) { // handle case when there were no CCs with at least 2 nodes [minX, maxX, minY, maxX] = [0, 0, 0, 0]; } // Single node per CC let baseX = maxX + offset; let baseY = minY; let perRowSingle = Math.ceil(Math.sqrt(ccsSingle.length)); let offsetSingle = 100; _.each(ccsSingle, function(cc, ccIdx) { if(!cc.length) return; let x = baseX + offsetSingle * (ccIdx % perRowSingle); let y = baseY + offsetSingle * Math.floor(ccIdx / perRowSingle); cc[0].x = x; cc[0].y = y; }); } /** * Creates and inserts a Node object from a plain-object description into this graph, * using the Node constructor. * @param {Object} plainNode The plain-object description of the node, e.g. received as JSON. */ _createNode(plainNode) { const defaultMeta = this._defaultNodeMeta; const node = new Node(plainNode, defaultMeta); this._idsToNodes[node.id] = node; return node; } /** * Creates and inserts an Edge object from a plain-object description into this graph, * using the Edge constructor. * @param {*} plainEdge */ _createEdge(plainEdge) { if(!(plainEdge.source in this._idsToNodes)) { throw new Error( `Cannot create an edge with unknown source ID ${plainEdge.source}!`); } if(!(plainEdge.target in this._idsToNodes)) { throw new Error( `Cannot create an edge with unknown target ID ${plainEdge.target}!`); } const defaultMeta = this._defaultEdgeMeta; const edge = new Edge(plainEdge, defaultMeta, (id) => this._idsToNodes[id]); this._idsToEdges[edge.id] = edge; edge.source.outgoingEdges.push(edge); edge.target.incomingEdges.push(edge); edge.source.incidentEdges.push(edge); edge.target.incidentEdges.push(edge); return edge; } /** * Finds and marks edges a->b where b->a exists as well, implying node equality. * Also re-orders edges such that equal edges come last (useful for rendering order). * Mutates this.edges: When the second edge of a pair is found, it is filtered out from * this.edges. */ _findMarkAndSortEqualEdges() { const lookup = {}; this.edges = _.sortBy(_.filter(this.edges, (edge) => { const [l, r] = [edge.source, edge.target]; const reverseEdge = lookup[(r.id + ',' + l.id)]; if(reverseEdge) { reverseEdge.type = 'equal'; // keep the other edge } lookup[(l.id + ',' + r.id)] = edge; return !reverseEdge; }), (e) => e.type == 'equal' ? 1 : 0); // sort equal edges to last positions } }
JavaScript
class SimulatedGraph { constructor(graph, simulation, activeEdgeFilter, activeNodeFilter) { this.real = Vue.reactive(graph); this.simulacrum = graph.plainClone(); this._activeNodeIds = _.reduce(_.filter(this.real.nodes, activeNodeFilter), (r, node) => { r[node.id] = true; return r; }, {}); this._activeEdgeIds = _.reduce(_.filter(this.real.edges, activeEdgeFilter), (r, edge) => { r[edge.id] = true; return r; }, {}); this.simulacrum.setPositionsFromCCs(activeEdgeFilter, activeNodeFilter); simulation.stop(); simulation.nodes( _.filter(this.simulacrum.nodes, (node) => this._activeNodeIds[node.id])); simulation.force('link').links( _.filter(this.simulacrum.edges, (edge) => this._activeEdgeIds[edge.id])); simulation.restart(); this.simulation = simulation; } addNode(node) { this.real.addNode(node); this.simulacrum.addNode(node); this.simulation.nodes(this.simulacrum.nodes).restart(); } addEdge(edge) { this.real.addEdge(edge); this.simulacrum.addEdge(edge); this.simulation.force('link').links(this.simulacrum.edges).restart(); } }
JavaScript
class AnthemWeb extends Component { static navigationOptions = ({ navigation }) => { // const { params } = navigation.state; return { // headerTitle: // <View style={{ flex: 1, alignSelf: 'center', justifyContent: 'center', alignItems: 'center' }}> // <TouchableHighlight onPress={() => navigation.navigate('MenuOptions')}> // <Image style={{ // height: 80, // width: 80, // // alignSelf: 'center', // borderRadius: 120, // resizeMode: 'contain' // }} // source={{ uri: params.logo }} /> // </TouchableHighlight> // <Text style={styles.assetHeaderLabel}>{params.name}</Text> // </View>, // headerStyle: { // height: Platform.OS === 'android' ? 100 + STATUS_BAR_HEIGHT : 100, // backgroundColor: '#021227', // }, // headerTitleStyle: { // marginTop: Platform.OS === 'android' ? STATUS_BAR_HEIGHT : 0, // textAlign: 'center', // alignSelf: 'center', // // textAlignVertical: 'center', // backgroundColor: '#021227', // }, headerLeft: <BackButton navigation={navigation} />, // headerRight: <View></View> } } render() { return ( <WebView source={{ uri: 'https://www.anthemvault.com/' }} style={{ marginTop: 20, flex: 1 }} /> ); } }
JavaScript
class CodeConsole extends widgets_1.Widget { /** * Construct a console widget. */ constructor(options) { super(); this._banner = null; this._executed = new signaling_1.Signal(this); this._mimetype = 'text/x-ipython'; this._promptCellCreated = new signaling_1.Signal(this); this.addClass(CONSOLE_CLASS); this.node.dataset[KERNEL_USER] = 'true'; this.node.dataset[CODE_RUNNER] = 'true'; this.node.tabIndex = -1; // Allow the widget to take focus. // Create the panels that hold the content and input. const layout = (this.layout = new widgets_1.PanelLayout()); this._cells = new observables_1.ObservableList(); this._content = new widgets_1.Panel(); this._input = new widgets_1.Panel(); this.contentFactory = options.contentFactory || CodeConsole.defaultContentFactory; this.modelFactory = options.modelFactory || CodeConsole.defaultModelFactory; this.rendermime = options.rendermime; this.session = options.session; this._mimeTypeService = options.mimeTypeService; // Add top-level CSS classes. this._content.addClass(CONTENT_CLASS); this._input.addClass(INPUT_CLASS); // Insert the content and input panes into the widget. layout.addWidget(this._content); layout.addWidget(this._input); // Set up the foreign iopub handler. this._foreignHandler = new foreign_1.ForeignHandler({ session: this.session, parent: this, cellFactory: () => this._createCodeCell() }); this._history = new history_1.ConsoleHistory({ session: this.session }); this._onKernelChanged(); this.session.kernelChanged.connect(this._onKernelChanged, this); this.session.statusChanged.connect(this._onKernelStatusChanged, this); } /** * A signal emitted when the console finished executing its prompt cell. */ get executed() { return this._executed; } /** * A signal emitted when a new prompt cell is created. */ get promptCellCreated() { return this._promptCellCreated; } /** * The list of content cells in the console. * * #### Notes * This list does not include the current banner or the prompt for a console. * It may include previous banners as raw cells. */ get cells() { return this._cells; } /* * The console input prompt cell. */ get promptCell() { let inputLayout = this._input.layout; return inputLayout.widgets[0] || null; } /** * Add a new cell to the content panel. * * @param cell - The cell widget being added to the content panel. * * #### Notes * This method is meant for use by outside classes that want to inject content * into a console. It is distinct from the `inject` method in that it requires * rendered code cell widgets and does not execute them. */ addCell(cell) { this._content.addWidget(cell); this._cells.push(cell); cell.disposed.connect(this._onCellDisposed, this); this.update(); } addBanner() { if (this._banner) { // An old banner just becomes a normal cell now. let cell = this._banner; this._cells.push(this._banner); cell.disposed.connect(this._onCellDisposed, this); } // Create the banner. let model = this.modelFactory.createRawCell({}); model.value.text = '...'; let banner = (this._banner = new cells_1.RawCell({ model, contentFactory: this.contentFactory })); banner.addClass(BANNER_CLASS); banner.readOnly = true; this._content.addWidget(banner); } /** * Clear the code cells. */ clear() { // Dispose all the content cells let cells = this._cells; while (cells.length > 0) { cells.get(0).dispose(); } } /** * Dispose of the resources held by the widget. */ dispose() { // Do nothing if already disposed. if (this.isDisposed) { return; } this._cells.clear(); this._history.dispose(); this._foreignHandler.dispose(); super.dispose(); } /** * Set whether the foreignHandler is able to inject foreign cells into a * console. */ get showAllActivity() { return this._foreignHandler.enabled; } set showAllActivity(value) { this._foreignHandler.enabled = value; } /** * Execute the current prompt. * * @param force - Whether to force execution without checking code * completeness. * * @param timeout - The length of time, in milliseconds, that the execution * should wait for the API to determine whether code being submitted is * incomplete before attempting submission anyway. The default value is `250`. */ execute(force = false, timeout = EXECUTION_TIMEOUT) { if (this.session.status === 'dead') { return Promise.resolve(void 0); } const promptCell = this.promptCell; if (!promptCell) { return Promise.reject('Cannot execute without a prompt cell'); } promptCell.model.trusted = true; if (force) { // Create a new prompt cell before kernel execution to allow typeahead. this.newPromptCell(); return this._execute(promptCell); } // Check whether we should execute. return this._shouldExecute(timeout).then(should => { if (this.isDisposed) { return; } if (should) { // Create a new prompt cell before kernel execution to allow typeahead. this.newPromptCell(); this.promptCell.editor.focus(); return this._execute(promptCell); } else { // add a newline if we shouldn't execute promptCell.editor.newIndentedLine(); } }); } /** * Inject arbitrary code for the console to execute immediately. * * @param code - The code contents of the cell being injected. * * @returns A promise that indicates when the injected cell's execution ends. */ inject(code) { let cell = this._createCodeCell(); cell.model.value.text = code; this.addCell(cell); return this._execute(cell); } /** * Insert a line break in the prompt cell. */ insertLinebreak() { let promptCell = this.promptCell; if (!promptCell) { return; } promptCell.editor.newIndentedLine(); } /** * Serialize the output. * * #### Notes * This only serializes the code cells and the prompt cell if it exists, and * skips any old banner cells. */ serialize() { const cells = []; algorithm_1.each(this._cells, cell => { let model = cell.model; if (cells_1.isCodeCellModel(model)) { cells.push(model.toJSON()); } }); if (this.promptCell) { cells.push(this.promptCell.model.toJSON()); } return cells; } /** * Handle the DOM events for the widget. * * @param event - The DOM event sent to the widget. * * #### Notes * This method implements the DOM `EventListener` interface and is * called in response to events on the notebook panel's node. It should * not be called directly by user code. */ handleEvent(event) { switch (event.type) { case 'keydown': this._evtKeyDown(event); break; case 'click': this._evtClick(event); break; default: break; } } /** * Handle `after_attach` messages for the widget. */ onAfterAttach(msg) { let node = this.node; node.addEventListener('keydown', this, true); node.addEventListener('click', this); // Create a prompt if necessary. if (!this.promptCell) { this.newPromptCell(); } else { this.promptCell.editor.focus(); this.update(); } } /** * Handle `before-detach` messages for the widget. */ onBeforeDetach(msg) { let node = this.node; node.removeEventListener('keydown', this, true); node.removeEventListener('click', this); } /** * Handle `'activate-request'` messages. */ onActivateRequest(msg) { let editor = this.promptCell && this.promptCell.editor; if (editor) { editor.focus(); } this.update(); } /** * Make a new prompt cell. */ newPromptCell() { let promptCell = this.promptCell; let input = this._input; // Make the last prompt read-only, clear its signals, and move to content. if (promptCell) { promptCell.readOnly = true; promptCell.removeClass(PROMPT_CLASS); signaling_1.Signal.clearData(promptCell.editor); let child = input.widgets[0]; child.parent = null; this.addCell(promptCell); } // Create the new prompt cell. let factory = this.contentFactory; let options = this._createCodeCellOptions(); promptCell = factory.createCodeCell(options); promptCell.model.mimeType = this._mimetype; promptCell.addClass(PROMPT_CLASS); this._input.addWidget(promptCell); // Suppress the default "Enter" key handling. let editor = promptCell.editor; editor.addKeydownHandler(this._onEditorKeydown); this._history.editor = editor; this._promptCellCreated.emit(promptCell); } /** * Handle `update-request` messages. */ onUpdateRequest(msg) { Private.scrollToBottom(this._content.node); } /** * Handle the `'keydown'` event for the widget. */ _evtKeyDown(event) { let editor = this.promptCell && this.promptCell.editor; if (!editor) { return; } if (event.keyCode === 13 && !editor.hasFocus()) { event.preventDefault(); editor.focus(); } } /** * Handle the `'click'` event for the widget. */ _evtClick(event) { if (this.promptCell && this.promptCell.node.contains(event.target)) { this.promptCell.editor.focus(); } } /** * Execute the code in the current prompt cell. */ _execute(cell) { let source = cell.model.value.text; this._history.push(source); // If the source of the console is just "clear", clear the console as we // do in IPython or QtConsole. if (source === 'clear' || source === '%clear') { this.clear(); return Promise.resolve(void 0); } cell.model.contentChanged.connect(this.update, this); let onSuccess = (value) => { if (this.isDisposed) { return; } if (value && value.content.status === 'ok') { let content = value.content; // Use deprecated payloads for backwards compatibility. if (content.payload && content.payload.length) { let setNextInput = content.payload.filter(i => { return i.source === 'set_next_input'; })[0]; if (setNextInput) { let text = setNextInput.text; // Ignore the `replace` value and always set the next cell. cell.model.value.text = text; } } } cell.model.contentChanged.disconnect(this.update, this); this.update(); this._executed.emit(new Date()); }; let onFailure = () => { if (this.isDisposed) { return; } cell.model.contentChanged.disconnect(this.update, this); this.update(); }; return cells_1.CodeCell.execute(cell, this.session).then(onSuccess, onFailure); } /** * Update the console based on the kernel info. */ _handleInfo(info) { this._banner.model.value.text = info.banner; let lang = info.language_info; this._mimetype = this._mimeTypeService.getMimeTypeByLanguage(lang); if (this.promptCell) { this.promptCell.model.mimeType = this._mimetype; } } /** * Create a new foreign cell. */ _createCodeCell() { let factory = this.contentFactory; let options = this._createCodeCellOptions(); let cell = factory.createCodeCell(options); cell.readOnly = true; cell.model.mimeType = this._mimetype; cell.addClass(FOREIGN_CELL_CLASS); return cell; } /** * Create the options used to initialize a code cell widget. */ _createCodeCellOptions() { let contentFactory = this.contentFactory; let modelFactory = this.modelFactory; let model = modelFactory.createCodeCell({}); let rendermime = this.rendermime; return { model, rendermime, contentFactory }; } /** * Handle cell disposed signals. */ _onCellDisposed(sender, args) { if (!this.isDisposed) { this._cells.removeValue(sender); } } /** * Test whether we should execute the prompt cell. */ _shouldExecute(timeout) { const promptCell = this.promptCell; if (!promptCell) { return Promise.resolve(false); } let model = promptCell.model; let code = model.value.text; return new Promise((resolve, reject) => { let timer = setTimeout(() => { resolve(true); }, timeout); let kernel = this.session.kernel; if (!kernel) { resolve(false); return; } kernel .requestIsComplete({ code }) .then(isComplete => { clearTimeout(timer); if (this.isDisposed) { resolve(false); } if (isComplete.content.status !== 'incomplete') { resolve(true); return; } resolve(false); }) .catch(() => { resolve(true); }); }); } /** * Handle a keydown event on an editor. */ _onEditorKeydown(editor, event) { // Suppress "Enter" events. return event.keyCode === 13; } /** * Handle a change to the kernel. */ _onKernelChanged() { this.clear(); if (this._banner) { this._banner.dispose(); this._banner = null; } this.addBanner(); } /** * Handle a change to the kernel status. */ _onKernelStatusChanged() { if (this.session.status === 'connected') { // we just had a kernel restart or reconnect - reset banner let kernel = this.session.kernel; if (!kernel) { return; } kernel .requestKernelInfo() .then(() => { if (this.isDisposed || !kernel || !kernel.info) { return; } this._handleInfo(this.session.kernel.info); }) .catch(err => { console.error('could not get kernel info'); }); } else if (this.session.status === 'restarting') { this.addBanner(); } } }
JavaScript
class ContentFactory extends cells_1.Cell.ContentFactory { /** * Create a new code cell widget. * * #### Notes * If no cell content factory is passed in with the options, the one on the * notebook content factory is used. */ createCodeCell(options) { if (!options.contentFactory) { options.contentFactory = this; } return new cells_1.CodeCell(options); } /** * Create a new raw cell widget. * * #### Notes * If no cell content factory is passed in with the options, the one on the * notebook content factory is used. */ createRawCell(options) { if (!options.contentFactory) { options.contentFactory = this; } return new cells_1.RawCell(options); } }
JavaScript
class ModelFactory { /** * Create a new cell model factory. */ constructor(options = {}) { this.codeCellContentFactory = options.codeCellContentFactory || cells_1.CodeCellModel.defaultContentFactory; } /** * Create a new code cell. * * @param source - The data to use for the original source data. * * @returns A new code cell. If a source cell is provided, the * new cell will be initialized with the data from the source. * If the contentFactory is not provided, the instance * `codeCellContentFactory` will be used. */ createCodeCell(options) { if (!options.contentFactory) { options.contentFactory = this.codeCellContentFactory; } return new cells_1.CodeCellModel(options); } /** * Create a new raw cell. * * @param source - The data to use for the original source data. * * @returns A new raw cell. If a source cell is provided, the * new cell will be initialized with the data from the source. */ createRawCell(options) { return new cells_1.RawCellModel(options); } }
JavaScript
class Url { static get className() { return 'vcs.Url'; } /** * @param {Object} options */ constructor(options) { this.className = Url.className; /** @type{string} */ this.base = options.base; this.base.replace('/$', ''); /** @type{Array<string>} */ this.path = options.path || []; /** @type{Array<string>} */ this.hashPath = options.hashPath || []; /** @type{!Object} */ this.queryParams = options.queryParams || {}; } /** * Adds Query Parameters * @param {!Object} queryParams */ addQueryParams(queryParams) { Object.keys(queryParams).forEach(function (key) { this.queryParams[key] = queryParams[key]; }, this); } /** * Gets a urls query params * @returns {Object<string, *>} */ getQueryParams() { return this.queryParams; } /** * Clears the query params */ clearQueryParams() { this.queryParams = {}; } /** * Sets the path of the url. Each argument is a path directory * @param {...string} var_args * @return {vcs.Url} */ setPath(var_args) { this.path.splice(0, this.path.length); for (let i = 0; i < arguments.length; i++) { this.path.push(arguments[i].replace('/', '')); } return this; } /** * Extends the url path, each argument is a path directory * @param {...string} var_args * @return {vcs.Url} */ extendPath(var_args) { for (let i = 0; i < arguments.length; i++) { const value = arguments[i].replace('/', ''); if (/^\.\.$/.test(value)) { this.path.pop(); } else { this.path.push(value); } } return this; } /** * Returns a new vcs.Url, a clone of this one * @return {!vcs.Url} */ clone() { return new Url({ base: this.base, path: this.path.slice(0), hashPath: this.hashPath.slice(0), queryParams: this._cloneQueryParams(), }); } /** * Clones the query params * @private */ _cloneQueryParams() { var extend = function (object) { const scratch = {}; Object.keys(object).forEach((key) => { const value = object[key]; if (Array.isArray(value)) { scratch[key] = value.splice(0); } else if (typeof value === 'object') { scratch[key] = extend(value); } else { scratch[key] = value; } }, this); return scratch; }; return extend(this.queryParams); }; /** * Makes an url with query parameters * @return {string} */ toString() { let stringUrl = `${this.base}/${this.path.join('/')}`; stringUrl = stringUrl.replace(/\/$/, ''); if (Object.keys(this.queryParams).length > 0) { stringUrl += `?${this._getStringQueryParams()}`; } if (this.hashPath.length > 0) { stringUrl += `#${this.hashPath.join('/')}`; } return stringUrl; } /** * returns the query params as kwp * @return {string} */ _getStringQueryParams() { return Object.keys(this.queryParams).map(function (key) { const value = this.queryParams[key]; let stringValue; if (value instanceof Object) { stringValue = JSON.stringify(value); } else { stringValue = String(value); } return `${key}=${encodeURIComponent(stringValue)}`; // XXX do I need to encode everything here? }, this).join('&'); } /** * Parses a string into a vcs.Url if its a valid url * @param {string} stringUrl * @return {vcs.Url} */ static parse(stringUrl) { if (Url.isUrl(stringUrl)) { const querySplit = stringUrl.split('?'); const hashSplit = stringUrl.split('#'); let query = null; if (querySplit.length > 1) { const queryBeforeHash = querySplit[1].split('#')[0]; let queryString = queryBeforeHash; if (queryString.endsWith('/')) { queryString = queryString.split('/')[0]; } query = Url.parseQueryParams(queryString); } let hashPath = []; if (hashSplit.length > 1) { const hashBeforeQuery = hashSplit[1].split('?')[0]; hashPath = hashBeforeQuery.split('/'); } let path = querySplit[0].split('#')[0].split('/'); let base; if (/^(https?:\/\/).*/.test(stringUrl)) { base = path.splice(0, 3).join('/'); } else { base = path.splice(0, 1); } path = path.filter(pathComponent => pathComponent !== ''); return new Url({ base, path, queryParams: query, hashPath, }); } throw new Error(`Cannot parse url: ${stringUrl}`); } /** * Parses the query parameters in a url to a JSON * @param {string} queryString * @return {Object} */ static parseQueryParams(queryString) { const kvps = queryString.split('&'); const queryParams = {}; kvps.forEach((kvp) => { const split = kvp.split('='); let value; if (split.length === 2 && split[1].length > 0) { value = decodeURIComponent(split[1]); if (/^\d*\.?\d*$/.test(value)) { value = Number(value); } else if (/^(\[|\{)(.*)(\]|\})$/.test(value)) { value = JSON.parse(value); } else if (value === 'true') { value = true; } else if (value === 'false') { value = false; } } const exists = queryParams[split[0]]; if (exists) { if (Array.isArray(exists)) { exists.push(value); } else { queryParams[split[0]] = [exists, value]; } } else { queryParams[split[0]] = value; } }); return queryParams; } /** * Tests whether the string representation of a URL is valid * Regex from https://mathiasbynens.be/demo/url-regex @Jeffrey Friedl * @param {string} url * @return {boolean} */ static isUrl(url) { const regEx = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i; return regEx.test(url); } /** * @param {string} url to check * @return {boolean} if the url has the same origin as the current domain */ static hasSameOrigin(url) { // relative Url, return true; if (!/^[a-z][a-z0-9+.-]*:/.test(url)) { return true; } const currentUri = Url.parse(window.location.href); const uri = Url.parse(url); if (currentUri.base.toLowerCase() === uri.base.toLocaleLowerCase()) { return true; } return false; }; }
JavaScript
class Registrator { _codes = {}; /** * Registers the error to the SmartError object. The code is accesible as the object's function with message and payload fields. * * @param {SmartError} SmartError * @param {string} code * @param {string} message * @param {Object} payload * @param {string} description */ register(SmartError, code, message, payload, description = null) { if (this._codes[code]) { console.error(`Error with code '${code}' is already registered.`); return; } this._codes[code] = { code: code, description: description, function: (m = message, p = payload) => new SmartError(m, code, p) } Object.defineProperty(SmartError, code, { get: () => this._call(code, SmartError), enumerable: true, configurable: true }); } /** * Removes the error from the SmartError object. * * @param {SmartError} SmartError * @param {string} code */ unregister(SmartError, code) { if (!this._codes[code]) { console.error(`Error with code '${code}' is not registered.`); return; } delete this._codes[code]; delete SmartError[code]; } /** * Gets all registered codes as an array. * * @returns {string[]} */ codes() { return Object.keys(this._codes); } /** * @typedef DocsObject * @property {object} [code] * @param {string} code.description */ /** * Gets the documentation of the registered error. * * @returns {DocsObject} */ docs() { const o = {}; for (let code in this._codes) { o[code] = { description: this._codes[code].description } } return o; } /** * Calls the registered function. * * @param {string} code * @param {SmartError} SmartError */ _call(code, SmartError) { return this._codes[code].function; } }
JavaScript
class CaptionComponent extends React.Component { constructor(props, context) { super(props, context); this.handleChange = this.handleChange.bind(this); } componentDidMount() { if (!this.props.readOnly) { findDOMNode(this.inputFieldRef).value= this.props.caption ? this.props.caption : null; } } componentDidUpdate() { if (!this.props.readOnly) { findDOMNode(this.inputFieldRef).value= this.props.caption ? this.props.caption : null; } } handleChange() { const value = findDOMNode(this.inputFieldRef).value; this.props.onCaptionChange(value); } render() { let child = null; if (this.props.readOnly) { let caption = this.props.caption ? this.props.caption.trim() : ''; if (caption.length > 0) { child = <div className={styles.caption}> <span className='cmcomp-caption fg-black75'> {this.props.caption} </span> </div> } } else { if(this.props.hookOnChangeEvent == true) { child = <div className={styles.caption}> <FormControl id='caption-component' style={{textAlign:'center'}} placeholder='Caption Text' ref={(node) => this.inputFieldRef = node} className='cmcomp-caption' onBlur={this.handleChange} onChange={this.handleChange}/> </div> } else { child = <div className={styles.caption}> <FormControl id='caption-component' style={{textAlign:'center'}} placeholder='Caption Text' ref={(node) => this.inputFieldRef = node} className='cmcomp-caption' onBlur={this.handleChange}/> </div> } } return child; } }
JavaScript
class VigenereCipheringMachine { constructor(type) { this.type = (type == undefined ? true : type); } encrypt(str, key) { if (str == undefined || key == undefined) throw new Error('Incorrect arguments!'); str = str.toUpperCase().split(''); key = key.padEnd(str.length, key).toUpperCase().split(''); let resutl = ''; function encryptLetter(char, key) { return String.fromCharCode((char.charCodeAt() + key.charCodeAt()) % 26 + 65) } let j = 0; for (let i = 0; i < str.length; i++) { if (str[i].charCodeAt() >= 65 && (str[i].charCodeAt() <= 90)) { resutl += encryptLetter(str[i], key[j]); j++; } else { resutl += str[i]; } } if (!this.type) return resutl.split('').reverse().join(''); return resutl; } decrypt(str, key) { if (str == undefined || key == undefined) throw new Error('Incorrect arguments!'); str = str.toUpperCase().split(''); key = key.padEnd(str.length, key).toUpperCase().split(''); let resutl = ''; function encryptLetter(char, key) { return String.fromCharCode((char.charCodeAt() - key.charCodeAt() + 26) % 26 + 65) } let j = 0; for (let i = 0; i < str.length; i++) { if (str[i].charCodeAt() >= 65 && (str[i].charCodeAt() <= 90)) { resutl += encryptLetter(str[i], key[j]); j++; } else { resutl += str[i]; } } if (!this.type) return resutl.split('').reverse().join(''); return resutl; } }
JavaScript
class OeWorkflowStatus extends OECommonMixin(PolymerElement) { static get template() { return html` <style include="iron-flex"> .fullsize { height:100%; width: 100%; } .pad{ padding: var(--my-padding, 12px); } #viewer { height:70vh; } .buttons { padding: 0px 20px; } </style> <app-header fixed condenses slot="header"> <app-toolbar> <paper-icon-button icon="arrow-back" on-tap="handleBackbuton"></paper-icon-button> <div main-title>[[procInstance.processDefinitionName]]</div> </app-toolbar> </app-header> <div class="layout vertical fullsize" id="OeWorkflowSt"> <div class="layout horizontal buttons"> <paper-icon-button icon="zoom-in" on-tap="zoomIn"></paper-icon-button> <paper-icon-button icon="zoom-out" on-tap="zoomOut"></paper-icon-button> <paper-icon-button icon="autorenew" on-tap="_resetZoom"></paper-icon-button> <paper-icon-button icon="refresh" on-tap="_procIdChanged"></paper-icon-button> </div> <oe-bpmn-viewer id="viewer"></oe-bpmn-viewer> </div>`; } static get is() { return 'oe-workflow-status'; } static get properties() { return { procInstance: { type: Object, observer: '_procChanged' }, bpmnDt: { type: Object, observer: '_bpmnChanged' }, procInstanceId: { type: String, observer: '_procIdChanged' }, userLt: { type: Array, value: function () { return []; } }, roleLt: { type: Array, value: function () { return []; } }, userRoleObject: { type: Object, observer: '_userRoleChanged' }, taskId: { type: String }, restUrlApi: { type: String }, reassign: { type: String, observer: '_procIdChanged' } }; } connectedCallback() { super.connectedCallback(); var self = this; window.addEventListener('oe-workflow-retry',this._handleError.bind(this)); this.$.viewer.addEventListener('refresh',function(event){ self._procIdChanged(event.detail); }) this.$.viewer.addEventListener('wheel', function (event) { event.preventDefault(); if (event.deltaY > 0) { self.zoomOut(); } else { self.zoomIn(); } }); } zoomIn(e) { var oeViewer = this.$.viewer; var zoom = oeViewer.zoom(); oeViewer.zoom(zoom + 0.1); } zoomOut(e) { var oeViewer = this.$.viewer; var zoom = oeViewer.zoom(); oeViewer.zoom(zoom - 0.1); } _resetZoom() { let canvas = this.$.viewer.viewer.get('canvas'); var zoomedAndScrolledViewbox = canvas.viewbox(); canvas.viewbox({ x: 0, y: 0, width: zoomedAndScrolledViewbox.outer.width, height: zoomedAndScrolledViewbox.outer.height }); canvas.zoom('fit-viewport'); } _xhrget(url, mime, callback) { if (!callback && typeof mime === 'function') { callback = mime; mime = 'json'; } var oReq = new XMLHttpRequest(); oReq.addEventListener('load', function (evt) { if (evt.target.status >= 200 && evt.target.status < 300) { callback(null, evt.target.response); } else { callback(evt.target.statusText, null); } }); oReq.addEventListener('error', function (err) { callback(err); }); oReq.open("GET", url); oReq.responseType = mime; oReq.send(); } _xhrput(url, body, mime, callback) { if (!callback && typeof mime === 'function') { callback = mime; mime = 'json'; } var oReq = new XMLHttpRequest(); oReq.addEventListener('load', function (evt) { if (evt.target.status >= 200 && evt.target.status < 300) { callback(null, evt.target.response); } else { callback(evt.target.statusText, null); } }); oReq.addEventListener('error', function (err) { callback(err); }); oReq.open("PUT", url); oReq.setRequestHeader("content-type", "application/json;charset=UTF-8"); oReq.send(JSON.stringify(body)); } _userRoleChanged() { var self = this; if (self.userRoleObject) { var id = self.userRoleObject.processTokenId; self._xhrget(`${self.restUrlApi}/Tasks`, function (err, data) { if (!err) { data.forEach(function (task) { if (task.processTokenId === id) { self.set('taskId', task.id); } }) } else { var error = err.message ? err.message : err; self.fire('oe-show-error', error); } if (self.taskId) { var taskid = self.taskId; var inputData = {}; inputData.assignee = self.userRoleObject.user; inputData.role = self.userRoleObject.role; inputData.group = []; if (inputData.assignee || inputData.role) { self._xhrput(`${self.restUrlApi}/Tasks/${taskid}/delegate`, inputData, function (err, res) { if (!err) { self.fire('oe-show-success', 'Task delegate is trigger for this Task Id'+ taskid); } else { var error = err.message ? err.message : err; self.fire('oe-show-error', error); } }); } else { self.fire('oe-show-error', 'Select Assignee or Role to the task') } } }); } } _procChanged(event) { var self = this; if (self.procInstance) { var fileName = self.procInstance.processDefinitionName; self._xhrget(`${self.restUrlApi}/bpmndata`, function (err, data) { if (!err) { data.forEach(function (bpmn) { if (bpmn.bpmnname === fileName) { self.set('bpmnDt', bpmn); } }) } else { var error = err.message ? err.message : err; self.fire('oe-show-error', error); } }); } } _procIdChanged(event) { var self = this; self.processInstanceId = self.procInstanceId ? self.procInstanceId : event; if (self.processInstanceId) { var id = self.processInstanceId; self._xhrget(`${self.restUrlApi}/ProcessInstances/${id}`, function (err, data) { self.set('procInstance', data); }); if (self.reassign) { self._xhrget(`${self.restUrlApi}/Users`, function (err, data) { if (!err) { var response1 = []; data.forEach(function (user) { var obj = {}; obj.userName = user.firstName.toLowerCase(); obj.userId = user.id; response1.push(obj); }) self.set('userLt', response1); } else{ var error = err.message ? err.message : err; self.fire('oe-show-error', error); } }); self._xhrget(`${self.restUrlApi}/Roles`, function (err, data) { if (!err) { var response = []; data.forEach(function (role) { var obj = {}; obj.roleName = role.name; obj.roleId = role.id; response.push(obj); }) self.set('roleLt', response); } else { var error = err.message ? err.message : err; self.fire('oe-show-error', error); } }); self.set('reassign',undefined); } } } _bpmnChanged() { var self = this; if (self.bpmnDt) { self.$.viewer.set('bpmnXml', self.bpmnDt.xmldata); self.$.viewer.set('processInstance', self.procInstance); var playgroundViewer = document.getElementsByTagName('oe-dashboard-element')[0].shadowRoot.getElementById('playground').shadowRoot.getElementById('viewer'); if(playgroundViewer){ playgroundViewer.set('userList', self.userLt); playgroundViewer.set('roleList', self.roleLt); } self.$.viewer.set('userList', self.userLt); self.$.viewer.set('roleList', self.roleLt); } } _handleError(event) { var self = this; var processInstanceId = event.detail.processInstanceId; var processTokenId = event.detail.processToken.id; var inputData = event.detail.data; self.$.viewer.$.sidepanel.style.display = 'none' if (inputData && typeof(inputData) === 'object') { self._xhrput(`${self.restUrlApi}/ProcessInstances/${processInstanceId}/retry/${processTokenId}`, inputData, function (err, data) { if (!err) { self.set('procInstanceId', null); self.fire('rerun-done', processInstanceId); self.fire('oe-show-success', 'Retry of failed Task is triggered for process token '+processTokenId); } else { var error = err.message ? err.message : err; self.fire('oe-show-error', error); } }); } else { self.fire('oe-show-error', 'Enter valid process variable to retry failed Task') } } handleBackbuton(e) { var self = this; this.fire('back-button-pressed'); self.set('procInstance', null); self.set('procInstanceId', null); self.set('bpmnDt', null); self.$.viewer.$.sidepanel.style.display = 'none'; } }
JavaScript
class UserProfile { constructor(pUserName, pEmail, pUrlAvatar){ this.username = pUserName; this.email = pEmail; this.urlAvatar = pUrlAvatar; } // Tiene username // email // url avatar getEmail() { return this.email; } setEmail(nuevoEmail){ this.email = nuevoEmail; } save(){ console.log("ACa se conecta a una base de datos..."); let myJSONObject = JSON.stringify(this); localStorage.setItem("UserProfile", myJSONObject); } load() { console.log("CArge datos de una base de datos...") localStorage.getItem("UserProfile"); // Devuelve } toString(){ return this.username + this.email + this.urlAvatar; } }
JavaScript
class ValidationError extends CatGLError { /** * @param {string} msg The error's message. */ constructor(msg) { super(msg); } }
JavaScript
@tagName('div') @templateLayout(layout) @classNames('nucleus-tabs__panel') @classNameBindings('isActive:is-active') @attributeBindings('tabindex', 'role', 'aria-labelledby', 'testId:data-test-panel-id') class TabPanel extends Component { /** * disabled * * @field disabled * @type string * @default 'false' * @readonly * @public */ @defaultProp disabled = 'false'; /** * testId * * @field testId * @type string|null * @default null * @readonly * @public */ @defaultProp testId = null; /** * tabindex * * @field tabindex * @default '0' * @type string * @public */ tabindex = '0'; /** * role * * @field role * @type string * @public */ role = 'tabpanel' /** * isActive * * @field isActive * @type boolean * @public */ @computed('selected', function() { return (get(this, 'selected') === get(this, 'name')); }) isActive; /** * aria-labelledby * * @field aria-labelledby * @type string * @public */ @computed('tabListItems.[]', function() { const tabListItems = get(this, 'tabListItems'); const tabList = tabListItems.findBy('name', get(this, 'name')); return (tabList)? tabList.id : ''; }) 'aria-labelledby'; /** * data-test-pane-id * * @field data-test-pane-id * @type string * @public */ @computed('testId', function() { return get(this, 'testId'); }) 'data-test-panel-id'; /** * didInsertElement * * @method didInsertElement * @description lifecycle event * @public * */ didInsertElement() { get(this, 'registerPanel').call(this, { id: get(this, 'elementId'), name: get(this, 'name'), disabled: get(this, 'disabled'), testId: get(this, 'testId') }); } }
JavaScript
class Allocator { constructor(max_value){ this.current_id = 1; this.max_value = max_value; this.available_ids = []; } allocate(){ if(this.current_id <= this.max_value){ let result = this.current_id; this.current_id += 1; return result; }else if(this.available_ids.length > 0){ let result = this.available_ids.shift(); return result; }else{ console.error('Error: No ID to allocate!') } } release(num){ if(num < 1 || num > this.max_value || this.available_ids.includes(num)){ console.error('Cannot release ID'); return this.available_ids; }else{ this.available_ids.push(num); console.log('ID released!'); return this.available_ids; } } }
JavaScript
class ScriptCategoryEnum extends AbstractEnum { static getNiceLabel(key) { return super.getNiceLabel(`core:enums.ScriptCategoryEnum.${key}`); } static findKeyBySymbol(sym) { return super.findKeyBySymbol(this, sym); } static findSymbolByKey(key) { return super.findSymbolByKey(this, key); } static getLevel(key) { if (!key) { return null; } // const sym = super.findSymbolByKey(this, key); // switch (sym) { case this.TRANSFORM_FROM: { return 'info'; } case this.TRANSFORM_TO: { return 'success'; } case this.SYSTEM: { return 'warning'; } case this.MAPPING_CONTEXT: { return 'info'; } default: { return 'default'; } } } }
JavaScript
class Messenger extends Component { state = { todos:[] // we can add our json data in this array } //getting data using API calls from third party URL componentDidMount(){ axios.get('https://jsonplaceholder.typicode.com/todos?_limit=10') .then(res => this.setState({todos:res.data}) ) } //delete the item using third party API calls delitem = (id) => { axios.delete(`https://jsonplaceholder.typicode.com/todos/${id}`) .then(res => this.setState({todos:[...this.state.todos.filter(todo =>todo.id !==id)]})); } // delete the item using local data // delitem = (id) => { // this.setState({todos:[...this.state.todos.filter(todo=> todo.id !==id)]}); // } //adding items to list using third party API inputPlace = (title) =>{ axios.post('https://jsonplaceholder.typicode.com/todos',{ title, completed:false }) .then(res => this.setState({todos:[...this.state.todos,res.data]})) } //adding items to list // inputPlace = (title) =>{ // const newTodo = { // id:uuid.v4(), // title, // completed: false // } // this.setState({todos:[...this.state.todos, newTodo]}); // } clickMe= (id) => { this.setState({todos:this.state.todos.map(todo =>{ if(todo.id === id){ todo.completed = !todo.completed } return todo; })}) } render() { return ( <div className="messenger"> {/* <Toolbar title="Messenger" leftItems={[ <ToolbarButton key="cog" icon="ion-ios-cog" /> ]} rightItems={[ <ToolbarButton key="add" icon="ion-ios-add-circle-outline" /> ]} /> */} {/* <Toolbar title="Conversation Title" rightItems={[ <ToolbarButton key="info" icon="ion-ios-information-circle-outline" />, <ToolbarButton key="video" icon="ion-ios-videocam" />, <ToolbarButton key="phone" icon="ion-ios-call" /> ]} /> */} <div className="scrollable sidebar"> <ConversationList /> </div> <div className="scrollable content"> <MessageList /> </div> <Router> <div className="scrollable todolist"> <div> <Header/> <Route exact path = "/" render={props =>( <React.Fragment> <Inputplace inputPlace={this.inputPlace}/> <Todos todos={this.state.todos} clickMe={this.clickMe} delitem={this.delitem}/> </React.Fragment> )}/> <Route path="/about" component={About} /> </div> </div> </Router> </div> ); } }
JavaScript
class RTCClientTopologyFactory { create (topology) { switch (topology) { case 'tree': return new RTCClientTree() case 'list': case 'chain': return new RTCClientLinkedList() default: return undefined } } }
JavaScript
class RoleCatalogueAttributeEnum extends Enums.AbstractEnum { static getNiceLabel(key) { return super.getNiceLabel(`acc:enums.RoleCatalogueAttributeEnum.${key}`); } static getHelpBlockLabel(key) { return super.getNiceLabel(`acc:enums.RoleCatalogueAttributeEnum.helpBlock.${key}`); } static findKeyBySymbol(sym) { return super.findKeyBySymbol(this, sym); } static findSymbolByKey(key) { return super.findSymbolByKey(this, key); } static getField(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { case this.CODE: { return 'code'; } case this.NAME: { return 'name'; } case this.PARENT: { return 'parent'; } case this.DESCRIPTION: { return 'description'; } case this.URL: { return 'url'; } case this.URL_TITLE: { return 'urlTitle'; } default: { return null; } } } static getEnum(field) { if (!field) { return null; } switch (field) { case 'code': { return this.CODE; } case 'name': { return this.NAME; } case 'parent': { return this.PARENT; } case 'description': { return this.DESCRIPTION; } case 'url': { return this.URL; } case 'urlTitle': { return this.URL_TITLE; } default: { return null; } } } static getLevel(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { default: { return 'default'; } } } }
JavaScript
class Model { constructor(state = {}) { this.state = {}; this.state = Object.assign(this.state, state || {}); } static fromObject(state, klass) { // const instance = Object.create(klass.prototype) // instance.state = state // return instance as T; return new klass(state); } static fromJson(state, klass) { return Model.fromObject(JSON.parse(state), klass); } static fake() { return new Model({}); } get id() { return this.state.id; } toObject() { const state = {}; for (const [key, value] of Object.entries(this.state)) { state[key] = value instanceof Model ? value.toObject() : value; } return state; } toJson() { return JSON.stringify(this.toObject()); } toString() { if (this.constructor !== Model) { return `@Folium\\Model\\${this.constructor.name}\\${this.id}`; } return `@Folium\\Model\\${this.id}`; } }
JavaScript
class Data extends Component { constructor(props) { super(props); this.state = { results: [], currentItemName: null } } //Used to make the initial api call getApiData(){ axios.get("https://swapi.co/api/" + this.props.search.searchType + "/?search=" + this.props.search.searchData+ "&format=json") .then((response) => { this.setState({results: response.data.results}); }) .catch((error) => { console.log(error); }); } //Was used to try and make the api call for the names, but was never used getApiNameData = (url) =>{ var instance = axios.create({ baseURL: url, timeout: 1000, headers: {'X-Requested-With': 'XMLHttpRequest'}, responseType: 'json' }); instance.get() .then((response) => { var data = response.data; this.setState({currentItemName: data[Object.keys(data)[0]]}); }) .catch((error) => { console.log(error); }); } //Used to translate returned objects into html prepareData = (dataObject) =>{ var displayText = Object.entries(dataObject).map(([key, value]) => { // Skip the arrays (unable to do them) if (!Array.isArray(value)) { //Check for links if (value.startsWith('http')) { // Tried to get array name working using this method //this.getApiNameData(value); //Trued rendering changes using this //{this.state.currentItemName} return ( <tr> <td colSpan="2"> <a href={value}> {key} </a> </td> </tr> ); } else { return ( <tr> <td> {key} </td> <td> {value} </td> </tr> ); } } }); return displayText; } render() { var data = ""; // object var displayText = ""; // html to render // Check for empty props if(this.props.search.searchData !== null){ // make the api call this.getApiData(); data = this.state.results[0]; // prepare the data if (data !== undefined){ displayText = this.prepareData(data) } } return ( <table id="dataTable"> <tbody> {displayText} </tbody> </table> ); } }
JavaScript
class SpeechExtractor extends EventEmitter { /** * @param {Object} options * @param {number} options.sampleRateHertz - Sample rate (default 16000) * @param {number} options.channels - Mic channels (default 1) * @param {string} options.device - Device of the mic (Only relevant for use with linux) * @constructor */ constructor(options) { super(); let self = this; let defaults = { callback: function() { console.log('Speech audio recieved'); }, sampleRateHertz: 16000, channels: 1, }; // extend defaults options = Object.assign({}, defaults, options); // active speech data holder. self.activeSpeechBuffer = undefined; // mic settings let micSettings = { rate: options.sampleRateHertz, channels: options.channels, device: options.device }; // setup the mic streams self.micInstance = new Audio(micSettings); self.micInputStream = self.micInstance.getAudioStream(); let devNull = new DevNullStream(); self.micInputStream.pipe(devNull); // speaking action self.micInputStream.on('speaking', function(buffer) { // stay clean if we are paused if (self.micInstance.isPaused()) { self.resetCounters(); } else { // append to the buffer of active speech self.appendToActiveSpeechBuffer(buffer); self.micInstance.incementSpeakingCount(); self.micInstance.silenceCount = 0; } }); // silence action self.micInputStream.on('silence', function(buffer) { // append to speech buffer if have started talking if (self.activeSpeechBuffer !== undefined) { self.appendToActiveSpeechBuffer(buffer); } // check if we met silence threashold if (self.micInstance.getSilenceCount() > 4) { if (self.micInstance.getSpeakingCount() > 1) { // we have enough speech to send it out and pause listening self.emit('speech', self.activeSpeechBuffer); } // if we processed or not, reset the counters self.resetCounters(); } self.micInstance.incementSilenceCount(); }); } /** * Callback when potential speech is recorded * * @callback speechCallback * @param {Buffer} buffer - Buffer with raw audio in it. */ /** * Append buffer to current active speech * @param {Buffer} buffer - Chunk of current silence or speech */ appendToActiveSpeechBuffer(buffer) { // append to the buffer of active speech if (typeof(this.activeSpeechBuffer) !== 'object') { this.activeSpeechBuffer = buffer; } else { let bufferLength = this.activeSpeechBuffer.length + buffer.length; let bufferList = [this.activeSpeechBuffer, buffer]; this.activeSpeechBuffer = Buffer.concat(bufferList, bufferLength); } } /** * Reset the counters used for speech detection */ resetCounters() { this.micInstance.silenceCount = 0; this.micInstance.speakingCount = 0; this.activeSpeechBuffer = undefined; } /** * Start mic listner. If speech is detected, the callback will run and the * listner will be paused. */ start() { this.micInstance.start(); } /** * Pause the mic listener */ pause() { this.micInstance.pause(); } /** * Resume the mic listener. This should be called after your speech * processing callback is finished. */ resume() { this.micInstance.resume(); } /** * Stop listening and exit */ stop() { this.micInstance.stop(); }; }
JavaScript
class SettingsGeneral { constructor() { // Initialization of the page plugins if (jQuery().select2) { this._initSelect2(); } else { console.error('[CS] select2 is undefined.'); } } // Select2 button initialization _initSelect2() { jQuery('.select-single-no-search').select2({minimumResultsForSearch: Infinity, placeholder: ''}); } }
JavaScript
class GMapMarkerDetail { domNode; closeButton; content; constructor(domNode) { this.domNode = domNode; this.closeButton = this.domNode.querySelector('.gmap-marker-detail__close'); this.content = this.domNode.querySelector('.gmap-marker-detail__content'); this.bindListeners(); } bindListeners() { this.closeButton.addEventListener('click', this.hide.bind(this)); } updateContent(htmlContent) { this.showLoading(); this.content.innerHTML = htmlContent; this.hideLoading(); } showLoading() { this.domNode.classList.add('gmap-marker-detail--loading'); } hideLoading() { this.domNode.classList.remove('gmap-marker-detail--loading'); } show() { this.domNode.classList.add('gmap-marker-detail--visible'); } hide() { this.domNode.classList.remove('gmap-marker-detail--visible'); } setPosition({x = 0, y = 0} = {}) { this.domNode.style.left = `${x}px`; this.domNode.style.top = `${y}px`; } getRect() { return this.domNode.getBoundingClientRect(); } }
JavaScript
class Main extends React.Component { constructor(props) { super(props) this.state = { waitForMVP : true }; } componentWillMount() { // For MVP generate default location if (typeof this.props.locations[0] === 'undefined') { this.props.saveLocation({ 'name': 'Minimal Viable Product', 'loc': { 'address': '1015 15th St NW #750, Washington, DC 20005, USA', 'coordinates': [-77.0340315,38.9031004] }, 'beds': {} }).then(() => { this.setState({ waitForMVP: false }); }); } else { this.setState({ waitForMVP: false }); } } render() { if (this.state.waitForMVP) { return <p>Loading...</p>; } else return ( <div> <Switch> {/*For MVP Redirect to default location*/} <Route exact path="/" render={() => <Redirect path="/" to="/locations/0/beds/add"/>} /> <Route path="/login" component={Login} /> <Route path="/register" component={Register} /> <Route path="/recover" component={Recover} /> <Route path="/locations" component={LocationsPage} /> <Route path="/about" component={AboutPage} /> </Switch> </div> ); } }
JavaScript
class Block { constructor(timestamp, transactions, previousHash = "") { this.previousHash = previousHash; //hash of previous block to ensure integrity this.hash = this.calculateHash(); //current block hash based on data this.timestamp = timestamp; this.transactions = transactions; // this.difficulty = difficulty; this.nonce = 0; // used to find the hidden hash that signed the block // this.transactionListHash; // let mempool = []; } //block header is a sha526 hash of the previous block //blake 3 root hash of transaction list //difficulty target for this block //nonce used to mine this block //block body is the list of transactions used to generate blake 3 root hash calculateHash() { return sha256( this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce ).toString(); } //TODO: - Blake3 root hash of transaction list mineBlock(difficulty) { //hash of block beginning with Rs let prefix = /R/i; while ( this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0") ) { this.nonce++; this.hash = this.calculateHash(); } console.log("block mined: " + this.hash); } hasValidTransactions() { //iterate over all transactions in the block for (const trans of this.transactions) { if (!trans.isTransactionValid()) { return false; } } return true; } }
JavaScript
class VideoLayer extends ImageLayer { leafletRequiredOptions = [ ...this.leafletRequiredOptions, /** * The URL of the video (or array of URLs, or even a video element) and the geographical bounds it is tied to. * * @argument video * @type {String|Array|HTMLVideoElement} */ 'video', /** * The geographical bounds the video is tied to. * * @argument bounds * @type {LatLngBounds} */ 'bounds' ]; leafletOptions = [ ...this.leafletOptions, /** * Whether the video starts playing automatically when loaded. * Defaults to `true`. * * @argument autoplay * @type {Boolean} */ 'autoplay', /** * Whether the video will loop back to the beginning when played. * Defaults to `true`. * * @argument loop * @type {Boolean} */ 'loop', /** * Whether the video will save aspect ratio after the projection. * Relevant for supported browsers. See browser compatibility * Defaults to `true`. * * @argument keepAspectRatio * @type {Boolean} */ 'keepAspectRatio', /** * Whether the video starts on mute when loaded. * Defaults to `false`. * * @argument muted * @type {Boolean} */ 'muted', /** * When true, a mouse event on this layer will trigger the same event on the map. * Defaults to `true`. * * @argument bubblingMouseEvents * @type {Boolean} */ 'bubblingMouseEvents' ]; leafletDescriptors = [...this.leafletDescriptors, 'url', 'opacity', 'bounds']; createLayer() { return this.L.videoOverlay(...this.requiredOptions, this.options); } }
JavaScript
class RingBuffer { static getStorageForCapacity(capacity, type) { if (!type.BYTES_PER_ELEMENT) { throw "Pass in a ArrayBuffer subclass"; } var bytes = 8 + (capacity + 1) * type.BYTES_PER_ELEMENT; return new SharedArrayBuffer(bytes); } // `sab` is a SharedArrayBuffer with a capacity calculated by calling // `getStorageForCapacity` with the desired capacity. constructor(sab, type) { if (!ArrayBuffer.__proto__.isPrototypeOf(type) && type.BYTES_PER_ELEMENT !== undefined) { throw "Pass a concrete typed array class as second argument"; } // Maximum usable size is 1<<32 - type.BYTES_PER_ELEMENT bytes in the ring // buffer for this version, easily changeable. // -4 for the write ptr (uint32_t offsets) // -4 for the read ptr (uint32_t offsets) // capacity counts the empty slot to distinguish between full and empty. this._type = type; this.capacity = (sab.byteLength - 8) / type.BYTES_PER_ELEMENT; this.buf = sab; this.write_ptr = new Uint32Array(this.buf, 0, 1); this.read_ptr = new Uint32Array(this.buf, 4, 1); this.storage = new type(this.buf, 8, this.capacity); } // Returns the type of the underlying ArrayBuffer for this RingBuffer. This // allows implementing crude type checking. type() { return this._type.name; } // Push bytes to the ring buffer. `bytes` is an typed array of the same type // as passed in the ctor, to be written to the queue. // Returns the number of elements written to the queue. push(elements) { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); if ((wr + 1) % this._storage_capacity() == rd) { // full return 0; } let to_write = Math.min(this._available_write(rd, wr), elements.length); let first_part = Math.min(this._storage_capacity() - wr, to_write); let second_part = to_write - first_part; this._copy(elements, 0, this.storage, wr, first_part); this._copy(elements, first_part, this.storage, 0, second_part); // publish the enqueued data to the other side Atomics.store( this.write_ptr, 0, (wr + to_write) % this._storage_capacity() ); return to_write; } // Read `elements.length` elements from the ring buffer. `elements` is a typed // array of the same type as passed in the ctor. // Returns the number of elements read from the queue, they are placed at the // beginning of the array passed as parameter. pop(elements) { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); if (wr == rd) { return 0; } let to_read = Math.min(this._available_read(rd, wr), elements.length); let first_part = Math.min(this._storage_capacity() - rd, elements.length); let second_part = to_read - first_part; this._copy(this.storage, rd, elements, 0, first_part); this._copy(this.storage, 0, elements, first_part, second_part); Atomics.store(this.read_ptr, 0, (rd + to_read) % this._storage_capacity()); return to_read; } // True if the ring buffer is empty false otherwise. This can be late on the // reader side: it can return true even if something has just been pushed. empty() { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); return wr == rd; } // True if the ring buffer is full, false otherwise. This can be late on the // write side: it can return true when something has just been poped. full() { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); return (wr + 1) % this.capacity != rd; } // The usable capacity for the ring buffer: the number of elements that can be // stored. capacity() { return this.capacity - 1; } // Number of elements available for reading. This can be late, and report less // elements that is actually in the queue, when something has just been // enqueued. available_read() { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); return this._available_read(rd, wr); } // Number of elements available for writing. This can be late, and report less // elemtns that is actually available for writing, when something has just // been dequeued. available_write() { var rd = Atomics.load(this.read_ptr, 0); var wr = Atomics.load(this.write_ptr, 0); return this._available_write(rd, wr); } // private methods // // Number of elements available for reading, given a read and write pointer.. _available_read(rd, wr) { if (wr > rd) { return wr - rd; } else { return wr + this._storage_capacity() - rd; } } // Number of elements available from writing, given a read and write pointer. _available_write(rd, wr) { let rv = rd - wr - 1; if (wr >= rd) { rv += this._storage_capacity(); } return rv; } // The size of the storage for elements not accounting the space for the index. _storage_capacity() { return this.capacity; } // Copy `size` elements from `input`, starting at offset `offset_input`, to // `output`, starting at offset `offset_output`. _copy(input, offset_input, output, offset_output, size) { for (var i = 0; i < size; i++) { output[offset_output + i] = input[offset_input + i]; } } }
JavaScript
class Logger { /** * @constructor */ constructor() { if (Logger.instance) { return Logger.instance; // Singleton pattern } Logger.instance = this; this.log = []; this.rawLog = ""; //raw log of string data this.dispatcher = new Dispatcher(); } //pass in svelte store, of log // setStore(storeLog){ // storeLog.set = this.rawLog; // } addEventListener(event, callback) { // console.log("registering", event, callback); if (this.dispatcher && event && callback) { this.dispatcher.addEventListener(event, callback); // console.log("registered"); } else throw new Error("Error adding event listener to Logger"); } push(data) { this.log.push(data); this.rawLog = this.rawLog + "\n" + data.type + " " + [...data.payload].join(); this.dispatcher.dispatch("onLog"); //console.log("getting dispatched", this.rawLog); //this.dispatcher.dispatch("onConsoleLogsUpdate", {test:10}); } //console.log = overrideConsoleLog(); takeOverConsole() { if (window.console) { // this.onMessageHandler.bind(this); let cl, ci, cw, ce; if (window.console.log) cl = console.log; if (window.console.info) ci = console.info; if (window.console.warn) cw = console.warn; if (window.console.error) ce = console.error; if (cl && ci && cw && ce) { cw("taking over MAIN console"); console.log = function (text) { this.push({ func: "logs", payload: [...arguments], type: "[MAIN]", }); cl.apply(this, arguments); }.bind(this); console.info = function (text) { this.push({ func: "logs", payload: [...arguments], type: "[MAIN]", }); ci.apply(this, arguments); }.bind(this); console.warn = function (text) { // window.postMessage({ this.push({ func: "logs", payload: [...arguments], type: "[MAIN]", }); cw.apply(this, arguments); }.bind(this); console.error = function (text) { // window.postMessage({ this.push({ func: "logs", payload: [...arguments], type: "[MAIN]", }); ce.apply(this, arguments); }.bind(this); ce("MAIN console taken over"); } } } // takeOverConsole(f) { // if (f) { // try { // var original = window.console; // function handle(method, args) { // var message = Array.prototype.slice.apply(args).join(" "); // if (original) original[method]("> " + message); // } // window.console = { // log: function () { // handle("log", arguments); // }, // warn: function () { // handle("warn", arguments); // }, // error: function () { // handle("error", arguments); // }, // info: function () { // handle("info", arguments); // }, // }; // } catch (error) { // console.error(error); // } // } // } }
JavaScript
class Engine { /** * @constructor */ constructor() { if (Engine.instance) { return Engine.instance; // Singleton pattern } Engine.instance = this; this.origin = ""; this.learners = {}; // Hash of on-demand analysers (e.g. spectrogram, oscilloscope) // NOTE: analysers serialized to localStorage are de-serialized // and loaded from localStorage before user-triggered audioContext init this.analysers = {}; this.mediaStreamSource = {}; this.mediaStream = {}; // Shared array buffers for sharing client side data to the audio engine- e.g. mouse coords this.sharedArrayBuffers = {}; // Event emitter that should be subscribed by SAB receivers this.dispatcher = new Dispatcher(); this.logger = new Logger(); this.samplesLoaded = false; this.isHushed = false; } /** * Add learner instance */ async addLearner(id, learner) { if (learner) { try { // `this` is the scope that will await learner.init(this.origin); this.addEventListener("onSharedBuffer", (e) => learner.addSharedBuffer(e) ); // Engine's SAB emissions subscribed by Learner learner.addEventListener("onSharedBuffer", (e) => this.addSharedBuffer(e) ); // Learner's SAB emissions subscribed by Engine this.learners[id] = learner; } catch (error) { console.error("Error adding Learner to Engine: ", error); } } else throw new Error("Error adding Learner instance to Engine"); } removeLearner(id) { if (id){ if (this.learners && ( id in this.learners ) ) { let learner = this.learners[id]; learner.removeEventListener("onSharedBuffer", (e) => this.addSharedBuffer(e) ); learner = null; delete this.learners[id]; } // else throw new Error("Error removing Learner from Engine: "); } else throw new Error("Error with learner ID when removing Learner from Engine"); } /** * Engine's event subscription * @addEventListener * @param {*} event * @param {*} callback */ addEventListener(event, callback) { if (this.dispatcher && event && callback) this.dispatcher.addEventListener(event, callback); else throw new Error("Error adding event listener to Engine"); } /* #region SharedBuffers */ /** * Create a shared array buffer for communicating with the audio engine * @param channelId * @param ttype * @param blocksize */ createSharedBuffer(channelId, ttype, blocksize) { let sab = RingBuffer.getStorageForCapacity(32 * blocksize, Float64Array); let ringbuf = new RingBuffer(sab, Float64Array); this.audioWorkletNode.port.postMessage({ func: "sab", value: sab, ttype: ttype, channelID: channelId, blocksize: blocksize, }); this.sharedArrayBuffers[channelId] = { sab: sab, // TODO: this is redundant, you can access the sab from the rb, // TODO change hashmap name it is confusing and induces error rb: ringbuf, }; return sab; } /** * Push data to shared array buffer for communicating with the audio engine and ML worker * @param {*} e */ addSharedBuffer(e) { if (e) { if (e.value && e.value instanceof SharedArrayBuffer) { try { let ringbuf = new RingBuffer(e.value, Float64Array); this.audioWorkletNode.port.postMessage({ func: "sab", value: e.value, ttype: e.ttype, channelID: e.channelID, blocksize: e.blocksize, }); this.sharedArrayBuffers[e.channelID] = { sab: e.value, // TODO this is redundant, you can access the sab from the rb, // TODO also change hashmap name it is confusing and induces error rb: ringbuf, }; } catch (err) { console.error("Error pushing SharedBuffer to engine"); } } else if (e.name && e.data) { this.audioWorkletNode.port.postMessage({ func: "sendbuf", name: e.name, data: e.data, }); } } else throw new Error("Error with onSharedBuffer event"); } /** * Push data to shared array buffer for communicating with the audio engine and ML worker * @param {*} e * @param {*} channelId */ pushDataToSharedBuffer(channelId, data) { if (channelId && data && typeof Array.isArray(data)) { if (this.sharedArrayBuffers && this.sharedArrayBuffers[channelId]) { this.sharedArrayBuffers[channelId].rb.push(data); } } else throw new Error("Error in function parameters"); } /* #region Analysers */ /** * Polls data from connected WAAPI analyser return structured object with data and time data in arrays * @param {*} analyser */ pollAnalyserData(analyser) { if (analyser !== undefined) { const timeDataArray = new Uint8Array(analyser.fftSize); // Uint8Array should be the same length as the fftSize const frequencyDataArray = new Uint8Array(analyser.fftSize); analyser.getByteTimeDomainData(timeDataArray); analyser.getByteFrequencyData(frequencyDataArray); return { smoothingTimeConstant: analyser.smoothingTimeConstant, fftSize: analyser.fftSize, frequencyDataArray: frequencyDataArray, timeDataArray: timeDataArray, }; } } /** * Creates a WAAPI analyser node * @todo configuration object as argumen * @createAnalyser */ createAnalyser(analyserID, callback) { // If Analyser creation happens after AudioContext intialization, create and connect WAAPI analyser if (analyserID && callback){ if(this.audioContext && this.audioWorkletNode ) { let analyser = this.audioContext.createAnalyser(); analyser.smoothingTimeConstant = 0.25; analyser.fftSize = 256; // default 2048; analyser.minDecibels = -90; // default analyser.maxDecibels = -0; // default -10; max 0 this.audioWorkletNode.connect(analyser); let analyserFrameId = -1, analyserData = {}; this.analysers[analyserID] = { analyser, analyserFrameId, callback, }; /** * Creates requestAnimationFrame loop for polling data and publishing * Returns Analyser Frame ID for adding to Analysers hash * and cancelling animation frame */ const analyserPollingLoop = () => { analyserData = this.pollAnalyserData( this.analysers[analyserID].analyser ); this.analysers[analyserID].callback(analyserData); // Invoke callback that carries // This will guarantee feeding poll request at steady animation framerate this.analysers[analyserID].analyserFrameId = requestAnimationFrame( analyserPollingLoop ); return analyserFrameId; }; console.info("Created analyser"); analyserPollingLoop(); // Other if AudioContext is NOT created yet (after app load, before splashScreen click) } else { this.analysers[analyserID] = { callback }; } } else throw new Error('Parameters to createAnalyser incorrect') } /** * Connects WAAPI analyser nodes to the main audio worklet for visualisation. * @connectAnalysers */ connectAnalysers() { Object.keys(this.analysers).map((id) => this.createAnalyser(id, this.analysers[id].callback) ); } /** * Removes a WAAPI analyser node, disconnects graph, cancels animation frame, deletes from hash * @removeAnalyser */ removeAnalyser(event) { if ( this.audioContext && this.audioWorkletNode ) { let analyser = this.analysers[event.id]; if (analyser !== undefined) { cancelAnimationFrame(this.analysers[event.id].analyserFrameId); delete this.analysers[event.id]; // this.audioWorkletNode.disconnect(analyser); } } } /* #endregion */ /** * Initialises audio context and sets worklet processor code * @play */ async init(origin) { if (origin && new URL(origin)) { let isWorkletProcessorLoaded; try{ // AudioContext needs lazy loading to workaround the Chrome warning // Audio Engine first play() call, triggered by user, prevents the warning // by setting this.audioContext = new AudioContext(); this.audioContext; this.origin = origin; this.audioWorkletName = "maxi-processor"; this.audioWorkletUrl = origin + "/" + this.audioWorkletName + ".js"; if (this.audioContext === undefined) { this.audioContext = new AudioContext({ // create audio context with latency optimally configured for playback latencyHint: "playback", // latencyHint: 32/44100, //this doesn't work below 512 on chrome (?) // sampleRate: 48000 }); } isWorkletProcessorLoaded = await this.loadWorkletProcessorCode(); console.log("Processor loaded"); } catch(err){ return false; } if (isWorkletProcessorLoaded) { this.connectWorkletNode(); return true; } else return false; // No need to inject the callback here, messaging is built in KuraClock // this.kuraClock = new kuramotoNetClock((phase, idx) => { // // console.log( `DEBUG:AudioEngine:sendPeersMyClockPhase:phase:${phase}:id:${idx}`); // // This requires an initialised audio worklet // this.audioWorkletNode.port.postMessage({ phase: phase, i: idx }); // }); // if (this.kuraClock.connected()) { // this.kuraClock.queryPeers(async numClockPeers => { // console.log(`DEBUG:AudioEngine:init:numClockPeers: ${numClockPeers}`); // }); // } } else { throw new Error("Name and valid URL required for AudioWorklet processor"); } } /** * Initialises audio context and sets worklet processor code * or re-starts audio playback by stopping and running the latest Audio Worklet Processor code * @play */ play() { if (this.audioContext !== undefined) { if (this.audioContext.state === "suspended") { this.audioContext.resume(); return true; } else { this.hush(); // this.stop(); return false; } } } /** * Suspends AudioContext (Pause) * @stop */ stop() { if (this.audioWorkletNode !== undefined) { this.hush(); // this.audioContext.suspend(); } } /** * Stops audio by disconnecting AudioNode with AudioWorkletProcessor code * from Web Audio graph TODO Investigate when it is best to just STOP the graph exectution * @stop */ stopAndRelease() { if (this.audioWorkletNode !== undefined) { this.audioWorkletNode.disconnect(this.audioContext.destination); this.audioWorkletNode = undefined; } } setGain(gain) { if (this.audioWorkletNode !== undefined && gain >= 0 && gain <= 1) { const gainParam = this.audioWorkletNode.parameters.get("gain"); gainParam.value = gain; console.log(gainParam.value); // DEBUG return true; } else return false; } more() { if (this.audioWorkletNode !== undefined) { const gainParam = this.audioWorkletNode.parameters.get("gain"); gainParam.value += 0.05; console.info(gainParam.value); // DEBUG return gainParam.value; } else throw new Error("error increasing sound level"); } less() { if (this.audioWorkletNode !== undefined) { const gainParam = this.audioWorkletNode.parameters.get("gain"); gainParam.value -= 0.05; console.info(gainParam.value); // DEBUG return gainParam.value; } else throw new Error("error decreasing sound level"); } hush() { if (this.audioWorkletNode !== undefined) { this.audioWorkletNode.port.postMessage({ hush: 1, }); this.isHushed = true; return true; } else return false; } unHush() { if (this.audioWorkletNode !== undefined) { this.audioWorkletNode.port.postMessage({ unhush: 1, }); this.isHushed = false; return true; } else return false; } eval(dspFunction) { if (this.audioWorkletNode && this.audioWorkletNode.port) { if (this.audioContext.state === "suspended") { this.audioContext.resume(); } this.audioWorkletNode.port.postMessage({ eval: 1, setup: dspFunction.setup, loop: dspFunction.loop, }); this.isHushed = false; return true; } else return false; } /** * Handler of the Pub/Sub message events * whose topics are subscribed to in the audio engine constructor * @asyncPostToProcessor * @param {*} event */ asyncPostToProcessor(event) { if (event && this.audioWorkletNode && this.audioWorkletNode.port) { // Receive notification from 'model-output-data' topic console.log("DEBUG:AudioEngine:onMessagingEventHandler:"); console.log(event); this.audioWorkletNode.port.postMessage(event); } else throw new Error("Error async posting to processor"); } sendClockPhase(phase, idx) { if (this.audioWorkletNode !== undefined) { this.audioWorkletNode.port.postMessage({ phase: phase, i: idx, }); } } onAudioInputInit(stream) { try { this.mediaStreamSource = this.audioContext.createMediaStreamSource(stream); this.mediaStreamSource.connect(this.audioWorkletNode); this.mediaStream = stream; this.mediaStreamSourceConnected = true; } catch (error) { console.error(error); } } onAudioInputFail(error) { this.mediaStreamSourceConnected = false; console.error( `ERROR:Engine:AudioInputFail: ${error.message} ${error.name}` ); } onAudioInputDisconnect() { } /** * Sets up an AudioIn WAAPI sub-graph * @connectMediaStreamSourceInput */ async connectMediaStream() { const constraints = ( window.constraints = { audio: { latency: 0.02, echoCancellation: false, mozNoiseSuppression: false, mozAutoGainControl: false }, video: false, }); // onAudioInputDisconnect(); await navigator.mediaDevices .getUserMedia(constraints) .then( s => this.onAudioInputInit(s) ) .catch(this.onAudioInputFail); return this.mediaStreamSourceConnected; } /** * Breaks up an AudioIn WAAPI sub-graph * @disconnectMediaStreamSourceInput */ async disconnectMediaStream() { try { this.mediaStreamSource.disconnect(this.audioWorkletNode); this.mediaStream.getAudioTracks().forEach((at) => at.stop()); this.mediaStreamSource = null; this.mediaStreamSourceConnected = false; } catch (error) { console.error(error); } finally { return this.mediaStreamSourceConnected; } // await navigator.mediaDevices // .getUserMedia(constraints) // .then((s) => this.onAudioInputDisconnect(s)) // .catch(this.onAudioInputFail); } /** * Loads audioWorklet processor code into a worklet, * setups up all handlers (errors, async messaging, etc), * connects the worklet processor to the WAAPI graph */ async loadWorkletProcessorCode() { if (this.audioContext !== undefined) { try { await this.audioContext.audioWorklet.addModule(this.audioWorkletUrl) .then( console.info( "running %csema-engine v0.1.0", "font-weight: bold; color: #ffb7c5" // "font-weight: bold; background: #000; color: #bada55" ) ); } catch (err) { console.error( "ERROR:Engine:loadWorkletProcessorCode: AudioWorklet not supported in this browser: ", err.message ); return false; } try { // Custom node constructor with required parameters // this.audioWorkletNode = new CustomMaxiNode( this.audioWorkletNode = new AudioWorkletNode( this.audioContext, this.audioWorkletName ); this.audioWorkletNode.channelInterpretation = "discrete"; this.audioWorkletNode.channelCountMode = "explicit"; this.audioWorkletNode.channelCount = this.audioContext.destination.maxChannelCount; return true; } catch (err) { console.error("Error loading worklet processor code: ", err); return false; } } else { return false; } } /** * connects all error event handlers and default processor message callback */ connectWorkletNode() { if (this.audioWorkletNode !== undefined) { try { this.audioContext.destination.channelInterpretation = "discrete"; this.audioContext.destination.channelCountMode = "explicit"; this.audioContext.destination.channelCount = this.audioContext.destination.maxChannelCount; // Connect the worklet node to the audio graph this.audioWorkletNode.connect(this.audioContext.destination); // All possible error event handlers subscribed this.audioWorkletNode.onprocessorerror = (e) => // Errors from the processor console.error(`Engine processor error detected`, e); // Subscribe state changes in the audio worklet processor this.audioWorkletNode.onprocessorstatechange = (e) => console.info( `Engine processor state change: ` + audioWorkletNode.processorState ); // Subscribe errors from the processor port this.audioWorkletNode.port.onmessageerror = (e) => console.error(`Engine processor port error: ` + e); // Default worklet processor message handler // gets replaced by user callback with 'subscribeAsyncMessage' this.audioWorkletNode.port.onmessage = (e) => this.onProcessorMessageHandler(e); } catch (err) { console.error("Error connecting WorkletNode: ", err); } } } /** * Default worklet processor message handler * gets replaced by user-supplied callback through 'subscribeProcessorMessage' * @param {*} event */ onProcessorMessageHandler(event) { if (event && event.data) { if (event.data.func === 'logs') { this.logger.push(event.data); //recieve data from the worker.js and push it to the logger. } else if (event.data.rq && event.data.rq === "send") { switch (event.data.ttype) { case "ML": // this.messaging.publish("model-input-data", { // type: "model-input-data", // value: event.data.value, // ch: event.data.ch // }); break; case "NET": this.peerNet.send( event.data.ch[0], event.data.value, event.data.ch[1] ); break; } } else if (event.data.rq && event.data.rq === "buf") { switch (event.data.ttype) { case "ML": this.dispatcher.dispatch("onSharedBuffer", { sab: event.data.value, channelID: event.data.channelID, //channel ID blocksize: event.data.blocksize, }); break; case "scope": // this.dispatcher.dispatch("onSharedBuffer", { // sab: event.data.value, // channelID: event.data.channelID, //channel ID // blocksize: event.data.blocksize, // }); let ringbuf = new RingBuffer(event.data.value, Float64Array); this.sharedArrayBuffers[event.data.channelID] = { sab: event.data.value, // TODO: this is redundant, you can access the sab from the rb, // TODO change hashmap name it is confusing and induces error rb: ringbuf, ttype: event.data.ttype, channelID: event.data.channelID, //channel ID blocksize: event.data.blocksize, }; break; } } else if (event.data.rq && event.data.rq === "rts") { // ready to suspend this.audioContext.suspend(); this.isHushed = true; } else if (event.data instanceof Error){ // TODO use a logger to inject error console.error(`On Processor Message ${event.data}`); } } } /** * Public method for subscribing async messaging from the Audio Worklet Processor scope * @param callback */ subscribeProcessorMessage(callback) { if (callback && this.audioWorkletNode) this.audioWorkletNode.port.onmessage = callback; else throw new Error("Error subscribing processor message"); } /** * Load individual audio sample, assuming an origin URL with which the engine * is initialised * @param {*} objectName name of the sample * @param {*} url relative URL to the origin URL, startgin with `/` */ loadSample(objectName, url) { if (this.audioContext && this.audioWorkletNode) { if ( url && url.length !== 0 && this.origin && this.origin.length !== 0 && new URL(this.origin + url) ) { try { loadSampleToArray( this.audioContext, objectName, this.origin + url, this.audioWorkletNode ); } catch (error) { console.error( `Error loading sample ${objectName} from ${url}: `, error ); } } else throw "Problem with sample relative URL"; } else throw "Engine is not initialised!"; } }
JavaScript
class Learner { /** * @constructor */ constructor() { // Manager of events subscrition and emission, that should be subscribed by SAB receivers this.dispatcher = new Dispatcher(); this.logger = new Logger(); } /** * Learner's event subscription * @addEventListener * @param {*} event * @param {*} callback */ addEventListener(event, callback) { if (this.dispatcher && event && callback) this.dispatcher.addEventListener(event, callback); else throw new Error("Error adding event listener to Learner"); } removeEventListener(event, callback) { if (this.dispatcher && event && callback) this.dispatcher.removeEventListener(event, callback); else throw new Error("Error removing event listener to Learner"); } /** * Initialises worker with origin URL * @param {*} url * @param {*} sab */ async init(url) { // this.dispatcher = new Dispatcher(); this.worker = new WorkerFactory(); //this.logger = new Logger(); //make a logger instance //console.log("TEST CONSOLE TAKEOVER IN LEARNER"); return new Promise( (resolve, reject) => { let result = {}; if (this.worker && new URL(url)) { this.worker.postMessage({ url }); this.worker.onerror = e => { console.log("onError"); reject(e); }; this.worker.onmessage = e => { result = e.data.init; console.info("running Learner"); resolve(result); // this.worker.onmessage = this.onMessageHandler; this.worker.onmessage = this.onMessageHandler.bind(this); }; } }); } onMessageHandler(m){ // data is a property of postMessage. func is then a property of data sent in our messages. if ( m && m.data && m.data.func ) { let responders = { sab: (data) => { // Publish data to audio engine this.dispatcher.dispatch("onSharedBuffer", data); }, sendbuf: (data) => { // Publish data to audio engine this.dispatcher.dispatch("onSharedBuffer", data); }, save: (data) => { // console.log("save"); window.localStorage.setItem(data.name, data.val); }, load: (data) => { // console.log("load"); let msg = { name: data.name, val: window.localStorage.getItem(data.name), }; modelWorker.postMessage(msg); }, download: (data) => { // console.log("download"); let downloadData = window.localStorage.getItem(data.name); let blob = new Blob([downloadData], { type: "text/plain;charset=utf-8", }); saveData(blob, `${data.name}.data`); }, sendcode: (data) => { // console.log(data); }, // DEPRECATED data: () => { // Publish data to audio engine // messaging.publish("model-output-data", data); }, pbcopy: (data) => { copyToPasteBuffer(data.msg); // let copyField=document.getElementById("hiddenCopyField"); // copyField.value = data.msg; // copyField.select(); // document.execCommand("Copy"); }, envsave: (data) => { messaging.publish("env-save", data); }, envload: (data) => { messaging.publish("env-load", data); }, domeval: (data) => { evalDOMCode(data.code); }, peerinfo: (data) => { messaging.publish("peerinfo-request", {}); }, // data from the worker.js for the logger widget logs: (data) => { // console.log(">", [...data.payload].join()); //for now just log to console and have it captured here. this.logger.push(data); //recieve data from the worker.js and push it to the logger. } }; responders[m.data.func](m.data); } else if (m.data !== undefined && m.data.length !== 0) { // res(m.data); console.log(m.data); } // clearTimeout(timeout); }; /** * */ eval(expression) { if (this.worker && expression) this.worker.postMessage({ eval: expression }); //console.log("DEBUG:ModelEditor:evalModelEditorExpression: " + code); // window.localStorage.setItem("modelEditorValue", codeMirror.getValue()); // addToHistory("model-history-", modelCode); } /** * * @param {*} sab * @param {*} blocksize * @param {*} channelID */ addSharedBuffer(e) { if (this.worker && e && e.sab && e.sab instanceof SharedArrayBuffer) { this.worker.postMessage({ sab: e.sab, blocksize: e.blocksize, channelID: e.channelID, }); } else throw new Error("Error pushing SharedBuffer in Learner"); } evalBlock(block) { // let modelCode = codeMirror.getBlock(); // console.log(modelCode); let linebreakPos = block.indexOf("\n"); let firstLine = block.substr(0, linebreakPos); // console.log(firstLine); if (firstLine == "//--DOM") { block = block.substr(linebreakPos); evalDomCode(block); addToHistory("dom-history-", block); } else { this.worker.postMessage({ eval: block }); // console.log("DEBUG:ModelEditor:evalModelEditorExpressionBlock: " + code); window.localStorage.setItem("modelEditorValue", codeMirror.getValue()); addToHistory("model-history-", block); } } /** * */ terminate() { this.worker.onmessage = null; // remove event handler subscription this.worker.terminate(); this.worker = null; // make sure it is deleted by GC } }
JavaScript
class ConfirmContainer extends React.Component { constructor(props, context) { super(props, context); } render() { return ( <div> confirm </div> ); } }
JavaScript
class IndexPage extends Component { generateTagAvatar = (tag, tagFillColor) => { let tagComponent = logosList[tag]; return tagComponent ? <tagComponent.icon fill={tagFillColor} /> : null; }; render() { const { data, classes } = this.props; const { edges: posts } = data.allContentfulPost; const tagFillColor = ''; return ( <EqualColumn posts={posts} /> ) } }
JavaScript
class Validator { /** * validate data by checking with a predefined Joi schema * @param {Object} data * @param {Object} schema * @param {Object} response * @param {Object} next * @callback {Function} next * @returns {Object} error */ static validateJoi(data, schema) { let error; const validationOptions = { allowUnknown: true, // allow unknow keys that will be ignored stripUnknown: true, // remove unknown keys from the validation data }; Joi.validate(data, schema, validationOptions, (err) => { if (err) { error = err.details ? err.details[0].message.replace(/['"]/g, '') : err.message; } }); return error; } }
JavaScript
class SourceServerVector extends VectorSource { /** * @param {SourceServerVectorOptions} [options={}] */ constructor (options = {}) { const parentOptions = copy(options) const urlTemplate = take(options, 'url') const type = take(options, 'type') || '' parentOptions.loader = (...args) => this.loader(...args) super(parentOptions) /** * @type {string} * @private */ this.strategyType_ = options.loadingStrategyType /** * @type {L10N} * @private */ this.localiser_ = options.localiser this.localised_ = options.localised || false /** * @type {URL} * @protected */ this.urlTemplate = urlTemplate /** * @type {string} * @private */ this.type_ = type const formatOptions = {} if (options.hasOwnProperty('defaultStyle')) { formatOptions.defaultStyle = options.defaultStyle } if (options.hasOwnProperty('extractStyles')) { formatOptions.extractStyles = options.extractStyles } if (options.hasOwnProperty('showPointNames')) { formatOptions.showPointNames = options.showPointNames } else { formatOptions.showPointNames = false } let formatProjection switch (this.type_) { case 'KML': this.format_ = new KML(formatOptions) this.dataType_ = 'text xml' // for $.ajax (GET-request) formatProjection = 'EPSG:4326' break case 'GeoJSON': this.format_ = new GeoJSON(formatOptions) this.dataType_ = 'text json' // for $.ajax (GET-request) formatProjection = 'EPSG:4326' break default: throw new Error(`${this.type_} is not supported by SourceServerVector!`) } /** * @type {number} * @private */ this.refresh_ = 0 if (options.hasOwnProperty('refresh')) { this.setRefresh(options.refresh) } this.refreshTimeoutId_ = null /** * indicates if the source needs to be emptied * @type {boolean} * @private */ this.doClear_ = false /** * @type {module:ol/proj~ProjectionLike} * @private */ this.urlProjection_ = options.urlProjection || formatProjection } /** * @param {module:ol/extent~Extent} extent * @param {number} resolution * @param {module:ol/proj~Projection} projection */ loader (extent, resolution, projection) { const url = this.urlTemplate.clone() if (this.strategyType_ === 'BBOX' || this.strategyType_ === 'TILE') { const transformedExtent = transformExtent(extent, projection, this.urlProjection_) if (url.url.includes('{bbox')) { Debug.warn('The {bbox...} url parameters are deprecated, please use {minx}, {miny}, {maxx}, {maxy} instead.') url.url.replace(/{bboxleft}/g, '{minx}') url.url.replace(/{bboxbottom}/g, '{miny}') url.url.replace(/{bboxright}/g, '{maxx}') url.url.replace(/{bboxtop}/g, '{maxy}') } url.expandTemplate('minx', transformedExtent[0].toString()) .expandTemplate('miny', transformedExtent[1].toString()) .expandTemplate('maxx', transformedExtent[2].toString()) .expandTemplate('maxy', transformedExtent[3].toString()) .expandTemplate('resolution', resolution.toString(), false) } if (this.refresh_) { if (this.refreshTimeoutId_) { clearTimeout(this.refreshTimeoutId_) } this.refreshTimeoutId_ = setTimeout(() => { this.doClear_ = true // clears the source this.loader(extent, resolution, projection) // calls the loader recursively }, this.refresh_) } if (this.localised_) { url.cache = false } const finalUrl = url.finalize() $.ajax({ url: finalUrl, dataType: this.dataType_, beforeSend: () => this.dispatchEvent('vectorloadstart'), success: (response) => { // processing urls in the xml-Data (e.g. for images) if (url.useProxy && /xml$/.test(this.dataType_)) { response = this.addProxyToHrefTags(response) } if (this.doClear_) { this.clear(true) this.doClear_ = false } const features = this.format_.readFeatures(response, { featureProjection: projection }) this.addFeatures(features) this.dispatchEvent('vectorloadend') }, error: () => { Debug.error(`Getting Feature resource failed with url ${finalUrl}`) this.dispatchEvent('vectorloaderror') }, headers: this.localiser_ ? { 'Accept-Language': this.localiser_.getCurrentLang() } : {} }) } /** * This sets the refresh rate. A value of 0 or smaller turns refresh off. * @param {number} refresh */ setRefresh (refresh) { this.refresh_ = (refresh > 0) ? refresh : 0 } /** * makes all urls in href-tags inside of a xmlDocument use the proxy address. * this function needs to extended with all Tags which could contain urls * @param {HTMLElement} text an xml-Document * @returns {HTMLElement} the xmlDocument */ addProxyToHrefTags (text) { const hrefTags = text.getElementsByTagName('href') // not working in IE11 let i, ii for (i = 0, ii = hrefTags.length; i < ii; i++) { if (hrefTags[i].textContent) { hrefTags[i].textContent = this.urlTemplate.useProxyFor(hrefTags[i].textContent.trim()).finalize() } else if (hrefTags[i].innerHTML) { hrefTags[i].innerHTML = this.urlTemplate.useProxyFor(hrefTags[i].innerHTML.trim()).finalize() } else { throw new Error("Can't prepend proxy inside KML (textContent and innerHTML missing)") } } return text } /** * @returns {URL} */ getUrlTemplate () { return this.urlTemplate } /** * @param {URL} urlTemplate */ setUrlTemplate (urlTemplate) { this.urlTemplate = urlTemplate } }
JavaScript
class usersController { /** * @description - Creates a new user * @static * * @param {Object} req - HTTP Request. * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static createUser(req, res) { const { username, email, bio, location, password, confirmPassword, } = req.body; const { Op } = Sequelize; db.User.findOne({ where: { [Op.or]: [{ username: req.body.username }, { email: req.body.email }], }, }) .then(existingUser => { if (existingUser) { return res.status(409).json({ errors: { title: 'Conflict', detail: 'Username or Email already exist, please login', }, }); } return db.User.create({ username, email, bio, location, password, }).then(newUser => { const token = generateToken(newUser); return res.status(201).json({ data: { token, }, }); }); }) .catch(Error => { res.status(500).json({ errors: { status: '500', detail: 'Internal server error', }, }); }); } /** * @description - Logs in a user * @static * * @param {Object} req - HTTP Request. * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static userLogin(req, res) { const errors = { title: 'Not Found', detail: 'These credentials do not match our record', }; const { username, password } = req.body; const { Op } = Sequelize; db.User.findOne({ where: { [Op.or]: [ { username: req.body.username }, { email: req.body.username }, ], }, }) .then(foundUser => { if (!foundUser) { return res.status(404).json({ errors, }); } if (!bcrypt.compareSync(password, foundUser.password)) { return res.status(404).json({ errors: { title: 'Not Found', detail: 'Wrong username or password', }, }); } const token = generateToken(foundUser); res.status(200).json({ data: { token, }, }); }) .catch(() => res.status(500).json({ errors: { status: '500', detail: 'Internal server error', }, }) ); } /** * @description - Gets a users' profile * @static * * @param {Object} req - HTTP Request. * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static userProfile(req, res) { const { token } = req.headers; if (!token) { return res.status(401).json({ errors: { title: 'Unauthorized', detail: 'You are not allowed to perform this action', }, }); } db.User.findOne({ where: { id: req.params.id, }, }) .then(existingUser => { if (!existingUser) { return res.status(404).json({ errors: { title: 'Not Found', detail: 'A user with that Id is not found', }, }); } if (existingUser && token) { jwt.verify(token, process.env.SECRET_KEY, (error, decoded) => { if (error) { return res.status(500).json({ detail: 'There was an error while authenticating you, please sign in again', }); } if (decoded.id === parseInt(req.params.id, 10)) { return res.status(200).json({ data: { user: { username: existingUser.username, email: existingUser.email, bio: existingUser.bio, location: existingUser.location, }, }, }); } return res.status(401).json({ errors: { title: 'Unauthorized', detail: 'You are not allowed to perform this action', }, }); }); } }) .catch(() => { res.status(500).json({ errors: { status: '500', detail: 'Internal server error', }, }); }); } /** * @description - Edits a users' profile * @static * * @param {Object} req - HTTP Request.pp * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static editUserProfile(req, res) { const { username, bio, location } = req.body; db.User.findOne({ where: { id: req.userId, }, }) .then(foundUser => { if (!foundUser) { return res.status(404).json({ error: { title: 'Not Found', detail: `Can't find user with id ${req.userId}`, }, }); } if (foundUser) { const userDetails = { username: username ? username.trim() : foundUser.username, bio: bio ? bio.trim() : foundUser.bio, location: location ? location.trim() : foundUser.location, }; foundUser.update(userDetails).then(updatedUser => res.status(200).json({ data: { user: { username: updatedUser.username, bio: updatedUser.bio, location: updatedUser.location, email: updatedUser.email, }, }, }) ); } }) .catch(error => { res.status(500).json({ errors: { status: '500', detail: 'Internal server error', }, }); }); } /** * @description - Request by user to recover lost password * @static * * @param {Object} req - HTTP Request. * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static recoverPassword(req, res) { const { email } = req.body; db.User.findOne({ where: { email, }, }) .then(foundUser => { if (!foundUser) { return res.status(404).json({ errors: { title: 'Not Found', detail: 'Email not found', }, }); } if (foundUser) { const token = generateToken(foundUser); foundUser.update({ token }).then(() => { const url = `http://${ req.headers.host }/api/v1/users/password-reset/${token}`; sendEmail(foundUser.email, url, res); }); } }) .catch(() => res.status(500).json({ errors: { detail: 'internal server error', }, }) ); } /** * @description - Link for user to reset their password * @static * * @param {Object} req - HTTP Request. * @param {Object} res - HTTP Response. * * @memberof usersController * * @returns {Object} Class instance. */ static resetPassword(req, res) { const { password } = req.body; db.User.findOne({ where: { id: req.userId, }, }) .then(foundUser => { if (foundUser.token === req.headers.token) { const newPassword = { password: bcrypt.hashSync(password, 10), token: null, }; foundUser.update(newPassword).then(() => res.status(200).json({ message: 'Password reset was successful, Please login', }) ); } else { return res.status(401).json({ message: 'You do not have the permission to perform this action', }); } }) .catch(Error => { res.status(500).json({ errors: { status: '500', detail: 'internal server error', }, }); }); } }
JavaScript
class Classic { constructor(m) {this.m = m } convert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } revert(x) {return x} reduce(x) {x.divRemTo(this.m,null,x)} mulTo(x,y,r) {x.multiplyTo(y,r); this.reduce(r)} sqrTo(x,r) {x.squareTo(r); this.reduce(r)} }
JavaScript
class Barrett { constructor(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } convert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { const r = nbi(); copyTo(x, r); this.reduce(r); return r; } } revert(x) { return x; } // x = x mod m (HAC 14.42) reduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; clamp(x); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r sqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r mulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } }
JavaScript
class ViewModelTranslatePlugin extends ViewModelPlugin { /** * @param {model.translation.TranslationsRepository} translationsRepository * @param {model.configuration.SystemModuleConfiguration} moduleConfiguration */ constructor(translationsRepository, moduleConfiguration) { super(); // Check params assertParameter(this, 'translationsRepository', translationsRepository, true, TranslationsRepository); assertParameter(this, 'moduleConfiguration', moduleConfiguration, true, SystemModuleConfiguration); // Assign options this._name = ['translate']; this._translationsRepository = translationsRepository; this._moduleConfiguration = moduleConfiguration; } /** * @inheritDoc */ static get injections() { return { 'parameters': [TranslationsRepository, SystemModuleConfiguration] }; } /** * @inheritDoc */ static get className() { return 'model.viewmodel.plugin/ViewModelTranslatePlugin'; } /** * @type {model.translation.TranslationsRepository} */ get translationsRepository() { return this._translationsRepository; } /** * @type {configuration.SystemModuleConfiguration} */ get moduleConfiguration() { return this._moduleConfiguration; } /** * @inheritDoc */ doExecute(repository, site, useStaticContent, name, parameters, options) { const scope = this; const promise = co(function*() { const language = options && options.language ? options.language : scope.moduleConfiguration.language; const translation = yield scope.translationsRepository.getByNameSiteAndLanguage(parameters, site, language); if (typeof translation == 'undefined') { return parameters; } return translation; }); return promise; } }
JavaScript
class WS extends EventEmitter { constructor(){ super(); // This is the class of the Websocket. It is used to open new WebSocket // connections. We don't directly use it from import, so the unittests // can replace it by a mock. this.WebSocket = _WebSocket; // Boolean to show when there is a websocket started with the server this.started = false; // Boolean to show when the websocket connection is working this.connected = undefined; // Store variable that is passed to Redux if ws is online this.isOnline = undefined; // Heartbeat interval in milliseconds. this.heartbeatInterval = HEARTBEAT_TMO; // Connection timeout. this.connectionTimeout = 5000; // Retry connection interval in milliseconds. this.retryConnectionInterval = 1000; // Open connection timeout. this.openConnectionTimeout = 20000; // Date of latest setup call. The setup is the way to open a new connection. this.latestSetupDate = null; // Date of latest ping. this.latestPingDate = null; // Latest round trip time measured by PING/PONG. this.latestRTT = null; // Timer used to detected when connection is down. this.timeoutTimer = null; } /** * Start websocket object and its methods */ setup() { if (this.started) { return; } let wsURL = helpers.getWSServerURL(); if (wsURL === null) { return; } if (this.ws) { const dt = (new Date() - this.latestSetupDate) / 1000; if (dt < this.openConnectionTimeout) { return; } this.ws.close(); } this.ws = new this.WebSocket(wsURL); this.latestSetupDate = new Date(); this.ws.onopen = () => { this.onOpen(); } this.ws.onmessage = (evt) => { this.onMessage(evt); } this.ws.onerror = (evt) => { this.onError(evt); } this.ws.onclose = () => { this.onClose(); } } onPong() { if (this.latestPingDate) { const dt = (new Date() - this.latestPingDate) / 1000; this.latestRTT = dt; this.latestPingDate = null; } if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); this.timeoutTimer = null; } } /** * Handle message receiving from websocket * * @param {Object} evt Event that has data (evt.data) sent in the websocket */ onMessage(evt) { const message = JSON.parse(evt.data) const _type = message.type.split(':')[0] if (_type === 'pong') { this.onPong(); } this.emit(_type, message) } /** * Method called when websocket connection is opened */ onOpen() { if (this.connected === false) { // If was not connected we need to reload data // Emits event to reload data this.emit('reload_data'); } this.connected = true; this.started = true; this.setIsOnline(true); this.heartbeat = setInterval(() => { this.sendPing(); }, this.heartbeatInterval); wallet.onWebsocketOpened(); } /** * Method called when websocket connection is closed */ onClose() { this.started = false; this.connected = false; this.setIsOnline(false); wallet.onWebsocketBeforeClose(); if (this.ws) { this.ws.close(); this.ws = null; } setTimeout(() => { this.setup() }, this.retryConnectionInterval); clearInterval(this.heartbeat); } /** * Method called when an error happend on websocket * * @param {Object} evt Event that contains the error */ onError(evt) { this.onClose(); // console.log('ws error', window.navigator.onLine, evt); } /** * Method called to send a message to the server * * @param {string} msg Message to be sent to the server (usually JSON stringified) */ sendMessage(msg) { if (!this.started) { this.setIsOnline(false); return; } if (this.ws.readyState === WS_READYSTATE_READY) { this.ws.send(msg); } else { // If it is still connecting, we wait a little and try again setTimeout(() => { this.sendMessage(msg); }, 1000); } } /** * Ping method to check if server is still alive * */ sendPing() { if (this.latestPingDate) { // Skipping sendPing. Still waiting for pong... return; } const msg = JSON.stringify({'type': 'ping'}) this.latestPingDate = new Date(); this.timeoutTimer = setTimeout(() => this.onConnectionDown(), this.connectionTimeout); this.sendMessage(msg) } onConnectionDown() { this.onClose(); }; /** * Method called to end a websocket connection * */ endConnection() { this.setIsOnline(undefined); this.started = false; this.connected = undefined; if (this.ws) { this.ws.onclose = () => {}; this.ws.close(); this.ws = null; } clearInterval(this.heartbeat); } /** * Set in redux if websocket is online * * @param {*} value Can be true|false|undefined */ setIsOnline(value) { // Save in redux // Need also to keep the value in 'this' because I was accessing redux store // from inside a reducer and was getting error if (this.isOnline !== value) { this.isOnline = value; // Emits event of online state change this.emit('is_online', value); } } }
JavaScript
class AbstractMapping { /** * Constructor. */ constructor() { /** * @type {string|undefined} * @protected */ this.id = undefined; /** * The type attribute value for the root XML node. * @type {!string} */ this.xmlType = 'AbstractMapping'; /** * @inheritDoc */ this.field = undefined; /** * @inheritDoc */ this.ui = undefined; /** * @inheritDoc */ this.warnings = undefined; } /** * @inheritDoc */ autoDetect(items) { return null; } /** * @inheritDoc */ getId() { return this.id; } /** * @inheritDoc */ getLabel() { return null; } /** * @inheritDoc */ getScore() { return 0; } /** * @inheritDoc */ getScoreType() { return osMapping.DEFAULT_SCORETYPE; } /** * @inheritDoc */ getFieldsChanged() { return [this.field]; } /** * @inheritDoc */ execute(item, opt_targetItem) { // Do nothing by default. } /** * @inheritDoc */ testField(value) { return value != null; } /** * @inheritDoc */ clone() { // HACK: The compiler doesn't like using "new" on abstract classes, so cast it as the interface. var other = new /** @type {function(new:IMapping)} */ (this.constructor)(); other.field = this.field; return other; } /** * @inheritDoc */ persist(opt_to) { opt_to = opt_to || {}; opt_to['id'] = this.getId(); opt_to['field'] = this.field; return opt_to; } /** * @inheritDoc */ restore(config) { this.field = config['field']; } /** * @inheritDoc */ toXml() { var mapping = createElement('mapping', undefined, undefined, { 'type': this.xmlType }); appendElement('field', mapping, osMapping.localFieldToXmlField(this.field)); return mapping; } /** * @inheritDoc */ fromXml(xml) { this.xmlType = xml.getAttribute('type'); this.field = osMapping.xmlFieldToLocalField(this.getXmlValue(xml, 'field')); } /** * Convert a string to a boolean * * @param {string} input An input string * @return {boolean} true if the string is 'true', false otherwise. */ toBoolean(input) { if ('true' === input) { return true; } return false; } /** * Safely extract from an xml Element the first value of the first tag * * @param {!Element} xml The xml element * @param {string} tagName The tag to look for. * @return {?string} The value if available. Null otherwise. */ getXmlValue(xml, tagName) { var list = xml.getElementsByTagName(tagName); if (list && list[0]) { return list[0].innerHTML; } return null; } }
JavaScript
class Browse extends React.Component { constructor(props){ super(props); this.state = { showModal: false, pitchList: [], API: 'https://dev-fund.herokuapp.com' } } getBulletin = async () => { await superagent .get(`${this.state.API}/api/bulletin`) .then( res => { this.setState({pitchList: res.body.results}) }) .catch(console.error); } componentDidMount = () => { this.getBulletin(); } toggleModal = () => { this.setState({ showModal: !this.state.showModal }); }; handleClick = (e, pitch) => { this.setState({pitch}) this.toggleModal() } render() { return( <> <main id="browsePage"> <section className="hero" id="browse"> <h1>DevFund a Request</h1> <h3>You can make a big difference!</h3> </section> <h2>All Pitches</h2> <When condition={this.state.showModal}> <Modal title="" close={this.toggleModal}> <Detail pitch={this.state.pitch}/> </Modal> </When> <ul>{this.state.pitchList.map((pitch, i) => <li key={i}> <div id="photoAndName"> <img src="http://placeimg.com/150/150/animals" alt="profile pic" /> <p className="username">{pitch.username}</p> </div> <div id="pitch"> <h4 className="pitchheader">{pitch.item} - ${pitch.price}</h4> <p>{pitch.pitch.slice(0, 150) + '...'}</p> </div> <button onClick={(e) => this.handleClick(e, pitch)}>Details</button> </li> )} </ul> </main> </> )} }
JavaScript
class MRequire { /** * @param {string[]} peers The identifiers of peers that the sender * requests. */ constructor (peers) { this.peers = peers this.type = 'MRequire' } }
JavaScript
class Application { /** * Create new application. The constructor is not used directly by the * application. Normally, it's created using * {@link module:thymes2js.createApplication} function. * * @param {ConfigFunction} configFn Application configuration access * function. * @param {Logger} logger The logger. */ constructor(configFn, logger) { // save configuration access function and the logger this._configFn = configFn; this._logger = logger; // endpoints this._endpoints = new Array(); // services this._serviceProviders = new Map(); this._serviceProviders.set( 'authenticator', new BasicAuthenticatorProvider()); this._serviceProviders.set( 'actorRegistry', new NoopActorRegistryProvider()); this._serviceProviders.set( 'actorRegistryCache', new ActorRegistryCacheProvider()); this._serviceProviders.set( 'marshaller:application/json', new JsonMarshallerProvider()); // header value handlers this._headerValueHandlers = new Map(); this._headerValueHandlers.set('vary', HeadersListHeaderValueHandler); this._headerValueHandlers.set( 'access-control-allow-headers', HeadersListHeaderValueHandler); this._headerValueHandlers.set( 'access-control-expose-headers', HeadersListHeaderValueHandler); this._headerValueHandlers.set('allow', MethodsListHeaderValueHandler); this._headerValueHandlers.set( 'access-control-allow-methods', MethodsListHeaderValueHandler); this._headerValueHandlers.set('DEFAULT', DefaultHeaderValueHandler); // known HTTP methods this._knownHttpMethods = new Set([ 'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE' ]); // cacheable HTTP response codes this._cacheableStatusCodes = new Array(); [ 200, 203, 204, 206, 300, 301, 304, 308, 404, 405, 410, 414, 501 ].forEach(statusCode => { this._cacheableStatusCodes[statusCode] = true; }); // "simple" response headers this._simpleResponseHeaders = new Set([ 'cache-control', 'content-language', 'content-type', 'expires', 'last-modified', 'pragma' ]); // multipart boundary this._boundary = 'thymes2js_boundary_gc0p4Jq0M2Yt08j34c0p'; // allowed origin patterns for CORS let allowedOriginsPattern = configFn('X2_ALLOWED_SECURE_ORIGINS'); if (allowedOriginsPattern) { this._allowedSecureOriginsPattern = new RegExp( '^' + allowedOriginsPattern + '$', 'i'); allowedOriginsPattern = configFn('X2_ALLOWED_PUBLIC_ORIGINS'); if (allowedOriginsPattern) this._allowedPublicOriginsPattern = new RegExp( '^' + allowedOriginsPattern + '$', 'i'); } // maximum request size this._maxRequestSize = (Number(configFn('X2_MAX_REQUEST_SIZE')) || 2048); // response timeout this._responseTimeout = (Number(configFn('X2_RESPONSE_TIMEOUT')) || null); // timed-out flag on the socket this._timedOutProp = new Symbol(); // the application is not initialized yet this._initialized = false; } /** * Add API endpoint to the application. * * @param {string} uriPattern Endpoint URI regular expression pattern. URI * parameters are groups in the pattern. * @param {EndpointDefinition} def Endpoint definition object. * @returns This object for chaining. * @throws {SyntaxError} The specified URI pattern is invalid. */ endpoint(uriPattern, def) { // make sure the app has not been initialized yet if (this._initialized) throw new Error( 'Cannot add endpoint after application initialization.'); // create and save the endpoint object this._endpoints.push(new Endpoint(uriPattern, def)); // done return this; } /** * Add resource to the application. * * @param {ResourceDefinition} def Resource definition. * @returns This object for chaining. */ resource(def) { // make sure the app has not been initialized yet if (this._initialized) throw new Error( 'Cannot add resource after application initialization.'); // TODO:... // done return this; } /** * Add multiple resources to the application at once. * * @param {ResourceDefinition[]} defs Resource definitions. * @returns This object for chaining. */ resources(defs) { // add each resource defs.forEach(def => { this.resource(def); }); // done return this; } /** * Add service to the application. * * @param {string} name Service name. * @param {ServiceProvider} serviceProvider Service provider. * @returns This object for chaining. */ service(name, serviceProvider) { // make sure the app has not been initialized yet if (this._initialized) throw new Error( 'Cannot add service after application initialization.'); // save service provider this._serviceProviders.set(name, serviceProvider); // done return this; } /** * Get HTTP response header handler. * * @function Application#headerValueHandler * @param {string} name All lower-case HTTP header name. * @returns {HeaderValueHandler} New empty handler. */ /** * Register custom HTTP response header handler. The method can be called * only before the application is initialized. * * @param {string} name All lower-case HTTP header name. * @param {function} handlerConstructor Constructor of * {@link HeaderValueHandler}. * @returns This object for chaining. */ headerValueHandler(name, handlerConstructor) { // check if getting the handler if (!handlerConstructor) return new ( this._headerValueHandlers.get(name) || this._headerValueHandlers.get('DEFAULT') ); // make sure the app has not been initialized yet if (this._initialized) throw new Error( 'Cannot register header value handler after application' + ' initialization.'); // register handler this._headerValueHandlers.set(name, handlerConstructor); // done return this; } /** * Initialize the application. * * <p>If the application has not been initialized by the first invocation of * {@link #respond}, it will be initialized automatically. However, the * application may want to explicitely call this method so that * initialization does not take time from the first API call response. * * <p>An application instance can be initialized only once. * * @returns This application. */ init() { // make sure the app has not been initialized yet if (this._initialized) throw new Error('The application is already initialized.'); // make application initialized this._initialized = true; // log it this._logger.info('initalizing the application'); // perform application initialization try { // configure service providers and build initialization sequence const serviceInitSequence = new Set(); const serviceDepsChain = new Set(); this._serviceProviders.forEach((serviceProvider, serviceName) => { // configure service provider is necessary if (typeof serviceProvider.configure === 'function') { this._logger.debug( 'configuring service provider "%s"', serviceName); serviceProvider.configure( this._configFn, this._logger, this._serviceProviders); } // add services to the initialization sequence this._addToServiceInitSequence( serviceName, serviceProvider, serviceInitSequence, serviceDepsChain); }); // create runtime this._services = new Map(); this._runtime = new Runtime(this._configFn, this._logger, this._services); // instantiate services serviceInitSequence.forEach(serviceName => { this._logger.debug('instantiating service "%s"', serviceName); this._services.set( serviceName, this._serviceProviders.get(serviceName).createService( this._runtime)); }); delete this._serviceProviders; // no need for the providers anymore // create endpoint mapper this._endpointMapper = new EndpointMapper( this._endpoints, this._configFn); delete this._endpoints; // the endpoints are in the mapper now // ready to serve this._logger.info('ready to accept requests'); } catch (err) { this._logger.error( 'error initializing the application: %s', err.message); this.shutdown(); throw err; } // done return this; } /** * Recursively process service provider and add the service and services, on * that which it depends to the service initialization sequence. * * @private * @param {string} serviceName Service name. * @param {ServiceProvider} serviceProvider Service provider. * @param {Set.<string>} serviceInitSequence Service initialization sequence * being built. * @param {Set.<string>} serviceDepsChain Service dependencies chain. */ _addToServiceInitSequence( serviceName, serviceProvider, serviceInitSequence, serviceDepsChain) { // check if already in the initialization sequence if (serviceInitSequence.has(serviceName)) return; // check if circular dependency if (serviceDepsChain.has(serviceName)) throw new Error( 'Circular dependency for service "' + serviceName + '": ' + serviceDepsChain); // add services, on which this one depends first const deps = serviceProvider.dependencies; if (deps && (deps.length > 0)) { serviceDepsChain.add(serviceName); deps.forEach(depServiceName => { const depServiceProvider = this._serviceProviders.get(depServiceName); if (!depServiceProvider) throw new Error( 'Service "' + serviceName + '" depends on unknown service "' + depServiceName + '".'); this._addToServiceInitSequence( depServiceName, depServiceProvider, serviceInitSequence, serviceDepsChain); }); serviceDepsChain.delete(serviceName); } // add service to the initalization sequence serviceInitSequence.add(serviceName); } /** * Gracefully shutdown the application. */ shutdown() { // check if initialized and not shutdown if (!this._initialized || this._shutdown) return; // disable responding to calls this._shutdown = true; // log it this._logger.info('shutting down the application'); // shutdown the services Array.from(this._services.entries()).reverse().forEach(entry => { const service = entry[1]; if (typeof service.shutdown === 'function') { this._logger.debug('shutting down service %s', entry[0]); try { service.shutdown(); } catch (err) { this._logger.error( 'error shutting down service %s: ', entry[0], err); } } }); // free runtime and the services delete this._runtime; delete this._services; } /** * Respond to a request. * * @param {external:"http.IncomingMessage"} httpRequest The HTTP request. * @param {external:"http.ServerResponse"} httpResponse The HTTP response. */ respond(httpRequest, httpResponse) { // check if already timed out if (httpRequest.connection[this._timedOutProp]) { httpResponse.writeHead(408, { 'Connection': 'close' }); httpResponse.end(); return; } // check if application has been shut down if (this._shutdown) { httpResponse.writeHead(503); httpResponse.end(); return; } // initialize the application if necessary if (!this._initialized) this.init(); // create endpoint call object and initiate the call processing try { (new EndpointCall(this, httpRequest, httpResponse)).process(); } catch (err) { this._logger.error(err.stack); httpResponse.writeHead(500); httpResponse.end(); } } /** * Handle connection "timeout" event. * * @param {external:"net.Socket"} socket The connection socket. */ onTimeout(socket) { this._logger.debug('connection inactivity timeout'); socket[this._timedOutProp] = true; return; //....... try { if (this._logger.isDebugEnabled()) this._logger.debug('connection inactivity timeout'); switch(socket[this._phaseProperty]) { case 'HANDLING': const respBody = '{"errorCode":"X2-500-2"' + ',"errorMessage":"Server side timeout."}'; socket.end( 'HTTP/1.1 500 Internal Server Error\r\n' + 'Date: ' + (new Date()).toUTCString() + '\r\n' + 'Content-Type: application/json\r\n' + 'Content-Length: ' + String(respBody.length) + '\r\n' + 'Connection: close\r\n' + '\r\n' + respBody); break; case 'RESPONDING': socket.destroy(); break; case 'ABORTED': break; default: socket.end( 'HTTP/1.1 408 Request Timeout\r\n' + 'Date: ' + (new Date()).toUTCString() + '\r\n' + 'Connection: close\r\n' + '\r\n'); } } catch (err) { this._logger.error('error handling timeout: ', err); } finally { socket[this._phaseProperty] = 'ABORTED'; } } }
JavaScript
class EndpointCall { /** * Create new processor for a request. * * @param {Application} app The application. * @param {external:"http.IncomingMessage"} httpRequest The HTTP request. * @param {external:"http.ServerResponse"} httpResponse The HTTP response. * @throws {Error} Unexpected internal server error. */ constructor(app, httpRequest, httpResponse) { // initial properties: this._app = app; this._httpRequest = httpRequest; this._httpResponse = httpResponse; this._requestUrl = url.parse(httpRequest.url, true); // the properties below are set at various points during the processing: this._endpointMatch = null; this._allowedMethods = null; this._authResult = null; this._responseActor = null; this._validateRequestEntity = null; this._ctx = null; } /** * Initiate the asynchronous chain of endpoint call processing. */ process() { try { // used refs const app = this._app; const method = this._httpRequest.method; // lookup the endpoint this._endpointMatch = app._endpointMapper.lookup(this._requestUrl); if (!this._endpointMatch) return this._sendResponse( (new EndpointCallResponse(app, 404)).entity({ errorCode: 'X2-404-1', errorMessage: 'No API endpoint at this URI.' })); // log the endpoint call if (app._logger.isDebugEnabled()) app._logger.debug( 'received endpoint request %s %s', method, this._endpointMatch.resourceUri); // check if the method is known if (!app._knownHttpMethods.has(method)) return this._sendResponse( (new EndpointCallResponse(app, 501)).entity({ errorCode: 'X2-501-1', errorMessage: 'Unsupported HTTP method.' })); // get allowed methods from the handler this._allowedMethods = this._endpointMatch.handler.getAllowedMethods( this._endpointMatch.resourceUri, this._endpointMatch.uriParams); // respond to an OPTIONS request if (method === 'OPTIONS') return this._sendOptionsResponse(); // verify that the method is allowed if (!this._allowedMethods.has(method === 'HEAD' ? 'GET' : method)) { const response = new EndpointCallResponse(app, 405); this._allowedMethods.forEach( method => { response.header( 'Allow', (method === 'GET' ? 'GET, HEAD' : method)); } ); response.header('Allow', 'OPTIONS'); response.entity({ errorCode: 'X2-405-1', errorMessage: 'Method not supported by the API endpoint.' }); return this._sendResponse(response); } // authenticate the request and continue processing after that this._app._services.get('authenticator') .authenticate(this._httpRequest, this._requestUrl) .then( this._process1.bind(this), this._sendInternalServerErrorResponse.bind(this) ); } catch (err) { this._sendInternalServerErrorResponse(err); } } /** * Continue endpoint call processing after authentication. * * @private * @param {AuthenticationResult} authResult Authentication result. */ _process1(authResult) { try { // save authentication information this._authResult = authResult; this._responseActor = authResult.actor; // used refs const endpointMatch = this._endpointMatch; const method = this._httpRequest.method; // check if actor is allowed to make the call if (!endpointMatch.handler.isAllowed( method, endpointMatch.resourceUri, endpointMatch.uriParams, this._authResult.actor)) { // check if could not authenticate and challenge if so if (this._authResult.actor === null) return this._sendResponse( (new EndpointCallResponse(this._app, 401)).header( 'WWW-Authenticate', this._authResult.challenge ).entity({ errorCode: 'X2-401-1', errorMessage: 'Authentication required.' })); // authenticated, but not authorized return this._sendResponse( (new EndpointCallResponse(this._app, 403)).entity({ errorCode: 'X2-403-1', errorMessage: 'Insufficient permissions.' })); } // get request entity validator this._validateRequestEntity = ( endpointMatch.handler.getRequestEntityValidator && endpointMatch.handler.getRequestEntityValidator( method, endpointMatch.resourceUri, endpointMatch.uriParams) ); // read the request entity if expected if (this._validateRequestEntity) { // get top content type const topCType = ( this._httpRequest.headers['content-type'] || 'application/octet-stream'); // check if multipart if (/^multipart\//i.test(topCType)) { // TODO:... } else { // not multipart // find marshaller for deserialization const marshaller = this._app._services.get( 'marshaller:' + topCType.split(/;\s*/)[0].toLowerCase()); if (!marshaller) return this._sendResponse( (new EndpointCallResponse(this._app, 415)).entity({ errorCode: 'X2-415', errorMessage: 'Unsupported request entity content type.' })); // check content length if (Number(this._httpRequest.headers['content-length']) > this._app._maxRequestSize) return this._sendResponse( (new EndpointCallResponse(this._app, 413)).entity({ errorCode: 'X2-413', errorMessage: 'The request entity is too large.' }).header('Connection', 'close')); // respond with 100 if expecting continue // KLUDGE: response properties used below are undocumented if (this._httpResponse._expect_continue && !this._httpResponse._sent100) this._httpResponse.writeContinue(); /*if (this._httpRequest.headers['expect'] === '100-continue') this._httpResponse.writeContinue();*/ // read the entity data const dataBufs = new Array(); let bytesRead = 0; this._httpRequest .on('data', chunk => { if ((bytesRead += chunk.length) > this._app._maxRequestSize); // TODO: send error and stop reading dataBufs.push(chunk); }) .on('end', () => { // TODO: parse the data try { this._process2( marshaller.deserialize( dataBufs.length === 1 ? dataBufs[0] : Buffer.concat(dataBufs)), null); } catch (err) { // TODO: syntax error, general error console.log('parsing request error: ', err); } }) .on('error', err => { // TODO: what to do? console.log('reading request error: ', err); }); // TODO:... } } else { // no request entity is expected, proceed with processing this._process2(null, null); } } catch (err) { this._sendInternalServerErrorResponse(err); } } /** * Continue endpoint call processing after getting the request entity. * * @param {?Object} requestEntity Parsed request entity, or <code>null</code> * if none. * @param {?Iterator.<HttpEntity>} requestAttachments Additional request * entities for a multipart request, or <code>null</code> if none. */ _process2(requestEntity, requestAttachments) { try { // TODO: validate entity console.log('>>> got request entity:'); //console.log(requestEntity); // create call context this._ctx = new EndpointCallContext( this._app, this._app._runtime, this._authResult.actor, requestEntity, requestAttachments); // call the handler Promise.resolve(this._endpointMatch.handler.handleCall(this._ctx)) .then( this._process3.bind(this), this._sendInternalServerErrorResponse.bind(this) ); } catch (err) { this._sendInternalServerErrorResponse(err); } } /** * Continue endpoint call processing after receiving result from the handler. * * @private * @param {?(EndpointCallResponse|Object)} result Result returned by the * handler. */ _process3(result) { try { // get the call response object let response; if (result instanceof EndpointCallResponse) response = result; else if (result === null) response = new EndpointCallResponse(this._app, 204); else response = new EndpointCallResponse(this._app, 200).entity( result); // update response actor this._responseActor = this._ctx.actor; // send the response this._sendResponse(response); } catch (err) { this._sendInternalServerErrorResponse(err); } } /** * Send HTTP 500 (Internal Server Error) response as a reaction to an * unexpected error. * * @private * @param {Error} err The error that caused the 500 response. */ _sendInternalServerErrorResponse(err) { this._app._logger.error(err.stack); this._sendResponse( (new EndpointCallResponse(this._app, 500)).entity({ errorCode: 'X2-500-1', errorMessage: 'Internal server error.' })); } /** * Send response to an OPTIONS request. * * @private */ _sendOptionsResponse() { // create response headers set const response = new EndpointCallResponse(this._app, 200); // list allowed methods this._allowedMethods.forEach( method => { response.header( 'Allow', (method === 'GET' ? 'GET, HEAD' : method)); } ); response.header('Allow', 'OPTIONS'); // add zero content length header response.header('Content-Length', 0); // response always varies depending on the "Origin" header response.header('Vary', 'Origin'); // process CORS preflight request const origin = this._httpRequest.headers['origin']; const requestedMethod = this._httpRequest.headers['access-control-request-method']; if (origin && requestedMethod) { // check if origin is allowed let allowedOrigin; if (this._app._allowedPublicOriginsPattern && this._endpointMatch.handler.isPublic( this._endpointMatch.resourceUri, this._endpointMatch.uriParams) && this._app._allowedPublicOriginsPattern.test(origin)) { allowedOrigin = 'ALLOWED_SPECIFIC'; } else if (!this._app._allowedSecureOriginsPattern) { allowedOrigin = 'ALLOWED_ANY'; } else if (this._app._allowedSecureOriginsPattern.test(origin)) { allowedOrigin = 'ALLOWED_SPECIFIC_PLUS_CRED'; } else { allowedOrigin = 'DISALLOWED'; } // proceed if allowed origin and method if (allowedOrigin !== 'DISALLOWED') { // allow the origin response.header( 'Access-Control-Allow-Origin', (allowedOrigin === 'ALLOWED_ANY' ? '*' : origin)); // allow credentials, if allowed if (allowedOrigin === 'ALLOWED_SPECIFIC_PLUS_CRED') response.header('Access-Control-Allow-Credentials', 'true'); // allow caching of the preflight response (for 20 days) response.header('Access-Control-Max-Age', 20 * 24 * 3600); // allow method and headers response.header('Access-Control-Allow-Method', requestedMethod); const requestedHeaders = this._httpRequest.headers['access-control-request-headers']; if (requestedHeaders) response.header( 'Access-Control-Allow-Headers', requestedHeaders); } } // send OK response this._httpResponse.writeHead(response.statusCode, response.headers); this._httpResponse.end(); } /** * Send normal response to the endpoint call. * * @private * @param {EndpointCallResponse} response The response to send. */ _sendResponse(response) { // used refs const app = this._app; const authService = app._services.get('authenticator'); const method = this._httpRequest.method; const httpRequestHeaders = this._httpRequest.headers; const endpointMatch = this._endpointMatch; // response always varies depending on the "Origin" header response.header('Vary', 'Origin'); // add CORS headers if cross-origin request const origin = httpRequestHeaders['origin']; if (origin) { // test if the origin is allowed let allowedOrigin = true; if (app._allowedPublicOriginsPattern && endpointMatch && endpointMatch.handler.isPublic( endpointMatch.resourceUri, endpointMatch.uriParams) && app._allowedPublicOriginsPattern.test(origin)) { response.header('Access-Control-Allow-Origin', origin); } else if (!app._allowedSecureOriginsPattern) { response.header('Access-Control-Allow-Origin', '*'); } else if (app._allowedSecureOriginsPattern.test(origin)) { response.header('Access-Control-Allow-Origin', origin); response.header('Access-Control-Allow-Credentials', 'true'); } else { allowedOrigin = false; } // add exposed headers, if origin allowed if (allowedOrigin) (authService.exposedResponseHeaders || []) .concat(( endpointMatch && endpointMatch.handler.exposedResponseHeaders ) || []) .filter( h => !app._simpleResponseHeaders.has(h.toLowerCase())) .forEach( h => { response.header('Access-Control-Expose-Headers', h); }); } // add authentication related headers authService.addResponseAuthInfo( response, this._authResult, this._responseActor, this._requestUrl, httpRequestHeaders); // default response cache control const statusCode = response.statusCode; if (((method === 'GET') || (method === 'HEAD')) && app._cacheableStatusCodes[statusCode] && !response.hasHeader('Cache-Control')) { response .header('Cache-Control', 'no-cache') .header('Expires', '0') .header('Pragma', 'no-cache'); } // get response entities const entities = response.entities; // content type if (entities) { if (entities.length === 1) { let entity = entities[0]; for (let h of Object.keys(entity.headers)) response.header(h, entity.headers[h]); } else { response.header( 'Content-Type', 'multipart/mixed; boundary=' + this._boundary); } } // done if no entities or "HEAD" request if (!entities || (method === 'HEAD')) { this._httpResponse.writeHead(statusCode, response.headers); this._httpResponse.end(); return; } // buffer or stream? if (response.hasStreams) { // TODO:... } else { // no streams // create sequence of buffers to send in the response body const bufs = []; if (entities.length === 1) { bufs.push(this._getResponseEntityDataBuffer(entities[0])); } else { // multipart // create buffers with auxilliary elements const boundaryMid = new Buffer('--' + app._boundary + '\r\n', 'ascii'); const boundaryEnd = new Buffer('--' + app._boundary + '--', 'ascii'); const crlf = new Buffer('\r\n', 'ascii'); // add payload parts entities.forEach((entity, ind) => { // part boundary bufs.push(boundaryMid); // part headers for (let h of Object.keys(entity.headers)) partHead += util.headerCase(h) + ': ' + entity.headers[h] + '\r\n'; partHead += '\r\n'; bufs.push(new Buffer(partHead, 'ascii')); // part body bufs.push(this._getResponseEntityDataBuffer(entity)); // part end bufs.push(crlf); }); // end boundary of the multipart payload bufs.push(boundaryEnd); } // set response content length response.header( 'Content-Length', bufs.reduce((totalLength, buf) => totalLength + buf.length, 0)); // write response head const httpResponse = this._httpResponse; httpResponse.writeHead(statusCode, response.headers); // write response body buffers const numBufs = bufs.length; let curBufInd = 0; function writeHttpResponse() { while (curBufInd < numBufs) { if (!httpResponse.write(bufs[curBufInd++])) { httpResponse.once('drain', writeHttpResponse); return; } } httpResponse.end(); } writeHttpResponse(); // TODO: error and close events } } /** * Get data buffer for the specified response entity invoking appropriate * marshaller service if necessary. * * @private * @param {HttpEntity} entity Response entity. * @returns {external:Buffer} Buffer with the response entity data. */ _getResponseEntityDataBuffer(entity) { if (entity.data instanceof Buffer) return entity.data; const contentType = entity.headers['content-type']; const marshaller = this._app._services.get( 'marshaller:' + contentType.split(/;\s*/)[0]); return marshaller.serialize(entity.data, contentType); } }
JavaScript
class Tabs extends React.Component { constructor(...args) { var _temp; return _temp = super(...args), this._handleTabChange = selectedTabName => { if (typeof this.props.onActiveTabChange === 'function') { this.props.onActiveTabChange((0, _nullthrows().default)(this.props.tabs.find(tab => tab.name === selectedTabName))); } }, this._renderTabMenu = () => { const closeButton = this.props.closeable ? React.createElement("div", { className: "close-icon", onClick: this.props.onClose }) : null; const tabs = this.props.tabs.map(tab => { const icon = tab.icon == null ? null : React.createElement(_Icon().Icon, { icon: tab.icon }); const handler = {}; handler[this.props.triggeringEvent] = this._handleTabChange.bind(this, tab.name); return React.createElement("li", Object.assign({ className: (0, _classnames().default)({ tab: true, active: this.props.activeTabName === tab.name, growable: this.props.growable }), key: tab.name, title: tab.name }, handler), React.createElement("div", { className: "title" }, icon, tab.tabContent), closeButton); }); return React.createElement("ul", { className: "tab-bar list-inline inset-panel" }, tabs); }, _temp; } render() { return React.createElement("div", { className: "nuclide-tabs" }, this._renderTabMenu()); } }
JavaScript
class Enemy extends Phaser.Sprite { constructor(game, ...args) { super(game, ...args); // TODO: // 1. Edit constructor parameters accordingly. // 2. Adjust object properties. } update() { // TODO: Stub. } }
JavaScript
class LogMsg{ constructor(options){ this.options = options || {}; this.writeLog = options.writeLog || false; this.logPath = options.logPath || './log'; this.prefixName = options.prefixName || 'log_'; this.logFileName = `${this.prefixName}${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}.log`; this.DEBUG_MODE = options.DEBUG_MODE || false; this.INFO_MODE = options.INFO_MODE || false; this.WARN_MODE = options.WARN_MODE || false; this.ERROR_MODE = options.ERROR_MODE || false; } /** * * @param {String} logType The log's type: DEBUG, INFO, WARN, ERROR * @param {String} logMsg The message that you would like to print */ log(logType, logMsg){ switch(logType){ case "DEBUG": this.writeLogFile(`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] DEBUG: ${logMsg}\n`); if(this.DEBUG_MODE) console.log("\x1b[94m",`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] DEBUG: ${logMsg}`); break; case "INFO": this.writeLogFile(`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] INFO: ${logMsg}\n`); if(this.INFO_MODE) console.log("\x1b[92m", `[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] INFO: ${logMsg}`); break; case "WARN": this.writeLogFile(`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] WARN: ${logMsg}\n`); if(this.WARN_MODE) console.log("\x1b[93m",`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] WARN: ${logMsg}`); break; case "ERROR": this.writeLogFile(`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] ERROR: ${logMsg}\n`); if(this.ERROR_MODE) console.log("\x1b[91m",`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] ERROR: ${logMsg}`); break; default: this.writeLogFile(`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] Error: The log type does not existed\n`); console.log("\x1b[91m",`[${moment(Timestamp).format('YYYY-MM-DDTHH:mm:ss.SSS')}] Error: The log type does not existed`); } } /** * * @param {String} msg The message that you would like to write in log file */ writeLogFile(msg){ if(this.writeLog){ if(!fs.existsSync(this.logPath)) fs.mkdirSync(this.logPath); fs.appendFile(this.logPath+"/"+this.logFileName, msg, function (err) { if (err) console.log(err); }); } } } // class logMsg
JavaScript
class SearchBar extends Component { static propTypes = { /** current page of results */ page: PropTypes.number.isRequired, /** number of results found */ numFound: PropTypes.number.isRequired, /** fetch books from the openlibrary api given a search term and a page */ fetchBooks: PropTypes.func.isRequired, /** reset the search */ clearSearch: PropTypes.func.isRequired } state = { searchTerm: "" } /** increment or decrement the pages of results */ prevPage = () => { this.props.fetchBooks(this.state.searchTerm, this.props.page - 1) } nextPage = () => { this.props.fetchBooks(this.state.searchTerm, this.props.page + 1) } /** if the search term is not empty then fetch the api else reset the search */ handleChange = (event) => { this.setState({ searchTerm: event.target.value }, () => { this.state.searchTerm.trim() ? this.props.fetchBooks(this.state.searchTerm, this.props.page) : this.props.clearSearch(); }); } render() { return ( <div className="search-bar"> <input type="search" id="search" placeholder="Harry Potter, Lord of the Rings, Moby Dick..." onChange={this.handleChange} value={this.state.searchTerm} /> <div className="page-controls"> <button onClick={this.prevPage} className="prev" disabled={this.props.page === 1}>{"<"}</button> <h2 className="page-number">{this.props.numFound < 1 ? 0 : `${this.props.page} / ${Math.ceil(this.props.numFound / 100)}`}</h2> <button onClick={this.nextPage} className="next" disabled={Math.ceil(this.props.numFound / 100) <= this.props.page}>{">"}</button> </div> </div> ) } }
JavaScript
class UserCollection { constructor() { this.schema = schema; } // method to create new users async create(userInfo) { let that = this; console.log('hello'); return new Promise(function (res, rej) { try { let user = new that.schema(userInfo); user .save() .then((data) => { return res(data.populate('acl').execPopulate()); }) .catch((e) => { console.log(e.message); rej(new Error({ status: 500, message: e.message })); }); } catch (e) { console.log(e.message, 'bsbs'); rej( new Error({ status: 500, message: 'Error in creating a new user.' }) ); } }); } // method for getting form user collection in the schema async read(userInfo) { if (userInfo !== undefined) { let record = await this.schema .findOne({ email: userInfo.email, }) .populate('acl') .populate('wishlist') .populate('review') .populate('productID') .populate('cart'); // .exec(); if (record) { let valid = await this.schema.authenticateUser( userInfo.password, record.password ); if (valid) { let token = await this.schema.generateToken(record._id); let userWithNewToken = await this.schema .findOneAndUpdate({ _id: record._id }, { token }, { new: true }) .populate('acl') .populate('wishlist') .populate('review') .populate('productID') .exec(); return userWithNewToken; } else { return 'Not The same pass'; } } else { return { status: 401, message: 'User is not found!' }; } } else { let record = await this.schema .find({}) .populate('acl') .populate('review') .populate('wishlist') .populate('productID') .exec(); return record; } } async readForResetPassword(email) { try { let record = await this.schema.findOne(email); if (record) return Promise.resolve(record); else return Promise.reject('user is not signup'); } catch (e) { return e.message; } } async update(obj, update) { console.log(obj, 'update'); return await this.schema.findOneAndUpdate(obj, update, { new: true }); } }
JavaScript
class GPEModal extends Component { render() { return ( <Overlay isVisible={this.props.isVisible} overlayStyle={{ width: '80%', height: '30%', alignItems: 'center', justifyContent: 'center', borderWidth: 2, borderColor: '#ffcc57', backgroundColor: '#3b3b3b', borderRadius: 8, }}> <View style={{flexDirection: 'column', justifyContent: 'space-between'}}> <Text style={{fontSize: 20, color: 'white'}}>{this.props.content}</Text> <View style={{flexDirection: 'row', justifyContent: 'space-around', alignItems: 'flex-end'}}> <Button type='clear' title={this.props.leftButtonTitle} onPress={this.props.leftButtonPress} titleStyle={{color: '#ffcc57'}}/> <Button type='clear' title={this.props.rightButtonTitle} onPress={this.props.rightButtonPress} titleStyle={{color: '#ffcc57'}}/> </View> </View> </Overlay> ); } }
JavaScript
class UserService { constructor() { this.users = [ { name: "lisandro", lastName: "martinez", email: "[email protected]", password: '14*DeSep' } ] } login(email, password, doOnLogin, doOnError) { const user = this.users.find(user => user.email === email && user.password === password) if (user) { doOnLogin(user) } else { doOnError() } } register(user, doOnSuccess, doOnError) { const alreadyExists = this.users.filter(user => user.email === email && user.password === password) if (alreadyExists.length !== 0) doOnError() else { this.users.push(user) doOnSuccess() } } }
JavaScript
class Block { constructor({ selector = null, filename = null, options = {}, variables = {}, blocks = [] }) { this.selector = selector; this.filename = filename; this.options = options; this.variables = variables; this.blocks = blocks; } write(data, formatter, out = null) { // run for all variants of this block's selector runOnSelector(data, this.selector, formatter.variables, (data, variables) => { // apply the selectors variables formatter = formatter.apply(variables); // new formatter with this blocks variables and options formatter = formatter.apply(this.variables, this.options); // check for an out stream or if a new filename should be written if (this.filename) { out = fs.createWriteStream(formatter.formatString(this.filename)); } else if (!out) { throw new Error('An exporter block cannot output without a filename or write stream'); } // walk the sub blocks for (let block of this.blocks) { // literal output else block output if (Array.isArray(block)) { for (let i = 0; i < block.length; ++i) { safeWrite(out, formatter.evalAndformat(block[i])); if (i < block.length - 1) { safeWrite(out, this.options.colDelimiter); } } safeWrite(out, this.options.lineDelimiter); } else if (block instanceof Block) { block.write(data, formatter, out); } } // end of block safeWrite(out, this.options.blockDelimiter); // end of stream (end if this block own's it) if (this.filename) { out.end(); } }); } validate(formatter) { if (!formatter.validateSelector(this.selector)) { return false; } // walk the sub blocks for (let block of this.blocks) { if (Array.isArray(block)) { for (let element of block) { if (!formatter.validate(element)) { return false; } } } else if (block instanceof Block) { if (!block.validate(formatter)) { return false; } } } return true; } static buildFromObj(obj, options = {}) { options = Object.assign({}, options, obj.options); let blocks = []; if (obj.blocks) { for (let block of obj.blocks) { if (Array.isArray(block)) { blocks.push(block); } else { blocks.push(Block.buildFromObj(block, options)); } } } return new Block({ ...obj, blocks, options }); } }
JavaScript
class TemplateContainer extends Component { /** * Other Class Methods */ /** * React Functions */ constructor (props) { super(props); // Member Variables this.state = { }; // Function Bindings this.render = this.render.bind(this); } // end constructor /** * Click and Event Handlers */ /** * Getter Methods */ /** * Other Render Methods */ /** * Render Function */ render () { return <Template />; } // end render }
JavaScript
class About { constructor() { this.settings = new Settings(); } init() { this.setupDomReferences(); this.updateClientVersion(); if (this.settings.loadExistingSettings() && this.settings.settings.url) { this.updateServerVersion(); } } setupDomReferences() { this.clientVersionEl = document.getElementById('clientVersion'); this.serverVersionEl = document.getElementById('serverVersion'); } // Draw the client version number taken from the package.json file updateClientVersion() { this.clientVersionEl.innerText = packageJson.version.toString(); } updateServerVersion() { const request = new XMLHttpRequest(); this.serverVersionEl.innerText = 'Retrieving version'; request.open('GET', url.resolve(this.settings.settings.url, '/version'), true); request.onload = () => { if (request.status >= 200 && request.status < 400) { // Success! const response = JSON.parse(request.responseText); this.serverVersionEl.innerText = response.server; } else { // We reached our target server, but it returned an error const errorStr = `Error: ${request.responseText}, Code: ${request.status}`; console.error(errorStr); this.serverVersionEl.innerText = ':('; } }; request.onerror = () => { // There was a connection error of some sort console.error('Request error'); }; request.send(); } }
JavaScript
class Color { constructor( r, g, b, a, mode = 'rgb' ) { this.r = 0xff; this.g = 0xff; this.b = 0xff; this.a = 1; if ( r === undefined ) return this; if ( r && g === undefined && b === undefined ) { let c = Color.parseColor( r ); r = c.r; g = c.g; b = c.b; } switch ( mode ) { case 'hsl': this.setHSL( r, g, b ); break; case 'rgb': default: this.setRGB( r, g, b, a ); } } setHSL( h, s, l, a ) { return this; } setRGB( r, g, b, a ) { return this; } get int() { return ( this.r << 16 ) | ( this.g << 8 ) | this.b; } get hex() { return `#${this.int}`; } get hsl() {} get h() {} get s() {} get l() {} set h( val ) { this.setHSL( val, s, l ); return val; } set s( val ) { this.setHSL( h, val, l ); return val; } set l( val ) { this.setHSL( h, s, val ); return val; } static parseColor( input ) { if ( input instanceof Color ) return Color; if ( typeof input === 'string' ) { input = parseInt( input, 16 ); } if ( typeof input === 'number' ) { return { r: input >> 16 & 0xff, g: input >> 8 & 0xff, b: input & 0xff } } return undefined; } }
JavaScript
class BaseAPI { configuration; middleware; constructor(configuration = new Configuration()) { this.configuration = configuration; this.middleware = configuration.middleware; } withMiddleware(...middlewares) { const next = this.clone(); next.middleware = next.middleware.concat(...middlewares); return next; } withPreMiddleware(...preMiddlewares) { const middlewares = preMiddlewares.map((pre) => ({ pre })); return this.withMiddleware(...middlewares); } withPostMiddleware(...postMiddlewares) { const middlewares = postMiddlewares.map((post) => ({ post })); return this.withMiddleware(...middlewares); } async request(context, initOverrides) { const { url, init } = this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); if (response.status >= 200 && response.status < 300) { return response; } throw response; } createFetchParams(context, initOverrides) { let url = this.configuration.basePath + context.path; if (context.query !== undefined && Object.keys(context.query).length !== 0) { // only add the querystring to the URL if there are query parameters. // this is done to avoid urls ending with a "?" character which buggy webservers // do not handle correctly sometimes. url += '?' + this.configuration.queryParamsStringify(context.query); } const body = ((typeof FormData !== "undefined" && context.body instanceof FormData) || context.body instanceof URLSearchParams || isBlob(context.body)) ? context.body : JSON.stringify(context.body); const headers = Object.assign({}, this.configuration.headers, context.headers); const init = { method: context.method, headers: headers, body, credentials: this.configuration.credentials, ...initOverrides }; return { url, init }; } fetchApi = async (url, init) => { let fetchParams = { url, init }; for (const middleware of this.middleware) { if (middleware.pre) { fetchParams = await middleware.pre({ fetch: this.fetchApi, ...fetchParams, }) || fetchParams; } } let response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); for (const middleware of this.middleware) { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, url: fetchParams.url, init: fetchParams.init, response: response.clone(), }) || response; } } return response; }; /** * Create a shallow clone of `this` by constructing a new instance * and then shallow cloning data members. */ clone() { const constructor = this.constructor; const next = new constructor(this.configuration); next.middleware = this.middleware.slice(); return next; } }
JavaScript
class ProductAddedToWishlistEvent extends ProductWishlistEvent { event() { return ECommerceEvents.PRODUCT_ADDED_TO_WISHLIST; } }
JavaScript
class BuildExecutor extends AbstractExecutor { /** * Default constructor. * @param {Context} context site build context */ constructor(context) { super(context); } /** * Checks to see if the executor should run. * @return {boolean} true, if the executor can run */ supports() { // always supports return true; } /** * Runs the executor. * @return {Promise} a promise that resolves on successful execution or gets rejected on error */ execute() { return new CleanBuilder(this.context) .execute() .then(() => Promise.all( [ new ContentBuilder(this.context), new StylesBuilder(this.context), new ScriptsBuilder(this.context), new ImagesBuilder(this.context), new FontsBuilder(this.context), new OtherContentBuilder(this.context), ].map((builder) => (this.context.serveMode ? builder.watch() : builder.execute())) ) ); } }
JavaScript
class ConnectFour extends Board { /** * The options for the game * @param {GameOptions} options */ constructor(options = {}) { super(options.boardWidth, options.boardHeight, { emoji: options.emoji }); this.options = options; /** * The game rounds * @type Round[] */ this.rounds = []; /** * The players of this board * @type Player[] */ this.players = []; } /** * The current game round * @type Round */ get round() { let currentRound = this.rounds.at(-1); if (currentRound.isFinished) currentRound = this.addRound(this.options.roundLimit); return currentRound; } /** * The game winner if has * @type {Player | null} */ get winner() { let winner = null; const columnWinner = this.columns.find((column) => column.winner)?.winner; const rowWinner = this.rows.find((row) => row.winner)?.winner; const obliqueWinner = this.obliques.find((oblique) => oblique.winner)?.winner; if (columnWinner) winner = columnWinner; if (rowWinner) winner = rowWinner; if (obliqueWinner) winner = obliqueWinner; return winner; } /** * Whatever if game is finished or not * @type {{resaon: String} | {resaon: String, winner: Player} | boolean} */ get isGameFinished() { if (this.winner) return { resaon: 'HAS_WINNER', winner: this.winner }; if (this.isBoardFull) return { resaon: 'FULL_BOARD' }; return false; } /** * Add a new round to the game * @param {Number} limit The round limit * @param {ConnectFour} game The round game * @returns {Round} The round */ addRound(limit, game = this) { const round = new Round(limit, game); this.rounds.push(round); return round; } /** * Add a new player to the game board * @param {String} id The player id * @param {String} emoji The player emoji * @returns {Player} The player */ addPlayer(id, emoji) { const player = new Player(id, emoji, this); this.players.push(player); return player; } /** * Start the game */ start() { if (!this.players.length) throw new Error('NO_PLAYER'); this.addRound(this.options.roundLimit); } }
JavaScript
class DCMSend extends DCMProcess { #port #AETitle #acseTimeout #dimseTimeout #maxPDU #peer #inputFileFormat #inputFiles #scanPattern #recurse #decompress #compression #noHalt #noIllegalProposal #noUidChecks #calledAETitle #association #timeout #maxSendPDU #reportFile /** * * @classdesc Class representing a DCM Sender * @class DCMSend * @param {string} peer ip or hostname of DICOM peer * @param {number} [port=104] port number to listen on * @param {('formatOrData'|'format'|'data')} inputFileFormat formatOrData; read file format or data set, format; read file format only (default), data; read * data set without file meta information * @param {('dicomdir'|'scan')} inputFiles * @param {string} scanPattern pattern for filename matching (wildcards) only with inputFiles = scan * @param {boolean} [recurse=false] recurse within specified directories * @param {('never'|'lossless'|'lossy')} decompress never; never decompress compressed data sets, lossless; only decompress lossless compression (default), * lossy; decompress both lossy and lossless compression * @param {number} compression 0=uncompressed, 1=fastest, 9=best compression * @param {boolean} [noHalt=false] do not halt on first invalid input file or if unsuccessful store encountered * @param {boolean} [noIllegalProposal=false] do not propose any presentation context that does not contain the default transfer syntax (if needed) * @param {boolean} [noUidChecks=false] do not check UID values of input files * @param {string} [AETitle='DCMSEND'] set my AE title * @param {string} [calledAETitle='ANY-SCP'] set called AE title of peer (default: ANY-SCP) * @param {('multi'|'single')} [association='multi'] multi; use multiple associations (one after the other) if needed to transfer the instances (default), * single; always use a single association * @param {number} timeout timeout for connection requests (default: unlimited) * @param {number} [acseTimeout=30] seconds timeout for ACSE messages * @param {number} dimseTimeout seconds timeout for DIMSE messages (default: unlimited) * @param {number} [maxPDU=131072] set max receive pdu to number of bytes (4096..131072) * @param {number} [maxSendPDU=131072] restrict max send pdu to n bytes (4096..131072) * @param {string} reportFile create a detailed report on the transfer (if successful) and write it to text file reportFile */ constructor({ peer, port = 104, inputFileFormat, inputFiles, scanPattern, recurse, decompress, compression, noHalt, noIllegalProposal, noUidChecks, AETitle, calledAETitle, association, timeout, acseTimeout = 30, dimseTimeout, maxPDU = 131072, maxSendPDU = 131072, reportFile, }) { super({binary: findDCMTK().dcmsend, events}) this.#port = port this.#AETitle = AETitle this.#acseTimeout = acseTimeout this.#dimseTimeout = dimseTimeout this.#maxPDU = maxPDU this.#peer = peer this.#inputFileFormat = inputFileFormat this.#inputFiles = inputFiles this.#scanPattern = scanPattern this.#recurse = recurse this.#decompress = decompress this.#compression = compression this.#noHalt = noHalt this.#noIllegalProposal = noIllegalProposal this.#noUidChecks = noUidChecks this.#calledAETitle = calledAETitle this.#association = association this.#timeout = timeout this.#maxSendPDU = maxSendPDU this.#reportFile = reportFile if (maxPDU % maxSendPDU !== 0) { throw new Error(`Invalid maxPDU ${maxPDU} and maxSendPDU ${maxSendPDU}! maxPDU % maxSendPDU === 0 must be true!`) } } /** * * @param peer * @param port * @param dcmFileIn * @param AETitle * @param calledAETitle * @return {string[]} */ #buildCommand({peer, port, dcmFileIn, AETitle, calledAETitle}) { const command = [] this.peer = peer || this.peer this.port = port || this.port this.AETitle = AETitle || this.AETitle this.calledAETitle = calledAETitle || this.calledAETitle if (!this.peer) { throw new Error('"peer" cannot be undefined.') } if (!this.port) { throw new Error('"port" cannot be undefined.') } if (!dcmFileIn) { throw new Error('"dcmFileIn" cannot be undefined.') } command.push(this.peer, this.port, dcmFileIn, '--debug') if (this.inputFileFormat === 'formatOrData') { command.push('--read-file') } else if (this.inputFileFormat === 'format') { command.push('--read-file-only') } else if (this.inputFileFormat === 'data') { command.push('--read-dataset') } if (this.inputFiles === 'dicomdir') { command.push('--read-from-dicomdir') } else if (this.inputFiles === 'scan') { command.push('--scan-directories') } if (this.scanPattern) { if (this.inputFiles !== 'scan') { throw new Error('"scanPattern" called without "inputFileFormat = scan".') } command.push('--scan-pattern', this.scanPattern) } if (this.recurse) { command.push('--recurse') } if (this.decompress === 'never') { command.push('--decompress-never') } else if (this.decompress === 'lossless') { command.push('--decompress-lossless') } else if (this.decompress === 'lossy') { command.push('--decompress-lossy') } if (this.compression !== undefined) { command.push('--compression-level', this.compression) } if (this.noHalt) { command.push('--no-halt') } if (this.noIllegalProposal) { command.push('--no-illegal-proposal') } if (this.noUidChecks) { command.push('--no-uid-checks') } if (this.AETitle) { command.push('--aetitle', this.AETitle) } if (this.calledAETitle) { command.push('--call', this.calledAETitle) } if (this.association === 'multi') { command.push('--multi-associations') } if (this.association === 'single') { command.push('--single-associations') } if (this.timeout) { command.push('--timeout', this.timeout) } if (this.acseTimeout) { command.push('--acse-timeout', this.acseTimeout) } if (this.dimseTimeout) { command.push('--dimse-timeout', this.dimseTimeout) } if (this.maxPDU) { command.push('--max-pdu', this.maxPDU) } if (this.maxSendPDU) { command.push('--max-send-pdu', this.maxSendPDU) } if (this.reportFile) { command.push('--create-report-file', this.reportFile) } return command } /** * Send dicom * @param {string} [peer=] ip or hostname of DICOM peer * @param {number} [port=] port number to listen on * @param {string} dcmFileIn DICOM file or directory to be transmitted * @param {string=} [AETitle='DCMSEND'] my AE title * @param {string=} [calledAETitle='ANY-SCP'] called AE title of peer (default: ANY-SCP) */ send({peer, port, dcmFileIn, AETitle, calledAETitle}) { return new Promise((resolve, reject) => { this.start(this.#buildCommand({peer, port, dcmFileIn, AETitle, calledAETitle}), 100) this.once('exit', (msg) => resolve(msg)) }) } async listDecoders() { return await this.execute([this._binary, '--debug', '--list-decoders']) } //region Getters/Setters get peer() { return this.#peer } set peer(value) { this.#peer = value } get port() { return this.#port } set port(value) { this.#port = value } get inputFileFormat() { return this.#inputFileFormat } set inputFileFormat(value) { this.#inputFileFormat = value } get inputFiles() { return this.#inputFiles } set inputFiles(value) { this.#inputFiles = value } get scanPattern() { return this.#scanPattern } set scanPattern(value) { this.#scanPattern = value } get recurse() { return this.#recurse } set recurse(value) { this.#recurse = value } get decompress() { return this.#decompress } set decompress(value) { this.#decompress = value } get compression() { return this.#compression } set compression(value) { this.#compression = value } get noHalt() { return this.#noHalt } set noHalt(value) { this.#noHalt = value } get noIllegalProposal() { return this.#noIllegalProposal } set noIllegalProposal(value) { this.#noIllegalProposal = value } get noUidChecks() { return this.#noUidChecks } set noUidChecks(value) { this.#noUidChecks = value } get AETitle() { return this.#AETitle } set AETitle(value) { this.#AETitle = value } get calledAETitle() { return this.#calledAETitle } set calledAETitle(value) { this.#calledAETitle = value } get association() { return this.#association } set association(value) { this.#association = value } get timeout() { return this.#timeout } set timeout(value) { this.#timeout = value } get acseTimeout() { return this.#acseTimeout } set acseTimeout(value) { this.#acseTimeout = value } get dimseTimeout() { return this.#dimseTimeout } set dimseTimeout(value) { this.#dimseTimeout = value } get maxPDU() { return this.#maxPDU } set maxPDU(value) { this.#maxPDU = value } get maxSendPDU() { return this.#maxSendPDU } set maxSendPDU(value) { this.#maxSendPDU = value } get reportFile() { return this.#reportFile } set reportFile(value) { this.#reportFile = value } //endregion }
JavaScript
class Wrapper extends Component { render() { return <Cite {...this.props}>{this.props.children}</Cite>; } }
JavaScript
class NetworkDetailsContainer extends React.Component { constructor(props) { super(props); } componentDidMount() { const networkId = this.props.match.params.id this.props.fetchData('/networks/' + networkId + '/'); // this.props.graphFetchData('/graphs/' + networkId + '/'); } render() { const links = [ { 'route': '/networks/', 'name': 'Networks', 'active': false }, { 'route': '/networks/' + this.props.hosts.network.id, 'name': this.props.hosts.network.name, 'active': true } ]; return ( <div> <BreadcrumbComponent links={links}/> <HeaderComponent title={this.props.hosts.network.name} subtitle={this.props.hosts.total + ' Hosts'} icon='sitemap' isLoading={this.props.isLoading}/> <NetworkDetailComponent {...this.props} /> </div> ); } }
JavaScript
class Search { constructor(query) { this.query = query; } async getResults() { //for new browsers-HTTP request //fetch //FAMOUS HTTP REQUEST LIBRARY AXIOS key , query, sort, page //for mac we may need proxy crossorigin,cors-anywhere etc to be able to allow requests from domains to other domains(CORS) try { const res = await axios(`https://www.food2fork.com/api/search?key=${key}&q=${this.query}`); this.result = res.data.recipes; //console.log(this.result); } catch (error) { alert(error); } } }
JavaScript
class Cluster { constructor (url) { // Turn the broker into an event emitter Emitter(this); // create a subscriber client this.redisSubscriber = redis.createClient(url); this.redisSubscriber.on('error', (err) => debug('Error', err)); this.redisSubscriber.subscribe(REDIS_CHANNEL); this.redisSubscriber.on('message', (channel, message) => this._receive(message)); // create a publisher client this.redisPublisher = redis.createClient(url); this.redisPublisher.on('error', (err) => debug('Error', err)); } /** * Send a signal to the other servers in the cluster * @param {{from: string, to: string, signal: Object}} params */ signal (params) { this._send('signal', params); } /** * Ask all servers whether they know a certain peer * @param {string} id * @return {Promise.<boolean, Error>} Resolves with `true` if any of the servers * knows this peer, else resolves with `false` */ exists (id) { return this._getSubscriberCount() .catch(err => { debug('Error', err); return Infinity; // this will simply wait until the timeout before concluding that a peer is not found }) .then(count => { return new Promise((resolve, reject) => { let responses = 0; // number of responses let callback = (response) => { if (response.id !== id) { return; } responses++; if (response.found || responses === count) { // a server responded with found=true, or all servers have responded this.off('found', callback); resolve(response.found); } }; // cancel listening after a timeout setTimeout(() => this.off('found', callback), TIMEOUT); // listen for found responses this.on('found', callback); // ask all servers whether they know this peer this._send('find', {id}); }); }); } /** * Publish a message via Redis. The message is send as stingified json * structured as {type: string, data: *}` * @param {string} type * @param {*} data * @private */ _send (type, data) { let message = {type, data}; debug('send message', message); this.redisPublisher.publish(REDIS_CHANNEL, JSON.stringify(message)); } /** * Receive a stringified message * @param {string} message Message is structured as * @private */ _receive (message) { debug('receive message', message); let json = JSON.parse(message); if (json.type === 'signal') { this.emit('signal', json.data); } if (json.type === 'find') { this.emit('find', json.data); // send a response let id = json.data.id; let socket = find(id); this._send('found', {id, found: socket ? true : false}); } if (json.type === 'found') { this.emit('found', json.data) } } /** * Retrieve the number of subscribers on our REDIS_CHANNEL from redis * @return {Promise.<number, Error>} * @private */ _getSubscriberCount () { return new Promise((resolve, reject) => { this.redisPublisher.send_command('pubsub', ['numsub', REDIS_CHANNEL], (err, result) => { if (err) { reject(err); } else { // result is an Array like ['linkup', 123] let count = result[1]; resolve(count); } }); }); } }
JavaScript
class GoogleAnalytics { /** * Initialize the Google Anlytics tracker * * @param {string} trackingID The tracking ID, of the form UA-XXXXXXXXX-X * @param {string} appName Application Name (user defined) * @param {object} additionalParams User parameters to add/override the defaults */ constructor(trackingID, appName, additionalParams = {}) { this.trackingID = trackingID; this.appName = appName; this.clientID = localStorage.getItem(GoogleAnalytics.CLIENT_ID_KEY); this.hasCreatedSession = false; this.debug = false; this.useValidator = false; if (!this.clientID) { this.clientID = UUID(); localStorage.setItem(GoogleAnalytics.CLIENT_ID_KEY, this.clientID); } const defaultParams = { // General: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#general v: 1, // protocol version. must be 1 tid: this.trackingID, ds: 'app', // data source. mobile app SDKs use "app" // User: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#user cid: this.clientID, // System Info: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#system ul: Settings.language, // App Tracking: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#apptracking an: this.appName, aid: Device.appIdentifier, av: Device.appVersion, }; this.commonParameters = { ...defaultParams, ...additionalParams }; } static get CLIENT_ID_KEY() { return 'tvOS_GoogleAnalyticsClientID'; } get debug() { return this.debugFlag; } set debug(flag) { this.debugFlag = flag; } get useValidator() { return this.validatorFlag; } set useValidator(flag) { this.validatorFlag = flag; } /** * Screenview is used to track when a user goes to a particular screen in your application. * * @param {string} screenName required */ screenview(screenName) { const params = { t: 'screenview', cd: screenName, }; this.postParams(params); } /** * Track an application defined event * * @param {string} category The event category. Required. * @param {string} action The event action. Required. * @param {string} label The event label. Optional. * @param {integer} value The event value. Optional. */ event(category, action, label, value) { const params = { t: 'event', ec: category, ea: action, }; if (label) { params.el = label; } if (value) { params.ev = value; } this.postParams(params); } /** * Process the post parameters into a post body, starting a new session if needed. * * @param {object} params An object of property/value arrays for GA parameters */ postParams(params) { const sessionParams = {}; if (!this.hasCreatedSession) { this.log('Starting new session'); this.hasCreatedSession = true; sessionParams.sc = 'start'; } const requestParams = { ...this.commonParameters, ...params, ...sessionParams }; const payload = Object .entries(requestParams) .map(param => `${param[0]}=${encodeURIComponent(param[1])}`).join('&'); this.post(payload); } /** * Post the payload to Google Analytics * * @param {string} payload The parameter body for the measurement request. */ post(payload) { const request = new XMLHttpRequest(); // Post is fire and forget, but log the response for developer info/discovery request.onreadystatechange = () => { if (request.readyState === 4) { if (request.status >= 200 && request.status < 300) { this.log('ANALYTICS RESPONSE', request); } else { console.warn(`Google Analytics error response: ${request.status}`, request); } } }; const url = this.useValidator ? 'https://www.google-analytics.com/debug/collect' : 'https://www.google-analytics.com/collect'; this.log('ANALYTICS REQUEST PAYLOAD', payload); request.open('POST', url); request.send(payload); } /** * Centralized logging method. * * @param {*} message The message to send to the console log * @param {*} data Spread of additional values to log */ log(message, ...data) { if (this.debug) { console.log(message, ...data); } } }
JavaScript
class TripSearchResultSegment { /** * Create a new Trip Search Result Segment from the provided Trip * @param {Trip} trip The Trip that makes up this Segment * @param {Stop|string} enter The Stop or Stop ID where the Segment starts * @param {Stop|string} exit The Stop or Stop ID where the Segment ends */ constructor(trip, enter, exit) { /** * The Trip that makes up this Segment * @type {Trip} */ this.trip = trip; /** * The StopTime where the Segment starts * @type {StopTime} */ this.enter = trip.getStopTime(enter); /** * The StopTime where the Segment ends * @type {StopTime} */ this.exit = trip.getStopTime(exit); /** * The Trip Origin StopTime * @type {StopTime} */ this.origin = this.trip.stopTimes[0]; /** * The Trip Destination StopTime * @type {StopTime} */ this.destination = this.trip.stopTimes[this.trip.stopTimes.length-1]; /** * Travel Time (in minutes) on this Segment * @type {number} */ this.travelTime = (this.exit.arrival.toTimestamp() - this.enter.departure.toTimestamp())/60000; } }
JavaScript
class SimpleEntity extends Entity { entity() { return this._entity; } }
JavaScript
class Course { constructor(code, name, credit) { this.code = code; this.name = name; this.credit = credit; } }
JavaScript
class SimpleDataMapper { constructor(reportEnabled = false) { this.reportEnabled = false; this.maps = []; this.collects = []; this.extras = []; this.caseStyle = CaseStyle_1.CaseStyle.ASIS; this.init(reportEnabled); } map(from, to, cb) { to = to ? to : from; this.maps.push({ from, to, cb }); return this; } collect(fields, to, cb) { if (typeof to === "function") { cb = to; to = undefined; } else { to = to ? to : fields.join("_"); } this.collects.push({ fields, to, cb }); return this; } add(fieldName, data) { this.extras.push({ fieldName, data }); return this; } /** * This will transform source data to the destination. * * @param srcData */ transform(srcData) { const maps = this.maps; let transformedData = {}; const transformed = []; const skipped = []; const collected = []; const uncollected = []; const getNestedData = (nestedData) => { const paths = nestedData.split("."); let currentData = Object.assign({}, srcData); paths.forEach((p) => { if (currentData) { // If we have array notation (somearray[n]) then capture groups const matches = p.match(/(.*)\[(.*)\]/); if (matches) { const g1 = matches[1]; const g2 = matches[2]; currentData = currentData[g1] ? currentData[g1][g2] : undefined; } else { currentData = currentData[p]; } } }); return currentData; }; const getTargetData = (transformedData, to) => { let target = transformedData; const fieldNames = to.split("."); const lastFieldName = fieldNames[fieldNames.length - 1]; for (let i = 0; i < fieldNames.length - 1; i++) { const fieldName = fieldNames[i]; target[fieldName] = target[fieldName] ? target[fieldName] : {}; target = target[fieldName]; } return { target, lastFieldName }; }; maps.forEach(({ from, to, cb }) => { const nestedData = getNestedData(from); if (nestedData) { const targetData = getTargetData(transformedData, to); targetData.target[targetData.lastFieldName] = cb ? cb(nestedData) : nestedData; transformed.push(`${from} -> ${to}`); } else { skipped.push(from); } }); this.collects.forEach(({ fields, to, cb }) => { const vals = fields.reduce((acc, cur) => { const nestedData = getNestedData(cur); if (nestedData) { acc.push(nestedData); collected.push(cur); } else { uncollected.push(cur); } return acc; }, []); const info = cb ? cb(vals) : vals.join(" "); if (info) { if (to && typeof to === "string") { const targetData = getTargetData(transformedData, to); targetData.target[targetData.lastFieldName] = info; } else { transformedData = Object.assign({}, transformedData, info); } } }); // Add extra data this.extras.forEach(extra => { let extraData = {}; extraData[extra.fieldName] = extra.data; transformedData = Object.assign({}, transformedData, extraData); }); if (this.caseStyle != CaseStyle_1.CaseStyle.ASIS) { // If transformedData is empty (no mapping applied) then use the srcData here directly! if (Object.keys(transformedData).length === 0) { transformedData = Object.assign({}, srcData); } transformedData = this.doChangeCase(transformedData, this.caseStyle); } // Show report if enabled if (this.reportEnabled) { const dataKeys = Object.keys(srcData); const untransformed = []; dataKeys.forEach(key => { const found = this.maps.findIndex(m => m.from === key); if (found === -1) { if (key !== "__reports__") { untransformed.push(key); } } }); transformed.sort(); untransformed.sort(); skipped.sort(); collected.sort(); uncollected.sort(); transformedData.__reports__ = { transformation: { transformed, untransformed, skipped, }, collection: { collected, uncollected } }; } return transformedData; } reset() { this.init(); return this; } report(enabled) { this.reportEnabled = enabled; return this; } mapToCamelCase(options) { this.caseStyle = CaseStyle_1.CaseStyle.CAMEL; this.caseStyleOptions = options; return this; } mapToSnakeCase(options) { this.caseStyle = CaseStyle_1.CaseStyle.SNAKE; this.caseStyleOptions = options; return this; } mapToLowerCase(options) { this.caseStyle = CaseStyle_1.CaseStyle.LOWER; this.caseStyleOptions = options; return this; } mapToUpperCase(options) { this.caseStyle = CaseStyle_1.CaseStyle.UPPER; this.caseStyleOptions = options; return this; } // --- Static Methods --- static create(reportEnabled = false) { return new SimpleDataMapper(reportEnabled); } static changeCase(obj, caseStyle, options) { const mapper = SimpleDataMapper.create(); mapper.caseStyle = caseStyle; mapper.caseStyleOptions = options; return mapper.transform(obj); } static toCamelCase(obj, options) { return SimpleDataMapper.create().mapToCamelCase(options).transform(obj); } static toSnakeCase(obj, options) { return SimpleDataMapper.create().mapToSnakeCase(options).transform(obj); } static toLowerCase(obj, options) { return SimpleDataMapper.create().mapToLowerCase(options).transform(obj); } static toUpperCase(obj, options) { return SimpleDataMapper.create().mapToUpperCase(options).transform(obj); } // --- Private Methods --- init(reportEnabled = false) { this.reportEnabled = reportEnabled; this.maps = []; this.collects = []; this.extras = []; this.caseStyle = CaseStyle_1.CaseStyle.ASIS; return this; } doChangeCase(obj, caseStyle) { const keep = (str) => { if (this.caseStyleOptions) { if (this.caseStyleOptions.keep && this.caseStyleOptions.keep.includes(str)) return true; } return false; }; const keepChildNodes = (str) => { if (keep(str)) { if (this.caseStyleOptions && this.caseStyleOptions.keepChildNodes) { return true; } } return false; }; const toCamelCase = (str) => { if (keep(str)) return str; return str.replace(/([-_][a-z])/ig, ($1) => { return $1.toUpperCase() .replace("-", "") .replace("_", ""); }); }; const toSnakeCase = (str) => { if (keep(str)) return str; return str.split(/(?=[A-Z])/).join("_").toLowerCase(); }; const toLowerCase = (str) => { if (keep(str)) return str; return str.toLowerCase(); }; const toUpperCase = (str) => { if (keep(str)) return str; return str.toUpperCase(); }; const getBaseFunction = (caseStyle) => { let fn; switch (caseStyle) { case CaseStyle_1.CaseStyle.CAMEL: fn = toCamelCase; break; case CaseStyle_1.CaseStyle.SNAKE: fn = toSnakeCase; break; case CaseStyle_1.CaseStyle.LOWER: fn = toLowerCase; break; case CaseStyle_1.CaseStyle.UPPER: fn = toUpperCase; break; default: break; } return fn; }; const startProcess = (obj, caseStyle) => { if (typeof obj !== "object") return obj; const baseFunction = getBaseFunction(caseStyle); if (!baseFunction) return; const fieldNames = Object.keys(obj); return fieldNames .map(fieldName => { const val = obj[fieldName]; if (!keepChildNodes(fieldName)) { if (Array.isArray(val)) { return { [baseFunction(fieldName)]: val.map(item => { return startProcess(item, caseStyle); }) }; } else if (typeof val === "object") { return { [baseFunction(fieldName)]: startProcess(val, caseStyle) }; } } return { [baseFunction(fieldName)]: val }; }) .reduce((acc, cur) => { const key = Object.keys(cur)[0]; acc[key] = cur[key]; return acc; }, {}); }; return startProcess(obj, caseStyle); } }
JavaScript
class WebStorage { save (key, val) { if (typeof localStorage !== 'undefined') { localStorage.setItem(key, val); return true; } return false; } /* Note: localStorage will always return a string /* You may need to coerce the type after loading */ load (key) { if (typeof localStorage !== 'undefined') { return localStorage.getItem(key); } return '' } }
JavaScript
class Contact extends Component { constructor(props) { super(props) this.state = {} } render() { return ( <div className="contact-wrapper"> <ContactForm /> <Locations /> </div> ) } }
JavaScript
class BatchReferencesFinder { /** * Constructor of Find * * @param editor editor text */ constructor(text) { this.text = text; } /** * Find the declaration of the term * * @param term Term to find * @param uri current source uri */ findReferences(term, uri) { return new Promise((resolve, reject) => { new BatchReferencesProvider_1.BatchReferencesProvider() .findReferences(this.text, term) .then((positions) => { const result = this.convertBatchPositionsToLocations(positions, uri); resolve(result); }) .catch(() => reject()); }); } convertBatchPositionsToLocations(positions, uri) { const result = []; positions.forEach(position => { const range = vscode_languageserver_1.Range.create(vscode_languageserver_1.Position.create(position.line, position.column), vscode_languageserver_1.Position.create(position.line, position.column)); result.push({ uri: uri, range: range }); }); return result; } }
JavaScript
class MyRenderingElements extends Component { render() { return <h1>MyRenderingElements</h1>; } }
JavaScript
class LoadingMessageComponent { constructor(text, side, utils) { this.text = text; this.side = side; this.utils = utils; } /** * Renders the loading message elements * <div class="loading-message"> * <div class="message-bubble right | left"> * <div class="message-content"> * {SpinnerComponent} * <span>{text}</span> * </div> * </div> * <div class="clear"></div> * </div> * @return {HTMLElement} */ render() { this.element = this.utils.createDiv(['loading-message', this.side]); let bubble = this.utils.createDiv(['message-bubble']); let content = this.utils.createDiv(['message-content']); content.appendChild(new SpinnerComponent(this.utils).render()); let text = this.utils.createSpan(); text.innerText = this.text; content.appendChild(text); bubble.appendChild(content); this.element.appendChild(bubble); this.element.appendChild(this.utils.createDiv(['clear'])); return this.element; } remove() { this.element.remove(); } }
JavaScript
class ModvMapper extends LitElement { static get properties() { return { width: { type: Number }, height: { type: Number }, colors: { type: Array }, slots: { type: Array } } } render() { const { width, height, colors, slots } = this return html` <section> <modv-color-grid width="${width}" height="${height}" .colors="${defaultValue(colors, [])}" .slots="${slots}" ></modv-color-grid> </section> ` } }
JavaScript
class Client extends TCPBase { getHeader() { return this.read(8); } getBodyLength(header) { return header.readInt32BE(4); } decode(body, header) { return { id: header.readInt32BE(0), data: body, }; } // heartbeat packet get heartBeatPacket() { return new Buffer([ 255, 255, 255, 255, 0, 0, 0, 0 ]); } }
JavaScript
class ActorQueryOperationSlice extends bus_query_operation_1.ActorQueryOperationTypedMediated { constructor(args) { super(args, 'slice'); } async testOperation(pattern, context) { return true; } async runOperation(pattern, context) { // Resolve the input const output = await this.mediatorQueryOperation.mediate({ operation: pattern.input, context }); const metadata = this.sliceMetadata(output, pattern); if (output.type === 'bindings') { const bindingsOutput = output; const bindingsStream = this.sliceStream(bindingsOutput.bindingsStream, pattern); return { type: 'bindings', bindingsStream, metadata, variables: bindingsOutput.variables }; } if (output.type === 'quads') { const quadOutput = output; const quadStream = this.sliceStream(quadOutput.quadStream, pattern); return { type: 'quads', quadStream, metadata }; } throw new Error(`Invalid query output type: Expected 'bindings' or 'quads' but got '${output.type}'`); } // Slice the stream based on the pattern values sliceStream(stream, pattern) { const hasLength = !!pattern.length || pattern.length === 0; return stream.range(pattern.start, hasLength ? pattern.start + pattern.length - 1 : Infinity); } // If we find metadata, apply slicing on the total number of items sliceMetadata(output, pattern) { const hasLength = !!pattern.length || pattern.length === 0; return !output.metadata ? undefined : () => output.metadata() .then((subMetadata) => { let totalItems = subMetadata.totalItems; if (isFinite(totalItems)) { totalItems = Math.max(0, totalItems - pattern.start); if (hasLength) { totalItems = Math.min(totalItems, pattern.length); } } return Object.assign({}, subMetadata, { totalItems }); }); } }
JavaScript
class SidebarModalExample extends React.Component { handleUnderstood = () => { this.props.resolve('Understood'); } handleDontRead = () => { this.props.dismiss("Doesn't care"); } render() { return <SidebarModal position="top" resolve={this.props.resolve} dismiss={this.props.dismiss}> <div style={styles.container}> <h4>Note</h4> <p>This is modal, it's <b>not thought to be sidenav</b> !</p> <p>You can use it to ask question or to fill forms...</p> <div> <a style={styles.cancelBtn} onClick={this.handleDontRead}> I'm just testing </a> <a style={styles.okBtn} onClick={this.handleUnderstood}> I got it ! </a> </div> </div> </SidebarModal>; } }
JavaScript
class UserRecorderTracker extends BaseTracker { /** * Static method for getting the tracker from window * @returns {Object | Proxy} the user-recorder object from the provider * if the function is not existed, this method will return Proxy to avoid error * @static */ static getTracker() { if (window.userRecorder) { return window.userRecorder } debug("Warning! Seems like window.userRecorder is undefined") return new Proxy( {}, { get: () => () => {} } ) } /** * identity the user information to provider script for mapping user on user recording provider * @param {Object} profile the user data object */ identifyUser(profile) { debug("=== UserRecorderTracker identifyUser is running... 💫 ===") debug("user data %o => ", profile) UserRecorderTracker.getTracker().identify(profile) debug("=== UserRecorderTracker identifyUser finished ✅ ===") } /** * This method is removing session recording with Local Storage and Cookie * for getting a newer recording session for recording correct a new user logged in */ logout() { debug("=== UserRecorderTracker logout is running... 💫 ===") UserRecorderTracker.getTracker().clearSession() debug("=== UserRecorderTracker logout finished ✅ ===") } }
JavaScript
class Mock { constructor(){ } // This will be skipped get foobar(){ } // This will be skipped set foobar(val){ } /** * This property will be memoized * * @type {string} * @column * @test */ get dbProperty(){ return privateProps.dbProperty; } /** * This property will be memoized * * @type {string} * @column * @test */ set dbProperty(val){ privateProps.dbProperty = val; } /** * This property will be memoized as read-only, unless a setter was found. * * @type {string} * @test */ get readOnlyProperty(){ return privateProps.readOnlyProperty; } doThing(){ } /** * This will be skipped * */ doNothing(){ } /** * This should be picked up * * @test foo * @bar */ doSomething(){ } /** * This should be picked up * * @test foo * @param {string} foo * @param {int} bar * @return {string | int} */ doSomethingElse(foo, bar){ return(foo ? 0 : ''); } /** * This should be picked up * * @test foo * @param {string} foo */ doAnotherThing(foo) { /** * This should be ignored. * @see adadadwad */ doThing(); } /** * This should be picked up * @test foo * @param {object} foo */ deconstructedMethod(bar, {foo}){ doThing(); } }
JavaScript
class TrackingBoundary extends React.Component { constructor() { super(...arguments); _defineProperty(this, "handleTrackContext", (_ref) => { let { nativeEvent } = _ref; const { name } = this.props; if (!name) { return; } if (nativeEvent.trackingContext) { nativeEvent.trackingContext.push(name); } else { nativeEvent.trackingContext = [name]; } }); } render() { const { children, name } = this.props; if (!name) { return children; } return React.createElement("tracking-boundary", { "data-tracking-name": name, onClick: this.handleTrackContext, onKeyDown: this.handleTrackContext }, children); } }
JavaScript
class Joystick { _autoReset; _radius; _centerX; _centerY; _x; _y; _lastPosX = 0; _lastPosY = 0; _offsetX = 0; _offsetY = 0; _distance = 0; _blockXAxis = false; _blockYAxis = false; error(message) { this.error("[Joystick - error]: " + message); } constructor(interactionHandler, id, radius, autoReset, joystickSizeRatio = 0.5) { this._jsOuter = document.getElementById(id); if (null === this._jsOuter) { this.error("Could not find joystick " + id); } this._autoReset = autoReset; this._radius = radius; // Outer part style this._jsOuter.style.width = (this._radius * 2) + "px"; this._jsOuter.style.height = (this._radius * 2) + "px"; this._jsOuter.style.borderRadius = "50%"; this._centerX = this._jsOuter.offsetLeft + this._jsOuter.offsetWidth / 2; this._centerY = this._jsOuter.offsetTop + this._jsOuter.offsetHeight / 2; // Create inner part this._jsOuter.innerHTML = "<div id='" + id + "_inner'/>"; this._jsInner = this._jsOuter.querySelector("#" + id + "_inner"); if (null === this._jsInner) { this.error("Could not find " + id + "_inner"); } // Calc inner part radius this._innerRadius = (this._radius * joystickSizeRatio); // Set inner part initial position if ("fixed" === this._jsOuter.style.position) { this._x = this._centerX; this._y = this._centerY; } else { this._x = this._jsOuter.offsetWidth / 2; this._y = this._jsOuter.offsetHeight / 2; } // Inner part style this._jsInner.style.width = (this._innerRadius * 2) + "px"; this._jsInner.style.height = (this._innerRadius * 2) + "px"; this._jsInner.style.zindex = this._jsOuter.zindex + 1; this._jsInner.style.position = this._jsOuter.style.position; this._jsInner.style.borderRadius = "50%"; // Register for interaction callback interactionHandler.registerObserver(this._jsInner, this); this.updateUI(); } get getThis() { return this; } get getDistance() { return this._distance; } get getXCoord() { return this._lastPosX; } get getYCoord() { return this._lastPosY; } get outer() { return this._jsOuter; } get inner() { return this._jsInner; } blockXAxis(block) { if (typeof (block) !== "boolean") { this.error("Invalid argument type"); } this._blockXAxis = block; } blockYAxis(block) { if (typeof (block) !== "boolean") { this.error("Invalid argument type"); } this._blockYAxis = block; } reset() { if ("fixed" === this._jsOuter.style.position) { this._x = this._centerX; this._y = this._centerY; } else { this._x = this._jsOuter.offsetWidth / 2; this._y = this._jsOuter.offsetHeight / 2; } this._distance = 0; this._offsetX = 0; this._offsetY = 0; this.updateUI(); } updateUI() { this._jsInner.style.left = (this._x - this._innerRadius) + "px"; this._jsInner.style.top = (this._y - this._innerRadius) + "px"; } handleInteraction(type, interactionData) { switch (type) { case "move": if (!this._blockXAxis) { this._lastPosX = this._offsetX + (interactionData._x - interactionData._startX); } if (!this._blockYAxis) { this._lastPosY = this._offsetY + (interactionData._y - interactionData._startY); } this._distance = Math.sqrt(this._lastPosX * this._lastPosX + this._lastPosY * this._lastPosY); if (this._distance > this._radius) { const ratio = this._radius / this._distance; this._lastPosX *= ratio; this._lastPosY *= ratio; this._distance = this._radius; } if ("fixed" === this._jsOuter.style.position) { this._x = this._centerX + this._lastPosX; this._y = this._centerY + this._lastPosY; } else { this._x = this._jsOuter.offsetWidth / 2 + this._lastPosX; this._y = this._jsOuter.offsetHeight / 2 + this._lastPosY; } this.updateUI(); break; case "up": if (this._autoReset) { this.reset(); } else { this._offsetX = this._lastPosX; this._offsetY = this._lastPosY; } break; } } }
JavaScript
class Tree { /** * Creates a Tree Object */ constructor() { } /** * Creates a node/edge structure and renders a tree layout based on the input data * * @param treeData an array of objects that contain parent/child information. */ createTree(treeData) { // ******* TODO: PART VI ******* var margin = {top: 20, right: 120, bottom: 20, left: 120}; //Create a tree and give it a size() of 800 by 300. let treemap = d3.tree().size([800, 300]); //Create a root for the tree using d3.stratify(); let data = d3.stratify() .id(function(d) { let name=d.Team+d.Opponent; let id=d.id; id=id.substring(name.length,id.length); return id; }) .parentId(function(d) { return d.ParentGame; }) (treeData); data.each(function(d) { d.name = d.id; }); var nodes = d3.hierarchy(data, function(d) { return d.children; }); //Add nodes and links to the tree. nodes = treemap(nodes); var svg = d3.select("#tree"); let g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // adds the links between the nodes var link = g.selectAll(".link") .data( nodes.descendants().slice(1)) .enter().append("path") .attr("class", function(d) { return "link link-" + d.data.data.Team + "-" + d.data.data.Opponent+" link-"+d.data.data.Team+ " link-"+d.data.parent.data.Team+"-"+d.data.data.Team; } ) .attr("d", function(d) { return "M" + d.y + "," + d.x + "C" + (d.y + d.parent.y) / 2 + "," + d.x + " " + (d.y + d.parent.y) / 2 + "," + d.parent.x + " " + d.parent.y + "," + d.parent.x; }); // adds each node as a group var node = g.selectAll(".node") .data(nodes.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); }) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); node.append("circle") .attr("r",10) .attr("fill", function(d){ if(d.data.data.Wins==1){ return "#034e7b"; }else{ return "#cb181d"; } }); // adds the text to the node node.append("text") .attr("dy", ".35em") .attr("x", function(d) { return d.children ? -13 : 13; }) .style("text-anchor", function(d) { return d.children ? "end" : "start"; }) .text(function(d) { return d.data.data.Team; }) .attr("class", function(d) { return "link-" + d.data.data.Team + " link-" + d.data.data.Team+"-"+ d.data.data.Opponent; }); }; /** * Updates the highlighting in the tree based on the selected team. * Highlights the appropriate team nodes and labels. * * @param row a string specifying which team was selected in the table. */ updateTree(row) { // ******* TODO: PART VII ******* this.clearTree(); if(row.value["type"]=="aggregate" && row.value) { let data=d3.selectAll("#tree").selectAll("text"); data.filter(function (d) { if(row.key===d.data.data.Team) { return true; } }).classed("highlight-text", true); data=d3.selectAll("#tree").selectAll("path"); data=data.filter(function (d) { if(row.key===d.data.data.Team&&row.key===d.data.parent.data.Team) { return true; } }); data.classed("highlight-link", true); }else { d3.selectAll(".link-" + row.value.Opponent+"-"+row.key).filter("text").classed("highlight-text", true); d3.selectAll(".link-" + row.key+"-"+row.value.Opponent).filter("text").classed("highlight-text", true); d3.selectAll(".link-" + row.value.Opponent+"-"+row.key).filter("path").classed("highlight-link", true); d3.selectAll(".link-" + row.key+"-"+row.value.Opponent).filter("path").classed("highlight-link", true); } } /** * Removes all highlighting from the tree. */ clearTree() { // ******* TODO: PART VII ******* // You only need two lines of code for this! No loops! d3.selectAll("text").classed("highlight-text",false); d3.selectAll("path").classed("highlight-link",false); } }
JavaScript
class IdFinder extends StateMachine { constructor(toggleId, toggle) { super(); this.toggleId = toggleId; this.toggle = toggle; this.promote(states.INITIAL); } tick() { switch (this.state) { case states.INITIAL: this.click(); break; case states.MENU: this.menu(); break; case states.ERROR: this.error(); break; default: this.error(); this.promote(states.ERROR, errors.INVARIANT); } } click() { refocus(() => this.toggle.click()); this.promote(states.MENU); } close() { refocus(() => this.toggle.click()); this.promote(states.DONE); } error() { refocus(() => this.toggle.click()); this.promote(states.ERROR, errors.NO_ID); } menu() { const menu = this.menuFilter(); // No menu yet, try again. if (!menu) return; const li = Array.from(menu.querySelectorAll("li")).filter(this.filter)[0]; if (!li) return; const endpoint = li.querySelector("a"); if (!endpoint) return; const url = endpoint.getAttribute("ajaxify"); try { this.id = new URL("https://facebook.com" + url).searchParams.get("id"); if (this.id) { this.url = url; this.close(); } else { this.error(); } } catch (e) { this.error(); } } menuFilter() { throw "Unimplemented!"; } filter() { throw "Unimplemented!"; } }
JavaScript
class Expandable extends React.Component { constructor(props){ super(props) this.myRef = React.createRef(); } componentDidMount(){ this.setMaxHeight(); } componentDidUpdate(){ this.setMaxHeight(); } setMaxHeight(){ let bodyElem = this.myRef.current const paddingVertical = 40 // Need to find a way to read it from css style let pixelMaxHeight = bodyElem.firstElementChild.clientHeight bodyElem.style.maxHeight = pixelMaxHeight + paddingVertical + "px" } render(){ return ( <div className="wal_acc_exp_container"> <div className="wal_acc_exp_header" onClick={this.props.toggleHandler}> { this.props.data.icon && <i className="material-icons">{this.props.data.icon}</i>} <p> {this.props.data.header} </p> </div> <div ref={this.myRef} className={"wal_acc_exp_body " + (this.props.collapsed ? "collapsed" : "" )} > <p> {this.props.data.body} </p> </div> </div> ) } }
JavaScript
class TimewiseMeasure { constructor(index, measures) { // this._index = index this._measures = measures } /** * Reference to the parent measures instance. * @member {TimewiseMeasures} */ get measures() { return this._measures } /** * Parts in timewise measure. * @type {Array.<Cell>} */ get parts() { return this._parts || (this._parts = []) } set parts(parts) { this._parts = parts } /** * Left bar of the measure. * @type {Bar} * @readonly */ get barLeft() { return this.parts[0].barLeft } /** * Right bar of the measure. * @type {Bar} * @readonly */ get barRight() { return this.parts[0].barRight } /** * Measure SVG group element. * @type {Snap.Element} * @readonly */ get el() { return this._el } /** * Minimun width of the measure. * @type {number} */ get minWidth() { var minWidth = 0 this.parts.forEach(function (cell) { minWidth = Math.max(minWidth, cell.minWidth) }) return minWidth + this.padding } /** * Reference to the parent system of this measure. * - (Getter) * - (Setter) The measure el will be created, and the height of the measure will be set. * @type {SystemLayout} */ get system() { return this._s } set system(system) { this._s = system this._el = system.el.g().addClass('mus-measure') } get padding() { const lo = this.layout.options return lo.measurePaddingRight + lo.measurePaddingLeft } get outerWidth() { return this.outerWidthLeft + this.outerWidthRight } get outerWidthLeft() { return this.layout.options.measurePaddingLeft + this.barLeftInSystem.width / 2 } get outerWidthRight() { return this.layout.options.measurePaddingRight + this.barRightInSystem.width / 2 } /** * Width of the measure. * @type {number} */ get width() { return this._w || (this._w = this.minWidth) } set width(w) { this._w = w this.parts.forEach(cell => { cell.width = w - this.outerWidth }) } get height() { return this.system.height } get minHeight() { const { partSep } = this.layout.options let minHeight = 0 this.parts.forEach(cell => { minHeight += cell.height + partSep }) return minHeight ? minHeight - partSep : 0 } /** * The x position of the measure in the system. * - (Getter) * - (Setter) Set x cause the measure element to translate. * @type {number} */ get x() { return this._x } set x(x) { this._x = x this.el.transform(Snap.matrix().translate(x, 0)) } /** * If the measure in the beginning of the system. * @type {boolean} * @readonly */ get inSystemBegin() { return this._sIndex === 0 } /** * If the measure in the end of the system. * @type {boolean} * @readonly */ get inSystemEnd() { return this._sIndex === this.system.measures.length - 1 } /** * Left bar of the measure in system. * @type {musje.Bar} * @readonly */ get barLeftInSystem() { return this.parts[0].barLeftInSystem } /** * Right bar of the measure in system. * @type {Bar} * @readonly */ get barRightInSystem() { return this.parts[0].barRightInSystem } /** * Flow the measure. */ flow() { this.parts.forEach(cell => { /** * Cell SVG group element. * @memberof CellLayout# * @alias el * @type {Snap.Element} * @readonly */ cell.el = this.el.g().addClass('mus-cell') cell.x = this.outerWidthLeft // cell.drawBox() }) } /** * Draw box of the cell. * @return {Snap.Element} The box SVG rect element. */ drawBox() { this._boxEl = this.el.rect(0, 0, this.width, this.height) .attr({ stroke: 'green', fill: 'none' }) } /** * Clear the box SVG element. */ clearBox() { this._boxEl.remove() this._boxEl = undefined } }
JavaScript
class NewPostHeader extends Component { render() { return ( <View style={styles.header}> <Text style={styles.headerText}>New Post</Text> </View> ) } }
JavaScript
class MapPage extends React.PureComponent { componentDidMount() { this.props.onLoadMaps() } //static get sagas() { // return mapSagas //} render() { return ( <article> <Helmet title="Map Editor" /> <ToolBar /> <MapEditor /> </article> ) } }
JavaScript
class ModelCache { /** * Create the model cache */ constructor(model, ...args) { this.__model = model; this.__args = args; this.__set = {}; } /** * Create a new model instance */ create(model, args) { return new model(...this.__args); } /** * Fetch all elements in the cache */ all() { return Object.assign({}, this.__set); } /** * Fetch an existing object and update it. * If it doesn't exist, create it * (Assumes first item in data is ID) */ fetch(id) { let item = this.__set[id]; if (item === undefined) { item = this.create(this.__model, this.__args); this.__set[id] = item; } return item; } /** * Update the cache */ update(data) { let ids = Object.assign({}, this.__set); for (let modelData of data) { let item = this.fetch(modelData[0]); item.__setData(modelData); delete ids[modelData[0]]; } for (let id in ids) { delete this.__set[id]; } return this; } }