language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class DataNode { /** * DataNode constructor. * * The created node will be frozen. * * @param {object} value The node value * @param {number} now The current update timestamp */ constructor(value, now) { this[priorityKey] = value['.priority']; this[valueKey] = value['.value']; if (this[priorityKey] != null && !isValidPriority(this[priorityKey])) { throw new Error(`Invalid node priority ${this[priorityKey]}`); } if (this[valueKey] != null && !isPrimitive(this[valueKey])) { throw new Error(`Invalid node value ${this[valueKey]}`); } const keys = value['.value'] === undefined ? Object.keys(value) : []; keys .filter(key => key !== '.value' && key !== '.priority') .forEach(key => { if (!isValidKey(key)) { throw new Error(`Invalid key "${key}"; it must not include [${invalidChar.join(',')}]`); } const childNode = DataNode.from(value[key], undefined, now); if (childNode.$isNull()) { return; } this[key] = childNode; }); if (this[valueKey] === undefined && Object.keys(this).length === 0) { this[valueKey] = null; } Object.freeze(this); } /** * Create a DataNode representing a null value. * * @return {DataNode} */ static null() { if (!nullNode) { nullNode = new DataNode({'.value': null}); } return nullNode; } /** * Create a DataNode from a compatible value. * * The value can be primitive value supported by Firebase, an object in the * Firebase data export format, a plain object, a DataNode or a mix of them. * * @param {any} value The node value * @param {any} [priority] The node priority * @param {number} [now] The current update timestamp * @return {DataNode} */ static from(value, priority, now) { if (value instanceof DataNode) { return value; } if (value == null || value['.value'] === null) { return DataNode.null(); } if (isPrimitive(value)) { return new DataNode({'.value': value, '.priority': priority}); } if (!isObject(value) && !Array.isArray(value)) { throw new Error(`Invalid data node type: ${value} (${typeof value})`); } priority = priority || value['.priority']; if (isPrimitive(value['.value'])) { return new DataNode({'.value': value['.value'], '.priority': priority}); } now = now || Date.now(); if (isServerValue(value)) { return new DataNode({'.value': convertServerValue(value, now), '.priority': priority}); } return new DataNode( Object.assign({}, value, {'.priority': priority, '.value': undefined}), now ); } /** * Returns the node priority. * * @return {any} */ $priority() { return this[priorityKey]; } /** * Returns the node value of a primitive or a plain object. * * @return {any} */ $value() { if (this[valueKey] !== undefined) { return this[valueKey]; } return Object.keys(this).reduce( (acc, key) => Object.assign(acc, {[key]: this[key].$value()}), {} ); } /** * Returns true if the node represent a null value. * * @return {boolean} */ $isNull() { return this[valueKey] === null; } /** * Returns true if the the node represent a primitive value (including null). * * @return {boolean} */ $isPrimitive() { return this[valueKey] !== undefined; } /** * Yield every child nodes. * * The callback can return true to cancel descending down a branch. Sibling * nodes would still get yield. * * @param {string} path Path to the current node * @param {function(path: string, parentPath: string, nodeKey: string): boolean} cb Callback receiving a node path */ $walk(path, cb) { Object.keys(this).forEach(key => { const nodePath = paths.join(path, key); const stop = cb(nodePath, path, key); if (stop) { return; } this[key].$walk(nodePath, cb); }); } /** * Return a child node. * * @param {string} path to the child. * @return {DataNode} */ $child(path) { return paths.split(path).reduce( (parent, key) => parent[key] || DataNode.null(), this ); } /** * Return a copy of this node with the data replaced at the path location. * * @param {string} path The node location * @param {any} value The replacement value * @param {any} [priority] The node priority * @param {number} [now] This update timestamp * @return {DataNode} */ $set(path, value, priority, now) { paths.mustBeValid(path); path = paths.trim(path); now = now || Date.now(); const newNode = DataNode.from(value, priority, now); if (!path) { return newNode; } if (newNode.$isNull()) { return this.$remove(path, now); } const copy = {}; let currSrc = this; let currDest = copy; paths.split(path).forEach((key, i, pathParts) => { const siblings = Object.keys(currSrc).filter(k => k !== key); const isLast = pathParts.length - i === 1; siblings.forEach(k => { currDest[k] = currSrc[k]; }); currSrc = currSrc[key] || {}; currDest[key] = isLast ? newNode : {}; currDest = currDest[key]; }); return DataNode.from(copy, this.$priority(), now); } /** * Return a copy of this node with the data replaced at the path locations. * * @param {string} path A root location for all the node to update * @param {object} patch Map of path (relative to the root location above) to their new data * @param {number} [now] This update timestamp * @return {DataNode} */ $merge(path, patch, now) { path = paths.trim(path); now = now || Date.now(); return Object.keys(patch).reduce((node, endPath) => { const pathToNode = paths.join(path, endPath); return node.$set(pathToNode, patch[endPath], undefined, now); }, this); } /** * Return a copy of the node with node at the path location. * * Any parent of the removed node becoming null as a result should be removed. * * @param {string} path Location to the node to remove * @param {number} now This operation timestamp * @return {DataNode} */ $remove(path, now) { paths.mustBeValid(path); path = paths.trim(path); if (!path) { return DataNode.null(); } const newRoot = {}; let currSrc = this; let dest = () => newRoot; paths.split(path).every(key => { const siblings = Object.keys(currSrc).filter(k => k !== key); const currDest = dest(); siblings.forEach(k => { currDest[k] = currSrc[k]; }); currSrc = currSrc[key]; // We will only create the next level if there's anything to copy. dest = () => { currDest[key] = {}; return currDest[key]; }; // we can abort the iteration if the branch node to remove doesn't exist. return currSrc !== undefined; }); return DataNode.from(newRoot, this.$priority(), now || Date.now()); } }
JavaScript
class LineOffset { /** * Gets the available alignment points. */ static get alignmentPoints() { return ['center', 'left', 'right']; } /** * Gets a value indicating to use the full label width. */ static get fullLabelWidth() { // TODO: Enum? return -1; } /** * Gets a value indicating to center on a label. */ static get centeredOnLabel() { // TODO: Enum? return -1; } /** * Initializes a new instance of the LineOffset class. * @param {string} alignmentPoint - Where to align the text from. 'center', 'left', or 'right'. * @param {boolean} isBold - Whether the text should be bold. * @param {number} maxWidth - The maximum width the text can occupy, in pixels. -1 means 'full label width'. * @param {number} maxHeight - The maximum height the text can occupy, in pixels. * @param {number} offsetX - The horizontal canvas offset to the alignment point. -1 means 'centered'. * @param {number} offsetY - The vertical canvas offset to the alignment point. */ constructor( alignmentPoint, isBold, maxWidth, maxHeight, offsetX, offsetY, ) { if (!this.constructor.alignmentPoints.includes(alignmentPoint)) { throw new Error(`Invalid alignment point '${alignmentPoint}', must be one of ${this.constructor.alignmentPoints.join(', ')}.`); } this.alignmentPoint = alignmentPoint; this.isBold = isBold; this.maxHeight = maxHeight; this.maxWidth = maxWidth; this.offsetX = offsetX; this.offsetY = offsetY; } }
JavaScript
class BadgeLabelBuilder { /** * Get the font family the label should be using. */ static get fontFamily() { return 'twemoji, sans-serif'; } /** * Get the line offset information for lines on a badge. */ static get lineOffsets() { return { // Manually calculated offsets to figure out a good mapping for a label // with a width of 589px and height of 193px. // These will absolutely need to be recalculated for other sizes. 'line1': new LineOffset('center', true, LineOffset.fullLabelWidth, 108, LineOffset.centeredOnLabel, 52), 'line2': new LineOffset('center', true, LineOffset.fullLabelWidth, 53, LineOffset.centeredOnLabel, 130), 'level': new LineOffset('center', false, 400, 40, LineOffset.centeredOnLabel, 175), 'minor': new LineOffset('right', false, 95, 20, 585, 180), 'badge': new LineOffset('left', false, 95, 20, 5, 180), }; } /** * Initializes a new instance of the LabelBuilder class. * @param {object} o - Parameter object * @param {string} o.line1 - First line of badge text * @param {string} o.line2 - Second line of badge text * @param {string} o.badgeId - Badge ID, lower left corner * @param {string} o.level - Membership level * @param {boolean} o.isMinor - Whether the badge is for a minor */ constructor({ line1, line2, badgeId, level, isMinor, }) { this.line1 = line1; this.line2 = line2; this.badgeId = badgeId; this.level = level.toUpperCase(); this.isMinor = isMinor === true; } /** * Load the custom fonts for this label builder to use. Run this before building any labels. * @param {Document} doc */ static async loadCustomFonts(doc) { // Range of unicode characters that we expect to be emoji. // This is probably out of date but it's also probably good enough. // We'll see if any badges come out looking wonky. const emojiUnicodeRange = 'U+0023,U+002A,U+0030-0039,U+00A9,U+00AE,U+203C,U+2049,U+2122,U+2139,U+2194-2199,U+21A9-21AA,U+231A-231B,U+2328,U+23CF,U+23E9-23F3,U+23F8-23FA,U+24C2,U+25AA-25AB,U+25B6,U+25C0,U+25FB-25FE,U+2600-2604,U+260E,U+2611,U+2614-2615,U+2618,U+261D,U+2620,U+2622-2623,U+2626,U+262A,U+262E-262F,U+2638-263A,U+2640,U+2642,U+2648-2653,U+265F-2660,U+2663,U+2665-2666,U+2668,U+267B,U+267E-267F,U+2692-2697,U+2699,U+269B-269C,U+26A0-26A1,U+26AA-26AB,U+26B0-26B1,U+26BD-26BE,U+26C4-26C5,U+26C8,U+26CE,U+26CF,U+26D1,U+26D3-26D4,U+26E9-26EA,U+26F0-26F5,U+26F7-26FA,U+26FD,U+2702,U+2705,U+2708-2709,U+270A-270B,U+270C-270D,U+270F,U+2712,U+2714,U+2716,U+271D,U+2721,U+2728,U+2733-2734,U+2744,U+2747,U+274C,U+274E,U+2753-2755,U+2757,U+2763-2764,U+2795-2797,U+27A1,U+27B0,U+27BF,U+2934-2935,U+2B05-2B07,U+2B1B-2B1C,U+2B50,U+2B55,U+3030,U+303D,U+3297,U+3299,U+1F004,U+1F0CF,U+1F170-1F171,U+1F17E,U+1F17F,U+1F18E,U+1F191-1F19A,U+1F1E6-1F1FF,U+1F201-1F202,U+1F21A,U+1F22F,U+1F232-1F23A,U+1F250-1F251,U+1F300-1F320,U+1F321,U+1F324-1F32C,U+1F32D-1F32F,U+1F330-1F335,U+1F336,U+1F337-1F37C,U+1F37D,U+1F37E-1F37F,U+1F380-1F393,U+1F396-1F397,U+1F399-1F39B,U+1F39E-1F39F,U+1F3A0-1F3C4,U+1F3C5,U+1F3C6-1F3CA,U+1F3CB-1F3CE,U+1F3CF-1F3D3,U+1F3D4-1F3DF,U+1F3E0-1F3F0,U+1F3F3-1F3F5,U+1F3F7,U+1F3F8-1F3FF,U+1F400-1F43E,U+1F43F,U+1F440,U+1F441,U+1F442-1F4F7,U+1F4F8,U+1F4F9-1F4FC,U+1F4FD,U+1F4FF,U+1F500-1F53D,U+1F549-1F54A,U+1F54B-1F54E,U+1F550-1F567,U+1F56F-1F570,U+1F573-1F579,U+1F57A,U+1F587,U+1F58A-1F58D,U+1F590,U+1F595-1F596,U+1F5A4,U+1F5A5,U+1F5A8,U+1F5B1-1F5B2,U+1F5BC,U+1F5C2-1F5C4,U+1F5D1-1F5D3,U+1F5DC-1F5DE,U+1F5E1,U+1F5E3,U+1F5E8,U+1F5EF,U+1F5F3,U+1F5FA,U+1F5FB-1F5FF,U+1F600,U+1F601-1F610,U+1F611,U+1F612-1F614,U+1F615,U+1F616,U+1F617,U+1F618,U+1F619,U+1F61A,U+1F61B,U+1F61C-1F61E,U+1F61F,U+1F620-1F625,U+1F626-1F627,U+1F628-1F62B,U+1F62C,U+1F62D,U+1F62E-1F62F,U+1F630-1F633,U+1F634,U+1F635-1F640,U+1F641-1F642,U+1F643-1F644,U+1F645-1F64F,U+1F680-1F6C5,U+1F6CB-1F6CF,U+1F6D0,U+1F6D1-1F6D2,U+1F6D5,U+1F6E0-1F6E5,U+1F6E9,U+1F6EB-1F6EC,U+1F6F0,U+1F6F3,U+1F6F4-1F6F6,U+1F6F7-1F6F8,U+1F6F9,U+1F6FA,U+1F7E0-1F7EB,U+1F90D-1F90F,U+1F910-1F918,U+1F919-1F91E,U+1F91F,U+1F920-1F927,U+1F928-1F92F,U+1F930,U+1F931-1F932,U+1F933-1F93A,U+1F93C-1F93E,U+1F93F,U+1F940-1F945,U+1F947-1F94B,U+1F94C,U+1F94D-1F94F,U+1F950-1F95E,U+1F95F-1F96B,U+1F96C-1F970,U+1F971,U+1F973-1F976,U+1F97A,U+1F97B,U+1F97C-1F97F,U+1F980-1F984,U+1F985-1F991,U+1F992-1F997,U+1F998-1F9A2,U+1F9A5-1F9AA,U+1F9AE-1F9AF,U+1F9B0-1F9B9,U+1F9BA-1F9BF,U+1F9C0,U+1F9C1-1F9C2,U+1F9C3-1F9CA,U+1F9CD-1F9CF,U+1F9D0-1F9E6,U+1F9E7-1F9FF,U+1FA70-1FA73,U+1FA78-1FA7A,U+1FA80-1FA82,U+1FA90-1FA95,U+231A-231B,U+23E9-23EC,U+23F0,U+23F3,U+25FD-25FE,U+2614-2615,U+2648-2653,U+267F,U+2693,U+26A1,U+26AA-26AB,U+26BD-26BE,U+26C4-26C5,U+26CE,U+26D4,U+26EA,U+26F2-26F3,U+26F5,U+26FA,U+26FD,U+2705,U+270A-270B,U+2728,U+274C,U+274E,U+2753-2755,U+2757,U+2795-2797,U+27B0,U+27BF,U+2B1B-2B1C,U+2B50,U+2B55,U+1F004,U+1F0CF,U+1F18E,U+1F191-1F19A,U+1F1E6-1F1FF,U+1F201,U+1F21A,U+1F22F,U+1F232-1F236,U+1F238-1F23A,U+1F250-1F251,U+1F300-1F320,U+1F32D-1F32F,U+1F330-1F335,U+1F337-1F37C,U+1F37E-1F37F,U+1F380-1F393,U+1F3A0-1F3C4,U+1F3C5,U+1F3C6-1F3CA,U+1F3CF-1F3D3,U+1F3E0-1F3F0,U+1F3F4,U+1F3F8-1F3FF,U+1F400-1F43E,U+1F440,U+1F442-1F4F7,U+1F4F8,U+1F4F9-1F4FC,U+1F4FF,U+1F500-1F53D,U+1F54B-1F54E,U+1F550-1F567,U+1F57A,U+1F595-1F596,U+1F5A4,U+1F5FB-1F5FF,U+1F600,U+1F601-1F610,U+1F611,U+1F612-1F614,U+1F615,U+1F616,U+1F617,U+1F618,U+1F619,U+1F61A,U+1F61B,U+1F61C-1F61E,U+1F61F,U+1F620-1F625,U+1F626-1F627,U+1F628-1F62B,U+1F62C,U+1F62D,U+1F62E-1F62F,U+1F630-1F633,U+1F634,U+1F635-1F640,U+1F641-1F642,U+1F643-1F644,U+1F645-1F64F,U+1F680-1F6C5,U+1F6CC,U+1F6D0,U+1F6D1-1F6D2,U+1F6D5,U+1F6EB-1F6EC,U+1F6F4-1F6F6,U+1F6F7-1F6F8,U+1F6F9,U+1F6FA,U+1F7E0-1F7EB,U+1F90D-1F90F,U+1F910-1F918,U+1F919-1F91E,U+1F91F,U+1F920-1F927,U+1F928-1F92F,U+1F930,U+1F931-1F932,U+1F933-1F93A,U+1F93C-1F93E,U+1F93F,U+1F940-1F945,U+1F947-1F94B,U+1F94C,U+1F94D-1F94F,U+1F950-1F95E,U+1F95F-1F96B,U+1F96C-1F970,U+1F971,U+1F973-1F976,U+1F97A,U+1F97B,U+1F97C-1F97F,U+1F980-1F984,U+1F985-1F991,U+1F992-1F997,U+1F998-1F9A2,U+1F9A5-1F9AA,U+1F9AE-1F9AF,U+1F9B0-1F9B9,U+1F9BA-1F9BF,U+1F9C0,U+1F9C1-1F9C2,U+1F9C3-1F9CA,U+1F9CD-1F9CF,U+1F9D0-1F9E6,U+1F9E7-1F9FF,U+1FA70-1FA73,U+1FA78-1FA7A,U+1FA80-1FA82,U+1FA90-1FA95,U+1F3FB-1F3FF,U+261D,U+26F9,U+270A-270B,U+270C-270D,U+1F385,U+1F3C2-1F3C4,U+1F3C7,U+1F3CA,U+1F3CB-1F3CC,U+1F442-1F443,U+1F446-1F450,U+1F466-1F478,U+1F47C,U+1F481-1F483,U+1F485-1F487,U+1F48F,U+1F491,U+1F4AA,U+1F574-1F575,U+1F57A,U+1F590,U+1F595-1F596,U+1F645-1F647,U+1F64B-1F64F,U+1F6A3,U+1F6B4-1F6B6,U+1F6C0,U+1F6CC,U+1F90F,U+1F918,U+1F919-1F91E,U+1F91F,U+1F926,U+1F930,U+1F931-1F932,U+1F933-1F939,U+1F93C-1F93E,U+1F9B5-1F9B6,U+1F9B8-1F9B9,U+1F9BB,U+1F9CD-1F9CF,U+1F9D1-1F9DD,U+0023,U+002A,U+0030-0039,U+200D,U+20E3,U+FE0F,U+1F1E6-1F1FF,U+1F3FB-1F3FF,U+1F9B0-1F9B3,U+E0020-E007F,U+00A9,U+00AE,U+203C,U+2049,U+2122,U+2139,U+2194-2199,U+21A9-21AA,U+231A-231B,U+2328,U+2388,U+23CF,U+23E9-23F3,U+23F8-23FA,U+24C2,U+25AA-25AB,U+25B6,U+25C0,U+25FB-25FE,U+2600-2605,U+2607-2612,U+2614-2615,U+2616-2617,U+2618,U+2619,U+261A-266F,U+2670-2671,U+2672-267D,U+267E-267F,U+2680-2685,U+2690-2691,U+2692-269C,U+269D,U+269E-269F,U+26A0-26A1,U+26A2-26B1,U+26B2,U+26B3-26BC,U+26BD-26BF,U+26C0-26C3,U+26C4-26CD,U+26CE,U+26CF-26E1,U+26E2,U+26E3,U+26E4-26E7,U+26E8-26FF,U+2700,U+2701-2704,U+2705,U+2708-2709,U+270A-270B,U+270C-2712,U+2714,U+2716,U+271D,U+2721,U+2728,U+2733-2734,U+2744,U+2747,U+274C,U+274E,U+2753-2755,U+2757,U+2763-2767,U+2795-2797,U+27A1,U+27B0,U+27BF,U+2934-2935,U+2B05-2B07,U+2B1B-2B1C,U+2B50,U+2B55,U+3030,U+303D,U+3297,U+3299,U+1F000-1F02B,U+1F02C-1F02F,U+1F030-1F093,U+1F094-1F09F,U+1F0A0-1F0AE,U+1F0AF-1F0B0,U+1F0B1-1F0BE,U+1F0BF,U+1F0C0,U+1F0C1-1F0CF,U+1F0D0,U+1F0D1-1F0DF,U+1F0E0-1F0F5,U+1F0F6-1F0FF,U+1F10D-1F10F,U+1F12F,U+1F16C,U+1F16D-1F16F,U+1F170-1F171,U+1F17E,U+1F17F,U+1F18E,U+1F191-1F19A,U+1F1AD-1F1E5,U+1F201-1F202,U+1F203-1F20F,U+1F21A,U+1F22F,U+1F232-1F23A,U+1F23C-1F23F,U+1F249-1F24F,U+1F250-1F251,U+1F252-1F25F,U+1F260-1F265,U+1F266-1F2FF,U+1F300-1F320,U+1F321-1F32C,U+1F32D-1F32F,U+1F330-1F335,U+1F336,U+1F337-1F37C,U+1F37D,U+1F37E-1F37F,U+1F380-1F393,U+1F394-1F39F,U+1F3A0-1F3C4,U+1F3C5,U+1F3C6-1F3CA,U+1F3CB-1F3CE,U+1F3CF-1F3D3,U+1F3D4-1F3DF,U+1F3E0-1F3F0,U+1F3F1-1F3F7,U+1F3F8-1F3FA,U+1F400-1F43E,U+1F43F,U+1F440,U+1F441,U+1F442-1F4F7,U+1F4F8,U+1F4F9-1F4FC,U+1F4FD-1F4FE,U+1F4FF,U+1F500-1F53D,U+1F546-1F54A,U+1F54B-1F54F,U+1F550-1F567,U+1F568-1F579,U+1F57A,U+1F57B-1F5A3,U+1F5A4,U+1F5A5-1F5FA,U+1F5FB-1F5FF,U+1F600,U+1F601-1F610,U+1F611,U+1F612-1F614,U+1F615,U+1F616,U+1F617,U+1F618,U+1F619,U+1F61A,U+1F61B,U+1F61C-1F61E,U+1F61F,U+1F620-1F625,U+1F626-1F627,U+1F628-1F62B,U+1F62C,U+1F62D,U+1F62E-1F62F,U+1F630-1F633,U+1F634,U+1F635-1F640,U+1F641-1F642,U+1F643-1F644,U+1F645-1F64F,U+1F680-1F6C5,U+1F6C6-1F6CF,U+1F6D0,U+1F6D1-1F6D2,U+1F6D3-1F6D4,U+1F6D5,U+1F6D6-1F6DF,U+1F6E0-1F6EC,U+1F6ED-1F6EF,U+1F6F0-1F6F3,U+1F6F4-1F6F6,U+1F6F7-1F6F8,U+1F6F9,U+1F6FA,U+1F6FB-1F6FF,U+1F774-1F77F,U+1F7D5-1F7D8,U+1F7D9-1F7DF,U+1F7E0-1F7EB,U+1F7EC-1F7FF,U+1F80C-1F80F,U+1F848-1F84F,U+1F85A-1F85F,U+1F888-1F88F,U+1F8AE-1F8FF,U+1F90C,U+1F90D-1F90F,U+1F910-1F918,U+1F919-1F91E,U+1F91F,U+1F920-1F927,U+1F928-1F92F,U+1F930,U+1F931-1F932,U+1F933-1F93A,U+1F93C-1F93E,U+1F93F,U+1F940-1F945,U+1F947-1F94B,U+1F94C,U+1F94D-1F94F,U+1F950-1F95E,U+1F95F-1F96B,U+1F96C-1F970,U+1F971,U+1F972,U+1F973-1F976,U+1F977-1F979,U+1F97A,U+1F97B,U+1F97C-1F97F,U+1F980-1F984,U+1F985-1F991,U+1F992-1F997,U+1F998-1F9A2,U+1F9A3-1F9A4,U+1F9A5-1F9AA,U+1F9AB-1F9AD,U+1F9AE-1F9AF,U+1F9B0-1F9B9,U+1F9BA-1F9BF,U+1F9C0,U+1F9C1-1F9C2,U+1F9C3-1F9CA,U+1F9CB-1F9CC,U+1F9CD-1F9CF,U+1F9D0-1F9E6,U+1F9E7-1F9FF,U+1FA00-1FA53,U+1FA54-1FA5F,U+1FA60-1FA6D,U+1FA6E-1FA6F,U+1FA70-1FA73,U+1FA74-1FA77,U+1FA78-1FA7A,U+1FA7B-1FA7F,U+1FA80-1FA82,U+1FA83-1FA8F,U+1FA90-1FA95,U+1FA96-1FFFD'; // TODO: Figure out a better way to do this? const font = new FontFace('twemoji', 'url(fonts/TwitterColorEmoji-SVGinOT.woff2)', { unicodeRange: emojiUnicodeRange, }); doc.fonts.add(await font.load()); } /** * Render the label image sized to a label's dimensions. Note the return widthOffset * should be set on the label for proper alignment. * @param {number} width - The label width to render the canvas data within. * @param {number} height - The label height to render the canvas data within. * @param {number} widthPadding - Dots to divide btween either side of the label as padding. * @param {number} heightPadding - Dots to add to the top of the label as padding. * @return {*} Tuple with a width offset and the canvas data to render. */ renderToImageSizedToLabel(width, height, widthPadding = 20, heightPadding = 10) { // Safety buffer around the edges of the printable area. // Make sure the width ends up on an byte boundary! const widthRemainder = (width - widthPadding) % 8; const widthOffset = widthPadding + widthRemainder; const canvasData = this.renderToImageData( width - widthOffset, height - heightPadding); return { canvasData, widthOffset: widthOffset / 2 }; } /** * Render this label's text onto a canvas, returning the ImageData. * @param {number} width - The width of the label. * @param {number} height - The height of the label. * @param {HTMLCanvasElement} canvas - The optional canvas element to re-use. * If not supplied an OffscreenCanvas will be used instead. * @return {ImageData} - The ImageData of the canvas with the label's text rendered. */ renderToImageData(width, height, canvas) { canvas = canvas || new OffscreenCanvas(width, height); const ctx = canvas.getContext('2d'); // Avoid too much antialiasing which the printer can't do anything with. ctx.imageSmoothingEnabled = false; ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; // TODO: Consider a modular system capable of passing this information in more // dynamically. Hardcoding is fine for the one-off-single-con work right now. const offsets = this.constructor.lineOffsets; this.#addLine(ctx, offsets['line1'], width, this.line1); this.#addLine(ctx, offsets['line2'], width, this.line2); this.#addLine(ctx, offsets['level'], width, this.level); this.#addLine(ctx, offsets['minor'], width, this.isMinor ? 'MINOR' : ''); this.#addLine(ctx, offsets['badge'], width, this.badgeId); return ctx.getImageData(0, 0, width, height); } /** * Add a text line to a canvas context, within the bounding box offsets. * @param {CanvasRenderingContext2D} ctx - The canvas to add the line to. * @param {LineOffset} offsets - The offsets and bounding box to place the line. * @param {number} maxWidth - The max width of the entire canvas. * @param {string} text - The text to add. */ #addLine(ctx, offsets, maxWidth, text) { const maxX = offsets.maxWidth !== LineOffset.fullLabelWidth ? offsets.maxWidth : maxWidth; const offsetX = offsets.offsetX !== LineOffset.centeredOnLabel ? offsets.offsetX : (maxWidth / 2); const size = this.#getMaxFontSizeInPx(ctx, text, maxX, offsets.maxHeight, offsets.isBold); ctx.font = this.#getFont(size, offsets.isBold); ctx.textAlign = offsets.alignmentPoint; ctx.fillText(text, offsetX, offsets.offsetY); } /** * Get a CSS string for a font configuration. * @param {number} size - The font size in pixels. * @param {boolean} isBold - Whether to bold the font. * @param {string} family - The font family. * @return {string} A CSS string for a font property. */ #getFont(size, isBold, family = this.constructor.fontFamily) { return `${isBold ? 'bold' : ''} ${size}px ${family}`; } /** * Get the maximum font size in px that will fit within a bounding box. * @param {CanvasRenderingContext2D} ctx - The canvas context to measure. * @param {string} text - The text to measure. * @param {number} maxWidth - The max width of the bounding box, in pixels. * @param {number} maxHeight - The max height of the bounding box, in pixels. * @param {boolean} isBold - Whether the text should be bold. * @return {number} The maximum font size to fit within the bounds of the label, in px. */ #getMaxFontSizeInPx(ctx, text, maxWidth, maxHeight, isBold) { // Rendering a font at 1px generates a multiplier to use for sizing. // The offset will be dependent on the actual printed characters, so we // need the real text that will be printed. ctx.font = this.#getFont(1, isBold); const fontSize = ctx.measureText(text); const fontWidth = maxWidth / fontSize.width; // Ascent and Descent are offsets from the 'centerpoint' of a character. Combined // they represent the total space taken up by characters in the string. // Note that the ascent and descent are calculated based on the character _set_ // that is used. If you have any lowercase characters it will calculate spacing // for a lowercase 'g' even if there isn't one. No lowercase characters = No // descenders calculated. This means allcaps is bigger for a given height limit. const fontHeight = maxHeight / (fontSize.actualBoundingBoxAscent + fontSize.actualBoundingBoxDescent); return Math.min(fontWidth, fontHeight); } }
JavaScript
class Request extends Accumulator { /** * * @param {IncomingMessage} request - request object * @example <caption>Creates Request stream instance</caption> * new Request(request); */ constructor(request) { super({ objectMode: true }); this[_request] = request; this[_data] = Buffer.from(''); request.pipe(this); } /** * @private */ _charge(data, enc, next) { this[_data] = Buffer.concat([this[_data], data]); next(); } /** * @private */ _release() { const protocol = this[_request].connection.encrypted ? 'https' : 'http'; this[_request].uri = URI.parse(`${protocol}://${this[_request].headers.host}${this[_request].url}`); this[_request].rawData = this[_data]; return this[_request]; } }
JavaScript
class MoneroDaemon { /** * Indicates if the daemon is trusted xor untrusted. * * @return {boolean} true if the daemon is trusted, false otherwise */ async isTrusted() { throw new MoneroError("Subclass must implement"); } /** * Get the number of blocks in the longest chain known to the node. * * @return {int} the number of blocks */ async getHeight() { throw new MoneroError("Subclass must implement"); } /** * Get a block's id by its height. * * @param {int} height is the height of the block id to get * @return {string} the block's id at the given height */ async getBlockId(height) { throw new MoneroError("Subclass must implement"); } /** * Get a block template for mining a new block. * * @param {string} walletAddress is the address of the wallet to receive miner transactions if block is successfully mined * @param {int} reserveSize is the reserve size (optional) * @return {MoneroBlockTemplate} is a block template for mining a new block */ async getBlockTemplate(walletAddress, reserveSize) { throw new MoneroError("Subclass must implement"); } /** * Get the last block's header. * * @return {MoneroBlockHeader} is the last block's header */ async getLastBlockHeader() { throw new MoneroError("Subclass must implement"); } /** * Get a block header by its id. * * @param {string} blockId is the id of the block to get the header of * @return {MoneroBlockHeader} is the block's header */ async getBlockHeaderById(blockId) { throw new MoneroError("Subclass must implement"); } /** * Get a block header by its height. * * @param {int} height is the height of the block to get the header of * @return {MoneroBlockHeader} is the block's header */ async getBlockHeaderByHeight(height) { throw new MoneroError("Subclass must implement"); } /** * Get block headers for the given range. * * @param {int} startHeight is the start height lower bound inclusive (optional) * @param {int} endHeight is the end height upper bound inclusive (optional) * @return {MoneroBlockHeader[]} for the given range */ async getBlockHeadersByRange(startHeight, endHeight) { throw new MoneroError("Subclass must implement"); } /** * Get a block by id. * * @param {string} blockId is the id of the block to get * @return {MoneroBlock} with the given id */ async getBlockById(blockId) { throw new MoneroError("Subclass must implement"); } /** * Get blocks by id. * * @param {string[]} blockIds are array of hashes; first 10 blocks id goes sequential, * next goes in pow(2,n) offset, like 2, 4, 8, 16, 32, 64 and so on, * and the last one is always genesis block * @param {int} startHeight is the start height to get blocks by id * @param {boolean} prune specifies if returned blocks should be pruned (defaults to false) // TODO: test default * @return {MoneroBlock[]} are the retrieved blocks */ async getBlocksById(blockIds, startHeight, prune) { throw new MoneroError("Subclass must implement"); } /** * Get a block by height. * * @param {int} height is the height of the block to get * @return {MoneroBlock} with the given height */ async getBlockByHeight(height) { throw new MoneroError("Subclass must implement"); } /** * Get blocks at the given heights. * * @param {int[]} heights are the heights of the blocks to get * @return {MoneroBlock[]} are blocks at the given heights */ async getBlocksByHeight(heights) { throw new MoneroError("Subclass must implement"); } /** * Get blocks in the given height range. * * @param {int} startHeight is the start height lower bound inclusive (optional) * @param {int} endHeight is the end height upper bound inclusive (optional) * @return {MoneroBlock[]} are blocks in the given height range */ async getBlocksByRange(startHeight, endHeight) { throw new MoneroError("Subclass must implement"); } /** * Get blocks in the given height range as chunked requests so that each request is * not too big. * * @param {int} startHeight is the start height lower bound inclusive (optional) * @param {int} endHeight is the end height upper bound inclusive (optional) * @param {int} maxChunkSize is the maximum chunk size in any one request (default 3,000,000 bytes) * @return {MoneroBlock[]} blocks in the given height range */ async getBlocksByRangeChunked(startHeight, endHeight, maxChunkSize) { throw new MoneroError("Subclass must implement"); } /** * Get block ids as a binary request to the daemon. * * @param {string[]} blockIds specify block ids to fetch; first 10 blocks id goes * sequential, next goes in pow(2,n) offset, like 2, 4, 8, 16, 32, 64 * and so on, and the last one is always genesis block * @param {int} startHeight is the starting height of block ids to return * @return {string[]} are the requested block ids */ async getBlockIds(blockIds, startHeight) { throw new MoneroError("Subclass must implement"); } /** * Get a transaction by id. * * @param {string} txId is the id of the transaction to get * @param {boolean} prune specifies if the returned tx should be pruned (defaults to false) * @return {MoneroTx} is the transaction with the given id */ async getTx(txId, prune = false) { return (await this.getTxs([txId], prune))[0]; } /** * Get transactions by ids. * * @param {string[]} txIds are ids of transactions to get * @param {boolean} prune specifies if the returned txs should be pruned (defaults to false) * @return {MoneroTx[]} are the transactions with the given ids */ async getTxs(txIds, prune = false) { throw new MoneroError("Subclass must implement"); } /** * Get a transaction hex by id. * * @param {string} txId is the id of the transaction to get hex from * @param {boolean} prune specifies if the returned tx hex should be pruned (defaults to false) * @return {string} is the tx hex with the given id */ async getTxHex(txId, prune = false) { return (await this.getTxHexes([txId], prune))[0]; } /** * Get transaction hexes by ids. * * @param {string[]} txIds are ids of transactions to get hexes from * @param {boolean} prune specifies if the returned tx hexes should be pruned (defaults to false) * @return {string[]} are the tx hexes */ async getTxHexes(txIds, prune = false) { throw new MoneroError("Subclass must implement"); } /** * Gets the total emissions and fees from the genesis block to the current height. * * @param {int} height is the height to start computing the miner sum * @param {int} numBlocks are the number of blocks to include in the sum * @return {MoneroMinerTxSum} encapsulates the total emissions and fees since the genesis block */ async getMinerTxSum(height, numBlocks) { throw new MoneroError("Subclass must implement"); } /** * Get the fee estimate per kB. * * @param {int} graceBlocks TODO * @return {BigInteger} is the fee estimate per kB. */ async getFeeEstimate(graceBlocks) { throw new MoneroError("Subclass must implement"); } /** * Submits a transaction to the daemon's pool. * * @param {string} txHex is the raw transaction hex to submit * @param {boolean} doNotRelay specifies if the tx should be relayed (optional) * @return {MoneroSubmitTxResult} contains submission results */ async submitTxHex(txHex, doNotRelay) { throw new MoneroError("Subclass must implement"); } /** * Relays a transaction by id. * * @param {string} txId identifies the transaction to relay */ async relayTxById(txId) { assert.equal(typeof txId, "string", "Must provide a transaction id"); await this.relayTxsById([txId]); } /** * Relays transactions by id. * * @param {string[]} txIds identify the transactions to relay */ async relayTxsById(txIds) { throw new MoneroError("Subclass must implement"); } /** * Get valid transactions seen by the node but not yet mined into a block, as well * as spent key image information for the tx pool. * * @return {MoneroTx[]} are transactions in the transaction pool */ async getTxPool() { throw new MoneroError("Subclass must implement"); } /** * Get ids of transactions in the transaction pool. * * @return {string[]} are ids of transactions in the transaction pool */ async getTxPoolIds() { throw new MoneroError("Subclass must implement"); } /** * Get all transaction pool backlog. * * @return {MoneroTxBacklogEntry[]} are the backlog entries */ async getTxPoolBacklog() { throw new MoneroError("Subclass must implement"); } /** * Get transaction pool statistics. * * @return {MoneroTxPoolStats} contains statistics about the transaction pool */ async getTxPoolStats() { throw new MoneroError("Subclass must implement"); } /** * Flush transactions from the tx pool. * * @param {(string|string[])} ids are specific transactions to flush (defaults to all) */ async flushTxPool(ids) { throw new MoneroError("Subclass must implement"); } /** * Get the spent status of the given key image. * * @param {string} keyImage is key image hex to get the status of * @return {MoneroKeyImageSpentStatus} is the status of the key image */ async getKeyImageSpentStatus(keyImage) { return (await this.getKeyImageSpentStatuses([keyImage]))[0]; } /** * Get the spent status of each given key image. * * @param {string[]} keyImages are hex key images to get the statuses of * @return {MoneroKeyImageSpentStatus[]} is the status for each key image */ async getKeyImageSpentStatuses(keyImages) { throw new MoneroError("Subclass must implement"); } /** * Get outputs identified by a list of output amounts and indices as a binary * request. * * @param {MoneroOutput[]} outputs identify each output by amount and index * @return {MoneroOutput[]} are the identified outputs */ async getOutputs(outputs) { throw new MoneroError("Subclass must implement"); } /** * Get a histogram of output amounts. For all amounts (possibly filtered by * parameters), gives the number of outputs on the chain for that amount. * RingCT outputs counts as 0 amount. * * @param {BigInteger[]} amounts are amounts of outputs to make the histogram with * @param {int} minCount TODO * @param {int} maxCount TODO * @param {boolean} isUnlocked makes a histogram with outputs with the specified lock state * @param {int} recentCutoff TODO * @return {MoneroOutputHistogramEntry[]} are entries meeting the parameters */ async getOutputHistogram(amounts, minCount, maxCount, isUnlocked, recentCutoff) { throw new MoneroError("Subclass must implement"); } /** * Creates an output distribution. * * @param {BigInteger[]} amounts are amounts of outputs to make the distribution with * @param {boolean} cumulative specifies if the results should be cumulative (defaults to TODO) * @param {int} startHeight is the start height lower bound inclusive (optional) * @param {int} endHeight is the end height upper bound inclusive (optional) * @return {MoneroOutputDistributionEntry[]} are entries meeting the parameters */ async getOutputDistribution(amounts, cumulative, startHeight, endHeight) { throw new MoneroError("Subclass must implement"); } /** * Get general information about the state of the node and the network. * * @return {MoneroDaemonInfo} is general information about the node and network */ async getInfo() { throw new MoneroError("Subclass must implement"); } /** * Get synchronization information. * * @return {MoneroDaemonSyncInfo} contains sync information */ async getSyncInfo() { throw new MoneroError("Subclass must implement"); } /** * Look up information regarding hard fork voting and readiness. * * @return {MoneroHardForkInfo} contains hard fork information */ async getHardForkInfo() { throw new MoneroError("Subclass must implement"); } /** * Get alternative chains seen by the node. * * @return {MoneroAltChain[]} are the alternative chains */ async getAltChains() { throw new MoneroError("Subclass must implement"); } /** * Get known block ids which are not on the main chain. * * @return {string[]} are the known block ids which are not on the main chain */ async getAltBlockIds() { throw new MoneroError("Subclass must implement"); } /** * Get the download bandwidth limit. * * @return {int} is the download bandwidth limit */ async getDownloadLimit() { throw new MoneroError("Subclass must implement"); } /** * Set the download bandwidth limit. * * @param {int} limit is the download limit to set (-1 to reset to default) * @return {int} is the new download limit after setting */ async setDownloadLimit(limit) { throw new MoneroError("Subclass must implement"); } /** * Reset the download bandwidth limit. * * @return {int} is the download bandwidth limit after resetting */ async resetDownloadLimit() { throw new MoneroError("Subclass must implement"); } /** * Get the upload bandwidth limit. * * @return {int} is the upload bandwidth limit */ async getUploadLimit() { throw new MoneroError("Subclass must implement"); } /** * Set the upload bandwidth limit. * * @param limit is the upload limit to set (-1 to reset to default) * @return {int} is the new upload limit after setting */ async setUploadLimit(limit) { throw new MoneroError("Subclass must implement"); } /** * Reset the upload bandwidth limit. * * @return {int} is the upload bandwidth limit after resetting */ async resetUploadLimit() { throw new MoneroError("Subclass must implement"); } /** * Get known peers including their last known online status. * * @return {MoneroDaemonPeer[]} are known peers */ async getKnownPeers() { throw new MoneroError("Subclass must implement"); } /** * Get incoming and outgoing connections to the node. * * @return {MoneroDaemonConnection[]} are the daemon's peer connections */ async getConnections() { throw new MoneroError("Subclass must implement"); } /** * Limit number of outgoing peers. * * @param {int} limit is the maximum number of outgoing peers */ async setOutgoingPeerLimit(limit) { throw new MoneroError("Subclass must implement"); } /** * Limit number of incoming peers. * * @param {int} limit is the maximum number of incoming peers */ async setIncomingPeerLimit(limit) { throw new MoneroError("Subclass must implement"); } /** * Get peer bans. * * @return {MoneroBan[]} are entries about banned peers */ async getPeerBans() { throw new MoneroError("Subclass must implement"); } /** * Ban a peer node. * * @param {MoneroBan} ban contains information about a node to ban */ async setPeerBan(ban) { throw new MoneroError("Subclass must implement"); } /** * Ban peers nodes. * * @param {MoneroBan[]} contain information about nodes to ban */ async setPeerBans(bans) { throw new MoneroError("Subclass must implement"); } /** * Start mining. * * @param {string} address is the address given miner rewards if the daemon mines a block * @param {integer} numThreads is the number of mining threads to run * @param {boolean} isBackground specifies if the miner should run in the background or not * @param {boolean} ignoreBattery specifies if the battery state (e.g. on laptop) should be ignored or not */ async startMining(address, numThreads, isBackground, ignoreBattery) { throw new MoneroError("Subclass must implement"); } /** * Stop mining. */ async stopMining() { throw new MoneroError("Subclass must implement"); } /** * Get the daemon's mining status. * * @return {MoneroMiningStatus} is the daemon's mining status */ async getMiningStatus() { throw new MoneroError("Subclass must implement"); } /** * Submit a mined block to the network. * * @param {string} blockBlob is the mined block to submit */ async submitBlock(blockBlob) { await this.submitBlocks([blockBlob]); } /** * Submit mined blocks to the network. * * @param {string[]} blockBlobs are the mined blocks to submit */ async submitBlocks(blockBlobs) { throw new MoneroError("Subclass must implement"); } /** * Check for update. * * @return {MoneroDaemonUpdateCheckResult} is the result */ async checkForUpdate() { throw new MoneroError("Subclass must implement"); } /** * Download an update. * * @param {string} path is the path to download the update (optional) * @return {MoneroDaemonUpdateDownloadResult} is the result */ async downloadUpdate(path) { throw new MoneroError("Subclass must implement"); } /** * Safely disconnect and shut down the daemon. */ async stop() { throw new MoneroError("Subclass must implement"); } /** * Get the header of the next block added to the chain. * * @return {MoneroBlockHeader} is the header of the next block added to the chain */ async getNextBlockHeader() { throw new MoneroError("Subclass must implement"); } /** * Register a listener to be notified when blocks are added to the chain. * * @param {function} listener({MoneroBlockHeader}) is invoked when blocks are added to the chain */ addBlockListener(listener) { throw new MoneroError("Subclass must implement"); } /** * Unregister a listener to be notified when blocks are added to the chain. * * @param {function} listener is a previously registered listener to be unregistered */ removeBlockListener(listener) { throw new MoneroError("Subclass must implement"); } // ----------------------------- STATIC UTILITIES --------------------------- /** * Parses a network string to an enumerated type. * * @param {string} network is the network string to parse * @return {MoneroNetworkType} is the enumerated network type */ static parseNetworkType(network) { if (network === "mainnet") return MoneroNetworkType.MAINNET; if (network === "testnet") return MoneroNetworkType.TESTNET; if (network === "stagenet") return MoneroNetworkType.STAGENET; throw new MoneroError("Invalid network type to parse: " + network); } }
JavaScript
class QueryResultSet { static setByApplyingModels(set, models) { if (models instanceof Array) { throw new Error("setByApplyingModels: A hash of models is required."); } const out = set.clone(); out._modelsHash = models; out._idToIndexHash = null; return out; } constructor(other = {}) { this._offset = (other._offset !== undefined) ? other._offset : null; this._query = (other._query !== undefined) ? other._query : null; this._idToIndexHash = (other._idToIndexHash !== undefined) ? other._idToIndexHash : null; // Clone, since the others may be frozen this._modelsHash = Object.assign({}, other._modelsHash || {}) this._ids = [].concat(other._ids || []); } clone() { return new this.constructor({ _ids: [].concat(this._ids), _modelsHash: Object.assign({}, this._modelsHash), _idToIndexHash: Object.assign({}, this._idToIndexHash), _query: this._query, _offset: this._offset, }); } isComplete() { return this._ids.every((id) => this._modelsHash[id]); } range() { return new QueryRange({offset: this._offset, limit: this._ids.length}); } query() { return this._query; } count() { return this._ids.length; } empty() { return this.count() === 0; } ids() { return this._ids; } idAtOffset(offset) { return this._ids[offset - this._offset]; } models() { return this._ids.map((id) => this._modelsHash[id]); } modelCacheCount() { return Object.keys(this._modelsHash).length; } modelAtOffset(offset) { if (!Number.isInteger(offset)) { throw new Error("QueryResultSet.modelAtOffset() takes a numeric index. Maybe you meant modelWithId()?"); } return this._modelsHash[this._ids[offset - this._offset]]; } modelWithId(id) { return this._modelsHash[id]; } buildIdToIndexHash() { this._idToIndexHash = {} this._ids.forEach((id, idx) => { this._idToIndexHash[id] = idx; const model = this._modelsHash[id]; if (model) { this._idToIndexHash[model.clientId] = idx; } }); } offsetOfId(id) { if (this._idToIndexHash === null) { this.buildIdToIndexHash(); } if (this._idToIndexHash[id] === undefined) { return -1; } return this._idToIndexHash[id] + this._offset } }
JavaScript
class Node { constructor(value) { this.value = value; this.prev = null; this.next = null; } }
JavaScript
class DoublyLinkedList { constructor() { this.head = null; this.tail = null; } // take a disconnected node and place on head setHead(node) { // Write your code here. if (this.head === null) { this.head = node; this.tail = node; } else if (this.head !== node) { this.head.prev = node; node.next = this.head; this.head = node; } } // take a disconnected node and place on tail setTail(node) { // Write your code here. if (this.tail === null) { this.head = node; this.tail = node; } else if (this.tail !== node) { this.tail.next = node; node.prev = this.tail; this.tail = node; } } insertBefore(node, nodeToInsert) { // Write your code here. if (this.head === null) return; let cur = this.head; while (cur) { if (cur === node) { let prev = cur.prev; let next = cur; prev.next = node; next.prev = node; node.prev = prev; node.next = next; break; } else { cur = cur.next; } } } insertAfter(node, nodeToInsert) { // Write your code here. if (this.head === null) return; let cur = this.head; while (cur) { if (cur === node) { let prev = cur; let next = cur.next; prev.next = node; next.prev = node; node.prev = prev; node.next = next; break; } else { cur = cur.next; } } } insertAtPosition(position, nodeToInsert) { // Write your code here. if (this.head === null) return; let i = 0; let cur = this.head; while (i < position) { cur = cur.next; } let prev = cur.prev; let next = cur.next; if (prev) { prev.next = nodeToInsert; nodeToInsert.prev = prev; } else { this.setHead(nodeToInsert); } if (next) { next.prev = nodeToInsert; nodeToInsert.next = next; } else { this.setTail(nodeToInsert); } } removeNodesWithValue(value) { // Write your code here. let cur = this.head; while (cur) { let maybeRemoveThis = cur; cur = cur.next; if (maybeRemoveThis.value === value) { this.remove(maybeRemoveThis); } } } remove(node) { // Write your code here. if (this.head === node && this.tail === node) { this.head = null; this.tail = null; return; } if (this.head === node) { this.head = node.next; this.remove(node); } if (this.tail === node) { this.tail = node.prev; this.remove(node); } let prev = node.prev; let next = node.next; if (prev) prev.next = next; if (next) next.prev = prev; node.next = null; node.prev = null; } containsNodeWithValue(value) { // Write your code here. let cur = this.head; while (cur) { if (cur.value === value) return true; cur = cur.next; } return false; } }
JavaScript
class Component { constructor(){ this._id = uniqid(); this.version = "1"; this.name = ""; this.description = ""; this.output = ""; this.inputComponents = []; this.outputComponents = []; this.type = "Component"; this.position = {top:0,left:0}; this.estimatedCost = ""; this.resources = []; } }
JavaScript
class EustacheClient extends discord.Client { constructor(data = {}) { super() /** * This registry (types & commands) * @type {EustacheRegistry} */ this.registry = new EustacheRegistry(this); /** * This dispatcher * @type {EustacheDispatcher} */ this.dispatcher = new EustacheDispatcher(this, this.registry); /** * This bot command prefix * @readonly * @type {string} */ this.commandPrefix = 'commandPrefix' in data ? data.commandPrefix : '!'; this.on('message', msg => { this.dispatcher.handleMessage(msg); }); } }
JavaScript
class Home extends Component { /** * Component State */ state = { shelfBooks: [], }; // Component propTypes static propTypes = { shelves: PropTypes.array, }; /** * Fetches and updates state shelfBooks */ updateShelfBooks() { const updater = async () => { try { const shelfBooks = await getAll(); this.setState(() => ({shelfBooks})); } catch (error) { console.log(error); } }; updater(); } /** * Runs functions after component is mounted */ componentDidMount() { this.updateShelfBooks(); } /** * Returns Home UI * @return {obj} The UI DOM object */ render() { return ( <div className="list-books"> <div className="list-books-title"> <h1>MyReads</h1> </div> {this.state.shelfBooks && ( <BookShelves shelfBooks={this.state.shelfBooks} shelves={this.props.shelves} onUpdateShelfBooks={() => this.updateShelfBooks()} /> )} <AddBook /> </div> ); } }
JavaScript
class Answers { constructor() { this.data = {}; } // Add a value by key add(key, value) { this.data[key] = value; } addObject(keyPrefix, object) { if(!object) { return; } let keys = Object.keys(object); if(!keys) { return; } for(let index in keys) { let key = keys[index]; let value = object[key]; let useKey = keyPrefix + "_" + key; if(typeof value === 'object') { this.addObject(useKey, value); } else { this.add(useKey, value); } } } remove(key) { let value = this.data[key]; delete this.data[key]; return value; } // Get a value by key get(key) { return this.data[key]; } // Check if a value is set by key has(key) { return typeof this.get(key) !== typeof undefined; } // Get the keys that are set keys() { return Object.keys(this.data); } // Get the number of values that are set size() { return this.keys().length; } getKeysWithPrefix(prefix) { let result = []; let keys = this.keys(); for(let i in keys) { let key = keys[i]; if(key.startsWith(prefix)) { result.push(key); } } return result; } getKeysContaining(substring) { let result = []; let keys = this.keys(); for(let i in keys) { let key = keys[i]; if(key.indexOf(substring) !== -1) { result.push(key); } } return result; } toJson() { return JSON.stringify(this.toObject()); } toObject() { let answersObject = {}; let keys = this.keys(); if(!keys) { return answersObject; } for(let index in keys) { let key = keys[index]; let value = this.get(key); if(value instanceof Answers) { answersObject[key] = value.toObject(); } else { answersObject[key] = value; } } return answersObject; } merge(answers, skipExistingKeys) { if(!answers) { return; } let keys = answers.keys(); for(let key of keys) { if(skipExistingKeys && this.has(key)) { continue; } let value = answers.get(key); this.add(key, value); } } static fromJson(json) { return this.fromObject(JSON.parse(json)); } static fromObject(object) { if(!object) { return null; } let keys = Object.keys(object); if(!keys) { return null; } let answers = new Answers(); for(let index in keys) { let key = keys[index]; let value = object[key]; if(typeof value === 'object') { answers.add(key, Answers.fromObject(value)); } else { answers.add(key, value); } } return answers; } }
JavaScript
class List extends Common { constructor(elements, selector) { super(List, { indexLookup: true }, elements, (method) => { if (typeof elements[method] === 'function') { return (...args) => elements[method](...args); } else if (elements[method]) { return elements[method]; } if (!elements.length && (method === 'length')) return 0; if (!elements.length) return; return (...args) => { let response = elements.map((el) => { return el[method].apply(el, args); }).filter((el) => { return !!el; }); switch (method) { case 'text': return response.join(''); default: return response } } }); this._elements_ = elements; this._selector_ = selector; return this.getProxyExt(); } inspect() { return `List [${this._elements_.map((el) => el.inspect())}]`; } static createFromSelector(context, selector, callback) { if (!Selector.isSelector(selector)) selector = new Selector('css', selector); selector.getElementsByContext(context, (error, elements) => { if (error) return callback(error); let list = List.createFromWD(elements, selector); callback(null, list); }); } static createFromWD(wdElements, selector) { let processedElements = []; for (let el in wdElements) { processedElements.push(new Element(wdElements[el], selector.value, List)); } return new List(processedElements, selector.value); } }
JavaScript
class WireAccessor { constructor(buffer, offset) { this.offset = offset; this.buffer = buffer; } update(from, to) { var buffer = this.buffer; var offset = this.offset; buffer[offset + 0] = from.x buffer[offset + 1] = from.y buffer[offset + 2] = to.x buffer[offset + 3] = to.y } }
JavaScript
class RestrictionList extends DataComponent { constructor() { super(); this.state = { url: "calibrations" }; } getDataUri() { return this.state.url; } render() { if (this.state.loaded && this.state.failed) { return ( <DataError /> ); } let children = this.state.loaded ? (this.state.data.items || []).map((item) => { return ( <li key={item.id} className="restriction-list-item" onClick={() => this.props.onNew(item)}> <span> {item.name} </span> </li> ); }) : []; if (children.length === 0) { children = [( <li key="empty" className="list-empty"> <i className={"fa fa-3x fa-child"}/> <br/> You have no calibrations yet!<br/> Let's change that! </li> )]; } return ( <Loader loaded={this.state.loaded} className="loader"> <ul className="list" ref="list"> {children} </ul> <div style={{textAlign: "center", padding: "20px"}}> <button className="action pagination pagination-prev" type="button" disabled={!(this.state.loaded && "prev" in this.state.meta.links)} onClick={this._onPrev.bind(this)}> <i className="fa fa-angle-left icon"/> previous </button> <button className="action pagination pagination-next" type="button" disabled={!(this.state.loaded && "next" in this.state.meta.links)} onClick={this._onNext.bind(this)}> <i className="fa fa-angle-right icon"/> next </button> </div> </Loader> ); } onFetched() { let node = ReactDOM.findDOMNode(this.refs.list); let bounds = node.getBoundingClientRect(); if (bounds.top < 0) { window.scrollTo(0, node.offsetTop - 50); } } _onNext() { if (!("next" in this.state.meta.links)) { return; } let from = encodeURIComponent(this.state.meta.links.next.from || "0"); let asc = encodeURIComponent(this.state.meta.links.next.asc || "true"); this.setState({ url: "calibration?from=" + from + "&asc=" + asc }, this.fetchData.bind(this)); } _onPrev() { if (!("prev" in this.state.meta.links)) { return; } let from = encodeURIComponent(this.state.meta.links.prev.from || "0"); let asc = encodeURIComponent(this.state.meta.links.prev.asc || "true"); this.setState({ url: "calibration?from=" + from + "&asc=" + asc }, this.fetchData.bind(this)); } }
JavaScript
class DefaultLogger { static log(message, ...args) { // tslint:disable-next-line:no-console console.log(message, ...args); } }
JavaScript
class Header extends Component { render() { return ( <div> <div className="container-fluid" style={containerstyle}> <div className="row" style={{ padding: "3%" }}> <div className="col-1 "> <img alt="Logo" src={quickfoods} width="50px"></img> </div> <div className="col-2 " align="left" style={namecontainer}> <h1>QuickFoods</h1> </div> </div> </div> </div> ); } }
JavaScript
class EmbeddedListField extends Field { constructor(name) { super(name); this._type = 'embedded_list'; this._flattenable = false; this._targetEntity = new Entity(); // link to an empty entity by default this._targetFields = []; this._sortField = null; this._sortDir = null; this._permanentFilters = null; this._listActions = []; } /** * Optionally set the target Entity * * Useful if the embedded entries can be edited in standalone */ targetEntity(entity) { if (!arguments.length) { return this._targetEntity; } this._targetEntity = entity; return this; } /** * List the fields to map in the embedded entries * * @example * * embeddedListField.targetFields([ * new DateField('date'), * new StringField('author'), * new StringField('body') * ]) */ targetFields(value) { if (!arguments.length) return this._targetFields; this._targetFields = value; return this; } /** * Name of the field used for sorting. * * @param string */ sortField() { if (arguments.length) { this._sortField = arguments[0]; return this; } return this._sortField ? this._sortField : this.targetEntity().identifier().name(); } /** * Direction used for sorting. * * @param String either 'ASC' or 'DESC' */ sortDir() { if (arguments.length) { this._sortDir = arguments[0]; return this; } return this._sortDir; } listActions(actions) { if (!arguments.length) { return this._listActions; } this._listActions = actions; return this; } /** * Define permanent filters to be added to the REST API calls * * nga.field('post_id', 'reference').permanentFilters({ * published: true * }); * // related API call will be /posts/:id?published=true * * @param {Object} filters list of filters to apply to the call */ permanentFilters(filters) { if (!arguments.length) { return this._permanentFilters; } this._permanentFilters = filters; return this; } }
JavaScript
class Message { /** * @param {Client} client The instantiating client * @param {string} threadID The ID of the thread * @param {object} data The data for the message */ constructor (client, threadID, data) { /** * @type {Client} * The client that instantiated this */ this.client = client /** * @type {string} * The ID of the message */ this.id = data.item_id /** * @type {string} * The ID of the chat the message was sent in */ this.chatID = threadID /** * @type {object} * The full message payload instagram is sending (forwarded by the dilame/instagram-private-api) */ Object.defineProperty(this, 'data', { value: data, writable: false }) /** * @type {string} * The type of the message, either: * * `text` - a simple message * * `media` - a photo, a file, a GIF or a sticker * * `voice_media` - a voice message * * `story_share` - a story share message */ this.type = data.item_type === 'link' ? 'text' : data.item_type === 'animated_media' ? 'media' : data.item_type /** * @type {number} * The timestamp the message was sent at */ this.timestamp = data.timestamp /** * @type {string} * The ID of the user who sent the message */ this.authorID = data.user_id /** * @type {string?} * The content of the message */ if ('text' in data) { this.content = data.text } if (data.item_type === 'link') { this.content = data.link.text } /** * @typedef {object} StoryShareData * @property {User} author The user who made the story * @property {string} sourceURL The url of the story's image/video */ /** * @type {StoryShareData?} * The data concerning the shared story */ this.storyShareData = undefined if (data.item_type === 'story_share') { const msg = data.story_share.message if (msg === undefined || msg === 'No longer available' || msg.startsWith("This story is hidden because")) { this.storyShareData = { author: null, sourceURL: null } } else { this.storyShareData = { author: this.client._patchOrCreateUser(data.story_share.media?.user.pk, data.story_share.media?.user), sourceURL: data.story_share.media.image_versions2.candidates[0].url } } } /** * @typedef {object} MessageMediaData * @property {boolean} isLike Whether the media is a like (mediaData.url will be `null`) * @property {boolean} isAnimated Whether the media is animated * @property {boolean} isSticker Whether the media is a sticker * @property {boolean} isRandom Whether the media was chosen randomly * @property {string?} url The URL of the media */ /** * @type {MessageMediaData?} * The data concerning the media */ this.mediaData = undefined if (data.item_type === 'animated_media') { this.mediaData = { isLike: false, isAnimated: true, isSticker: data.animated_media.is_sticker, url: data.animated_media.images.fixed_height.url } } else if (data.item_type === 'like') { this.mediaData = { isLike: true, isAnimated: false, isSticker: false, url: null } } else if (data.item_type === 'media') { this.mediaData = { isLike: true, isAnimated: false, isSticker: false, url: data.media.image_versions2.candidates[0].url } } /** * @typedef {object} MessageVoiceData * @property {number} duration The duration (in milliseconds) of the voice message. * @property {string} sourceURL The URL to retrieve the file that contains the voice message. */ /** * @type {MessageVoiceData?} * The data concerning the voice */ this.voiceData = this.type === 'voice_media' ? { duration: data.voice_media.media.audio.duration, sourceURL: data.voice_media.media.audio.audio_src } : undefined // handle promises if (this.chat && this.chat._sentMessagesPromises.has(this.id)) { this.chat._sentMessagesPromises.get(this.id)(this) this.chat._sentMessagesPromises.delete(this.id) } this._patch(data) } /** * @type {Chat} * The chat the message was sent in */ get chat () { return this.client.cache.chats.get(this.chatID) } /** * @type {User} * The author of the message */ get author () { return this.client.cache.users.get(this.authorID) } _patch (data) { /** * @typedef {object} MessageLike * * @property {string} userID The user who added the like to the message * @property {number} timestamp The time the user added the like */ /** * @type {MessageLike[]} * The likes on this message */ this.likes = 'reactions' in data ? data.reactions.likes.map((r) => { return { userID: r.sender_id, timestamp: r.timestamp } }) : [] } /** * Create a message collector in this chat * @param {MessageCollectorOptions} options The options for the collector * @returns {MessageCollector} */ createMessageCollector (options) { const collector = new MessageCollector(this.chat, options) return collector } /** * Mark the message as seen. * @returns {Promise<void>} */ markSeen () { return this.chat.markMessageSeen(this.id) } /** * Delete the message * @returns {Promise<void>} */ delete () { return this.chat.deleteMessage(this.id) } /** * Reply to the message * @param {string} content The content of the message * @returns {Promise<Message>} */ reply (content) { return this.chat.sendMessage(`${this.client.options.disableReplyPrefix ? '' : `@${this.author.username}, `}${content}`) } toString () { return this.content } toJSON () { return { client: this.client.toJSON(), chatID: this.chatID, type: this.type, timestamp: this.timestamp, authorID: this.authorID, content: this.content, mediaData: this.mediaData, voiceData: this.voiceData, storyShareData: this.storyShareData, likes: this.likes } } }
JavaScript
class FileSelection { constructor(task_manager) { this.items = []; this.task_manager = task_manager; this.reload = null; /** @type {Prop.<Boolean>} if true, display the folder creation modal */ this.show_folder_creation_modal = prop(false); /** @type {Prop.<Boolean>} if true, display the upload modal */ this.show_upload_modal = prop(false); } all_selected(items) { // TODO: it's a hack, not a real cmp! return this.items.length === items.length; } clear() { this.items = []; } select_all(items) { this.items = Array.from(items); } is_selected(item) { return this.items.includes(item); } select(item) { if (!this.is_selected(item)) this.items.push(item); } deselect(item) { let idx = this.items.indexOf(item); if (idx !== -1) this.items.splice(idx, 1); } available_actions() { let actions = [ SelectionAction.CREATE_FOLDER, SelectionAction.UPLOAD, SelectionAction.REFRESH ]; if (this.items.length !== 0) { actions.push(SelectionAction.DELETE); } return actions; } execute(action) { let res = false; switch (action) { case SelectionAction.DELETE: res = this._del(); break; case SelectionAction.CREATE_FOLDER: this.show_folder_creation_modal(true); break; case SelectionAction.UPLOAD: this.show_upload_modal(true); break; case SelectionAction.REFRESH: this.reload(); res = true; } if (res) this.clear(); } _deletion_task_builder(item) { return item instanceof File ? new FileDeletion(item) : new FolderDeletion(item); } _del() { if (this.items.length === 0) return false; if (!window.confirm(_('Are you sure to delete these files ?'))) return false; let task = null; if (this.items.length === 1) task = this._deletion_task_builder(this.items[0]); else task = new GroupedTasks(TaskType.DELETION, this.items.map(item => this._deletion_task_builder(item)), (task, ltpl) => ltpl`Deletion of ${task.task_list.length} items`); this.task_manager.start(task); return true; } }
JavaScript
class MergedFs extends EventEmitter { constructor({devicesManager, isFileReady, fs = defaultNodeFs} = {}) { super(); if (!devicesManager) { throw new Error('No "devicesManager" parameter'); } this.devicesManager = devicesManager; // remove dependency on this this.isFileReady = isFileReady; // remove dependency on this this.fs = fs; } _getRelativePath(path) { return String(path) .replace(this.devicesManager.getDevicesPath(), '') .replace(/^\//, ''); } _resolvePath(path, callback) { const relativePath = this._getRelativePath(path); let stat; async.detectSeries( this.devicesManager.getDevices(), (dev, done) => this.fs.stat(join(dev, relativePath), (err, devStat) => { if (err || (this.isFileReady && !this.isFileReady(dev, relativePath))) { return done(null, false); } stat = devStat; return done(null, true); }), (err, dev) => { if (!err && typeof dev === 'undefined') { return callback(createNotExistError(`Failed to resolve path "${relativePath}"`)); } callback(err, join(dev, relativePath), stat); } ); } _resolvePathSync(path) { const relativePath = this._getRelativePath(path); const resolvedPath = this.devicesManager.getDevices().reduce((acc, dev) => { if (acc) { return acc; } const devPath = join(dev, relativePath); try { this.fs.accessSync(devPath); return devPath; } catch (e) { return null; } }, null); if (!resolvedPath) { throw createNotExistError(`Failed to resolve path "${relativePath}"`); } return resolvedPath; } _mkdirRecursive(path, mode, callback) { if (!callback) { callback = mode; mode = 0o777; } this.fs.mkdir(path, mode, (err) => { if (err && err.code === CODES.ENOENT) { return this._mkdirRecursive(dirname(path), mode, (subErr) => { if (subErr) { return callback(subErr); } this._mkdirRecursive(path, mode, callback); }); } return callback(err); }); } _mkdirRecursiveSync(path, mode) { try { return this.fs.mkdirSync(path, mode); } catch (e) { if (e.code === CODES.ENOENT) { this._mkdirRecursiveSync(dirname(path), mode); return this._mkdirRecursiveSync(path, mode); } throw e; } } exists(path, callback) { return this._resolvePath(path, (err, resolvedPath) => callback(Boolean(resolvedPath))); } stat(path, callback) { return this._resolvePath(path, (err, resolvedPath) => { if (err) { return callback(err); } this.fs.stat(resolvedPath, callback); }); } statSync(path) { return this.fs.statSync(this._resolvePathSync(path)); } lstat(path, callback) { return this._resolvePath(path, (err, resolvedPath) => { if (err) { return callback(err); } this.fs.lstat(resolvedPath, callback); }); } mkdir(path, mode, callback) { if (!callback) { callback = mode; mode = 0o777; } const relativePath = this._getRelativePath(path); this._resolvePath(path, (err, resolvedPath) => { if (!err) { return callback(createError(`Directory already exist: ${resolvedPath}`, CODES.EEXIST)); } this._resolvePath(dirname(path), (parentErr) => { if (parentErr) { return callback(parentErr); } this.devicesManager.getDeviceForWrite((devErr, devices) => { if (devErr) { return callback(devErr); } //TODO handle multiply devices this._mkdirRecursive(join(devices[0], relativePath), mode, (mkdirErr) => { if (mkdirErr) { return callback(mkdirErr); } return callback(); }); }); }); }); } readdir(path, callback) { const relativePath = this._getRelativePath(path); let isExist = false; async.concat( this.devicesManager.getDevices().map((d) => join(d, relativePath)), (item, done) => this.fs.readdir(item, (err, res) => { if (err && err.code === CODES.ENOENT) { return done(null, []); } isExist = true; return done(err, res); }), (err, contents) => { if (!isExist) { return callback(createNotExistError(`Cannot read directory: "${relativePath}"`)); } return callback(err, [...new Set(contents)]); } ); } rename(oldPath, newPath, callback) { async.waterfall( [ (done) => this._resolvePath(oldPath, (oldPathErr) => done(oldPathErr)), (done) => this._resolvePath(newPath, (newPathErr, newResolverPath, newStat) => { if (!newPathErr && newStat.isDirectory()) { // path exists return done(createError('Rename destination already exist', CODES.ENOTEMPTY)); } return done(); }), (done) => process.nextTick(() => done(null, this._getRelativePath(oldPath), this._getRelativePath(newPath))), (oldRelativePath, newRelativePath, done) => { let isRenamed = false; async.each( this.devicesManager.getDevices(), (dev, eachRenameDone) => this.fs.rename(join(dev, oldRelativePath), join(dev, newRelativePath), (renameErr) => { if (renameErr && renameErr.code === CODES.ENOENT) { return eachRenameDone(null); } if (!renameErr) { isRenamed = true; } return eachRenameDone(renameErr); }), (renameErr) => { if (!isRenamed) { return done(createNotExistError(`Cannot rename path: "${oldRelativePath}" -> "${newRelativePath}"`)); } return done(renameErr); } ); } ], (err) => callback(err) ); } rmdir(path, callback) { const relativePath = this._getRelativePath(path); let isExist = false; async.each( this.devicesManager.getDevices().map((d) => join(d, relativePath)), (item, done) => this.fs.rmdir(item, (err) => { if (err && err.code === CODES.ENOENT) { return done(null); } isExist = true; return done(err); }), (err) => { if (!isExist) { return callback(createNotExistError(`Cannot read directory: "${relativePath}"`)); } return callback(err); } ); } readFile(path, options, callback) { if (!callback) { callback = options; options = {}; } const relativePath = this._getRelativePath(path); async.tryEach( this.devicesManager.getDevices().map((dev) => (done) => this.fs.readFile(join(dev, relativePath), options, done)), callback ); } unlink(path, callback) { const relativePath = this._getRelativePath(path); let isExist = false; async.each( this.devicesManager.getDevices().map((dev) => join(dev, relativePath)), (item, done) => this.fs.unlink(item, (err) => { if (err && err.code === CODES.ENOENT) { return done(null); } isExist = true; return done(err); }), (err) => { if (!isExist) { return callback(createNotExistError(`Cannot remove file: "${relativePath}"`)); } return callback(err); } ); } writeFile(path, data, options, callback) { if (!callback) { callback = options; options = {}; } const relativePath = this._getRelativePath(path); async.waterfall( [ (done) => this.stat(path, (err) => { if (!err) { return done(createError(`Cannot write file: File already exist: ${relativePath}`, CODES.EEXIST)); } return done(null); }), (done) => this.stat(dirname(path), (dirErr, dirStat) => { if (dirErr) { return done(dirErr); } else if (!dirStat.isDirectory()) { return done( createError( `Cannot write file: Failed to resolve path "${relativePath}": path contains a file in the middle`, CODES.EISFILE ) ); } else { return done(null); } }), (done) => this.devicesManager.getDeviceForWrite(done), //TODO rename, add s (devices, done) => done(null, devices[0]), (device, done) => done(null, device, join(device, relativePath)), (device, resolvedDevicePath, done) => this._mkdirRecursive(dirname(resolvedDevicePath), (err) => { // device may already has this directory created if (err && err.code !== CODES.EEXIST) { return done(err); } else { return done(null, device, resolvedDevicePath); } }), (device, resolvedDevicePath, done) => this.fs.writeFile(resolvedDevicePath, data, options, (err) => { process.nextTick(() => this.emit(MergedFs.EVENTS.FILE_UPDATED, device, relativePath)); return done(err); }) ], callback ); } //UNSTABLE (NOT IMPLEMENTED PROPERLY) createReadStream(path, options) { let resolvedPath; try { if (!path) { throw new Error('path is empty'); } resolvedPath = this._resolvePathSync(path); return this.fs.createReadStream(resolvedPath, options); } catch (e) { throw createNotExistError(`Failed to create read stream for "${resolvedPath || path}": ${e}`); } } //UNSTABLE (NOT IMPLEMENTED PROPERLY) createWriteStream(path, options) { const relativePath = this._getRelativePath(path); const device = this.devicesManager.getDeviceForWriteSync()[0]; const resolvedPath = join(device, relativePath); if (!path) { throw createNotExistError(`Cannot create write stream, path is empty: ${path}`); } let stat; try { stat = this.statSync(path); } catch (e) { // file doesn't exist } if (stat) { throw createError(`File already exist: ${relativePath}`, CODES.EEXIST); } const dirStat = this.statSync(dirname(path)); if (!dirStat.isDirectory()) { throw createError(`Failed to resolve path "${relativePath}": path contains a file in the middle`, CODES.EISFILE); } try { this._mkdirRecursiveSync(dirname(resolvedPath)); } catch (e) { if (e.code !== CODES.EEXIST) { // device may already has this directory created throw e; } } const resolvedFileWriteStream = this.fs.createWriteStream(resolvedPath, options); resolvedFileWriteStream.on('finish', () => this.emit(MergedFs.EVENTS.FILE_UPDATED, device, relativePath)); return resolvedFileWriteStream; } //TODO //open() }
JavaScript
class Recipient extends Component { /** * The constructor method initializes the component's state object and * binds the methods of the component to the current instance. * @param {Object} props The properties passed to the component. */ constructor(props) { super(props); this.state = { recipients: [], locations: [], filtered_recipients: [], filtered_locations: [], fileContent: [], new_recipients: [], show: false, allShow: false, recipientToDelete: {}, allRecipientsDelete: [], locationToDelete: {}, sorted: false, loading: false }; this.fileInput = React.createRef(); this.handleRecipientDelete = this.handleRecipientDelete.bind(this); this.handleAllRecipientsDelete = this.handleAllRecipientsDelete.bind(this); this.handleLocationDelete = this.handleLocationDelete.bind(this); this.handleAllLocationsDelete = this.handleAllLocationsDelete.bind(this); this.handleSearch = this.handleSearch.bind(this); this.readFile = this.readFile.bind(this); this.refreshRecipients = this.refreshRecipients.bind(this); this.handleClose = this.handleClose.bind(this); this.handleSave = this.handleSave.bind(this); this.handleShow = this.handleShow.bind(this); this.handleAllShow = this.handleAllShow.bind(this); this.handleUploadSubmit = this.handleUploadSubmit.bind(this); } /** * Life cycle hook that is called after the component is first rendered. */ componentDidMount() { var self = this; recipientService.getRecipients().then(function (result) { self.setState({ recipients: result, filtered_recipients: result}); }); locationService.getLocations().then((result) => { this.setState({ locations: result, }); }); } sortColumn(key) { const isSorted = this.state.sorted; if (key === 'firstname') { if (this.state.sorted) { this.state.recipients.sort((recipient1, recipient2) => {return recipient2.first_name.localeCompare(recipient1.first_name)}); } else { this.state.recipients.sort((recipient1, recipient2) => {return recipient1.first_name.localeCompare(recipient2.first_name)}); } } else if (key === 'lastname') { if (this.state.sorted) { this.state.recipients.sort((recipient1, recipient2) => {return recipient2.last_name.localeCompare(recipient1.last_name)}); } else { this.state.recipients.sort((recipient1, recipient2) => {return recipient1.last_name.localeCompare(recipient2.last_name)}); } } else if (key === 'quantity') { if (this.state.sorted) { this.state.recipients.sort((recipient1, recipient2) => {return recipient2.quantity - recipient1.quantity}); } else { this.state.recipients.sort((recipient1, recipient2) => {return recipient1.quantity - recipient2.quantity}); } } else if (key == 'address') { if (this.state.sorted) { this.state.recipients.sort((recipient1, recipient2) => {return recipient2.location.address.localeCompare(recipient1.location.address)}); } else { this.state.recipients.sort((recipient1, recipient2) => {return recipient1.location.address.localeCompare(recipient2.location.address)}); } } this.setState({recipients: this.state.recipients, sorted: !isSorted}); } refreshRecipients(){ var self = this; recipientService.getRecipients().then(function (result) { self.setState({ recipients: result, filtered_recipients: result, loading: false}); }); } handleClose() { this.setState({show: false, allShow: false}); } // For deleting 1 or all recipients with associated locations handleSave() { this.handleClose(); if (this.state.show) { this.handleRecipientDelete(this.state.recipientToDelete); this.handleLocationDelete(this.state.locationToDelete); this.setState({recipientToDelete: {}, locationToDelete: {}}); } else if (this.state.allShow) { this.handleAllRecipientsDelete(this.state.allRecipientsDelete); this.handleAllLocationsDelete(this.state.allLocationsDelete); this.setState({ allRecipientsDelete: [], allLocationsDelete: [] }); } } // For deleting 1 recipient and associated location handleShow(e, r) { e.preventDefault(); this.setState({show: true, recipientToDelete: r, locationToDelete: r.location}); } // For deleting all recipients and associated locations handleAllShow(e, r) { e.preventDefault(); let locsToDelete = []; for (let i = 0; i < r.length; i++) { locsToDelete.push(r[i].location); } this.setState({allShow: true, allRecipientsDelete: r, allLocationsDelete: locsToDelete}); } /** * Event handler used to delete a recipient from the database when the * user clicks on the delete button. * @param {Object} r The recipient object to be deleted. */ handleRecipientDelete(r){ var self = this; recipientService.deleteRecipient(r).then(()=>{ var newArr = self.state.recipients.filter(function(obj) { return obj.id !== r.id; }); self.setState({recipients: newArr, filtered_recipients: newArr}) }); } /** * Event handler used to delete all recipients from the database when the * user clicks on the delete all button. * @param {Object} r The recipients object to be deleted. */ handleAllRecipientsDelete(r) { var self = this; for (var i = 0; i < r.length; i++) { this.handleRecipientDelete(r[i]); } } /** * Event handler used to delete a location from the database when the * user clicks on the delete button. * @param {Object} loc The location object to be deleted. */ handleLocationDelete(loc){ let self = this; locationService.deleteLocation(loc).then(()=>{ let newArr = self.state.locations.filter(function(obj) { return obj.id !== loc.id; }); self.setState({locations: newArr, filtered_locations: newArr}) }); } /** * Event handler used to delete all locations except ones designated as center from the database when the * user clicks on the delete all button. * @param {Object} locs the array of locations to be deleted. */ handleAllLocationsDelete(locs) { let notCenterLocs = locs.filter(loc => loc.is_center == false) for (var i = 0; i < notCenterLocs.length; i++) { this.handleLocationDelete(notCenterLocs[i]); } } /** * Event handler method called when the user enters a value into the * recipient search box. * @param {Object} e The event triggered when a user enters information * into the search field. */ handleSearch(e) { let newList = searchService.findRecipients(e, this.state.recipients); this.setState({ filtered_recipients: newList }); } get_languages(languages_list) { var languages = []; for (var index in languages_list) { let language_template = {}; let language = this.capitalize(languages_list[index].trim()); language_template.name = language; languages.push(language_template); } return languages; } capitalize(str) { if (typeof(str) == 'string') { if (str.length > 0) { str = str.toLowerCase(); str = str.charAt(0).toUpperCase() + str.slice(1); } } return str; } get_phone(phone) { if (phone.length > 0) { phone = phone.trim(); phone = phone.replaceAll(/['\D']/g, ''); if (phone.length === 10) { phone = phone.slice(0, 3) + '-' + phone.slice(3, 6) + '-' + phone.slice(6); } else { phone = ''; } } return phone } readFile(event) { const file = event.target.files[0]; const promise = fileService.readFile(file); let recipients = []; promise.then((data) => { this.setState({ fileContent: data }); for(var row in data) { let recipient_template = { 'user': '', 'first_name': '', 'last_name': '', 'phone' : '', 'quantity': 1, 'location': {'address':'', 'city':'', 'state':'', 'room_number':'', 'zipcode':'', 'is_center':false}, 'languages': []}; var recipient_data = data[row]; let keys = Object.keys(recipient_data) for (var index in keys) { let key = keys[index]; let value = recipient_data[key]; delete recipient_data[key]; recipient_data[key.toLowerCase()] = value; } keys = Object.keys(recipient_data); if (keys.includes('firstname')) { recipient_template.first_name = recipient_data.firstname.trim(); } else { recipient_template.first_name = " "; } if (keys.includes('lastname')) { recipient_template.last_name = recipient_data.lastname.trim(); } else { recipient_template.last_name = " "; } recipient_template.languages = this.get_languages(recipient_data.language.split(',')); recipient_template.phone = this.get_phone(recipient_data.phone); recipient_template.location.address = recipient_data.address.trim(); if (keys.includes('room_number')) { recipient_template.location.room_number = recipient_data.room_number; } recipient_template.location.city = this.capitalize(recipient_data.city.trim()); recipient_template.location.state = recipient_data.state.trim().toUpperCase(); recipient_template.location.zipcode = this.capitalize(recipient_data.zipcode); recipient_template.quantity = String(recipient_data.quantity); if (recipient_data.center === 1) { recipient_template.location.is_center = true; } recipients.push(recipient_template); } this.setState({ new_recipients: JSON.stringify(recipients) }); }); } // Handles upload Recipients button when clicked handleUploadSubmit = (event) => { if (this.fileInput.current.value) { this.setState({ loading: true }); recipientService.uploadRecipients(this.state.new_recipients); this.fileInput.current.value = ''; this.refreshRecipients(); this.setState({ new_recipients: [], }); } } /** * Method which returns a String of a recipients's languages * @param {Object} recipient The driver whose known languages are to be returned. */ getRecipientLanguages(recipient) { let languages = ""; for (let i = 0; i < recipient.languages.length; i++) { languages = languages.concat(" ", recipient.languages[i].name); } languages = languages.trim(); languages = languages.split(" ").join(", "); return languages; } /** * Method which returns an array of recipient data to be used in exporting CSV file */ getCSVData() { let data = []; let recipients = this.state.recipients; for (let i = 0; i < recipients.length; i++) { let row = []; row.push(recipients[i].phone); row.push(recipients[i].first_name); row.push(recipients[i].last_name); row.push(recipients[i].location.address); row.push(recipients[i].location.city); row.push(recipients[i].location.state); row.push(recipients[i].location.zipcode); if (recipients[i].location.is_center == false) { row.push(0); } else row.push(1); row.push(recipients[i].location.room_number); row.push(this.getRecipientLanguages(recipients[i])); row.push(recipients[i].quantity); data.push(row); } return data; } /** * The render method used to display the component. * @returns The HTML to be rendered. */ render() { return ( <Container className="card mt-2 mb-4"> <Row className="card-header"> <Col> <Row className="d-flex flex-row"> <Col sm={2} className="table-title title">Recipients</Col> <Col sm={8} class="mt-3"> <InputGroup class="mb-2"> <InputGroup.Text> {// <Search icon="search"></Search> } </InputGroup.Text> <FormControl type="text" placeholder="Search recipients" id="search" v-model="search" name="search" aria-label="Search" onChange={this.handleSearch} //ref="title" ></FormControl> </InputGroup> </Col> <Col sm={2} className="justify-content-around d-flex flex-row"> <Button href="/addRecipient" style={{ marginRight: 2.5 }}>Add New</Button> <Button onClick={(e) => this.handleAllShow(e, searchService.findRecipients(e, this.state.recipients))} style={{ marginLeft: 2.5 }}>Delete All</Button> <DialogBox show={this.state.allShow} modalTitle='Confirm Deletion' mainMessageText='Are you sure you want to delete all entries?' handleClose={this.handleClose} handleSave={this.handleSave} closeText='Cancel' saveText='Delete' buttonType='danger' /> </Col> </Row> </Col> </Row> <Row className="card-body table-wrapper-scroll-y my-custom-scrollbar"> <Table className="striped bordered hover table table-bordered table-striped mb-0"> <thead > <tr> <th> <Stack direction='horizontal' gap={3}> <div >First Name</div> <div className='ms-auto'> <Button variant='outline-secondary' size='sm' onClick={() => this.sortColumn('firstname')} >&#8693;</Button> </div> </Stack> </th> <th> <Stack direction='horizontal' gap={3}> <div >Last Name</div> <div className='ms-auto'> <Button variant='outline-secondary' size='sm' onClick={() => this.sortColumn('lastname')} >&#8693;</Button> </div> </Stack> </th> <th> <Stack direction='horizontal' gap={3}> <div >Quantity</div> <div className='ms-auto'> <Button variant='outline-secondary' size='sm' onClick={() => this.sortColumn('quantity')} >&#8693;</Button> </div> </Stack> </th> <th> <Stack direction='horizontal' gap={3}> <div >Address</div> <div className='ms-auto'> <Button variant='outline-secondary' size='sm' onClick={() => this.sortColumn('address')} >&#8693;</Button> </div> </Stack> </th> <th></th> </tr> </thead> <tbody> {this.state.filtered_recipients.map( r => <tr key={r.id}> <td>{r.first_name}</td> <td>{r.last_name}</td> <td>{r.quantity}</td> <td>{r.location.address}</td> <td> <Button className="mr-2" href={"/recipientDetail/" + r.id}>View</Button> <Button className="mr-2" href={"/updateRecipient/" + r.id}>Edit</Button> <Button onClick={(e) => this.handleShow(e, r)}> Delete</Button> <DialogBox show={this.state.show} modalTitle='Confirm Deletion' mainMessageText='Are you sure you want to delete this entry?' handleClose={this.handleClose} handleSave={this.handleSave} closeText='Cancel' saveText='Delete' buttonType='danger' /> </td> </tr>)} </tbody> </Table> </Row> <Row className="justify-content-md-left mt-2 pt-2 mb-2 title border-top"> <Col xs md="auto" className="h4">File Upload</Col> </Row> <Row classname="pb-4 mb-4"> <Col md="auto" className="ml-4"> <Row> <Form.Group controlId="formFile" className="mb-3"> <Form.Control type="file" onChange={ (e) => { this.readFile(e); } } ref= {this.fileInput} accept='.csv, .xls, .xlsx' /> </Form.Group> </Row> </Col> <Col> <Row> <Col sm={2} className="d-flex flex-row"> <Button className="mx-1" onClick={this.handleUploadSubmit}> {this.state.loading ? <Spinner animation="border" role="status" style={{ height: 25, width: 25 }}> </Spinner> : "Add Recipients"} </Button> </Col> <Col> <CSVLink style={{ margin: 20}} data={this.getCSVData()} headers={headers} filename='recipients.csv' >Download Recipients</CSVLink> </Col> </Row> </Col> </Row> </Container> ); } }
JavaScript
class LexerAction { /** * Gets the serialization type of the lexer action. * * @return {number} The serialization type of the lexer action. */ getActionType() {} /** * Gets whether the lexer action is position-dependent. Position-dependent * actions may have different semantics depending on the {@link CharStream} * index at the time the action is executed. * * <p>Many lexer commands, including {@code type}, {@code skip}, and * {@code more}, do not check the input index during their execution. * Actions like this are position-independent, and may be stored more * efficiently as part of the {@link LexerATNConfig#lexerActionExecutor}.</p> * * @return {boolean} {@code true} if the lexer action semantics can be affected by the * position of the input {@link CharStream} at the time it is executed; * otherwise, {@code false}. */ isPositionDependent() {} /** * Execute the lexer action in the context of the specified {@link Lexer}. * * <p>For position-dependent actions, the input stream must already be * positioned correctly prior to calling this method.</p> * * @param {org.antlr.v4.runtime.Lexer} lexer The lexer instance. * @return {void} */ execute(lexer) {} /** * @param {Object} o * @return {boolean} */ equals(o) {} }
JavaScript
class Root extends React.Component { componentDidMount() { Font.loadAsync({ RobotoThin: require('./assets/fonts/Roboto/Roboto-Thin.ttf'), RobotoLight: require('./assets/fonts/Roboto/Roboto-Light.ttf'), Roboto: require('./assets/fonts/Roboto/Roboto-Regular.ttf'), RobotoMedium: require('./assets/fonts/Roboto/Roboto-Medium.ttf'), RobotoBlack: require('./assets/fonts/Roboto/Roboto-Black.ttf'), RobotoMono: require('./assets/fonts/RobotoMono/RobotoMono-Regular.ttf') }) }; render() { return ( <Provider store={Store}> <StyleProvider style={getTheme()}> <AppWithNavigationState/> </StyleProvider> </Provider> ); } }
JavaScript
class DataCollection extends Loggable { /** * DataCollection class is responsible to manage one model records from one adapter: * all records operations, cached records, model logic (field value validation, triggers). * DataCollection instances are managed by a DataStore instance. * * @param {CacheManager} arg_cache_manager - cache manager instance. * @param {DataAdapter} arg_data_adapter - collection data adapter. * @param {array} arg_model_schema - topology model schema. * * @returns {nothing} */ constructor(arg_cache_manager, arg_data_adapter, arg_model_schema) { assert( T.isObject(arg_cache_manager) && arg_cache_manager.is_cache_manager, context + ':constructor:bad cache manager object') assert( T.isObject(arg_data_adapter) && arg_data_adapter.is_data_adapter, context + ':constructor:bad data adapter object') assert( T.isObject(arg_model_schema) && arg_model_schema.is_topology_model, context + ':constructor:bad model schema object') const model_plural_name = arg_model_schema.get_plural_name() assert( T.isString(model_plural_name) && model_plural_name.length > 0, context + ':constructor:bad collection name string') super(context) /** * Class type flag. * @type {boolean} */ this.is_data_collection = true /** * CacheManager instance. * @type {CacheManager} */ this._cache_manager = arg_cache_manager /** * Datas adapter instance. * @type {DataAdapter} */ this._adapter = arg_data_adapter /** * Topology model schema instance. * @type {array} */ this._schema = arg_model_schema /** * Datas collection prefix. * @type {string} */ this._cache_prefix = model_plural_name /** * Datas collection name. * @type {string} */ this._name = model_plural_name } /** * Emit on event. * @private * * @param {string} arg_event - event name. * @param {any} arg_datas - event datas (optional, default:undefined). * * @returns {nothing} */ _emit(arg_event, arg_datas=undefined) // TODO { this.debug(context + ':emit:' + arg_event) // if ( this._schema.has_rules_agenda() ) // { // this._schema.push_on_rule_agenda(arg_event, arg_datas) // } } /** * Call event triggers. * @private * * @param {string} arg_event - event name. * @param {any} arg_datas - event datas (optional, default:undefined). * * @returns {nothing} */ _trigger(arg_event, arg_datas=undefined) // TODO { this.debug(context + ':trigger:' + arg_event) // this._schema._trigger(arg_event, arg_datas) this._emit(arg_event, arg_datas) // TODO: UPDATE METRICS } /** * Test if a record is cached. * @private * * @param {string} arg_id - record id. * * @returns {Promise} - Promise of boolean value: found (true) or not found (false). */ _has_cached_record_by_id(arg_id) { const key = this._cache_prefix + ':' + arg_id return this._cache_manager.has(key) } /** * Test if a record array is cached. * @private * * @param {DataQuery} arg_query - data query. * * @returns {Promise} - Promise of boolean value: found (true) or not found (false). */ _has_cached_record_by_query(arg_query) { const key = this._cache_prefix + ':query:' + arg_query.hash() return this._cache_manager.has(key) } /** * Get a cached record. * @private * * @param {string} arg_id - record id. * * @returns {Promise} - Promise of a DataRecord instance. */ _get_cached_record_by_id(arg_id) { const key = this._cache_prefix + ':' + arg_id return this._cache_manager.get(key, undefined) } /** * Get a cached record array. * @private * * @param {DataQuery} arg_query - data query. * * @returns {Promise} - Promise of a DataRecordArray instance. */ _get_cached_record_by_query(arg_query) { const key = this._cache_prefix + ':query:' + arg_query.hash() return this._cache_manager.get(key, undefined) } /** * Add a record to cache. * @private * * @param {DataRecord} arg_record - record * * @returns {Promise} - Promise of boolean value: success (true) or failure (false). */ _set_cached_record_by_id(arg_record) { assert( T.isObject(arg_record) && arg_record.is_data_record, context + ':_set_cached_record_by_id:bad data record object') const key = this._cache_prefix + ':' + arg_record.get_id() return this._cache_manager.set(key, arg_record, this._schema.get_ttl()) } /** * Add a record array to cache. * @private * * @param {DataQuery} arg_query - data query. * @param {DataRecordArray} arg_record_array - record array. * * @returns {Promise} - Promise of boolean value: success (true) or failure (false). */ _set_cached_record_by_query(arg_query, arg_record_array) { assert( T.isObject(arg_query) && arg_query.is_data_query, context + ':_set_cached_record_by_query:bad data query object') assert( T.isObject(arg_record_array) && arg_record_array.is_data_record_array, context + ':_set_cached_record_by_query:bad data record object') const promises = [] // CACHE RECORD ARRAY const key = this._cache_prefix + ':query:' + arg_query.hash() promises.push( this._cache_manager.set(key, arg_record_array, this._schema.get_ttl()) ) // CACHE ALL ARRAY RECORDS arg_record_array._records.forEach( (record)=>{ promises.push( this._set_cached_record_by_id(record) ) } ) return Promise.all(promises) } /** * Remove a cached record. * @private * * @param {string} arg_id - record id. * * @returns {Promise} - Promise of boolean value: success (true) or failure (false). */ _remove_cached_record_by_id(arg_id) { const key = this._cache_prefix + ':' + arg_id return this._cache_manager.remove(key) } /** * Get collection name. * * @returns {string} */ get_name() { return this._name } /** * Get cache manager. * * @returns {DataAdapter} */ get_cache_manager() { assert( T.isObject(this._cache_manager) && this._cache_manager.is_cache_manager, context + ':get_cache_manager:bad cache manager object') return this._cache_manager } /** * Get data adapter. * * @returns {DataAdapter} */ get_adapter() { assert( T.isObject(this._adapter) && this._adapter.is_data_adapter, context + ':get_adapter:bad data adapter object') return this._adapter } /** * Get data model. * * @returns {DataModel} */ get_model() { assert( T.isObject(this._schema) && this._schema.is_topology_model, context + ':get_model:bad data model object') return this._schema } /** * Get data model. * * @returns {DataModel} */ get_schema() { assert( T.isObject(this._schema) && this._schema.is_topology_model, context + ':get_model:bad data model object') return this._schema } /** * Validate data record values. * 1-Call 'before_validate' triggers. * 2-Check all fields values. * 3-Call 'after_validate_ok' triggers on success. * Call 'after_validate_ko' triggers on failure. * 4-Return success (true) or failure (false) * * @param {DataRecord} arg_record - data record instance. * * @returns {Promise} - Promise of a boolean. */ validate_record(arg_record) // TODO { assert( T.isObject(arg_record) && arg_record.is_data_record, context + ':validate_record:bad data record object') this._trigger('before_validate', { record:arg_record }) const result = this._schema.validate(arg_record.get_attributes_object()) this._trigger(result.is_valid ? 'after_validate_ok' : 'after_validate_ko', { record:arg_record }) return Promise.resolve(result) } /** * Create a new data record instance, not saved. * * @param {object} arg_record_datas - new record attributes. * @param {string} arg_record_id - new record unique id (optional). * * @returns {Promise} - Promise(DataRecord) */ new_record(arg_record_datas, arg_record_id) { // const is_cached_promise = this._has_cached_record_by_id(arg_record_id) // if (is_cached) // { // console.log('collection:is cached') // return this._get_cached_record_by_id(arg_record_id) // } return this._adapter.new_record(this._schema.get_name(), arg_record_datas, arg_record_id) } /** * Create a data collection record. * 1-Call 'before_create' triggers. * 2-Check existing record id within cached records. * 3-Validate record datas: reject on failure * 4-Create a DataRecord instance with adapter.new_record. * 5-Add record to cache. * 6-Call record.save() * 7-Call 'after_create' triggers. * * @param {DataRecord} arg_record - data record instance. * * @returns {Promise} - Promise of a DataRecord object. */ create_record(arg_record) { assert( T.isObject(arg_record) && arg_record.is_data_record, context + ':create_record:bad data record object') this._trigger('before_create', { has_error:false, error_msg:undefined, record:arg_record}) return this._has_cached_record_by_id(arg_record.get_id()) .then( (is_cached)=>{ if (is_cached) { this._trigger('after_create', { has_error:true, error_msg:'already_exists', record:arg_record }) return Promise.reject('already_exists') } } ) .then( ()=>{ const is_valid = this.validate_record(arg_record) if ( ! is_valid) { this._trigger('after_create', { has_error:true, error_msg:'not_valid', record:arg_record }) return Promise.reject('not_valid') } } ) .then( ()=>{ return this._adapter.create_record(this._schema.get_name(), arg_record.get_attributes_object()) } ) .then( (record)=>{ this._trigger('after_create', { has_error:false, error_msg:undefined, record:record}) return record } ) .catch( (e)=>{ this._trigger('after_create', { has_error:true, error_msg:e, record:arg_record}) console.error(context + ':create_record:', e) return undefined } ) } /** * Delete a data collection record. * 1-Call 'before_delete' triggers. * 2-Remove cached record. * 3-Call record.delete() * 4-Call 'after_delete' triggers. * * @param {DataRecord} arg_record - data record instance. * * @returns {Promise} - Promise of boolean success. */ delete_record(arg_record) { assert( T.isObject(arg_record) && arg_record.is_data_record, context + ':delete_record:bad data record object') this._trigger('before_delete', { has_error:false, error_msg:undefined, record:arg_record}) return this._remove_cached_record_by_id(arg_record.get_id()) .then( ()=>{ return this._adapter.delete_record(this._schema.get_name(), arg_record.get_id()) .then( (record)=> { return record.set_removed() } ) } ).then( ()=>{ this._trigger('after_delete', { has_error:false, error_msg:undefined, record:arg_record}) return true } ).catch( (e)=>{ this._trigger('after_delete', { has_error:true, error_msg:e, record:arg_record}) return false } ) } /** * Update a data collection record. * 1-Call 'before_update' triggers. * 2-Update cached record. * 3-Call record.update() * 4-Call 'after_update' triggers. * * @param {DataRecord} arg_record - data record instance. * * @returns {Promise} - Promise of boolean success. */ update_record(arg_record) { assert( T.isObject(arg_record) && arg_record.is_data_record, context + ':update_record:bad data record object') this._trigger('before_update', { has_error:false, error_msg:undefined, record:arg_record}) return this._adapter.update_record(this._schema.get_name(), arg_record) .then( (record)=>{ console.log(context + ':update_record:record', record) return this._set_cached_record_by_id(arg_record.get_id(), record) } ) .then( ()=>{ this._trigger('after_update', { has_error:false, error_msg:undefined, record:arg_record}) console.log(context + ':update_record:true') return true } ) .catch( (e)=>{ this._trigger('after_update', { has_error:true, error_msg:e, record:arg_record}) return false } ) } /** * Update a data collection record. * 1-Search record into cache * 2-Search record into adapter * * @param {string} arg_record_id - data record id. * * @returns {Promise} - Promise of boolean found:true, not found:false. */ has_record(arg_record_id) { assert( T.isString(arg_record_id) && arg_record_id.length > 0, context + ':has_record:bad record id string') return this._has_cached_record_by_id(arg_record_id) .then( (found)=>{ if (found) { return true } return this._adapter.has_record(this._schema.get_name(), arg_record_id) } ).catch( (e)=>{ this._trigger('has_record', { has_error:true, error_msg:e, id:arg_record_id} ) return false } ) } /** * Find an existing data record with an id. * 1-Search record into cache * 2-Search record into adapter * 3-Save record into cache * * @param {string} arg_record_id - data record id. * * @returns {Promise} - Promise of DataRecord. */ find_one_record(arg_record_id) { assert( T.isString(arg_record_id) && arg_record_id.length > 0, context + ':find_one_record:bad record id string') return this._get_cached_record_by_id(arg_record_id) .then( (record)=>{ if ( T.isObject(record) && record.is_data_record ) { this._trigger('find_one_record', { has_error:false, error_msg:undefined, id:arg_record_id, from:'cache'}) return record } return this._adapter.find_one_record(this._schema.get_name(), arg_record_id) .then( (attributes)=>{ // console.log(context + ':find_one_record:adapter:attributes', attributes) return this.new_record(attributes, arg_record_id) } ) .then( (record)=>{ if ( T.isObject(record) && record.is_data_record ) { this._trigger('find_one_record', { has_error:false, error_msg:undefined, id:arg_record_id, record:record, from:'adapter'}) // console.log(context + ':find_one_record:adapter:good record', record) return record } console.error(context + ':find_one_record:adapter:bad record', record) this._trigger('find_one_record', { has_error:false, error_msg:undefined, id:arg_record_id, from:'notfound'}) return undefined } ) } ) .catch( (e)=>{ this._trigger('find_one_record', { has_error:true, error_msg:e, id:arg_record_id} ) console.error(context + ':find_one_record:error', e) return undefined } ) } /** * Find existing data records with a query. * 1-Search records into cache * 2-Search records into adapter * 3-Save records into cache * * @param {DataQuery} arg_query - data query. * * @returns {Promise} - Promise of DataRecordArray. */ find_records(arg_query) { assert( T.isObject(arg_query) && arg_query.is_data_query, context + ':find_records:bad query object') return this._get_cached_record_by_query(arg_query) .then( (record_array)=>{ if ( T.isObject(record_array) && record_array.is_data_record_array ) { this._trigger('find_records', { has_error:false, error_msg:undefined, query:arg_query, from:'cache'}) return record_array } return this._adapter.find_records(this._schema.get_name(), arg_query) .then( (attributes_array)=>{ if ( T.isArray(attributes_array) ) { return this.new_record_array(attributes_array) } this._trigger('find_records', { has_error:true, error_msg:'bad attributes array', query:arg_query, from:'notfound'}) return undefined } ) .then( (record_array)=>{ if ( T.isObject(record_array) && record_array.is_data_record_array ) { return this._set_cached_record_by_query(arg_query, record_array).then( ()=>{ this._trigger('find_records', { has_error:false, error_msg:undefined, query:arg_query, records:record_array, from:'adapter'}) return record_array } ) } this._trigger('find_records', { has_error:false, error_msg:'bad DataRecordArray', query:arg_query, from:'notfound'}) return undefined } ) } ).catch( (e)=>{ this._trigger('find_one_record', { has_error:true, error_msg:e, query:arg_query} ) return undefined } ) } /** * Find all existing data records from adapter. * * @returns {Promise} - Promise of DataRecordArray. */ find_all_records() // TODO use a query and cache: calling find_records(query) with query.select_all() { return this._adapter.find_all_records(this._schema.get_name()) .then( (record_array)=>{ if ( T.isObject(record_array) && record_array.is_data_record_array ) { this._trigger('find_all_records', { has_error:false, error_msg:undefined, from:'adapter'}) return record_array } this._trigger('find_all_records', { has_error:true, error_msg:'bad DataRecordArray'} ) return undefined } ) .catch( (e)=>{ this._trigger('find_all_records', { has_error:true, error_msg:e } ) return undefined } ) } }
JavaScript
class Login extends React.Component { constructor() { super(); this.state = { display: false, activeLoginSection: 'activateCoin', loginPassphrase: '', seedInputVisibility: false, loginPassPhraseSeedType: null, bitsOption: 256, randomSeed: PassPhraseGenerator.generatePassPhrase(256), randomSeedConfirm: '', isSeedConfirmError: false, isSeedBlank: false, displaySeedBackupModal: false, customWalletSeed: false, isCustomSeedWeak: false, nativeOnly: Config.iguanaLessMode, trimPassphraseTimer: null, displayLoginSettingsDropdown: false, displayLoginSettingsDropdownSection: null, shouldEncryptSeed: false, encryptKey: '', pubKey: '', decryptKey: '', selectedPin: '', isExperimentalOn: false, enableEncryptSeed: false, selectedShortcutNative: '', selectedShortcutSPV: '', seedExtraSpaces: false, }; this.defaultState = JSON.parse(JSON.stringify(this.state)); this.toggleActivateCoinForm = this.toggleActivateCoinForm.bind(this); this.updateRegisterConfirmPassPhraseInput = this.updateRegisterConfirmPassPhraseInput.bind(this); this.updateLoginPassPhraseInput = this.updateLoginPassPhraseInput.bind(this); this.loginSeed = this.loginSeed.bind(this); this.toggleSeedInputVisibility = this.toggleSeedInputVisibility.bind(this); this.handleRegisterWallet = this.handleRegisterWallet.bind(this); this.toggleSeedBackupModal = this.toggleSeedBackupModal.bind(this); this.copyPassPhraseToClipboard = this.copyPassPhraseToClipboard.bind(this); this.execWalletCreate = this.execWalletCreate.bind(this); this.resizeLoginTextarea = this.resizeLoginTextarea.bind(this); this.toggleLoginSettingsDropdown = this.toggleLoginSettingsDropdown.bind(this); this.updateEncryptKey = this.updateEncryptKey.bind(this); this.updatePubKey = this.updatePubKey.bind(this); this.updateDecryptKey = this.updateDecryptKey.bind(this); this.loadPinList = this.loadPinList.bind(this); this.updateSelectedShortcut = this.updateSelectedShortcut.bind(this); this.setRecieverFromScan = this.setRecieverFromScan.bind(this); } _toggleNotaryElectionsModal() { this.setState({ displayLoginSettingsDropdown: false, }); Store.dispatch(toggleNotaryElectionsModal(true)); } // the setInterval handler for 'activeCoins' _iguanaActiveCoins = null; toggleLoginSettingsDropdownSection(sectionName) { Store.dispatch(toggleLoginSettingsModal(true)); this.setState({ displayLoginSettingsDropdown: false, displayLoginSettingsDropdownSection: sectionName, }); } setRecieverFromScan(receiver) { if (receiver) { this.setState({ loginPassphrase: receiver, }); } else { Store.dispatch( triggerToaster( 'Unable to recognize QR code', 'QR scan Error', 'error' ) ); } } isCustomWalletSeed() { return this.state.customWalletSeed; } toggleCustomWalletSeed() { this.setState({ customWalletSeed: !this.state.customWalletSeed, }, () => { // if customWalletSeed is set to false, regenerate the seed if (!this.state.customWalletSeed) { this.setState({ randomSeed: PassPhraseGenerator.generatePassPhrase(this.state.bitsOption), isSeedConfirmError: false, isSeedBlank: false, isCustomSeedWeak: false, }); } else { // if customWalletSeed is set to true, reset to seed to an empty string this.setState({ randomSeed: '', randomSeedConfirm: '', }); } }); } shouldEncryptSeed() { return this.state.shouldEncryptSeed; } toggleShouldEncryptSeed() { this.setState({ shouldEncryptSeed: !this.state.shouldEncryptSeed, }); } updateEncryptKey(e) { this.setState({ encryptKey: e.target.value, }); } updatePubKey(e) { this.setState({ pubKey: e.target.value, }); } updateDecryptKey(e) { this.setState({ decryptKey: e.target.value, }); } componentDidMount() { this.setState({ isExperimentalOn: mainWindow.experimentalFeatures, }); } toggleSeedInputVisibility() { this.setState({ seedInputVisibility: !this.state.seedInputVisibility, }); this.resizeLoginTextarea(); } generateNewSeed(bits) { this.setState(Object.assign({}, this.state, { randomSeed: PassPhraseGenerator.generatePassPhrase(bits), bitsOption: bits, isSeedBlank: false, })); } toggleLoginSettingsDropdown() { this.setState(Object.assign({}, this.state, { displayLoginSettingsDropdown: !this.state.displayLoginSettingsDropdown, })); } componentWillReceiveProps(props) { if (props.Login.pinList === 'no pins') { props.Login.pinList = []; } if (props && props.Main && props.Main.isLoggedIn) { if (props.Main.total === 0) { this.setState({ activeLoginSection: 'activateCoin', loginPassphrase: '', display: true, }); } else { this.setState({ loginPassphrase: '', display: false, }); } } if (props && props.Main && !props.Main.isLoggedIn) { document.body.className = 'page-login layout-full page-dark'; if (props.Interval && props.Interval.interval && props.Interval.interval.sync) { Store.dispatch(dashboardChangeActiveCoin()); Store.dispatch( stopInterval( 'sync', props.Interval.interval ) ); } this.setState({ display: true, activeLoginSection: this.state.activeLoginSection !== 'signup' ? 'login' : 'signup', }); } if (props.Main && props.Main.total === 0) { document.body.className = 'page-login layout-full page-dark'; if (props.Interval && props.Interval.interval && props.Interval.interval.sync) { Store.dispatch(dashboardChangeActiveCoin()); Store.dispatch( stopInterval( 'sync', props.Interval.interval ) ); } } if (this.state.activeLoginSection !== 'signup' && props && props.Main && props.Main.isLoggedIn) { this.setState({ loginPassphrase: '', activeLoginSection: 'activateCoin', }); } } toggleActivateCoinForm() { Store.dispatch(toggleAddcoinModal(true, false)); } resizeLoginTextarea() { // auto-size textarea setTimeout(() => { if (this.state.seedInputVisibility) { document.querySelector('#loginPassphrase').style.height = '1px'; document.querySelector('#loginPassphrase').style.height = `${(15 + document.querySelector('#loginPassphrase').scrollHeight)}px`; } }, 100); } updateLoginPassPhraseInput(e) { const newValue = e.target.value; clearTimeout(this.state.trimPassphraseTimer); const _trimPassphraseTimer = setTimeout(() => { if (newValue[0] === ' ' || newValue[newValue.length - 1] === ' ') { this.setState({ seedExtraSpaces: true, }); } else { this.setState({ seedExtraSpaces: false, }); } }, SEED_TRIM_TIMEOUT); this.resizeLoginTextarea(); this.setState({ trimPassphraseTimer: _trimPassphraseTimer, [e.target.name === 'loginPassphraseTextarea' ? 'loginPassphrase' : e.target.name]: newValue, loginPassPhraseSeedType: this.getLoginPassPhraseSeedType(newValue), }); } updateRegisterConfirmPassPhraseInput(e) { this.setState({ [e.target.name]: e.target.value, isSeedConfirmError: false, isSeedBlank: this.isBlank(e.target.value), }); } updateWalletSeed(e) { this.setState({ randomSeed: e.target.value, isSeedConfirmError: false, isSeedBlank: this.isBlank(e.target.value), }); } loginSeed() { mainWindow.createSeed.secondaryLoginPH = md5(this.state.loginPassphrase); // reset the login pass phrase values so that when the user logs out, the values are clear this.setState({ loginPassphrase: '', loginPassPhraseSeedType: null, }); // reset login input vals this.refs.loginPassphrase.value = ''; this.refs.loginPassphraseTextarea.value = ''; if (this.state.shouldEncryptSeed) { Store.dispatch(encryptPassphrase(this.state.loginPassphrase, this.state.encryptKey, this.state.pubKey)); } if (this.state.selectedPin) { Store.dispatch(loginWithPin(this.state.decryptKey, this.state.selectedPin)); } else { Store.dispatch(shepherdElectrumAuth(this.state.loginPassphrase)); Store.dispatch(shepherdElectrumCoins()); } this.setState(this.defaultState); } loadPinList() { Store.dispatch(loadPinList()); } updateSelectedPin(e) { this.setState({ selectedPin: e.target.value, }); } getLoginPassPhraseSeedType(passPhrase) { if (!passPhrase) { return null; } const passPhraseWords = passPhrase.split(' '); if (!PassPhraseGenerator.arePassPhraseWordsValid(passPhraseWords)) { return null; } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 256)) { return translate('LOGIN.IGUANA_SEED'); } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 160)) { return translate('LOGIN.WAVES_SEED'); } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 128)) { return translate('LOGIN.NXT_SEED'); } return null; } updateActiveLoginSection(name) { // reset login/create form this.setState({ activeLoginSection: name, loginPassphrase: null, loginPassPhraseSeedType: null, seedInputVisibility: false, bitsOption: 256, randomSeed: PassPhraseGenerator.generatePassPhrase(256), randomSeedConfirm: '', isSeedConfirmError: false, isSeedBlank: false, displaySeedBackupModal: false, customWalletSeed: false, isCustomSeedWeak: false, }); } execWalletCreate() { mainWindow.createSeed.triggered = true; mainWindow.createSeed.firstLoginPH = md5(this.state.randomSeed); Store.dispatch( shepherdElectrumAuth(this.state.randomSeedConfirm) ); Store.dispatch( shepherdElectrumCoins() ); this.setState({ activeLoginSection: 'activateCoin', displaySeedBackupModal: false, isSeedConfirmError: false, }); } // TODO: disable register btn if seed or seed conf is incorrect handleRegisterWallet() { const enteredSeedsMatch = this.state.randomSeed === this.state.randomSeedConfirm; const isSeedBlank = this.isBlank(this.state.randomSeed); // if custom seed check for string strength // at least 1 letter in upper case // at least 1 digit // at least one special char // min length 10 chars const _customSeed = this.state.customWalletSeed ? this.state.randomSeed.match('^(?=.*[A-Z])(?=.*[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[_+]*$)(?=.*[0-9])(?=.*[a-z]).{10,99}$') : false; this.setState({ isCustomSeedWeak: _customSeed === null ? true : false, isSeedConfirmError: !enteredSeedsMatch ? true : false, isSeedBlank: isSeedBlank ? true : false, }); if (enteredSeedsMatch && !isSeedBlank && _customSeed !== null) { this.toggleSeedBackupModal(); } } isBlank(str) { return (!str || /^\s*$/.test(str)); } handleKeydown(e) { this.updateLoginPassPhraseInput(e); if (e.key === 'Enter' && this.state.loginPassphrase) { this.loginSeed(); } } toggleSeedBackupModal() { this.setState(Object.assign({}, this.state, { displaySeedBackupModal: !this.state.displaySeedBackupModal, })); } copyPassPhraseToClipboard() { const passPhrase = this.state.randomSeed; const textField = document.createElement('textarea'); textField.innerText = passPhrase; document.body.appendChild(textField); textField.select(); document.execCommand('copy'); textField.remove(); Store.dispatch( triggerToaster( translate('LOGIN.SEED_SUCCESSFULLY_COPIED'), translate('LOGIN.SEED_COPIED'), 'success' ) ); } updateSelectedShortcut(e, type) { this.setState({ [type === 'native' ? 'selectedShortcutNative' : 'selectedShortcutSPV'] : e.value, }); if (type === 'native') { const _res = mainWindow.zcashParamsExist; const __errors = zcashParamsCheckErrors(_res); if (__errors) { mainWindow.zcashParamsExistPromise() .then((res) => { const _errors = zcashParamsCheckErrors(res); mainWindow.zcashParamsExist = res; if (_errors) { Store.dispatch( triggerToaster( _errors, 'Safecoind', 'error', false ) ); Store.dispatch(toggleZcparamsFetchModal(true)); } else { mainWindow.startSAFENative(e.value.toUpperCase()); } }); } else { mainWindow.startSAFENative(e.value.toUpperCase()); } } else { mainWindow.startSPV(e.value.toUpperCase()); } setTimeout(() => { Store.dispatch(activeHandle()); if (type === 'native') { Store.dispatch(shepherdElectrumCoins()); } Store.dispatch(getDexCoins()); }, 500); setTimeout(() => { Store.dispatch(activeHandle()); if (type === 'native') { Store.dispatch(shepherdElectrumCoins()); } Store.dispatch(getDexCoins()); }, 1000); setTimeout(() => { Store.dispatch(activeHandle()); if (type === 'native') { Store.dispatch(shepherdElectrumCoins()); } Store.dispatch(getDexCoins()); }, type === 'native' ? 5000 : 2000); } renderSwallModal() { if (this.state.displaySeedBackupModal) { return SwallModalRender.call(this); } return null; } renderShortcutOption(option) { if (option.value.indexOf('+') > -1) { const _comps = option.value.split('+'); let _items = []; for (let i = 0; i < _comps.length; i++) { _items.push( <span key={ `addcoin-shortcut-icons-${i}` }> <img src={ `assets/images/cryptologo/${_comps[i].toLowerCase()}.png` } alt={ _comps[i].toUpperCase() } width="30px" height="30px" /> { i !== _comps.length - 1 && <span className="margin-left-10 margin-right-10">+</span> } </span> ); } return _items; } else { return ( <div> <img src={ `assets/images/cryptologo/${option.value.toLowerCase()}.png` } alt={ option.value.toUpperCase() } width="30px" height="30px" /> <span className="margin-left-10">{ option.value.toUpperCase() }</span> </div> ); } } render() { if ((this.state && this.state.display) || !this.props.Main) { return LoginRender.call(this); } return null; } }
JavaScript
class RecordSet { constructor() { /** * The records within this record set. * @type {Array} */ this.records = []; /** * List of failed records (ParseError). * @type {ParseError[]} */ this.failed = []; } /** * The total number of parsed records in the record set. * @type {Number} * @readonly */ get length() { return this.records.length; } /** * Boolean flag if this record set has failed records. * @type {Boolean} * @readonly */ get hasErrors() { return !!this.failed.length; } /** * Adds a record to the record set. * @ignore * @param {*} record The record to add to the set. * @returns {RecordSet} The instance of RecordSet. */ add(record) { if(record instanceof ParseError) { this.failed.push(record); } else { this.records.push(record); } return this; } }
JavaScript
class Cornea extends events.EventEmitter { /** @prototype */ constructor() { super(); // Can be set to 0 to allow for unlimited number of listeners per a single event; set to 50 initially // https://nodejs.org/docs/latest-v5.x/api/events.html#events_emitter_setmaxlisteners_n this.setMaxListeners(50); this.resetState(); } /** * @function resetState * * Resets the internal state of Cornea. */ resetState() { this.id = null; this.connected = null; this.connectionPromise = null; this.socket = null; this.reconnecting = null; this.connecting = null; this.wasConnected = false; this.backoff = null; this.requests = {}; } /** * @function initialize * * Begins the WebSocket connection process. * @param {String} url The WebSocket url. */ initialize(url) { if (typeof url !== 'string') { throw new Error('URL must be defined to establish a web socket connection'); } if (!('WebSocket' in window && window.WebSocket !== undefined)) { throw new Error('WebSockets not supported in the current browser. Please update your browser to a newer version.'); } if (!this.backoff) { this.backoff = new Backoff({ initial: 100, max: 30000, callback: this.connect.bind(this), }); } this.url = url; // If there is already a connection open, close it and let this new one happen if (!this.socket) { this.connect(); } return this.connected; } /** * @function log * * Log a message to the console if not in production. */ log(type, ...args) { if (!System.isEnv('production')) { args.unshift(`Cornea ${type}`); console.log(...args); // eslint-disable-line no-console } } /** * @function connect * * Attempt to connect to the url provided. * If the connection is successful event handlers are attached to the WebSocket instance. * @return {Promise} deferred that will resolve with the WebSocket instance when successful. */ connect() { const url = this.url; this.log('Connecting...'); this.connecting = true; if (!this.connected) { this.connected = new Promise((resolve, reject) => { this.connectionPromise = { resolve, reject, }; }); } this.socket = new window.WebSocket(url); this.socket.onopen = () => { this.connectionPromise.resolve(); this.onOpen(); }; this.socket.onerror = (ev) => { if (this.connectionPromise) { this.connectionPromise.reject(); } this.onError(ev); }; // Setup event handling ['close', 'message'].forEach((name) => { this.socket[`on${name}`] = this[`on${capitalize(name)}`].bind(this); }); return this.connected.then(this.onConnected.bind(this)); } /** * @function onConnected * * Called when the WebSocket instance is connected. * Stops reconnection process (if active). */ onConnected() { this.log('Connected!'); this.connecting = false; this.stopReconnect(); } /** * @function stopReconnect * * Cancels the backoff and clears the reconnecting flag. */ stopReconnect() { this.reconnecting = false; if (this.backoff) { this.backoff.cancel(); } } /** * @function reconnect * * Attempts to reconnect to the web scoket API using an exponential backoff. */ reconnect() { if (this.reconnecting) { return; } this.reconnecting = true; this.log('Attempting to reconnect...'); this.backoff.start(); } /** * @function send * * Sends a message via the WebSocket instance. * Stringifies JSON payloads. * @param {String|Object} msg payload to send to server. * @param {Promise} deferred representing the status of sending the message. */ send(msg) { return new Promise((resolve, reject) => { const socket = this.socket; // The socket hasn't been created if we entered in an invalid URL. But // we also want to make sure the state of the socket is one that can // send messages. if (!socket || socket.readyState !== window.WebSocket.OPEN) { // We could queue messages to be sent when a connection is re-established const errorMessage = this.getErrorMessage(`Wait a moment... we're getting things ready for you.`, msg); reject(errorMessage.payload.attributes); return; } this.connected.then(() => { const uuid = nodeUuid.v1(); const currentId = this.id; msg.headers.correlationId = uuid; this.requests[uuid] = { resolve, reject, timeout: setTimeout(() => { // Only reject if the connection that made the request is still open if (this.id === currentId) { const timeoutMessage = this.getErrorMessage('Oops, there seems to be a problem connecting right now.', msg); reject(timeoutMessage.payload.attributes); } }, this.timeout), }; this.log(`--> ${msg.type}`, msg); const payload = typeof msg === 'object' ? JSON.stringify(msg) : msg; queueIfPlatformRequires(() => { try { socket.send(payload); } catch (e) { this.log('Error', e); reject(e); } }); }).catch(e => reject(e)); }); } /** * @function close * * Close the connection. */ close() { this.log('Closing Connection'); this.stopReconnect(); if (!this.socket) { return; } this.socket.close(); } /** * @function onOpen * * onopen handler of the WebSocket instance. */ onOpen() { this.id = nodeUuid.v1(); this.wasConnected = true; this.log('Connected'); } /** * @function getEventSubject * * Parse the source for the id, namespace and address of an object. * @param {String} source. * @return {Object} */ getEventSubject(source) { if (!source) { return null; } const parts = source.split(':'); // the hub has the id structure of SERV:LWF-5229:hub // so we need to adjust the parts if (parts[0] === 'SERV' && parts[2] === 'hub') { return { id: parts[1], namespace: parts[2], address: source, }; } // the namespace of a subsystem is its group name // therefore we need to check if the namespace starts with sub or // is cellbackup (since it doesn't start with sub) if (parts[1].indexOf('sub') === 0 || parts[1] === 'cellbackup') { parts[1] = 'sub'; } return { id: parts[2], namespace: parts[1], address: source, }; } /** * @function onMessage * * onmessage handler for the WebSocket instance. * Emits an event with the payload (parsed JSON or String). * @param {MessageEvent} ev */ onMessage(ev) { if (!this.socket) { return; } // Crude check to see if payload is JSON or a String const message = ev.data[0] === '{' || ev.data[0] === '[' ? JSON.parse(ev.data) : ev.data; this.log(`<-- ${message.type}`, message); const eventType = message.type; const subject = this.getEventSubject(message.headers.source); const uuid = message.headers.correlationId; const request = this.requests[uuid]; if (request) { if (eventType === 'Error') { if (message.payload.code === 'error.unauthorized') { this.emit('sess unauthorized', {}); } request.reject(message.payload.attributes); } else { clearTimeout(request.timeout); request.resolve(message.payload.attributes); } } if (subject) { this.emit(`${subject.namespace} ${eventType}`, Object.assign({ 'base:address': subject.address }, message.payload.attributes)); } else { this.emit(eventType, message.payload.attributes); } } /** * @function onError * * onerror handler for the WebSocket instance. * @param {Event} ev */ onError(ev) { this.log('Error', ev); } /** * @function getTimeoutMessage * * Return a formatted message. * @param {Object} originalMessage The request that has caused the error. * @return {Object} */ getErrorMessage(errorMessage, originalMessage) { return { type: 'Error', headers: { isRequest: false, destination: originalMessage.headers.destination, }, payload: { messageType: 'Error', attributes: { type: 'Error', message: errorMessage, }, }, }; } /** * @function onClose * * Handles the closing of the socket connection. * Attempts to reconnect if the closure was unclean. * @param {CloseEvent} ev */ onClose(ev) { this.log('Connection Closed', ev); this.emit('WebSocketClosed', ev); this.connected = false; // 1000 means a normal close, 4001 means session ended // anything else is abnormal and triggers a reconnection if (![1000, 4001].includes(ev.code)) { if (this.reconnecting) { // Continuing trying to reconnect this.backoff.continue(); } else if (this.wasConnected) { // Try to reconnect if we are not already this.reconnect(); } else { this.cleanup(); } } else { this.cleanup(); if (ev.code === 4001) { this.emit('sess unauthorized'); } } } /** * @function cleanup * * Closes the current WebSocket and cleans up the properties used to track state. */ cleanup() { this.close(); this.resetState(); } }
JavaScript
class CreateScimUserJSONRequest { /** * Constructs a new <code>CreateScimUserJSONRequest</code>. * @alias module:model/CreateScimUserJSONRequest */ constructor() { CreateScimUserJSONRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>CreateScimUserJSONRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/CreateScimUserJSONRequest} obj Optional instance to populate. * @return {module:model/CreateScimUserJSONRequest} The populated <code>CreateScimUserJSONRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new CreateScimUserJSONRequest(); if (data.hasOwnProperty('userName')) { obj['userName'] = ApiClient.convertToType(data['userName'], 'String'); } if (data.hasOwnProperty('password')) { obj['password'] = ApiClient.convertToType(data['password'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ScimUserName.constructFromObject(data['name']); } if (data.hasOwnProperty('preferredLanguage')) { obj['preferredLanguage'] = ApiClient.convertToType(data['preferredLanguage'], 'String'); } if (data.hasOwnProperty('active')) { obj['active'] = ApiClient.convertToType(data['active'], 'Boolean'); } if (data.hasOwnProperty('authenticatedUserName')) { obj['authenticatedUserName'] = ApiClient.convertToType(data['authenticatedUserName'], 'String'); } if (data.hasOwnProperty('tenant')) { obj['tenant'] = ApiClient.convertToType(data['tenant'], 'String'); } if (data.hasOwnProperty('phoneNumbers')) { obj['phoneNumbers'] = ApiClient.convertToType(data['phoneNumbers'], [ScimPhone]); } if (data.hasOwnProperty('emails')) { obj['emails'] = ApiClient.convertToType(data['emails'], [ScimEmail]); } if (data.hasOwnProperty('photos')) { obj['photos'] = ApiClient.convertToType(data['photos'], [ScimPhoto]); } } return obj; } }
JavaScript
class Wax extends universal_authenticator_library_1.Authenticator { constructor(chains, options) { super(chains, options); this.users = []; this.initiated = false; this.apiSigner = { getAvailableKeys: async () => { return [ "PUB_K1_7FUX7yAxiff74N2GEgainGr5jYnKmeY2NjXagLMsyFbNX9Hkup", ]; }, sign: async (data) => { if (data.requiredKeys.indexOf("PUB_K1_7FUX7yAxiff74N2GEgainGr5jYnKmeY2NjXagLMsyFbNX9Hkup") === -1) { console.log("Test3"); return { signatures: [], serializedTransaction: data.serializedTransaction, }; } // TODO: Find a single source of truth for the same enum in the backend const request = { transaction: Array.from(data.serializedTransaction), }; const response = await fetch("https://api.limitlesswax.co/cpu-rent", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(request), }); console.log(response); if (!response.ok) { const body = await response.json(); alert(body.reason); throw Error(body.reason || "Failed to connect to endpoint"); } const json = await response.json(); console.debug("response:", json); if (!json.isOk) { // TODO: display alert here with the json.reason alert(json.message); throw Error(json.message); } const output = { signatures: json.signature, serializedTransaction: data.serializedTransaction, }; return output; }, }; this.waxSigningURL = options && options.waxSigningURL; this.waxAutoSigningURL = options && options.waxAutoSigningURL; } /** * Called after `shouldRender` and should be used to handle any async actions required to initialize the authenticator */ async init() { this.initWaxJS(); try { if (this.wax) { if (await this.wax.isAutoLoginAvailable()) { this.receiveLogin(); } else { const data = JSON.parse(localStorage.getItem("ual-wax:autologin") || "null"); if (data && data.expire >= Date.now()) { this.receiveLogin(data.userAccount, data.pubKeys); } } } } catch (e) { console.log("UAL-WAX: autologin error", e); } this.initiated = true; console.log(`UAL-WAX: init`); } /** * Resets the authenticator to its initial, default state then calls `init` method */ reset() { this.wax = undefined; this.users = []; this.initiated = false; this.session = undefined; } /** * Returns true if the authenticator has errored while initializing. */ isErrored() { return false; } /** * Returns a URL where the user can download and install the underlying authenticator * if it is not found by the UAL Authenticator. */ getOnboardingLink() { return "https://all-access.wax.io/"; } /** * Returns error (if available) if the authenticator has errored while initializing. */ getError() { return null; } /** * Returns true if the authenticator is loading while initializing its internal state. */ isLoading() { return !this.initiated; } /** * Returns the style of the Button that will be rendered. */ getStyle() { return { icon: WaxIcon_1.WaxIcon, text: "WAX Cloud Wallet", textColor: "white", background: "#111111", }; } /** * Returns whether or not the button should render based on the operating environment and other factors. * ie. If your Authenticator App does not support mobile, it returns false when running in a mobile browser. */ shouldRender() { return true; } /** * Returns whether or not the dapp should attempt to auto login with the Authenticator app. * Auto login will only occur when there is only one Authenticator that returns shouldRender() true and * shouldAutoLogin() true. */ shouldAutoLogin() { return false; } /** * Returns whether or not the button should show an account name input field. * This is for Authenticators that do not have a concept of account names. */ async shouldRequestAccountName() { return false; } /** * Returns the amount of seconds after the authentication will be invalid for logging in on new * browser sessions. Setting this value to zero will cause users to re-attempt authentication on * every new browser session. Please note that the invalidate time will be saved client-side and * should not be relied on for security. */ shouldInvalidateAfter() { return 86400; } /** * Login using the Authenticator App. This can return one or more users depending on multiple chain support. */ async login() { console.log(`UAL-WAX: login requested`); console.log(this.apiSigner); // Commented for now to support multiple wax chains such as testnets/staging in the future // Mainnet check: this.chains[0].chainId !== '1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4' if (this.chains.length > 1) { throw new UALWaxError_1.UALWaxError("WAX Could Wallet only supports one WAX chain", dist_1.UALErrorType.Unsupported, null); } if (!this.wax) { throw new UALWaxError_1.UALWaxError("WAX Cloud Wallet not initialized yet", dist_1.UALErrorType.Initialization, null); } try { if (!this.session) { await this.wax.login(); this.receiveLogin(); } if (!this.session) { throw new Error("Could not receive login information"); } this.users = [ new WaxUser_1.WaxUser(this.chains[0], this.session.userAccount, this.session.pubKeys, this.wax), ]; console.log(`UAL-WAX: login`, this.users); return this.users; } catch (e) { throw new UALWaxError_1.UALWaxError(e.message ? e.message : "Could not login to the WAX Cloud Wallet", dist_1.UALErrorType.Login, e); } } /** * Logs the user out of the dapp. This will be strongly dependent on each Authenticator app's patterns. */ async logout() { this.initWaxJS(); this.users = []; this.session = undefined; localStorage.setItem("ual-wax:autologin", "null"); console.log(`UAL-WAX: logout`); } /** * Returns true if user confirmation is required for `getKeys` */ requiresGetKeyConfirmation() { return false; } /** * Returns name of authenticator for persistence in local storage */ getName() { return "wax"; } receiveLogin(userAccount, pubKeys) { if (!this.wax) { return; } const login = { // @ts-ignore userAccount: userAccount || this.wax.userAccount, // @ts-ignore pubKeys: pubKeys || this.wax.pubKeys, expire: Date.now() + this.shouldInvalidateAfter() * 1000, }; if (!login.userAccount || !login.pubKeys) { return; } localStorage.setItem("ual-wax:autologin", JSON.stringify(login)); this.session = login; } initWaxJS() { console.log(this.apiSigner); this.wax = new dist_2.WaxJS({ rpcEndpoint: this.getEndpoint(), tryAutoLogin: false, apiSigner: this.apiSigner, waxSigningURL: this.waxSigningURL, waxAutoSigningURL: this.waxAutoSigningURL, }); } getEndpoint() { return `${this.chains[0].rpcEndpoints[0].protocol}://${this.chains[0].rpcEndpoints[0].host}:${this.chains[0].rpcEndpoints[0].port}`; } }
JavaScript
class Observers { /** * Add observer for target. * @param {Proto} target * @param {IObserver} [observer] */ static add(target, observer = target) { let set = locals.get(target); if (observable(target)) { if (!set) { locals.set(target, (set = new Set())); } set.add(observer); } else { observererror(target); } } /** * Remove observer for target. * @param {Proto} target * @param {IObserver} [observer] */ static remove(target, observer = target) { let set = locals.get(target); if (observable(target)) { if (set) { set.delete(observer); if (!set.size) { locals.delete(target); } } } else { observererror(target); } } /** * Add observer for all targets. * @param {IObserver} observer */ static addGlobal(observer) { globals.add(observer); } /** * Remove observer for all targets. * @param {IObserver} observer */ static removeGlobal(observer) { globals.delete(observer); } /** * Model property inspected. * TODO: For globals, confirm that the property (descriptor) is writable. * @param {Proto} target * @param {string} name */ static $peek(target, name) { if (observable(target) && peeking) { if (globals.size) { suspendpeeking(() => { globals.forEach(observer => { if (observer.onpeek) { observer.onpeek(getProxy(target), name); } }); }); } if (locals.has(target) && ispublic(name)) { let names = peeks.get(target); if (!names) { peeks.set(target, (names = new Set())); } names.add(name); debug('$peek', target); schedule(); } } } /** * TODO: Local observers should NOT be notified about "private" * changes (unless they have been proxied by a "public" getter) * Model property changed. * @param {Proto} target * @param {string} name * @param {*} newval * @param {*} oldval */ static $poke(target, name, newval, oldval) { if (observable(target)) { if (globals.size || locals.has(target)) { let props = pokes.get(target); if (props) { if (props.has(name)) { props.get(name)[0] = newval; } else { props.set(name, [newval, oldval]); } } else { props = new Map(); props.set(name, [newval, oldval]); pokes.set(target, props); } debug('$poke', target, name); schedule(); } } } /** * Collection members changed somehow. This gets called *before* the * update operation(s) happens: We'll snapshot the old collection and * compare it to the new so that we can figure out what was changed. * @param {Collection} target */ static $splice(target) { if (observable(target) && (globals.size || locals.has(target))) { if (!mutes.has(target)) { mutes.set(target, Array.from(target)); debug('$splice', target); schedule(); } } } }
JavaScript
class NotFound extends Component { render() { return( <div className="app-wrapper"> <div className="row full-page-section origin"> <div className="col-xs-12 col-sm-6 col-md-6 col-lg-6 center-xs"> <div className='tagline'>Error 404: We can't find the page you're looking for. </div> </div> </div> </div> ); } }
JavaScript
class Controller { constructor() { this.visibleFramesInfo = []; } onDatasetChanged() { this.initVisibleFramesInfo(); } initVisibleFramesInfo() { // Initially only show a depth of 0 // Starting at frame of index 0 this.visibleFramesInfo = []; this.visibleFramesInfo.push({ start: 0, zoomedFromFrame: -1 }); // Loading variables this.framesBeingLoaded = 0; this.clickedWhileLoading = false; Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } setNavigationEvents(row) { let leftButton = row.getElementsByClassName("btn-nav-left")[0]; leftButton.onclick = this.onNavigationClickLeft.bind(this); let rightButton = row.getElementsByClassName("btn-nav-right")[0]; rightButton.onclick = this.onNavigationClickRight.bind(this); } onNavigationClickLeft(event) { // Get row from the button let row = event.srcElement.parentElement; let rowId = parseInt(row.getAttribute("data-row-id")); // Decrement and clamp to zero this.visibleFramesInfo[rowId].start = Math.max(this.visibleFramesInfo[rowId].start - Controller.rowNavigationStep, 0); //console.log(`Row: ${rowId} | Start: ${this.visibleFramesInfo[rowId].start}`); Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } onNavigationClickRight() { // Get row from the button let row = event.target.closest(".storyboard-row"); let rowId = parseInt(row.getAttribute("data-row-id")); // Increment and clamp to total number of frames this.visibleFramesInfo[rowId].start = Math.max(0, Math.min(this.visibleFramesInfo[rowId].start + Controller.rowNavigationStep, this.getTotalNumberFramesInRow(rowId) - Renderer.instance.maxFramesPerPage) ); //console.log(`Row: ${rowId} | Start: ${this.visibleFramesInfo[rowId].start}`); Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } setFrameDetailEvents(frameElement) { frameElement.onclick = this.onFrameClick.bind(this); frameElement.onmouseover = this.onFrameMouseOver.bind(this); frameElement.onmouseout = this.onFrameMouseOut.bind(this); } onFrameMouseOver(event) { let frame = event.target.closest(".storyboard-frame"); let frameId = parseInt(frame.getAttribute("data-frame-id")); let rowContainer = frame.closest(".row-container"); let frameTimeline = rowContainer.getElementsByClassName("frame-timeline")[0]; let frameTimelineItem = frameTimeline.children[frameId]; frameTimelineItem.classList.add("frame-hover"); } onFrameMouseOut(event) { let frame = event.target.closest(".storyboard-frame"); let frameId = parseInt(frame.getAttribute("data-frame-id")); let rowContainer = frame.closest(".row-container"); let frameTimeline = rowContainer.getElementsByClassName("frame-timeline")[0]; let frameTimelineItem = frameTimeline.children[frameId]; frameTimelineItem.classList.remove("frame-hover"); } onFrameClick(event) { // Get frame and row let frame = event.target.closest(".storyboard-frame"); let frameId = parseInt(frame.getAttribute("data-frame-id")); let row = frame.closest(".storyboard-row"); let rowId = parseInt(row.getAttribute("data-row-id")); //console.log(`Row: ${rowId} | Frame: ${frameId}`); // Make sure row is present in the visible frames let rowInfo = this.visibleFramesInfo[rowId]; if( rowInfo !== undefined && rowInfo !== null ) { // Check if this frame is already zoomed let frameIsZoomed = rowId+1 < this.visibleFramesInfo.length && this.visibleFramesInfo[rowId+1].zoomedFromFrame === frameId; // Clear all content after (bellow) this row this.visibleFramesInfo = this.visibleFramesInfo.slice(0, rowId+1); if ( !frameIsZoomed ) { // Get frame object let frameObject = this.getFrameById(this.getRowById(rowId), frameId); // If the frame's child frames have not been loaded, request them if ( frameObject.childFrames === null ) { this.framesBeingLoaded++; Loader.SendRequest((childFrames) => { //console.log(childFrames); // Set frame's child frames frameObject.childFrames = childFrames; this.framesBeingLoaded--; if ( this.framesBeingLoaded === 0 && !this.clickedWhileLoading ) { // Add a new row this.visibleFramesInfo.push({ start: 0, zoomedFromFrame: frameId }); Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } }, (error) => { console.error(error); this.framesBeingLoaded--; }, rowId+1, frameObject.initialTimestamp, frameObject.finalTimestamp); return; } this.clickedWhileLoading = this.framesBeingLoaded > 0; // Add a new row this.visibleFramesInfo.push({ start: 0, zoomedFromFrame: frameId }); } Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } } setFrameTimelineItemEvent(item) { item.onclick = this.onFrameTimelineItemClick.bind(this); } onFrameTimelineItemClick(event) { // Get frame and row let frameId = parseInt(event.target.getAttribute("data-frame-id")); let row = event.target.closest(".frame-timeline"); let rowId = parseInt(row.getAttribute("data-row-id")); //console.log(`Row: ${rowId} | Frame: ${frameId}`); // Set start to the frame clicked this.visibleFramesInfo[rowId].start = Math.max(0, Math.min(frameId, this.getTotalNumberFramesInRow(rowId) - Renderer.instance.maxFramesPerPage)); //console.log(`Row: ${rowId} | Start: ${this.visibleFramesInfo[rowId].start}`); Renderer.instance.setVisibleFramesInfo(this.visibleFramesInfo); } getFrameById(row, frameId) { return row[frameId]; } getRowById(rowId) { // Loop Visible Frames Info let row = null; let i = 0; while (i <= rowId) { const info = this.visibleFramesInfo[i]; if (i == 0) row = Storyboard.instance.frames; // Initial set of frames (depth = 0) else row = row[info.zoomedFromFrame].childFrames; // Access the element that got zoomed from the previous row i++; } return row; } getTotalNumberFramesInRow(rowId) { return this.getRowById(rowId).length; } /* --------------- Constants --------------- */ // Number of frames incremented/decremented when navigating static get rowNavigationStep() { return 1; } }
JavaScript
class ConnectionDetails { constructor() { this.options = {}; } }
JavaScript
class FuroDataDisplay extends FBP(LitElement) { constructor() { super(); this._FBPAddWireHook("--valueChanged", (val) => { if (this.field) { this.field._value= val; } }); this.field = {}; } /** * flow is ready lifecycle method */ _FBPReady() { super._FBPReady(); //this._FBPTraceWires(); // check initial overrides CheckMetaAndOverrides.UpdateMetaAndConstraints(this); } _updateField() { this.text = this.field._value; if (this.displayfield && this.field[this.displayfield]) { this.text = this.field[this.displayfield]; } else { if (this.field.display_name) { this.text = this.field.display_name; } } if (this.text && this.text.toString() == undefined) { this.text = ""; } this.requestUpdate(); } /** * @private * @return {Object} */ static get properties() { return { /** * If your field type does not have a display_name, use this attribute to set the field that should be used * instead of display_name. */ displayfield: {type: String}, /** * Overrides the label text from the **specs**. * * Use with caution, normally the specs defines this value. */ label: { type: String, }, /** * Overrides the hint text from the **specs**. * * Use with caution, normally the specs defines this value. */ hint: { type: String, }, /** * Icon on the left side */ leadingIcon: { type: String, attribute: "leading-icon" }, /** * Icon on the right side */ trailingIcon: { type: String, attribute: "trailing-icon" }, /** * The default style (md like) supports a condensed form. It is a little bit smaller then the default */ condensed: { type: Boolean }, /** * passes always float the label */ float: { type: Boolean } } } /** * Bind a entity field to the text-input. You can use the entity even when no data was received. * When you use `@-object-ready` from a `furo-data-object` which emits a EntityNode, just bind the field with `--entity(*.fields.fieldname)` * @param {Object|FieldNode} fieldNode a Field object */ bindData(fieldNode) { Helper.BindData(this, fieldNode); } /** * Themable Styles * @private * @return {CSSResult} */ static get styles() { // language=CSS return Theme.getThemeForComponent(this.name) || css` :host { display: inline-block; position: relative; box-sizing: border-box; margin: 10px 0 15px 0; height: 56px; width: 190px; } :host([hidden]) { display: none; } .wrapper { position: relative; padding: 0 12px; box-sizing: border-box; height: 56px; border-top-left-radius: 4px; border-top-right-radius: 4px; } .iwrap { position: relative; } .text { position: absolute; top: 16px; border: none; background: none; box-sizing: border-box; margin: 0; padding: 0; width: 100%; line-height: 24px; color: inherit; outline: none; font-family: "Roboto", "Noto", sans-serif; font-kerning: auto; font-size: 16px; font-stretch: 100%; font-style: normal; } furo-icon { display: none; top: 16px; } furo-icon.lead { position: absolute; left: 8px; } furo-icon.trail { position: absolute; right: 8px; } :host([leading-icon]:not([leading-icon="undefined"])) furo-icon.lead, :host([trailing-icon]:not([trailing-icon="undefined"])) furo-icon.trail { display: block; } :host([leading-icon]:not([leading-icon="undefined"])) .wrapper { padding-left: 36px; } :host([trailing-icon]:not([trailing-icon="undefined"])) .wrapper { padding-right: 36px; } .borderlabel { pointer-events: none; position: absolute; box-sizing: border-box; top: 0; right: 0; left: 0; height: 56px; display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-direction: row; -webkit-flex-direction: row; flex-direction: row; } .left-border { width: 8px; box-sizing: border-box; pointer-events: none; border: 1px solid var(--input-activation-indicator-color, var(--disabled, #333333)); border-right: none; border-top-left-radius: 4px; border-bottom-left-radius: 4px; } .right-border { pointer-events: none; border: 1px solid var(--input-activation-indicator-color, var(--disabled, #333333)); border-left: none; border-top-right-radius: 4px; border-bottom-right-radius: 4px; -ms-flex: 1 1 0.000000001px; -webkit-flex: 1; flex: 1; -webkit-flex-basis: 0.000000001px; flex-basis: 0.000000001px; } label { color: var(--display-label-color, var(--disabled, #8c8c8c)); font-size: 12px; padding: 0 4px; font-weight: 400; position: relative; border-bottom: 1px solid var(--input-activation-indicator-color, var(--disabled, #333333)); } label span { font-size: 12px; top: -10px; position: relative; } /** Condensed **/ :host([condensed]) .text { top: 12px; font-size: 14px; } :host([condensed]:not([filled])) label, :host([filled][condensed]) label { line-height: 40px; font-size: 14px; } :host([condensed][filled]) .text { top: 12px; } :host([condensed]) .borderlabel, :host([condensed]) .wrapper { height: 40px; } :host([condensed]) furo-icon { top: 10px; } :host([condensed]) label span { top: -20px; } :host([condensed]) { height: 40px; } :host([noborder]) label, :host([noborder]) .left-border, :host([noborder]) .right-border { border: none; } ` } /** * @private * @returns {TemplateResult} * @private */ render() { // language=HTML return html` <div class="wrapper"> <furo-icon class="lead" icon="${this.leadingIcon}"></furo-icon> <div class="iwrap"> <div class="text"> ${this.text}</div> </div> <furo-icon class="trail" icon="${this.trailingIcon}"></furo-icon> </div> <div class="borderlabel"> <div class="left-border"></div> <label title="${this._hint}"><span>${this._label}</span></label> <div class="right-border"></div> </div> `; } }
JavaScript
class MockAgent { constructor() { this.__MOCK__ = new mock_1.Mock(); } head(path, params = {}, headers = {}) { return this.__MOCK__.invoke('head', [path, params, headers], res); } get(path, params = {}, headers = {}) { return this.__MOCK__.invoke('get', [path, params, headers], res); } post(path, body, headers = {}) { return this.__MOCK__.invoke('post', [path, body, headers], res); } put(path, body, headers = {}) { return this.__MOCK__.invoke('put', [path, body, headers], res); } patch(path, body, headers = {}) { return this.__MOCK__.invoke('patch', [path, body, headers], res); } delete(path, body, headers) { return this.__MOCK__.invoke('delete', [path, body, headers], res); } send(req) { return this.__MOCK__.invoke('send', [req], res); } }
JavaScript
class Tree extends PureComponent { static propTypes = { nodes: PropTypes.array.isRequired, checked: PropTypes.array.isRequired, onChange: PropTypes.func.isRequired, checkAllButtonText: PropTypes.string, uncheckAllButtonText: PropTypes.string, showTree: PropTypes.bool.isRequired, filterMode: PropTypes.bool.isRequired, } static defaultProps = { checkAllButtonText: 'Check all', uncheckAllButtonText: 'Uncheck all', } /** * Checks if all nodes of the tree were checked. * @param {number} numOfNodes - number of tree nodes * @param {Array} checkedList - list of checked tree nodes */ static isAllNodesChecked(numOfNodes, checkedList) { if (!numOfNodes || !checkedList) { return false; } if (numOfNodes === checkedList[0].checked.length + checkedList[1].checked.length) { return true; } return false; } /** * Checks if flat node has defined checkState * @param {Object} flatNode - flat node */ static isCheckStateSet(flatNode) { const { checkState } = flatNode; if (checkState === null || checkState === undefined) { return false; } return (checkState === 0 || checkState === 1 || checkState === 2); } constructor(props) { super(props); this.flatNodes = {}; flattenNodes(props.nodes, this.flatNodes); this.updateNodesWithChecked(props.checked, props.filterMode); this.state = { expanded: [], }; this.updateNodesWithExpanded(this.state.expanded); if (props.filterMode) { this.recountTree(); } this.onCheck = this.onCheck.bind(this); this.onExpand = this.onExpand.bind(this); this.checkAll = this.checkAll.bind(this); this.uncheckAll = this.uncheckAll.bind(this); } /** * Updates the tree data if the props were changed. * @param {Object} - next component properties */ componentWillReceiveProps({ nodes: netxtNodes, checked: nextChecked, filterMode: nextFilterMode }) { const { nodes: currentNodes, checked: currentChecked, filterMode: currentFilterMode } = this.props; if (!isEqual(currentNodes, netxtNodes)) { flattenNodes(netxtNodes, this.getFlatNodes()); } const needToRecount = (nextFilterMode && !currentFilterMode) || (currentFilterMode && !nextFilterMode) || (currentFilterMode && nextFilterMode); if (!isEqual(currentChecked, nextChecked)) { this.updateNodesWithChecked(nextChecked, needToRecount); if (needToRecount) { this.recountTree(); } } } /** * Handles the checking of a language or dictionary. * @param {Object} - info about checked tree node */ onCheck(nodeInfo) { this.toggleChecked(nodeInfo.value, nodeInfo.checked); this.recountParentsCheck(nodeInfo.value); this.sendCheckedListToTop(); } /** * Handles the expand or collapse of the tree node. * @param {Object} nodeInfo - info about expanded or collapsed node tree */ onExpand(nodeInfo) { this.toggleNode(nodeInfo.value, 'expanded', nodeInfo.expanded); this.setState({ expanded: this.getExpandedList(), }); } /** * Gets all nodes from wich recounting will go to the top * @param {Object} node - root node * @param {Array} container - array with all nodes from which recounting will go to the top */ getAllNodesToRecount(node, container = []) { if (node.children.length === 0) { if (node.dictionaries.length > 0) { container.push(node.dictionaries[0]); } else { container.push(node); } } else { node.children.forEach((child) => { this.getAllNodesToRecount(child, container); }); } return container; } /** * Gets state of the tree node for its visual presentation. * @param {Object} node - tree node * @returns {number} - state of the tree node. * 0 - unchecked, 1 - checked, 2 - unchecked, but has at least one checked child. */ getShallowCheckState(node) { const flatNode = this.getFlatNodeByNode(node); if (flatNode.isLeaf) { return flatNode.checked ? 1 : 0; } if (this.isEveryChildChecked(node)) { return 1; } if (this.isSomeChildChecked(node)) { return 2; } return 0; } /** * Generates a list of ids of checked tree nodes. * @returns {Array} - list pf ids of checked tree nodes */ getCheckedList() { const list = { language: [], dictionary: [], }; const flatNodes = this.getFlatNodes(); Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); if (flatNode.checked) { list[flatNode.type].push(value); } }); return Object.keys(list).map(item => ({ type: item, checked: list[item], })); } /** * Generates a list of ids of visually expanded tree nodes. * @returns {Array} - list pf ids of visually expanded tree nodes */ getExpandedList() { const list = []; const flatNodes = this.getFlatNodes(); Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); if (flatNode.expanded) { list.push(value); } }); return list; } getFlatNodes() { return this.flatNodes; } getFlatNodeByValue(value) { const flatNodes = this.getFlatNodes(); return flatNodes[value]; } getFlatNodeByNode(node) { const value = getNodeValue(node); return this.getFlatNodeByValue(value); } /** * Full recounting of the tree */ recountTree() { const flatNodes = this.getFlatNodes(); const rootNodeValues = Object.keys(flatNodes).filter((value) => { return !this.getFlatNodeByValue(value).parent.id; }); rootNodeValues.forEach((value) => { const flatNode = this.getFlatNodeByValue(value).self; const allNodesToRecount = this.getAllNodesToRecount(flatNode); allNodesToRecount.forEach(item => this.recountParentsCheck(getNodeValue(item))); }); } /** * Gets list of checked tree nodes and sends it to the parent component. */ sendCheckedListToTop() { const nextCheckedList = this.getCheckedList(); this.props.onChange(nextCheckedList); } /** * Recounts the checked state of the parent of the tree node. * @param {string} flatNodeValue - tree node value */ recountParentsCheck(flatNodeValue) { const flatNode = this.getFlatNodeByValue(flatNodeValue); let everyChildChecked = null; let someChildChecked = null; let parentValue = null; let parentFlatNode = null; let parentNode = null; if (flatNode.parent.id) { parentNode = flatNode.parent; everyChildChecked = this.isEveryChildChecked(parentNode); parentValue = getNodeValue(parentNode); parentFlatNode = this.getFlatNodeByValue(parentValue); if (everyChildChecked) { parentFlatNode.checkState = 1; parentFlatNode.checked = true; } else { someChildChecked = this.isSomeChildChecked(parentNode); parentFlatNode.checkState = someChildChecked ? 2 : 0; parentFlatNode.checked = false; } this.recountParentsCheck(parentValue); } } /** * Toggles checked state of the tree node and its children. * @param {string} value - tree node value * @param {boolean} isChecked - is tree node checked */ toggleChecked(value, isChecked) { const flatNode = this.getFlatNodeByValue(value); if (flatNode.isLeaf) { if (flatNode.self.disabled) { return; } this.toggleNode(value, 'checked', isChecked); flatNode.checkState = this.getShallowCheckState(flatNode.self); } else { flatNode.self[propsNames.languages].forEach((language) => { this.toggleChecked(getNodeValue(language), isChecked); }); flatNode.self[propsNames.dictionaries].forEach((dictionary) => { this.toggleChecked(getNodeValue(dictionary), isChecked); }); this.toggleNode(value, 'checked', isChecked); flatNode.checkState = this.getShallowCheckState(flatNode.self); } } /** * Toggles checked state of all tree nodes. * @param {boolean} isChecked - needed checked state */ toggleCheckedAll(isChecked) { const flatNodes = this.getFlatNodes(); Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); this.toggleNode(value, 'checked', isChecked); flatNode.checkState = isChecked ? 1 : 0; }); this.sendCheckedListToTop(); } /** * Toggles checked state of all tree nodes to true. */ checkAll() { this.toggleCheckedAll(true); } /** * Toggles checked state of all tree nodes to false. */ uncheckAll() { this.toggleCheckedAll(false); } /** * Toggles tree node property "key" with the value "toggleValue". * @param {string} nodeValue * @param {string} key * @param {boolean} toggleValue */ toggleNode(nodeValue, key, toggleValue) { const flatNode = this.getFlatNodeByValue(nodeValue); flatNode[key] = toggleValue; } /** * Checks if all node childs is in the checked state. * @param {Object} node - tree node * @returns {boolean} - result of the checking */ isEveryChildChecked(node) { const everyLanguagesChecked = node[propsNames.languages] .every(language => this.getFlatNodeByNode(language).checkState === 1); return !nodeHasDictionariesChildren(node) ? everyLanguagesChecked : everyLanguagesChecked && node[propsNames.dictionaries] .every(dictionary => this.getFlatNodeByNode(dictionary).checkState === 1); } /** * Checks if at least one of the children (at every level below) is in the checked state. * @param {Object} node - tree node * @returns {boolean} - result of the checking */ isSomeChildChecked(node) { const someLanguagesChecked = node[propsNames.languages] .some(language => this.getFlatNodeByNode(language).checkState > 0); return !nodeHasDictionariesChildren(node) ? someLanguagesChecked : someLanguagesChecked || node[propsNames.dictionaries] .some(dictionary => this.getFlatNodeByNode(dictionary).checkState > 0); } /** * Checks if node is checked. * @param {object} node - node */ isNodeChecked(node) { const { checked: checkedList } = this.props; const languageInChecked = checkedList[0].checked.find((value) => { return getNodeValue(node) === value; }); if (languageInChecked !== undefined) { return true; } const dictionaryInChecked = checkedList[1].checked.find((value) => { return getNodeValue(node) === value; }); if (dictionaryInChecked !== undefined) { return true; } return false; } /** * Adds checked state to the tree nodes depending on list of checked tree nodes. * @param {Array} checkedLists - list of checked tree nodes */ updateNodesWithChecked(checkedLists, filterMode) { const flatNodes = this.getFlatNodes(); const isAllChecked = this.constructor.isAllNodesChecked(Object.keys(flatNodes).length, checkedLists); if (isAllChecked) { // Set all values to true Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); flatNode.checked = true; if (filterMode) { flatNode.checkState = 1; } }); } else { // Reset values to false Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); flatNode.checked = false; if (filterMode) { flatNode.checkState = 0; } }); checkedLists.forEach((item) => { item.checked.forEach((value) => { const flatNode = this.getFlatNodeByValue(value); if (flatNode !== undefined && flatNode.type === item.type) { flatNode.checked = true; if (filterMode) { flatNode.checkState = 1; } } }); }); } } /** * Adds expanded state to the tree nodes depending on list of expanded tree nodes. * @param {Array} checkedLists - list of expanded tree nodes */ updateNodesWithExpanded(expandedList) { const flatNodes = this.getFlatNodes(); Object.keys(flatNodes).forEach((value) => { const flatNode = this.getFlatNodeByValue(value); flatNode.expanded = false; }); expandedList.forEach((value) => { const flatNode = this.getFlatNodeByValue(value); if (flatNode !== undefined) { flatNode.expanded = true; } }); } /** * Renders tree nodes. * @param {Array} nodes - list of the tree nodes * @param {Object} parent - tree node-parent * @return {TreeNode} - object represents all tree nodes for rendering */ renderTreeNodes(nodes, parent = {}) { const treeNodes = nodes.map((node) => { const nodeValue = getNodeValue(node); const flatNode = this.getFlatNodeByValue(nodeValue); const childrenLanguages = flatNode.isParentWithLanguages ? this.renderTreeNodes(node[propsNames.languages], node) : null; const childrenDictionaries = flatNode.isParentWithDictionaries ? this.renderTreeNodes(node[propsNames.dictionaries], node) : null; // Get the checked state after all children checked states are determined if (!this.constructor.isCheckStateSet(flatNode)) { flatNode.checkState = this.isNodeChecked(node) ? 1 : 0; } let parentExpanded = true; if (parent.value) { const parentFlatNode = this.getFlatNodeByNode(parent); parentExpanded = parentFlatNode.expanded; } if (!parentExpanded) { return null; } return ( <TreeNode key={nodeValue} checked={flatNode.checkState} expanded={flatNode.expanded} label={node.translation} isLeaf={flatNode.isLeaf} isParent={flatNode.isParent} type={flatNode.type} value={flatNode.value} onCheck={this.onCheck} onExpand={this.onExpand} > {childrenLanguages} {childrenDictionaries} </TreeNode> ); }); return treeNodes; } render() { const { nodes, showTree } = this.props; const groupClassName = showTree ? `${classNames.group}` : `${classNames.group} ${classNames.groupHidden}`; return ( <Segment.Group className={groupClassName}> {showTree ? <Segment> <div className={classNames.container}> <div className={classNames.wrap}> <div className={classNames.items}> {this.renderTreeNodes(nodes)} </div> </div> <div className={classNames.buttons}> <Button primary basic onClick={this.uncheckAll}> {this.props.uncheckAllButtonText} </Button> <Button primary basic onClick={this.checkAll}> {this.props.checkAllButtonText} </Button> </div> </div> </Segment> : null } </Segment.Group> ); } }
JavaScript
class CiteUI extends Plugin { /** * Register a button to execute an CitationCommand */ init() { const editor = this.editor; const t = editor.t; // Register the "citation" button editor.ui.componentFactory.add(CiteConstants.componentFactory, locale => { const command = editor.commands.get(CiteConstants.command); const buttonView = new ButtonView(locale); buttonView.set({ // The t() function helps localize the editor. All strings enclosed in t() can be // translated and change when the language of the editor changes. label: t('Citation'), icon: quoteIcon, withText: true, tooltip: true }); // Bind the state of the button to the state of the command. buttonView.bind('isOn', 'isEnabled').to(command, 'value', 'isEnabled'); // Execute the command when the button is clicked. this.listenTo(buttonView, 'execute', () => editor.execute(CiteConstants.command)); return buttonView; }); } }
JavaScript
class VirtualScroller { constructor(config) { this._benchmarkStart = null; /** * Whether the layout should receive an updated viewport size on the next * render. */ // private _needsUpdateView: boolean = false; this._layout = null; /** * The element that generates scroll events and defines the container * viewport. Set by scrollTarget. */ this._scrollTarget = null; /** * A sentinel element that sizes the container when it is a scrolling * element. This ensures the scroll bar accurately reflects the total * size of the list. */ this._sizer = null; /** * Layout provides these values, we set them on _render(). * TODO @straversi: Can we find an XOR type, usable for the key here? */ this._scrollSize = null; /** * Difference between scroll target's current and required scroll offsets. * Provided by layout. */ this._scrollErr = null; /** * A list of the positions (top, left) of the children in the current range. */ this._childrenPos = null; // TODO: (graynorton): type this._childMeasurements = null; this._toBeMeasured = new Map(); this._rangeChanged = true; this._itemsChanged = true; this._visibilityChanged = true; /** * Containing element. Set by container. */ this._container = null; /** * The parent of all child nodes to be rendered. Set by container. */ this._containerElement = null; /** * Keep track of original inline style of the container, so it can be * restored when container is changed. */ this._containerInlineStyle = null; /** * Size of the container. */ this._containerSize = null; /** * Resize observer attached to container. */ this._containerRO = null; /** * Resize observer attached to children. */ this._childrenRO = null; this._mutationObserver = null; this._mutationPromise = null; this._mutationPromiseResolver = null; this._mutationsObserved = false; // TODO (graynorton): Rethink, per longer comment below this._loadListener = this._childLoaded.bind(this); /** * Index and position of item to scroll to. */ this._scrollToIndex = null; /** * Items to render. Set by items. */ this._items = []; /** * Total number of items to render. Set by totalItems. */ this._totalItems = null; /** * Index of the first child in the range, not necessarily the first visible child. * TODO @straversi: Consider renaming these. */ this._first = 0; /** * Index of the last child in the range. */ this._last = 0; /** * Index of the first item intersecting the container element. */ this._firstVisible = 0; /** * Index of the last item intersecting the container element. */ this._lastVisible = 0; this._scheduled = new WeakSet(); /** * Invoked at the end of each render cycle: children in the range are * measured, and their dimensions passed to this callback. Use it to layout * children as needed. */ this._measureCallback = null; this._measureChildOverride = null; this._first = -1; this._last = -1; if (config) { Object.assign(this, config); } } set items(items) { if (Array.isArray(items) && items !== this._items) { this._itemsChanged = true; this._items = items; this._schedule(this._updateLayout); } } /** * The total number of items, regardless of the range, that can be rendered * as child nodes. */ get totalItems() { return this._totalItems === null ? this._items.length : this._totalItems; } set totalItems(num) { if (typeof num !== "number" && num !== null) { throw new Error("New value must be a number."); } // TODO(valdrin) should we check if it is a finite number? // Technically, Infinity would break Layout, not VirtualRepeater. if (num !== this._totalItems) { this._totalItems = num; this._schedule(this._updateLayout); } } /** * The parent of all child nodes to be rendered. */ get container() { return this._container; } set container(container) { if (container === this._container) { return; } if (this._container) { // Remove children from old container. // TODO (graynorton): Decide whether we'd rather fire an event to clear // the range and let the renderer take care of removing the DOM children this._children.forEach((child) => child.parentNode.removeChild(child)); } this._container = container; this._schedule(this._updateLayout); this._initResizeObservers().then(() => { const oldEl = this._containerElement; // Consider document fragments as shadowRoots. const newEl = container && container.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? container.host : container; if (oldEl === newEl) { return; } this._containerRO.disconnect(); this._containerSize = null; if (oldEl) { if (this._containerInlineStyle) { oldEl.setAttribute("style", this._containerInlineStyle); } else { oldEl.removeAttribute("style"); } this._containerInlineStyle = null; if (oldEl === this._scrollTarget) { oldEl.removeEventListener("scroll", this, { passive: true }); this._sizer && this._sizer.remove(); } oldEl.removeEventListener("load", this._loadListener, true); this._mutationObserver.disconnect(); } else { // First time container was setup, add listeners only now. addEventListener("scroll", this, { passive: true }); } this._containerElement = newEl; if (newEl) { this._containerInlineStyle = newEl.getAttribute("style") || null; // https://github.com/PolymerLabs/uni-virtualizer/issues/104 // Would rather set these CSS properties on the host using Shadow Root // style scoping (and fall back to a global stylesheet where native // Shadow DOM is not available), but this Mobile Safari bug is preventing // that from working: https://bugs.webkit.org/show_bug.cgi?id=226195 const style = newEl.style; style.display = style.display || "block"; style.position = style.position || "relative"; style.overflow = style.overflow || "auto"; style.contain = style.contain || "strict"; if (newEl === this._scrollTarget) { this._sizer = this._sizer || this._createContainerSizer(); this._container.insertBefore(this._sizer, this._container.firstChild); } this._schedule(this._updateLayout); this._containerRO.observe(newEl); this._mutationObserver.observe(newEl, { childList: true }); this._mutationPromise = new Promise( (resolve) => (this._mutationPromiseResolver = resolve) ); if (this._layout && this._layout.listenForChildLoadEvents) { newEl.addEventListener("load", this._loadListener, true); } } }); } // This will always actually return a layout instance, // but TypeScript wants the getter and setter types to be the same get layout() { return this._layout; } set layout(layout) { if (this._layout === layout) { return; } let _layout = null; let _config = {}; if (typeof layout === "object") { if (layout.type !== undefined) { _layout = layout.type; // delete (layout as LayoutSpecifier).type; } _config = layout; } else { _layout = layout; } if (typeof _layout === "function") { if (this._layout instanceof _layout) { if (_config) { this._layout.config = _config; } return; } else { _layout = new _layout(_config); } } if (this._layout) { this._measureCallback = null; this._measureChildOverride = null; this._layout.removeEventListener("scrollsizechange", this); this._layout.removeEventListener("scrollerrorchange", this); this._layout.removeEventListener("itempositionchange", this); this._layout.removeEventListener("rangechange", this); delete this.container[scrollerRef]; this.container.removeEventListener("load", this._loadListener, true); // Reset container size so layout can get correct viewport size. if (this._containerElement) { this._sizeContainer(undefined); } } this._layout = _layout; if (this._layout) { if ( this._layout.measureChildren && typeof this._layout.updateItemSizes === "function" ) { if (typeof this._layout.measureChildren === "function") { this._measureChildOverride = this._layout.measureChildren; } this._measureCallback = this._layout.updateItemSizes.bind(this._layout); } this._layout.addEventListener("scrollsizechange", this); this._layout.addEventListener("scrollerrorchange", this); this._layout.addEventListener("itempositionchange", this); this._layout.addEventListener("rangechange", this); this._container[scrollerRef] = this; if (this._layout.listenForChildLoadEvents) { this._container.addEventListener("load", this._loadListener, true); } this._schedule(this._updateLayout); } } // TODO (graynorton): Rework benchmarking so that it has no API and // instead is always on except in production builds startBenchmarking() { if (this._benchmarkStart === null) { this._benchmarkStart = window.performance.now(); } } stopBenchmarking() { if (this._benchmarkStart !== null) { const now = window.performance.now(); const timeElapsed = now - this._benchmarkStart; const entries = performance.getEntriesByName( "uv-virtualizing", "measure" ); const virtualizationTime = entries .filter((e) => e.startTime >= this._benchmarkStart && e.startTime < now) .reduce((t, m) => t + m.duration, 0); this._benchmarkStart = null; return { timeElapsed, virtualizationTime }; } return null; } _measureChildren() { const mm = {}; const children = this._children; const fn = this._measureChildOverride || this._measureChild; for (let i = 0; i < children.length; i++) { const child = children[i]; const idx = this._first + i; if (this._itemsChanged || this._toBeMeasured.has(child)) { mm[idx] = fn.call( this, child, this._items[idx] /*as unknown as object*/ ); } } this._childMeasurements = mm; this._schedule(this._updateLayout); this._toBeMeasured.clear(); } /** * Returns the width, height, and margins of the given child. */ _measureChild(element) { // offsetWidth doesn't take transforms in consideration, so we use // getBoundingClientRect which does. const { width, height } = element.getBoundingClientRect(); return Object.assign({ width, height }, getMargins(element)); } /** * The element that generates scroll events and defines the container * viewport. The value `null` (default) corresponds to `window` as scroll * target. */ get scrollTarget() { return this._scrollTarget; } set scrollTarget(target) { // Consider window as null. if (target === window) { target = null; } if (this._scrollTarget === target) { return; } this._sizeContainer(undefined); if (this._scrollTarget) { this._scrollTarget.removeEventListener("scroll", this, { passive: true }); if (this._sizer && this._scrollTarget === this._containerElement) { this._sizer.remove(); } } this._scrollTarget = target; if (target) { target.addEventListener("scroll", this, { passive: true }); if (target === this._containerElement) { this._sizer = this._sizer || this._createContainerSizer(); this._container.insertBefore(this._sizer, this._container.firstChild); } } } /** * Index and position of item to scroll to. The scroller will fix to that point * until the user scrolls. */ set scrollToIndex(newValue) { this._scrollToIndex = newValue; this._schedule(this._updateLayout); } async _schedule(method) { if (!this._scheduled.has(method)) { this._scheduled.add(method); await Promise.resolve(); this._scheduled.delete(method); method.call(this); } } async _updateDOM() { const { _rangeChanged, _itemsChanged } = this; if (this._visibilityChanged) { this._notifyVisibility(); this._visibilityChanged = false; } if (_rangeChanged || _itemsChanged) { this._notifyRange(); this._rangeChanged = false; this._itemsChanged = false; await this._mutationPromise; } if (this._layout.measureChildren) { this._children.forEach((child) => this._childrenRO.observe(child)); } this._positionChildren(this._childrenPos); this._sizeContainer(this._scrollSize); if (this._scrollErr) { this._correctScrollError(this._scrollErr); this._scrollErr = null; } if (this._benchmarkStart && "mark" in window.performance) { window.performance.mark("uv-end"); } } _updateLayout() { this._layout.totalItems = this._totalItems; if (this._scrollToIndex !== null) { this._layout.scrollToIndex( this._scrollToIndex.index, this._scrollToIndex.position ); this._scrollToIndex = null; } this._updateView(); if (this._childMeasurements !== null) { // If the layout has been changed, we may have measurements but no callback if (this._measureCallback) { this._measureCallback(this._childMeasurements); } this._childMeasurements = null; } this._layout.reflowIfNeeded(this._itemsChanged); if (this._benchmarkStart && "mark" in window.performance) { window.performance.mark("uv-end"); } } _handleScrollEvent() { if (this._benchmarkStart && "mark" in window.performance) { try { window.performance.measure("uv-virtualizing", "uv-start", "uv-end"); } catch (e) { console.warn("Error measuring performance data: ", e); } window.performance.mark("uv-start"); } this._schedule(this._updateLayout); } handleEvent(event) { switch (event.type) { case "scroll": if (!this._scrollTarget || event.target === this._scrollTarget) { this._handleScrollEvent(); } break; case "scrollsizechange": this._scrollSize = event.detail; this._schedule(this._updateDOM); break; case "scrollerrorchange": this._scrollErr = event.detail; this._schedule(this._updateDOM); break; case "itempositionchange": this._childrenPos = event.detail; this._schedule(this._updateDOM); break; case "rangechange": this._adjustRange(event.detail); this._schedule(this._updateDOM); break; default: console.warn("event not handled", event); } } async _initResizeObservers() { if (this._containerRO === null) { const ResizeObserver = await getResizeObserver(); this._containerRO = new ResizeObserver((entries) => this._containerSizeChanged(entries[0].contentRect) ); this._childrenRO = new ResizeObserver( this._childrenSizeChanged.bind(this) ); this._mutationObserver = new MutationObserver( this._observeMutations.bind(this) ); } } _createContainerSizer() { const sizer = document.createElement("div"); // When the scrollHeight is large, the height of this element might be // ignored. Setting content and font-size ensures the element has a size. Object.assign(sizer.style, { position: "absolute", margin: "-2px 0 0 0", padding: 0, visibility: "hidden", fontSize: "2px", }); sizer.innerHTML = "&nbsp;"; sizer.id = "uni-virtualizer-spacer"; return sizer; } get _children() { const arr = []; let next = this.container.firstElementChild; while (next) { // Skip our spacer. TODO (graynorton): Feels a bit hacky. Anything better? if (next.id !== "uni-virtualizer-spacer") { arr.push(next); } next = next.nextElementSibling; } return arr; } _updateView() { if (!this.container || !this._containerElement || !this._layout) { return; } let width, height, top, left; if ( this._scrollTarget === this._containerElement && this._containerSize !== null ) { width = this._containerSize.width; height = this._containerSize.height; left = this._containerElement.scrollLeft; top = this._containerElement.scrollTop; } else { const containerBounds = this._containerElement.getBoundingClientRect(); const scrollBounds = this._scrollTarget ? this._scrollTarget.getBoundingClientRect() : { top: containerBounds.top + window.pageYOffset, left: containerBounds.left + window.pageXOffset, width: innerWidth, height: innerHeight, }; const scrollerWidth = scrollBounds.width; const scrollerHeight = scrollBounds.height; const xMin = Math.max( 0, Math.min(scrollerWidth, containerBounds.left - scrollBounds.left) ); const yMin = Math.max( 0, Math.min(scrollerHeight, containerBounds.top - scrollBounds.top) ); // TODO (graynorton): Direction is intended to be a layout-level concept, not a scroller-level concept, // so this feels like a factoring problem const xMax = this._layout.direction === "vertical" ? Math.max( 0, Math.min(scrollerWidth, containerBounds.right - scrollBounds.left) ) : scrollerWidth; const yMax = this._layout.direction === "vertical" ? scrollerHeight : Math.max( 0, Math.min( scrollerHeight, containerBounds.bottom - scrollBounds.top ) ); width = xMax - xMin; height = yMax - yMin; left = Math.max(0, -(containerBounds.left - scrollBounds.left)); top = Math.max(0, -(containerBounds.top - scrollBounds.top)); } this._layout.viewportSize = { width, height }; this._layout.viewportScroll = { top, left }; } /** * Styles the _sizer element or the container so that its size reflects the * total size of all items. */ _sizeContainer(size) { if (this._scrollTarget === this._containerElement) { const left = size && size.width ? size.width - 1 : 0; const top = size && size.height ? size.height - 1 : 0; if (this._sizer) { this._sizer.style.transform = `translate(${left}px, ${top}px)`; } } else { if (this._containerElement) { const style = this._containerElement.style; style.minWidth = size && size.width ? size.width + "px" : null; style.minHeight = size && size.height ? size.height + "px" : null; } } } /** * Sets the top and left transform style of the children from the values in * pos. */ _positionChildren(pos) { if (pos) { const children = this._children; Object.keys(pos).forEach((key) => { const idx = key - this._first; const child = children[idx]; if (child) { const { top, left, width, height } = pos[key]; child.style.position = "absolute"; child.style.boxSizing = "border-box"; child.style.transform = `translate(${left}px, ${top}px)`; if (width !== undefined) { child.style.width = width + "px"; } if (height !== undefined) { child.style.height = height + "px"; } } }); } } async _adjustRange(range) { const { _first, _last, _firstVisible, _lastVisible } = this; this._first = range.first; this._last = range.last; this._firstVisible = range.firstVisible; this._lastVisible = range.lastVisible; this._rangeChanged = this._rangeChanged || this._first !== _first || this._last !== _last; this._visibilityChanged = this._visibilityChanged || this._firstVisible !== _firstVisible || this._lastVisible !== _lastVisible; } _correctScrollError(err) { if (this._scrollTarget) { this._scrollTarget.scrollTop -= err.top; this._scrollTarget.scrollLeft -= err.left; } else { window.scroll( window.pageXOffset - err.left, window.pageYOffset - err.top ); } } /** * Emits a rangechange event with the current first, last, firstVisible, and * lastVisible. */ _notifyRange() { // TODO (graynorton): Including visibility here for backward compat, but // may decide to remove at some point. The rationale for separating is that // range change events are mainly intended for "internal" consumption by the // renderer, whereas visibility change events are mainly intended for "external" // consumption by application code. this._container.dispatchEvent( new CustomEvent("rangeChanged", { detail: { first: this._first, last: this._last, firstVisible: this._firstVisible, lastVisible: this._lastVisible, }, }) ); } _notifyVisibility() { this._container.dispatchEvent( new CustomEvent("visibilityChanged", { detail: { first: this._first, last: this._last, firstVisible: this._firstVisible, lastVisible: this._lastVisible, }, }) ); } /** * Render and update the view at the next opportunity with the given * container size. */ _containerSizeChanged(size) { const { width, height } = size; this._containerSize = { width, height }; this._schedule(this._updateLayout); } async _observeMutations() { if (!this._mutationsObserved) { this._mutationsObserved = true; this._mutationPromiseResolver(); this._mutationPromise = new Promise( (resolve) => (this._mutationPromiseResolver = resolve) ); this._mutationsObserved = false; } } // TODO (graynorton): Rethink how this works. Probably child loading is too specific // to have dedicated support for; might want some more generic lifecycle hooks for // layouts to use. Possibly handle measurement this way, too, or maybe that remains // a first-class feature? _childLoaded() { // this.requestRemeasure(); } _childrenSizeChanged(changes) { for (const change of changes) { this._toBeMeasured.set(change.target, change.contentRect); } this._measureChildren(); this._schedule(this._updateLayout); } }
JavaScript
class Map { constructor(mapBoxKey) { // set mapBox api key this.mapBoxKey = mapBoxKey; this.style = 'mapbox://styles/cernst11/cj28e31au00072tpeqo01n9gf'; this.html = document.querySelector('html'); // this.setStyle = this.setStyle.bind(this); // create the style selectors and build the map this.buildMap(); // this.getMapData(); } static async getMapData() { const earthQuakes = null; let response = await fetch(earthQuakes); // only proceed once promise is resolved let data = await response.json(); // only proceed once second promise is resolved const locations = []; let i = 0; data.locations.forEach((location) => { const loc = { type: 'Feature', geometry: { type: 'Point', coordinates: [location.longitudeE7 * (10 ** -7), location.latitudeE7 * (10 ** -7), 0.0], }, properties: { time: location.timestampMs, }, }; if (i % 2 === 0) { locations.push(loc); } i += 1; // console.log(loc) }); data = {}; response = {}; const x = { type: 'FeatureCollection', features: locations, }; return x; } async buildMap() { mapboxgl.accessToken = this.mapBoxKey; const map = new mapboxgl.Map({ container: 'map', center: [13.404953999999975, 52.52000659999999], style: this.style, zoom: 13, preserveDrawingBuffer: true, }); this.map = map; map.addControl(new mapboxgl.NavigationControl()); /* let that = this; map.on('load', async () => { //Add a geojson point source. //Heatmap layers also work with a vector tile source. let data = await that.getMapData(); map.addSource('earthquakes', { "type": "geojson", "data": data }); map.addLayer({ "id": "earthquakes-heat", "type": "heatmap", "source": "earthquakes", "maxzoom": 15, "paint": { //Increase the heatmap weight based on frequency and property magnitude 'heatmap-radius': 25, //Increase the heatmap color weight weight by zoom level //heatmap-ntensity is a multiplier on top of heatmap-weight "heatmap-intensity": { "stops": [ [0, 1], [9, 3] ] }, //Color ramp for heatmap. Domain is 0 (low) to 1 (high). //Begin color ramp at 0-stop with a 0-transparancy color //to create a blur-like effect. "heatmap-color": [ "interpolate", ["linear"], ["heatmap-density"], 0, "rgba(33,102,172,0)", 0.2, "rgb(103,169,207)", 0.4, "rgb(209,229,240)", 0.5, "rgb(216, 253, 199)", 0.9, "rgb(239,138,98)", 1, "rgb(178,24,43)" ], //Transition from heatmap to circle layer by zoom level "heatmap-opacity": { "default": 1, "stops": [ [7, .65], [9, .55], [15, .50] ] }, } }, 'waterway-label'); }); */ } static createLayer() { } }
JavaScript
class PostCss { /** * @experimental */ constructor(project, options) { var _b, _c, _d; this.fileName = (_b = options === null || options === void 0 ? void 0 : options.fileName) !== null && _b !== void 0 ? _b : 'postcss.config.json'; project.addDeps('postcss'); const config = { plugins: {} }; if ((_c = options === null || options === void 0 ? void 0 : options.tailwind) !== null && _c !== void 0 ? _c : true) { config.plugins.tailwindcss = {}; config.plugins.autoprefixer = {}; this.tailwind = new tailwind_1.TailwindConfig(project, options === null || options === void 0 ? void 0 : options.tailwindOptions); project.addDeps('tailwindcss', 'autoprefixer'); } this.file = new json_1.JsonFile(project, this.fileName, { obj: config }); (_d = project.npmignore) === null || _d === void 0 ? void 0 : _d.exclude(`/${this.fileName}`); } }
JavaScript
class GalleryView extends Lightning.Component { /** * @static * @returns * @memberof GalleryView * Renders the template */ static _template() { return { GalleryRowList: { x: 232, y: 296, w: 1690, h: 1000, type: Lightning.components.ListComponent, horizontal: false, spacing: 72, roll: true, rollMin: 0, rollMax: 400, itemSize: 250, viewportSize: 700, invertDirection: true, clipping: true, rect: true, color: Colors.TRANSPARENT }, Down: { x: 930, y: 980, src: Utils.asset(ImageConstants.DOWN), zIndex: 3, visible: true } } } _init() { const xhr = new XMLHttpRequest(); xhr.open('GET', "http://"+ window.serverdata.Server_ip + ":" + window.serverdata.Server_port +"/CustomUI/getPosition?customer_id="+window.serverdata.serial_number); xhr.responseType = 'json'; xhr.onload = () => { if(xhr.status === 200) { List = xhr.response; this.getData() } }; xhr.send(); this.current = this.tag('GalleryRowList').element this._setState('GalleryViewState') } getData() { for (var i = 0; i < List.length; i++) { if (List[i] == "Recommended for you") { this.tag('GalleryRowList').items = { Recommended: { type: ScrollableList, horizontal: true, itemSize: 520, spacing: 70, rollMax: 1400, headerFont:header_Font, headerfontColor:header_fontColor } } } else if (List[i] == "premium Apps") { this.tag('GalleryRowList').items = { Apps: { type: ScrollableList, horizontal: true, itemSize: 260, spacing: 20, headerFont:header_Font, headerfontColor:header_fontColor } } } else if (List[i] == "metro Apps") { this.tag('GalleryRowList').items = { MetroApps: { type: ScrollableList, horizontal: true, itemSize: 260, spacing: 20, headerFont:header_Font, headerfontColor:header_fontColor } } } } if(List.indexOf("Recommended for you") == 0) { this.tag('GalleryRowList').itemSize = 400; this.tag('GalleryRowList').items[2].patch({ y: -140, alpha: 1 }) } else if(List.indexOf("Recommended for you") == 1) { this.tag('GalleryRowList').itemSize = 250; this.tag('GalleryRowList').items[2].patch({ y: 140, alpha: 1 }) } } set theme(v) { console.log(v["home"].bg_image) header_Font= v["home"].fontFace; header_fontColor =v["home"].text_fontColor } /** * Sets data in Tile component through data passed from JSON file */ set data(v) { if(List.length == 0) { List = ["Recommended for you","premium Apps","metro Apps"] this.getData() } for(var i=0;i<v.length;i++) { if(v[i].ref == "Recommended for you ") { this.tag('GalleryRowList').items[List.indexOf("Recommended for you")].header = Language.translate(v[i].data.header)|| "" this.tag('GalleryRowList').items[List.indexOf("Recommended for you")].items = (v[i].data.assets || []).map((data, index) => { return { ref: 'Tile_' + index, type: Tile, image: data.url, category: data.category, title: data.title, duration: data.Duration, w: 500, h: 282, offset: 30, scaleX: 1.1, scaleY: 1.1, highlight: true, videoData: { title: data.title, videourl: data.videourl, name: data.name, category: data.category, logoPath: data.logoPath, number: data.number } } }) } if(v[i].ref == "Premium Apps") { this.tag('GalleryRowList').items[List.indexOf("premium Apps")].header = Language.translate(v[i].data.header)|| "" this.tag('GalleryRowList').items[List.indexOf("premium Apps")].items = (v[i].data.assets || []).map((data, index) => { return { ref: 'Tile_' + index, type: Tile, image: data.url, w: 240, h: 135, scaleX: 1.2, scaleY: 1.2, appData: { url: data.appUrl, title: data.title } } }) } if(v[i].ref == "Metrological Appstore Experience") { //this.tag('GalleryRowList').items[List.indexOf("metro Apps")].patch({ y: 140, alpha: 1 }) this.tag('GalleryRowList').items[List.indexOf("metro Apps")].header = Language.translate(v[i].data.header)|| "" this.tag('GalleryRowList').items[List.indexOf("metro Apps")].items = (v[i].data.assets || []).map((data, index) => { return { ref: 'Tile_' + index, type: Tile, image: data.url, w: 240, h: 135, scaleX: 1.2, scaleY: 1.2, appUrl: data.appUrl } }) } } } _focus() { this.tag('GalleryRowList').x = 230 this.tag('GalleryRowList').w = 1690 } _unfocus() { this.tag('GalleryRowList').x = 440 this.tag('GalleryRowList').w = 1440 } /** * To reset the List */ _reset() { this.tag('GalleryRowList').start() this.current = this.tag('GalleryRowList').element } /** * @static * @returns * @memberof GalleryView * GalleryView States */ static _states() { return [ class GalleryViewState extends this { _getFocused() { return this.current } /** * Set next gallery row if not on the last row or Remain in the same row on pressing Down Arrow * Reset the current row */ _handleDown() { if (this.tag('GalleryRowList').length - 1 != this.tag('GalleryRowList').index) { this.tag('GalleryRowList').element._reset() this.tag('GalleryRowList').setNext() } this.current = this.tag('GalleryRowList').element //Make the down arrow invisible when we scroll to last row if (this.tag('GalleryRowList').length - 1 == this.tag('GalleryRowList').index) { this.tag('Down').visible = false } } /** * Set Apps or Set Player */ _handleEnter() { let currentTile = this.current.tag('Wrapper').element if (currentTile.videoData) { let channelData = currentTile.videoData this.fireAncestors('$setPlayer', channelData) } else if (this.current.tag('Wrapper').element.appData) { let appData = this.current.tag('Wrapper').element.appData this.fireAncestors('$setPremiumApp', appData) } else if (this.current.tag('Wrapper').element.appUrl) { let url = this.current.tag('Wrapper').element.appUrl this.fireAncestors('$setMetroApp', url) } } /** * Set previous row and reset the gallery tiles */ _handleUp() { if (0 != this.tag('GalleryRowList').index) { this.tag('GalleryRowList').element._reset() this.tag('GalleryRowList').setPrevious() } this.current = this.tag('GalleryRowList').element //Make the down arrow visible on all other cases other than at the last row if (this.tag('GalleryRowList').length - 1 != this.tag('GalleryRowList').index) { this.tag('Down').visible = true } } } ] } }
JavaScript
class FuroUi5DataTextareaInput extends TextArea.default { /** * Fired when the input value changed. * the event detail is the value of the input field * @event value-changed */ /** * Fired when the input operation has finished by pressing Enter or on focusout. * @event change */ /** * Fired when the value of the furo-ui5-data-textarea changes at each keystroke, and when a suggestion item has been selected. * @event input */ /** * connectedCallback() method is called when an element is added to the DOM. * webcomponent lifecycle event */ connectedCallback() { setTimeout(() => { super.connectedCallback(); }, 0); this._initBinder(); } /** * inits the universalFieldNodeBinder. * Set the mapped attributes and labels. * @private */ _initBinder() { this.binder = new UniversalFieldNodeBinder(this); this.applyBindingSet(); } /** * apply the binding set to the universal field node binder */ applyBindingSet() { // set the attribute mappings this.binder.attributeMappings = { label: 'label', // map label to placeholder rows: 'rows', // map rows placeholder: 'placeholder', // map placeholder to placeholder 'value-state': '_valueState', errortext: '_errorMsg', // name errortext is for compatibility with spec 'error-msg': '_errorMsg', 'warning-msg': '_warningMsg', 'success-msg': '_successMsg', 'information-msg': '_informationMsg', pattern: 'pattern', name: 'name', maxlength: 'maxlength', // for the input element itself }; // set the label mappings this.binder.labelMappings = { error: '_error', readonly: 'readonly', required: 'required', disabled: 'disabled', pristine: 'pristine', highlight: 'highlight', }; // set attributes to constrains mapping for furo.fat types this.binder.fatAttributesToConstraintsMappings = { maxlength: 'value._constraints.max.is', // for the fieldnode constraint minlength: 'value._constraints.min.is', // for the fieldnode constraint pattern: 'value._constraints.pattern.is', // for the fieldnode constraint required: 'value._constraints.required.is', // for the fieldnode constraint 'min-msg': 'value._constraints.min.message', // for the fieldnode constraint message 'max-msg': 'value._constraints.max.message', // for the fieldnode constraint message }; // set constrains to attributes mapping for furo.fat types this.binder.constraintsTofatAttributesMappings = { max: 'maxlength', min: 'minlength', pattern: 'pattern', required: 'required', }; /** * check overrides from the used component, attributes set on the component itself overrides all */ this.binder.checkLabelandAttributeOverrrides(); // update the value on input changes this.addEventListener('input', val => { // update the value this.binder.fieldValue = val.target.value; /** * Fired when value changed * @type {Event} */ const customEvent = new Event('value-changed', { composed: true, bubbles: true }); customEvent.detail = val.target.value; this.dispatchEvent(customEvent); // set flag empty on empty strings (for fat types) if (val.target.value) { this.binder.deleteLabel('empty'); } else { this.binder.addLabel('empty'); } // if something was entered the field is not empty this.binder.deleteLabel('pristine'); }); } /** * Sets the value for the field. This will update the fieldNode. * @param val */ setValue(val) { this.binder.fieldValue = val; } /** * Bind a entity field to the text-input. You can use the entity even when no data was received. * When you use `@-object-ready` from a `furo-data-object` which emits a EntityNode, just bind the field with `--entity(*.fields.fieldname)` * @param {Object|FieldNode} fieldNode a Field object */ bindData(fieldNode) { /** * Because of the UI5 TextArea Tokenizer we can not pass NULL as a value. * If the value is null, we pass an empty string * @type {string} * @private */ // eslint-disable-next-line no-param-reassign fieldNode._value = fieldNode._value || ''; this.binder.bindField(fieldNode); if (this.binder.fieldNode) { /** * handle pristine * Set to pristine label to the same _pristine from the fieldNode */ if (this.binder.fieldNode._pristine) { this.binder.addLabel('pristine'); } else { this.binder.deleteLabel('pristine'); } // set pristine on new data this.binder.fieldNode.addEventListener('new-data-injected', () => { this.binder.addLabel('pristine'); }); } } }
JavaScript
class Substance extends DomainResource { /** A code (or set of codes) that identify this substance. @returns {CodeableConcept} */ type () { if (this.json['type']) { return new CodeableConcept(this.json['type']) } } /** A description of the substance - its appearance, handling requirements, and other usage notes. @returns {Array} an array of {@link String} objects */ description () { return this.json['description'] } /** Substance may be used to describe a kind of substance, or a specific package/container of the substance: an instance. @returns {SubstanceInstanceComponent} */ instance () { if (this.json['instance']) { return new SubstanceInstanceComponent(this.json['instance']) } } /** A substance can be composed of other substances. @returns {Array} an array of {@link SubstanceIngredientComponent} objects */ ingredient () { if (this.json['ingredient']) { return this.json['ingredient'].map(item => new SubstanceIngredientComponent(item)) } } }
JavaScript
class RecallEntry extends makeQuerying(data, StateEngineEntry) { constructor() { super(); this.init(`Recall<${data.actionCount}>`); /** * The action text and score that best matches `History(0)`. * * @type {[text: string, score: number] | null} */ this.bestResult = null; } /** * How far back in the history we'll begin the search at. */ static get earliestActionForQuery() { return Math.max(0, config.get("integer", "earliestActionForQuery")); } /** * The number of entries after `earliestActionForQuery` that need to exist * before the system will try to find something in the history. This is * intended to try and have at least a little bit of history built up to * search through. */ static get minimumEntriesRequired() { return Math.max(0, config.get("integer", "minimumEntriesRequired")); } /** * How many entries after that we'll look through. */ static get queryCountLimit() { return Math.max(0, config.get("integer", "queryCountLimit")); } /** * @param {AIDData} data * @returns {Iterable<StateEngineEntry>} */ static *produceEntries(data) { const { earliestActionForQuery, minimumEntriesRequired, queryCountLimit } = this; // Bail if this module is basically disabled. if (queryCountLimit === 0) return; // Only produce an entry if we have enough action history for it // to be useful. We'll throw in an extra 20 actions, just so we // have a few entries to work with. const neededLength = earliestActionForQuery + minimumEntriesRequired; // How many history entries it provides seems to vary. One adventure // gave me 100 while another gave 200. Weird. if (data.history.length < neededLength) return; yield new RecallEntry(); } static get forType() { return "Recall"; } get targetSources() { return tuple("implicit"); } get priority() { return -1; } /** Use the text of our best result as the actual entry text. */ get text() { if (this.bestResult == null) return ""; const [text] = this.bestResult; return `An earlier, relevant event: ${text}`; } /** Use the history's stemmed text for the query. */ get stemText() { return this.stemMap.get("History(0)") ?? ""; } /** * Re-scores a line against the latest history entry. * * Produces `undefined` if its score was not above zero. * * @param {string} line * @returns {[line: string, score: number] | undefined} */ rescoreLine(line) { const stemLine = stemText(line); if (!stemLine) return undefined; const terms = new Document(stemLine).getUniqueTerms(); const score = this.corpus.evaluateScore(terms, "History(0)"); if (score <= 0) return undefined; return tuple(line, score); } *fetchRelevantActionLines() { const { earliestActionForQuery, queryCountLimit } = RecallEntry; // Perform a query on history entries in the range we want to search. // These queries can take a while. Only consider a limited amount. const limit = earliestActionForQuery + queryCountLimit; const results = this.corpus.filteredQuery(this.stemText, (docKey) => { const source = parseHistoryKey(docKey); if (source == null) return false; if (source < earliestActionForQuery) return false; return source < limit; }); // We'll emit up to 5 unique results from the query. let resultsEmitted = 0; // But avoid emitting the same blocks of continuous text. /** @type {Set<number>} */ const emittedBlocks = new Set(); for (const [docKey, score] of results) { if (resultsEmitted >= 5) return; /** @type {number} We know this will parse. */ const source = shutUpTS(parseHistoryKey(docKey)); // Translate from source to index. const historyIndex = (data.history.length - 1) - source; // Get the continuous entries from that index; short circuit if we've already // emitted this block. This can actually happen often, as relevant material // is often grouped up together. const { start, elements } = getContinuousText(historyIndex, data.history); if (emittedBlocks.has(start)) continue; emittedBlocks.add(start); // Sanity check; we do have something, right? if (elements.length === 0) continue; // Otherwise, join them together then split on the newlines. Some posts // can get awfully long, so we may not need the whole block. const contText = chain(elements) .map((history) => history.text) .toArray().join("").split("\n") .map((text) => text.trim()) .filter(Boolean); // Do upkeep and short circuiting. We don't need to do anything special // if the entry has only one line or no lines. if (contText.length > 0) resultsEmitted += 1; if (contText.length === 1) yield tuple(contText[0], score); if (contText.length <= 1) continue; // If we get here, we have a bit of an odd situation. The information we // want may not be a complete thought because the entry carries across // multiple actions. So, let's re-score it all so we can find which was // the most relevant portion. for (const line of contText) { const lineScore = this.rescoreLine(line); if (lineScore) yield lineScore; } } } modifier() { // Here we figure out our result. `fetchRelevantActionLines` may not // produce results in descending score order, so we'll do that here. // It should produce 5 results from querying the history, but because // actions can continue previous actions, we may have more than that, // with lines from multiple entries being re-scored. const [result = null] = [...this.fetchRelevantActionLines()].sort((a, b) => b[1] - a[1]); this.bestResult = result; } /** * @param {MatchableEntry} matcher * @param {AssociationParamsFor<this>} params * @returns {boolean} */ associator(matcher, params) { if (this.bestResult == null) return false; return this.bestResult[1] > 0; } valuator() { // Sanity check. if (this.bestResult == null) return 0; const [, bestScore] = this.bestResult; // Grab the top terms for the latest action. const topTerms = this.corpus.getTopTermsForDocument("History(0)"); // If there's a good number of terms, we'll trim off one of the strongest // terms for every 5 terms in the entry. This gives an edge to the // recalled text. const usedTerms = topTerms.slice(Math.floor(topTerms.length / 5)); if (usedTerms.length === 0) return 0; // Only allow this match if the best score is more than double the // average of the latest action's terms' scores. This generally means // it needs to have matched one very strong term or a few middling terms. // This is intended to improve relevancy. const sumOfTerms = usedTerms.reduce((pv, [, score]) => pv + score, 0); const threshold = (sumOfTerms / usedTerms.length) * 2; if (bestScore <= threshold) return 0; // Apply the same scoring booster as Deep-State. return 20 * Math.pow(1.05, this.bestResult[1]); } /** * Serializes a `RecallEntry` into a `StateEngineData`. * * @returns {StateEngineData} */ toJSON() { return { ...super.toJSON(), text: this.text }; } }
JavaScript
class TvGetDataMixin extends Vue { getPeople() { this.$api.getPeople().then(response => { if (response) { const people = response.results // Store the response this.$store.commit('peopleState/setPeople', people) this.$store.commit('appState/setloading', false) } else { console.warn('No people data available.') } }) } getPlanets() { this.$api.getPlanets().then(response => { if (response) { const planets = response.results // Store the response this.$store.commit('planetsState/setPlanets', planets) this.$store.commit('appState/setloading', false) } else { console.warn('No planets data available.') } }) } getStarships() { this.$api.getStarships().then(response => { if (response) { const starships = response.results // Store the response this.$store.commit('starshipsState/setStarships', starships) this.$store.commit('appState/setloading', false) } else { console.warn('No starships data available.') } }) } }
JavaScript
class ControllerNotFoundError extends Error { /** * Creates an instance of ControllerNotFoundError. * * @param {String} controllerName name of controller * @param {String} path path of controller */ constructor(controllerName, path, e) { super(`Controller ${controllerName} not found in path ${path}, origin error is \n${e}`); this.controllerName = controllerName; this.path = path; } }
JavaScript
class ActionNotFoundError extends Error { /** * Creates an instance of ActionNotFoundError. * * @param {String} controllerName name of controller * @param {String} actionName name of action to execute */ constructor(controllerName, actionName) { super(`Action ${actionName} not found in controller ${controllerName}`); this.actionName = actionName; this.controllerName = controllerName; } }
JavaScript
class CompleterFactory { /** * Constructor for completer factory * @constructor */ constructor() { this.variable_dec = /([a-z])+ .*/i; this.package_dec = /([a-z0-9])+:.*/i; } /** * Return the Source view completer * @param {object} langserverController - language server controller * @return {*[]} - array */ getSourceViewCompleter(langserverController, fileData) { return [{ getCompletions: (editor, session, pos, prefix, callback) => { const cursorPosition = editor.getCursorPosition(); const content = editor.getValue(); this.getCompletions(cursorPosition, content, fileData, langserverController, callback); }, }]; } /** * Get the completions and call the given callback function with the completions * @param {object} cursorPosition * @param {string} content * @param {object} fileData * @param {object} langserverController * @param {function} callback */ getCompletions(cursorPosition, content, fileData, langserverController, callback) { const completions = []; const options = { textDocument: content, position: { line: cursorPosition.row + 1, character: cursorPosition.column, }, fileName: fileData.fileName, filePath: fileData.filePath, fullPath: fileData.fullPath, uri: fileData.toURI(), packageName: fileData.packageName, }; langserverController.getCompletions(options, (response) => { const sortedArr = _.orderBy(response.result.left, ['sortText'], ['desc']); let score = sortedArr.length; sortedArr.map((completionItem) => { completions.push( { caption: completionItem.label, snippet: completionItem.insertText, meta: completionItem.detail, score: 100 + (score || 0), }); score--; }); callback(null, completions); }); } }
JavaScript
class Node { constructor (value) { this.value = value; this.next = null; } }
JavaScript
class MarioBarcodeSensor extends device_1.Device { constructor(hub, portId) { super(hub, portId, exports.ModeMap, Consts.DeviceType.MARIO_BARCODE_SENSOR); } receive(message) { const mode = this._mode; switch (mode) { case Mode.BARCODE: /** * Emits when the barcode sensor sees a barcode. * @event MarioBarcodeSensor#barcode * @type {object} * @param {number} id */ const barcode = message.readUInt16LE(4); const color = message.readUInt16LE(6); if (color === 0xffff) { // This is a barcode this.notify("barcode", { barcode }); } else if (barcode === 0xffff) { // This is a color this.notify("barcode", { color }); } break; case Mode.RGB: /** * Emits when the barcode sensor sees a RGB color. * @event MarioBarcodeSensor#rgb * @type {object} * @param {number} r * @param {number} g * @param {number} b */ const r = message[4]; const g = message[5]; const b = message[6]; this.notify("rgb", { r, g, b }); break; } } }
JavaScript
class PageMaterialui extends Component { render() { return ( <div className="PageHome"> <Navigation /> <DrawerButton /> </div> ); } }
JavaScript
class PageLayout extends React.Component { state = { expanded: false, } handleChange = panel => (event, expanded) => { this.setState({ expanded: expanded ? panel : false, }) } render() { // const { expanded } = this.state; return ( <ServicesWrapper> <SideImage /> <ServicesMargin> <Grid container spacing={24}> <Grid item xs={4} className="responsive_grid_1" /> <Grid item xs={8} className="responsive_grid_2"> <div className="title_wrapper"> <h1 className="service_name">naše služby</h1> <h1 className="services"> Služby so starostlivosťou o klienta 24/7 </h1> <Divider height="70px" /> <p className="text_title">Personálna agentúra </p> <ul> <li> Kompletná personálna agenda a mzdový servis pre zamestnávateľov </li> <li>Vyhľadávanie pracovníkov pre firmy</li> <li> Vyhľadávania pracovných miest v oblastiach: logistika, priemysel, stavebníctvo a administratíva </li> </ul> <Divider height="25px" /> <ButtonWrapper buttonText="Personálna agentúra" buttonLink="/personalna_agentura" /> <Divider height="40px" /> <p className="text_title">Dopravca do 3.5t</p> <ul> <li>Vyzdvihnutie tovaru z Košického a Prešovského kraja</li> <li>Doprava v rámci SR a EÚ</li> </ul> <Divider height="25px" /> <ButtonWrapper buttonText="Dopravca do 3.5t" buttonLink="/dopravca" /> <Divider height="40px" /> <p className="text_title">Upratovací servis </p> <ul> <li>Ponuka upratovacieho servisu</li> <li>Viacero typov upratovacích intervalov</li> <li> Maximálna snaha o efektívnosť a kvalitu vykonávaných prác </li> <li> Doplnková služba - údržba a kosenie vonkajších trávnatých plôch </li> </ul> <Divider height="25px" /> <ButtonWrapper buttonText="Upratovací servis" buttonLink="/upratovaci_servis" /> <Divider height="40px" /> <p className="text_title"> Zabezpečenie a organizovanie firemných akcií </p> <ul> <li>Organizovanie outdorových a indorových eventov</li> <li> Catering priamo k vám do firmy, alebo na Vami určené miesto </li> </ul> <Divider height="25px" /> <ButtonWrapper buttonText="Organizovanie eventov" buttonLink="/organizovanie_eventov" /> <Divider height="40px" /> </div> </Grid> </Grid> <Grid container spacing={24}> <Grid item xs={4} className="responsive_grid_1" /> <Grid item xs={8} className="responsive_grid_2"> <div className="title_wrapper"> <h1 className="service_name">komplexnosť a flexibilita</h1> <h1 className="services"> Sme partner, na ktorého sa môžete spoľahnúť </h1> <p className="info_text"> Pracovníci spoločnosti PaS Services s.r.o. tvoria najdôležitejšie prepojenie medzi viacerými štruktúrami spoločnosti. Kvalita služieb poskytovaných našou firmou je zameraná na spokojnosť zákazníka a objednávateľa. Organizácia monitoruje potreby, ktoré sú odrazom našich služieb v oblasti logistiky. </p> <Divider height="50px" /> <p className="text_title"> Čo získate spoluprácou s našou agentúrou?  </p> <ul> <li> Zabezpečíme uzatvorenie pracovných zmlúv s pridelenými zamestnancami </li> <li> Vyhľadáme pracovníkov podľa Vašich stanovených požiadaviek </li> <li>Vyriešime nárazové alebo sezónne pracovné sily </li> <li> Zastrešíme problém výpadku Vášho kmeňového zamestnanca </li> <li> Znížime Úsporu Vašich nákladov spojených s vyhľadaním a umiestnením personálu </li> <li> Náklady pri výbere, vyhľadávaní a zaškolení pracovníkov budú nulové </li> <li> Vaša spoločnosť nebudee vykazovať zamestnancovi mesačnú mzdu., neodvádza za zamestnanca dane, neplatí sociálne a zdravotné poistenie.t.j. Kompletný mzdový servis je na nás </li> <li> Prevezmeme všetky potrebné pracovno-právne úkony, personálnu a mzdovú agendu voči zamestnancovi </li> </ul> <Divider height="70px" /> <ButtonWrapper buttonText="o nás" buttonLink="/o_nas" /> </div> </Grid> </Grid> </ServicesMargin> </ServicesWrapper> ) } }
JavaScript
class DetectTokensController { /** * Creates a DetectTokensController * * @param {Object} [config] - Options to configure controller */ constructor({ interval = DEFAULT_INTERVAL, preferences, network, keyringMemStore, tokenList, tokensController, } = {}) { this.tokensController = tokensController; this.preferences = preferences; this.interval = interval; this.network = network; this.keyringMemStore = keyringMemStore; this.tokenList = tokenList; this.selectedAddress = this.preferences?.store.getState().selectedAddress; this.tokenAddresses = this.tokensController?.state.tokens.map((token) => { return token.address; }); this.hiddenTokens = this.tokensController?.state.ignoredTokens; preferences?.store.subscribe(({ selectedAddress, useTokenDetection }) => { if ( this.selectedAddress !== selectedAddress || this.useTokenDetection !== useTokenDetection ) { this.selectedAddress = selectedAddress; this.useTokenDetection = useTokenDetection; this.restartTokenDetection(); } }); tokensController?.subscribe(({ tokens = [], ignoredTokens = [] }) => { this.tokenAddresses = tokens.map((token) => { return token.address; }); this.hiddenTokens = ignoredTokens; }); } async _getTokenBalances(tokens) { const ethContract = this.web3.eth .contract(SINGLE_CALL_BALANCES_ABI) .at(SINGLE_CALL_BALANCES_ADDRESS); return new Promise((resolve, reject) => { ethContract.balances([this.selectedAddress], tokens, (error, result) => { if (error) { return reject(error); } return resolve(result); }); }); } /** * For each token in the tokenlist provided by the TokenListController, check selectedAddress balance. */ async detectNewTokens() { if (!this.isActive) { return; } const { tokenList } = this._tokenList.state; // since the token detection is currently enabled only on Mainnet // we can use the chainId check to ensure token detection is not triggered for any other network // but once the balance check contract for other networks are deploayed and ready to use, we need to update this check. if ( this._network.store.getState().provider.chainId !== MAINNET_CHAIN_ID || Object.keys(tokenList).length === 0 ) { return; } const tokensToDetect = []; this.web3.setProvider(this._network._provider); for (const tokenAddress in tokenList) { if ( !this.tokenAddresses.find((address) => isEqualCaseInsensitive(address, tokenAddress), ) && !this.hiddenTokens.find((address) => isEqualCaseInsensitive(address, tokenAddress), ) ) { tokensToDetect.push(tokenAddress); } } const sliceOfTokensToDetect = [ tokensToDetect.slice(0, 1000), tokensToDetect.slice(1000, tokensToDetect.length - 1), ]; for (const tokensSlice of sliceOfTokensToDetect) { let result; try { result = await this._getTokenBalances(tokensSlice); } catch (error) { warn( `MetaMask - DetectTokensController single call balance fetch failed`, error, ); return; } const tokensWithBalance = tokensSlice.filter((_, index) => { const balance = result[index]; return balance && !balance.isZero(); }); await Promise.all( tokensWithBalance.map((tokenAddress) => { return this.tokensController.addToken( tokenAddress, tokenList[tokenAddress].symbol, tokenList[tokenAddress].decimals, ); }), ); } } /** * Restart token detection polling period and call detectNewTokens * in case of address change or user session initialization. * */ restartTokenDetection() { if (!(this.isActive && this.selectedAddress)) { return; } this.detectNewTokens(); this.interval = DEFAULT_INTERVAL; } /* eslint-disable accessor-pairs */ /** * @type {Number} */ set interval(interval) { this._handle && clearInterval(this._handle); if (!interval) { return; } this._handle = setInterval(() => { this.detectNewTokens(); }, interval); } /** * @type {Object} */ set network(network) { if (!network) { return; } this._network = network; this.web3 = new Web3(network._provider); } /** * In setter when isUnlocked is updated to true, detectNewTokens and restart polling * @type {Object} */ set keyringMemStore(keyringMemStore) { if (!keyringMemStore) { return; } this._keyringMemStore = keyringMemStore; this._keyringMemStore.subscribe(({ isUnlocked }) => { if (this.isUnlocked !== isUnlocked) { this.isUnlocked = isUnlocked; if (isUnlocked) { this.restartTokenDetection(); } } }); } /** * @type {Object} */ set tokenList(tokenList) { if (!tokenList) { return; } this._tokenList = tokenList; } /** * Internal isActive state * @type {Object} */ get isActive() { return this.isOpen && this.isUnlocked; } /* eslint-enable accessor-pairs */ }
JavaScript
class XmlResponse extends JsonResponse { /** * Initializes a new instance of the `XmlResponse` class. * @param {string} xmlContent The xml content of the response. */ constructor(xmlContent) { super(); this.content = xmlContent; } /** Gets the xml content. */ content = []; }
JavaScript
class NFTViewer extends Component { state = { nft: null, nfts: null } /** * Get the image URL from the Uniform Resource Identifier given in * parameter * URI gives access to Metadata JSON file * Metadata JSON file gives access to image URL * @param {*} ipfsURI URI to the metadata JSON file * @returns image URL */ async getImageUrlFromUri(ipfsURI) { const url = ipfsURI.replace(/^ipfs:\/\//, "https://dweb.link/ipfs/"); const resp = await fetch(url); const json = await resp.json(); return json.image.replace(/^ipfs:\/\//, "https://dweb.link/ipfs/"); } /** * Loads the NFT which identifier is equals to the one given in * "txt_tokenId" text field. */ async loadNFT() { //TODO check that the text from txt_tokenId is parsable const tokenId = parseInt(document.getElementById("txt_tokenId").value, 10); const uri = await call(this.props.web3, this.props.contract_nft, this.props.address_nft, "getURI", [tokenId]); const owner = await call(this.props.web3, this.props.contract_nft, this.props.address_nft, "ownerOf", [tokenId]); const image_url = await this.getImageUrlFromUri(uri); const nft = {"id":tokenId, "url":image_url, "owner":owner}; this.setState({"nft": nft}); } /** * Loads all ids stored in the blockchain and puts every NFT data * in the state. NFT data are: * - unique identifier; * - image URL; * - NFT owner. */ async loadNFTs() { const ids = await call(this.props.web3, this.props.contract_nft, this.props.address_nft, "getIds", null); var nfts = []; for(var id in ids) { const uri = await call(this.props.web3, this.props.contract_nft, this.props.address_nft, "getURI", [ids[id]]); const owner = await call(this.props.web3, this.props.contract_nft, this.props.address_nft, "ownerOf", [ids[id]]); const image_url = await this.getImageUrlFromUri(uri); nfts.push({"id":ids[id], "url":image_url, "owner": owner}); } this.setState({"nfts": nfts}); } /** * In order to display all NFT, we load all NFT when the component did * mount. */ componentDidMount() { this.loadNFTs(); } /** * Display the header of NFT table */ displayHeader() { return ( <thead> <tr> <th>Identifier</th> <th>Image</th> <th>Owner</th> </tr> </thead> ); } /** * Display all NFT data: * - Identifier; * - Image; * - Owner. */ displayNFT() { return this.state.nfts.map((nfts, index) => { const { id, url, owner} = nfts; return ( <> <tr> <td>{id}</td> <td><img src={url} /></td> <td>{owner}</td> </tr> </> ); }); } /** * Display every form and data concerning NFT */ render() { return ( <div className='content'> <h3>NFT Viewer</h3> <br/> <table> <tbody> <tr> <td><label>Enter NFT id to search:</label></td> <td><input id="txt_tokenId" type="text"></input></td> <td><Button onClick={() => this.loadNFT()}>Submit id</Button></td> </tr> </tbody> </table> <br/> {this.state.nft && <img src={this.state.nft.url} />} <table> {this.state.nfts && this.displayHeader()} <tbody> {this.state.nfts && this.displayNFT()} </tbody> </table> </div> ); } }
JavaScript
class QualityThresholdNotMet extends Error { /** * @param {string} text */ constructor(text) { super( `The translation of ${text} does not meet the requested quality threshold.` ); this.text = text; } }
JavaScript
class BatchIsEmpty extends Error { constructor() { super( `Requested a batch translation, but there are no texts in the batch.` ); } }
JavaScript
class TimelineEvents { constructor() { /** @private @type {!Map<T,{id:string,event:T,date:!Date,year:number,color:string}>} */ this.map_ = new Map(); /** @private @type {!Array<T>} */ this.events_ = []; } /** * @return {number} */ getSize() { return this.events_.length; } /** * @param {T} event * @param {number} year * @param {!Date} date * @param {string} color * @param {?string=} opt_id */ addEvent(event, year, date, color, opt_id) { const entry = { year: year, date: date, color: color, event: event, id: opt_id || String(this.getSize()), }; this.map_.set(event, entry); this.events_.push(event); } /** * @return {!Array<T>} */ getEvents() { return this.events_; } /** * @param {T} event * @override */ getEventId(event) { return this.map_.get(event).id; } /** * @param {T} event * @override */ getEventDate(event) { return this.map_.get(event).date; } /** * @param {T} event * @override */ getEventYear(event) { return this.map_.get(event).year; } /** * @param {T} event * @override */ getEventColor(event) { return this.map_.get(event).color; } /** * @override */ setEventROI(min, max) { } }
JavaScript
class BindingLogger { constructor(context) { this.context = context; } logSpan(span) { this.context.bindings["zipkin"] = [span.toJSON()]; } }
JavaScript
class Base { /** * @param {object} obj */ constructor(obj) { /** * The raw object used to create the class and gave class values. * @readonly * @type {object} * @name Base#raw */ Object.defineProperty(this, 'raw', { get: () => obj, enumerable: true }); } }
JavaScript
class VirtualAuthenticatorOptions { static Protocol = { "CTAP2": 'ctap2', "U2F": 'ctap1/u2f', } static Transport = { "BLE": 'ble', "USB": 'usb', "NFC": 'nfc', "INTERNAL": 'internal', } /** * Constructor to initialise VirtualAuthenticatorOptions object. */ constructor() { this._protocol = VirtualAuthenticatorOptions.Protocol["CTAP2"] this._transport = VirtualAuthenticatorOptions.Transport["USB"] this._hasResidentKey = false this._hasUserVerification = false this._isUserConsenting = true this._isUserVerified = false } getProtocol() { return this._protocol } setProtocol(protocol) { this._protocol = protocol } getTransport() { return this._transport } setTransport(transport) { this._transport = transport } getHasResidentKey() { return this._hasResidentKey } setHasResidentKey(value) { this._hasResidentKey = value } getHasUserVerification() { return this._hasUserVerification } setHasUserVerification(value) { this._hasUserVerification = value } getIsUserConsenting() { return this._isUserConsenting } setIsUserConsenting(value) { this._isUserConsenting = value } getIsUserVerified() { return this._isUserVerified } setIsUserVerified(value) { this._isUserVerified = value } toDict() { return { "protocol": this.getProtocol(), "transport": this.getTransport(), "hasResidentKey": this.getHasResidentKey(), "hasUserVerification": this.getHasUserVerification(), "isUserConsenting": this.getIsUserConsenting(), "isUserVerified": this.getIsUserVerified(), } } }
JavaScript
class Credential { constructor( credentialId, isResidentCredential, rpId, userHandle, privateKey, signCount ) { this._id = credentialId this._isResidentCredential = isResidentCredential this._rpId = rpId this._userHandle = userHandle this._privateKey = privateKey this._signCount = signCount } id() { return this._id } isResidentCredential() { return this._isResidentCredential } rpId() { return this._rpId } userHandle() { if (this._userHandle != null) { return this._userHandle } return null } privateKey() { return this._privateKey } signCount() { return this._signCount } /** * Creates a resident (i.e. stateless) credential. * @param id Unique base64 encoded string. * @param rpId Relying party identifier. * @param userHandle userHandle associated to the credential. Must be Base64 encoded string. * @param privateKey Base64 encoded PKCS * @param signCount initial value for a signature counter. * @returns A resident credential */ createResidentCredential(id, rpId, userHandle, privateKey, signCount) { return new Credential(id, true, rpId, userHandle, privateKey, signCount) } /** * Creates a non-resident (i.e. stateless) credential. * @param id Unique base64 encoded string. * @param rpId Relying party identifier. * @param privateKey Base64 encoded PKCS * @param signCount initial value for a signature counter. * @returns A non-resident credential */ createNonResidentCredential(id, rpId, privateKey, signCount) { return new Credential(id, false, rpId, null, privateKey, signCount) } toDict() { let credentialData = { 'credentialId': Buffer.from(this._id).toString('base64url'), 'isResidentCredential': this._isResidentCredential, 'rpId': this._rpId, 'privateKey': Buffer.from(this._privateKey, 'binary').toString('base64url'), 'signCount': this._signCount, } if (this.userHandle() != null) { credentialData['userHandle'] = Buffer.from(this._userHandle).toString('base64url') } return credentialData } /** * Creates a credential from a map. */ fromDict(data) { let id = new Uint8Array(Buffer.from(data['credentialId'], 'base64url')) let isResidentCredential = data['isResidentCredential'] let rpId = data['rpId'] let privateKey = Buffer.from(data['privateKey'], 'base64url').toString('binary') let signCount = data['signCount'] let userHandle if ('userHandle' in data) { userHandle = new Uint8Array(Buffer.from(data['userHandle'], 'base64url')) } else { userHandle = null } return new Credential( id, isResidentCredential, rpId, userHandle, privateKey, signCount ) } }
JavaScript
class HashHistory extends React.Component { static propTypes = { basename: PropTypes.string, getUserConfirmation: PropTypes.func, hashType: PropTypes.oneOf(["hashbang", "noslash", "slash"]), children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired }; static childContextTypes = { history: historyType.isRequired }; getChildContext() { return { history: this.history }; } componentWillMount() { const { basename, getUserConfirmation, hashType } = this.props; this.history = createHashHistory({ basename, getUserConfirmation, hashType }); // Do this here so we catch actions in cDM. this.unlisten = this.history.listen(() => this.forceUpdate()); } componentWillUnmount() { this.unlisten(); } render() { const { children } = this.props; return typeof children === "function" ? children(this.history) : React.Children.only(children); } }
JavaScript
class orderController { /** * @method createOrder * @returns { null } returns Error ordering meal * @param { String } mealId mealId of the meal to be ordered * @param { String } quantity of the meal to be ordered * @param { String } address of the person ordering the meal * @returns { object } returns order details * @description It takes meal id, quantity and address of the person that is ordering the meal and create an order */ async createOrder(req, res) { const { meals, address, menu } = req.body; const presentTime = new Date().getHours() + (new Date().getMinutes() / 60); const myOrder = []; for (const eachMenu of menu) { const { orderBefore } = eachMenu; const catererId = eachMenu.userId; if (orderBefore < Number(presentTime)) { return res.status(422) .json({ message: 'You cannot order meal from this menu at this time' }); } const allMenuMealId = eachMenu.Meals.map(meal => meal.id); // extract all meal that that has above menuId const allMeal = meals.filter(meal => meal.menuId === eachMenu.id); const allMealId = allMeal.map(meal => meal.mealId); const mealsExistInMenu = new mealFilter().checkMeals(allMenuMealId, allMealId); if (!mealsExistInMenu) { return res.status(404).json({ message: 'Meal not found' }); } const { id } = req.decoded; const order = await Order.create({ status: 'pending', address, catererId }); const user = User.build({ id }); order.setUser(user); for (const meal of allMeal) { order.setMeals(meal.mealId, { through: { quantity: meal.quantity } }); } order.dataValues.meals = allMealId; myOrder.push(order); } return res.status(201).json(myOrder); } /** * @method updateOrder * @returns { null } returns Order not found * @param { String } orderId of the order to be updated * @param { String } quantity of the meal to be ordered * @param { String } address of the person ordering the meal * @returns { object } returns updated order * @description It takes order id, quantity or address of the person that is ordering the meal and updates an order */ async updateOrder(req, res) { const { meals, address, order } = req.body; const { orderId } = req.params; const allOrderMealId = order.meals.map(meal => meal.id); const allMealId = meals.map(meal => meal.mealId); const mealsExistInOrder = new mealFilter().checkMeals(allOrderMealId, allMealId); if (!mealsExistInOrder) { return res.status(404).json({ message: 'Meal not found' }); } const update = await order.update({ address }); for (const meal of meals) { await update.addMeal(meal.mealId, { through: { quantity: meal.quantity } }); } return res.status(201).json(update); } /** * @method getOrders * @returns { null } returns users have not ordered a meal * @returns { array } returns all orders * @description used to get the orders users have made in the specified in limit and offset * functionality limited to caterers only */ async getOrders(req, res) { const { id } = req.decoded; let { limit, offset } = req.query; limit = parseInt(limit, 10) || 6; offset = parseInt(offset, 10) || 0; if (limit < 0 || offset < 0) { return res.status(401).json({ message: 'Your query param cannot be negative' }); } const catererId = id; const orders = await Order.findAll({ where: { catererId }, include: [ { model: Meal, as: 'meals', attributes: ['id', 'name', 'price', 'description', 'image', 'createdAt', 'updatedAt'], through: { attributes: ['quantity', 'totalPrice'] }, }, { model: User, as: 'user', attributes: ['id', 'name', 'username', 'image'] } ], order: [ ['createdAt', 'DESC'] ], limit, offset }); const count = await Order.count({ where: { catererId } }); if (!orders || orders.length < 1) { return res.status(404).json({ message: 'Users have not ordered a meal' }); } orders.forEach((order) => { const totalPrice = new mealFilter().getPrice(order.meals); order.dataValues.totalPrice = totalPrice; }); return res.status(200).json({ orders, count }); } /** * @method getOrders * @returns { null } returns users have not ordered a meal * @returns { array } returns all orders * @description used to get the orders made by a particular user */ async getUserOrders(req, res) { let { limit, offset } = req.query; limit = parseInt(limit, 10) || 6; offset = parseInt(offset, 10) || 0; if (limit < 0 || offset < 0) { return res.status(401).json({ message: 'Your query param cannot be negative' }); } const userId = req.decoded.id; const orders = await Order.findAll({ where: { userId }, include: [ { model: Meal, as: 'meals', attributes: ['id', 'name', 'price', 'description', 'image', 'createdAt', 'updatedAt'] }, ], order: [ ['createdAt', 'DESC'] ], limit, offset }); const count = await Order.count({ where: { userId } }); if (!orders || orders.length < 1) { return res.status(404).json({ message: 'You have not ordered a meal' }); } orders.forEach((order) => { const totalPrice = new mealFilter().getPrice(order.meals); order.dataValues.totalPrice = totalPrice; }); return res.status(200).json({ count, orders }); } /** * @method confirmStatus * @description acknowledges that meal is received */ async confirmStatus(req, res) { const userId = req.decoded.id; const id = req.params.orderId; const order = await Order.findOne({ where: { id } }); if (!order) { return res.status(404).json({ message: 'Order not found' }); } if (userId !== order.userId) { return res.status(401).json({ message: 'You cannot update order you did not add' }); } const update = await order.update({ status: 'confirmed' }); if (!update) { return res.status(404).json({ message: 'Update failed' }); } return res.status(201).json(update); } }
JavaScript
class Vector { constructor(x, y) { this.x = x; this.y = y; } Equals(vector) { return this.x === vector.x && this.y === vector.y; } Neighbor(direction) { let neighbor = new Vector(this.x, this.y); switch (direction) { case "UP": neighbor.y--; break; case "DOWN": neighbor.y++; break; case "LEFT": neighbor.x--; break; case "RIGHT": neighbor.x++; break; } return neighbor; } }
JavaScript
class Sprite { constructor( name, // name of the sprite ctx, // reference to canvas spriteSheetImg, // Sprite sheet containing all images sourceSize, // size of sprite in source image targetSize, // size of sprite when rendered in output. The target size MUST be the same size as the maze cell size (normally 16 or 32 pixels). imageCount, // number of images that can be animated / cycled through imageSet, // parameters / meta data for each image in the image set x, // starting x coordinate (top-left) y, // starting y coordinate (top-left) frameSpeed, direction ) { this.name = name; this.ctx = ctx; this.spriteSheetImg = spriteSheetImg; this.sourceSize = sourceSize; this.targetSize = targetSize; this.imageCount = imageCount; // 3 this.imageSet = imageSet; this.x = x; this.y = y; this.frame = 1; this.frameSpeed = frameSpeed; this.direction = direction; // Initial direction // Additional calculations this.movement = Math.floor(this.targetSize / 5); // 5 frames per logical tile } // Gets the logical-x tile that the top-left part of the sprite is in getLogicalx() { return Math.floor(this.x / this.targetSize); } // Gets the logical-y tile that the top-left part of the sprite is in getLogicaly() { return Math.floor(this.y / this.targetSize); } // Gets the x-coordinate of the middle of the sprite getMiddlex() { return Math.floor(this.x + this.targetSize / 2); } // Gets the y-coordinate of the middle of the sprite getMiddley() { return Math.floor(this.y + this.targetSize / 2); } // Gets the logical-x tile that the middle of the sprite is in. getMiddleLogicalx() { return Math.floor(this.getMiddlex() / this.targetSize); } // Gets the logical-y tile that the middle of the sprite is in. getMiddleLogicaly() { return Math.floor(this.getMiddley() / this.targetSize); } // Sets the direction of the sprite setDirection(direction) { this.direction = direction; } getMovementx() { return this.direction === "LEFT" ? -this.movement : this.direction === "RIGHT" ? this.movement : 0; } getMovementy() { return this.direction === "UP" ? -this.movement : this.direction === "DOWN" ? this.movement : 0; } getNextLogicalx() { return Math.floor((this.x + this.getMovementx()) / this.targetSize); } getNextLogicaly() { return Math.floor((this.y + this.getMovementy()) / this.targetSize); } // returns true if the sprite is blocked by the maze based on its // current direction. isBlocked(maze) { // boolean to determine whether sprite's movement is blocked return ( (this.direction === "RIGHT" && maze.GetCellAtVector( new Vector(this.getLogicalx(), this.getMiddleLogicaly()) ).borders["RIGHT"] !== "GAP") || (this.direction === "DOWN" && maze.GetCellAtVector( new Vector(this.getMiddleLogicalx(), this.getLogicaly()) ).borders["DOWN"] !== "GAP") || (this.direction === "LEFT" && this.getLogicalx() !== this.getNextLogicalx() && maze.GetCellAtVector( new Vector(this.getNextLogicalx() + 1, this.getMiddleLogicaly()) ).borders["LEFT"] !== "GAP") || (this.direction === "UP" && this.getLogicaly() !== this.getNextLogicaly() && maze.GetCellAtVector( new Vector(this.getMiddleLogicalx(), this.getNextLogicaly() + 1) ).borders["UP"] !== "GAP") ); } // Allows for a system algorithm to be implemented instead of // using user input. This function normally used for pc-controlled // sprites systemInputFn(game) {} // Calculates the next state / position of the sprite within the maze, // taking into account obstacles like the maze walls. // This function can also do collison detection using the sprites array. calculateState(game) { const maze = game.maze; const sprites = [...game.monsterSprites, game.playerSprite, game.keySprite]; const counter = game.counter; this.collisionDetection(game, sprites); if (!this.direction) { this.update(this.x, this.y, "DEFAULT", counter); } else { if (this.isBlocked(maze)) { // If movement is blocked by the maze, don't actually move, but re-center non-movement axis. this.update( this.direction === "UP" || this.direction === "DOWN" ? this.x : this.getLogicalx() * this.targetSize + 1, this.direction === "LEFT" || this.direction === "RIGHT" ? this.y : this.getLogicaly() * this.targetSize, this.direction, counter ); } else { // Not blocked - move sprite. if (this.direction === "RIGHT") { this.update( this.x + this.getMovementx(), this.getMiddleLogicaly() * this.targetSize, "RIGHT", counter ); } if (this.direction === "LEFT") { this.update( this.x + this.getMovementx(), this.getMiddleLogicaly() * this.targetSize, "LEFT", counter ); } if (this.direction === "UP") { this.update( this.getMiddleLogicalx() * this.targetSize, this.y + this.getMovementy(), "UP", counter ); } if (this.direction === "DOWN") { this.update( this.getMiddleLogicalx() * this.targetSize, this.y + this.getMovementy(), "DOWN", counter ); } } } } collisionDetection(game, sprites) { if (this.name === "player1") { const key = sprites.filter((s) => s.name === "key")[0]; if ( key.getMiddleLogicalx() === this.getMiddleLogicalx() && key.getMiddleLogicaly() === this.getMiddleLogicaly() ) { alert("You Win!"); game.resetGame(); } const monsters = sprites.filter((s) => s.name === "monster"); for (let m = 0; m < monsters.length; m++) { if ( monsters[m].getMiddleLogicalx() === this.getMiddleLogicalx() && monsters[m].getMiddleLogicaly() === this.getMiddleLogicaly() ) { alert("You Lose!"); game.resetGame(); } } } } // Actually applies the change in position update(x, y, type, counter) { this.oldx = this.x; this.oldy = this.y; this.x = x; this.y = y; this.type = type; this.frame = Math.floor(counter / this.frameSpeed) % this.imageCount; } preRender() { this.ctx.clearRect(this.oldx, this.oldy, this.targetSize, this.targetSize); } render() { const image = this.imageSet.filter((f) => f.type === this.type)[0][ "images" ][this.frame]; this.ctx.drawImage( this.spriteSheetImg, this.sourceSize * image[0], this.sourceSize * image[1], this.sourceSize, this.sourceSize, this.x, this.y, this.targetSize, this.targetSize ); } }
JavaScript
class Table extends Component { /** * render - Converts the property 'tableData' (see below) into a HTML-table * and renders it. * * @return {JSX} JSX-Code of component */ render() { let table; if(this.props.tableData.length > 4) { table = <tr>Bitte melden Sie sich für grössere Auswertungen an <a href='mailto:[email protected]'>[email protected]</a>. Die eonum AG bietet weitergehende Datenanalysen mit zusätzlichen Datenquellen an. Weitere Informationen dazu finden Sie <a href='https://eonum.ch/de/allgemein/medical-landscape-schweiz/' target='_blank'>hier</a></tr>; } else { table = this.props.tableData.map((row, rowIndex) => { return (<tr key={this.props.tableData.indexOf(row)}>{row.map((cell, cellIndex) => { return <td key={row.length * rowIndex + cellIndex}>{cell}</td> })}</tr>); }) } return ( <table className="table"> <tbody> { table } </tbody> </table> ); } }
JavaScript
class VertexArray { /** * @param {number} num_attrs -- num of attributes buffers this vertex array will hold, * (without including vertex coordinates, which are allways attribute 0) * can be any non-negative integer, including 0 * @param {number} vec_len -- length of each vector with a vertex coordinates, must be 2,3, or 4 * @param {Float32Array} coords_data -- vertex coordinates, its length must be multiple of 'vec_len' */ constructor( num_attrs, vec_len, coords_data ) { this.debug = false const fname = 'VertexArray.constructor: ()' CheckNat( num_attrs ) let coords_buffer = new AttrBuffer( vec_len, coords_data ) this.num_vertexes = coords_buffer.num_vecs this.indexes_buffer = null // by default, this is a non-indexed sequence this.attr_buffers = [ coords_buffer ] // array with vertexes attributes buffers (index 0 allways refers to the vertexes coordinates buffer) for( let i = 0 ; i < num_attrs ; i++ ) // add uninitialized attribute arrays this.attr_buffers.push( null ) } // ------------------------------------------------------------------------------------------- /** * sets the indexes for this vertex arry (removes previous one, if any) * @param {UInt32Array} indexes_data -- ( can also be a 'Unit16Array' ) */ setIndexesData( indexes_data ) { this.indexes_buffer = new IndexesBuffer( indexes_data ) } // ------------------------------------------------------------------------------------------- /** * Sets a new vertex attribute data (other than vertex coordinates) * @param {number} attr_index -- attribute index, must be >0 (we cannot set the coordinates), and less than 'attr_buffers' length. * @param {number} vec_len -- length of each vector in 'attr_array' * @param {Float32Array} attr_data -- new attributes array (can be 'null', then the corresponding * attribute buffer is also set to null */ setAttrData( attr_index, vec_len, attr_data ) { const fname = `VertexArray.setAttrData(): ` const nb = this.attr_buffers.length // number of attributes buffers, including 0 == vertex coordinates CheckNat( attr_index ) Check( 0 < attr_index && attr_index < nb , `${fname} 'attr_index' (==${attr_index}) must be between 1 and ${nb-1}, both included` ) let attr_buffer = null if ( attr_data != null ) { CheckType( attr_data, 'Float32Array' ) Check( attr_data.length/vec_len === this.num_vertexes, `${fname} attr. array length not coherent with num of vertexes of this vertex seq.`) attr_buffer = new AttrBuffer( vec_len, attr_data ) } this.attr_buffers[attr_index] = attr_buffer // when 'attr_data' is null, sets 'attr_buffer[i]' also to null } // --------------------------------------------------------------------------------------------- /** * Draws this vertex sequence * @param {WebGLRenderingContext} gl -- rendering context * @param {number} mode -- mode: (triangles,lines, line_strip, points, etc...) */ draw( gl, mode ) { const fname = 'VertexArray.draw():' if ( this.debug ) Log(`${fname} begins.`) CheckGLError( gl ) // enable/disable each attribute array for( let i = 0 ; i < this.attr_buffers.length ; i++ ) if ( this.attr_buffers[i] != null ) this.attr_buffers[i].enable( gl, i ) else gl.disableVertexAttribArray( i ) if ( this.indexes_buffer == null ) gl.drawArrays( mode, 0, this.num_vertexes ) else this.indexes_buffer.drawElements( gl, mode ) // disable attr arrays for( let i = 0 ; i < this.attr_buffers.length ; i++ ) gl.disableVertexAttribArray( i ) CheckGLError( gl ) if ( this.debug ) Log(`${fname} ends.`) } }
JavaScript
class SimpleVertexArray extends VertexArray { constructor() { const vertex_coords = [ -0.9, -0.9, 0.0, +0.9, -0.9, 0.0, +0.9, +0.9, 0.0, -0.9, -0.9, 0.0, +0.9, +0.9, 0.0, -0.9, +0.9, 0.0 ] const vertex_colors = [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0 ] super( 1, 3, new Float32Array( vertex_coords ) ) this.setAttrData( 1, 3, new Float32Array( vertex_colors ) ) } }
JavaScript
class SimpleIndexedVertexArray extends VertexArray { constructor() { const vertex_coords = [ -0.9, -0.9, 0.0, +0.9, -0.9, 0.0, -0.9, +0.9, 0.0, +0.9, +0.9, 0.0 ] const vertex_colors = [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0 ] const indexes = [ 0,1,3, 0,3,2 ] super( 1, 3, new Float32Array( vertex_coords ) ) this.setAttrData( 1, 3, new Float32Array( vertex_colors )) this.setIndexesData( new Uint16Array( indexes )) } }
JavaScript
class ConnectionsNodePopupController { /** * Initialize global variables for this controller * @param $rootScope Angular application main scope * * @ngInject */ constructor($rootScope) { this.$rootScope = $rootScope; } closePopup() { $('#networkLabel').hide(); } addExpression(op) { let fullExpression = `${this.node.exp} == ${this.node.id}`; this.$rootScope.$broadcast('add:to:typeahead', { expression: fullExpression, op: op }); } hideNode() { let self = this; $('#networkLabel').hide(); self.svg.select('#id'+self.node.id.replace(/[:\.]/g,'_')).remove(); self.svg.selectAll('.link') .filter(function(d, i) { return d.source.id === self.node.id || d.target.id === self.node.id; }) .remove(); } }
JavaScript
class ProposalManager extends Proposal { /** * * @param {IdentityContext} identityContext * @param {Endorser[]} endorsers * @param {string} [chaincodeId] * @param {Channel} [channel] */ constructor(identityContext, endorsers, chaincodeId, channel) { super(chaincodeId || null, channel || null); Object.assign(this, {identityContext, endorsers}); } /** * * @param {ProposalResultHandler} assertFunction */ setProposalResultAssert(assertFunction) { this.assertProposalResult = assertFunction; } /** * @param {CommitResultHandler} assertFunction */ setCommitResultAssert(assertFunction) { this.assertCommitResult = assertFunction; } asQuery() { this.type = 'Query'; } asEndorsement() { this.type = 'Endorsement'; } /** * * @param {BuildProposalRequest} buildProposalRequest * @param {{[requestTimeout]:number, [handler]:function}} [connectOptions] * @return ProposalResponse */ async send(buildProposalRequest, connectOptions = {}) { const {requestTimeout, handler} = connectOptions; const {identityContext} = this; const {nonce} = buildProposalRequest; if (nonce) { buildProposalRequest.generateTransactionId = false; identityContext.nonce = nonce; identityContext.transactionId = calculateTransactionId(identityContext, nonce); } this.build(identityContext, buildProposalRequest); this.sign(identityContext); // TODO take care of offline signing /** * @type {SendProposalRequest} */ const sendProposalRequest = { targets: this.endorsers, requestTimeout, handler, // TODO investigate }; const results = await super.send(sendProposalRequest); typeof this.assertProposalResult === 'function' && this.assertProposalResult(results); return results; } /** * * @param {Committer[]} committers * @param [requestTimeout] * @return Promise<CommitResponse|*> */ async commit(committers, {requestTimeout} = {}) { const commit = new Commit(this.chaincodeId, this.channel, this); commit.build(this.identityContext); commit.sign(this.identityContext); const result = await commit.send({targets: committers, requestTimeout}); typeof this.assertCommitResult === 'function' && this.assertCommitResult(result); return result; } }
JavaScript
class PrintingSupport { constructor() { // The margins around the whole printed content in page coordinates. this.margin = 5 // The scale factor to apply to the printed content. this.scale = 1.0 // Whether to print multiple pages if the content does not fit on a single page. this.tiledPrinting = false // The width of a single tile (page) in pt (1/72 inch). this.tileWidth = 595 // The height of a single tile (page) in pt (1/72 inch). this.tileHeight = 842 // The URL of the print document that's created and then opened. this.targetUrl = './printdocument.html' // The projection for the print content. When exporting a GraphComponent with a projection // this should be set to the same value. this.projection = Matrix.IDENTITY } /** * Prints the detail of the given graph that is specified by either a * rectangle in world coordinates or a collection of world coordinate points which * define a bounding box in view coordinates. * If no <code>region</code> is specified, the complete graph is printed. * @param {!IGraph} graph * @param {!(Rect|Array.<Point>)} [region] */ printGraph(graph, region) { // Create a new graph component for exporting the original SVG content const exportComponent = new GraphComponent() // ... and assign it the same graph. exportComponent.graph = graph this.print(exportComponent, region) } /** * Prints the detail of the given GraphComponent's graph that is specified by either a * rectangle in world coordinates or a collection of world coordinate points which * define a bounding box in view coordinates. * If no <code>region</code> is specified, the complete graph is printed. * @param {!GraphComponent} graphComponent * @param {!(Rect|Array.<Point>)} [region] * @returns {!Promise} */ async print(graphComponent, region) { let targetRect if (Array.isArray(region)) { targetRect = this.getBoundsFromPoints(region) } else if (region instanceof Rect) { const { topLeft, topRight, bottomLeft, bottomRight } = region targetRect = this.getBoundsFromPoints([topLeft, topRight, bottomLeft, bottomRight]) } else { targetRect = this.getBoundsFromPoints( graphComponent .getCanvasObjects(graphComponent.rootGroup) .map(co => co.descriptor.getBoundsProvider(co.userObject).getBounds(graphComponent.canvasContext) ) .filter(bounds => bounds.isFinite) .flatMap(bounds => IEnumerable.from([ bounds.topLeft, bounds.topRight, bounds.bottomLeft, bounds.bottomRight ]) ) ) } let rows let columns let tiles const invertedProjection = this.projection.clone() invertedProjection.invert() if (!this.tiledPrinting) { // no tiles - just one row and column rows = 1 columns = 1 tiles = [[this.getPointsForTile(targetRect, invertedProjection)]] } else { // get the size of the printed tiles const tileSize = new Size(this.tileWidth, this.tileHeight) const tileSizeScaled = new Size(tileSize.width / this.scale, tileSize.height / this.scale) // calculate number of rows and columns rows = Math.ceil((targetRect.height * this.scale) / tileSize.height) columns = Math.ceil((targetRect.width * this.scale) / tileSize.width) // calculate tile bounds tiles = [] for (let i = 0; i < rows; i++) { const column = [] for (let k = 0; k < columns; k++) { column.push( this.getPointsForTile( new Rect( targetRect.x + tileSizeScaled.width * k, targetRect.y + tileSizeScaled.height * i, tileSizeScaled.width, tileSizeScaled.height ), invertedProjection ) ) } tiles.push(column) } // calculate bounds of last row/column const lastX = targetRect.x + tileSizeScaled.width * (columns - 1) const lastY = targetRect.y + tileSizeScaled.height * (rows - 1) const lastWidth = targetRect.width - tileSizeScaled.width * (columns - 1) const lastHeight = targetRect.height - tileSizeScaled.height * (rows - 1) // set bounds of last row for (let k = 0; k < columns - 1; k++) { tiles[rows - 1][k] = this.getPointsForTile( new Rect( targetRect.x + tileSizeScaled.width * k, lastY, tileSizeScaled.width, lastHeight ), invertedProjection ) } // set bounds of last column for (let i = 0; i < rows - 1; i++) { tiles[i][columns - 1] = this.getPointsForTile( new Rect( lastX, targetRect.y + tileSizeScaled.height * i, lastWidth, tileSizeScaled.height ), invertedProjection ) } // set bounds of bottom right tile tiles[rows - 1][columns - 1] = this.getPointsForTile( new Rect(lastX, lastY, lastWidth, lastHeight), invertedProjection ) } let resultingHTML = '' // loop through all rows and columns for (let i = 0; i < rows; i++) { for (let k = 0; k < columns; k++) { const lastRow = i === rows - 1 const lastColumn = k === columns - 1 const exporter = new SvgExport({ worldBounds: Rect.EMPTY, // dummy rectangle that's overwritten by worldPoints below worldPoints: tiles[i][k], scale: this.scale, copyDefsElements: true, encodeImagesBase64: true, inlineSvgImages: true, projection: this.projection }) this.configureMargin(exporter, i === 0, lastRow, k === 0, lastColumn) if (!lastRow || !lastColumn) { resultingHTML += "<div class='pagebreak'>" } else { resultingHTML += '<div>' } // export the svg to an XML string const svgElement = await exporter.exportSvgAsync(graphComponent) resultingHTML += SvgExport.exportSvgString(svgElement) resultingHTML += '</div>' } } // This function has to be global, because it is called from the print preview window. window.addPrintDom = win => { win.document.body.innerHTML = resultingHTML win.document.close() // Wait for everything to be rendered before printing setTimeout(() => { win.print() }, 0) } // display exported svg in new window const printWindow = window.open(this.targetUrl) if (!printWindow) { alert('Could not open print preview window - maybe it was blocked?') } } // Returns the corners of the tile, projected back to world coordinates /** * @param {!Rect} bounds * @param {!Matrix} invertedProjection * @returns {!Array.<Point>} */ getPointsForTile(bounds, invertedProjection) { return [ invertedProjection.transform(bounds.topLeft), invertedProjection.transform(bounds.topRight), invertedProjection.transform(bounds.bottomRight), invertedProjection.transform(bounds.bottomLeft) ] } // Returns the projected bounding box for the given points /** * @param {!Iterable.<Point>} points */ getBoundsFromPoints(points) { let bounds = Rect.EMPTY for (const p of points) { bounds = bounds.add(this.projection.transform(p)) } return bounds } /** * @param {!SvgExport} exporter * @param {boolean} firstRow * @param {boolean} lastRow * @param {boolean} firstColumn * @param {boolean} lastColumn */ configureMargin(exporter, firstRow, lastRow, firstColumn, lastColumn) { if (!this.tiledPrinting) { // set margin if we don't print tiles exporter.margins = new Insets(this.margin) } else { // for tile printing, set margin only for border tiles const top = firstRow ? this.margin : 0 const bottom = lastRow ? this.margin : 0 const right = lastColumn ? this.margin : 0 const left = firstColumn ? this.margin : 0 exporter.margins = new Insets(left, top, right, bottom) } } }
JavaScript
class TubeMeshBuffer extends MeshBuffer { /** * @param {Object} data - attribute object * @param {Float32Array} data.position - positions * @param {Float32Array} data.normal - normals * @param {Float32Array} data.binormal - binormals * @param {Float32Array} data.tangent - tangents * @param {Float32Array} data.color - colors * @param {Float32Array} data.size - sizes * @param {Picker} data.picking - picking ids * @param {BufferParameters} params - parameter object */ constructor(data, params = {}) { super(getData(data, params), params); this.capVertices = this.parameters.capped ? this.parameters.radialSegments : 0; this.capTriangles = this.parameters.capped ? this.parameters.radialSegments - 2 : 0; this.size2 = data.position.length / 3; data.primitiveId = serialArray(this.size2); this.setAttributes(data); this.makeIndex(); } get defaultParameters() { return TubeMeshBufferDefaultParameters; } setAttributes(data = {}) { const aspectRatio = this.parameters.aspectRatio; const n = this.size2; const n1 = n - 1; const radialSegments = this.parameters.radialSegments; const attributes = this.geometry.attributes; let position, normal, binormal, tangent, color, size, primitiveId; let meshPosition, meshColor, meshNormal, meshPrimitiveId; if (data.position) { position = data.position; normal = data.normal; binormal = data.binormal; tangent = data.tangent; size = data.size; meshPosition = attributes.position.array; meshNormal = attributes.normal.array; attributes.position.needsUpdate = true; attributes.normal.needsUpdate = true; } if (data.color) { color = data.color; meshColor = attributes.color.array; attributes.color.needsUpdate = true; } if (data.primitiveId) { primitiveId = data.primitiveId; meshPrimitiveId = attributes.primitiveId.array; attributes.primitiveId.needsUpdate = true; } let k, l; let radius = 0; let normX = 0; let normY = 0; let normZ = 0; let biX = 0; let biY = 0; let biZ = 0; let posX = 0; let posY = 0; let posZ = 0; const cxArr = []; const cyArr = []; const cx1Arr = []; const cy1Arr = []; const cx2Arr = []; const cy2Arr = []; if (position) { for (let j = 0; j < radialSegments; ++j) { const v = (j / radialSegments) * 2 * Math.PI; cxArr[j] = aspectRatio * Math.cos(v); cyArr[j] = Math.sin(v); cx1Arr[j] = aspectRatio * Math.cos(v - 0.01); cy1Arr[j] = Math.sin(v - 0.01); cx2Arr[j] = aspectRatio * Math.cos(v + 0.01); cy2Arr[j] = Math.sin(v + 0.01); } } for (let i = 0; i < n; ++i) { k = i * 3; l = k * radialSegments; if (position && tangent && normal && binormal && size) { vTangent.set(tangent[k], tangent[k + 1], tangent[k + 2]); normX = normal[k]; normY = normal[k + 1]; normZ = normal[k + 2]; biX = binormal[k]; biY = binormal[k + 1]; biZ = binormal[k + 2]; posX = position[k]; posY = position[k + 1]; posZ = position[k + 2]; radius = size[i]; } for (let j = 0; j < radialSegments; ++j) { const s = l + j * 3; if (position) { const cx = -radius * cxArr[j]; // TODO: Hack: Negating it so it faces outside. const cy = radius * cyArr[j]; const cx1 = -radius * cx1Arr[j]; const cy1 = radius * cy1Arr[j]; const cx2 = -radius * cx2Arr[j]; const cy2 = radius * cy2Arr[j]; meshPosition[s] = posX + cx * normX + cy * biX; meshPosition[s + 1] = posY + cx * normY + cy * biY; meshPosition[s + 2] = posZ + cx * normZ + cy * biZ; // TODO half of these are symmetric vMeshNormal.set( // ellipse tangent approximated as vector from/to adjacent points (cx2 * normX + cy2 * biX) - (cx1 * normX + cy1 * biX), (cx2 * normY + cy2 * biY) - (cx1 * normY + cy1 * biY), (cx2 * normZ + cy2 * biZ) - (cx1 * normZ + cy1 * biZ)).cross(vTangent); meshNormal[s] = vMeshNormal.x; meshNormal[s + 1] = vMeshNormal.y; meshNormal[s + 2] = vMeshNormal.z; } if (color) { meshColor[s] = color[k]; meshColor[s + 1] = color[k + 1]; meshColor[s + 2] = color[k + 2]; } if (primitiveId) { meshPrimitiveId[i * radialSegments + j] = primitiveId[i]; } } } // front cap k = 0; l = n * 3 * radialSegments; for (let j = 0; j < radialSegments; ++j) { const s = k + j * 3; const t = l + j * 3; if (position && tangent) { meshPosition[t] = meshPosition[s]; meshPosition[t + 1] = meshPosition[s + 1]; meshPosition[t + 2] = meshPosition[s + 2]; meshNormal[t] = tangent[k]; meshNormal[t + 1] = tangent[k + 1]; meshNormal[t + 2] = tangent[k + 2]; } if (color) { meshColor[t] = meshColor[s]; meshColor[t + 1] = meshColor[s + 1]; meshColor[t + 2] = meshColor[s + 2]; } if (primitiveId) { meshPrimitiveId[n * radialSegments + j] = meshPrimitiveId[0 + j]; } } // back cap k = (n - 1) * 3 * radialSegments; l = (n + 1) * 3 * radialSegments; for (let j = 0; j < radialSegments; ++j) { const s = k + j * 3; const t = l + j * 3; if (position && tangent) { meshPosition[t] = meshPosition[s]; meshPosition[t + 1] = meshPosition[s + 1]; meshPosition[t + 2] = meshPosition[s + 2]; meshNormal[t] = tangent[n1 * 3]; meshNormal[t + 1] = tangent[n1 * 3 + 1]; meshNormal[t + 2] = tangent[n1 * 3 + 2]; } if (color) { meshColor[t] = meshColor[s]; meshColor[t + 1] = meshColor[s + 1]; meshColor[t + 2] = meshColor[s + 2]; } if (primitiveId) { meshPrimitiveId[(n + 1) * radialSegments + j] = meshPrimitiveId[(n - 1) * radialSegments + j]; } } } makeIndex() { const meshIndex = this.geometry.getIndex().array; const n = this.size2; const n1 = n - 1; const capTriangles = this.capTriangles; const radialSegments = this.parameters.radialSegments; const radialSegments1 = this.parameters.radialSegments + 1; let k, l; for (let i = 0; i < n1; ++i) { const k = i * radialSegments * 3 * 2; const irs = i * radialSegments; const irs1 = (i + 1) * radialSegments; for (let j = 0; j < radialSegments; ++j) { l = k + j * 3 * 2; // meshIndex[ l + 0 ] = irs + ( ( j + 0 ) % radialSegments ); meshIndex[l] = irs + j; meshIndex[l + 1] = irs + ((j + 1) % radialSegments); // meshIndex[ l + 2 ] = irs1 + ( ( j + 0 ) % radialSegments ); meshIndex[l + 2] = irs1 + j; // meshIndex[ l + 3 ] = irs1 + ( ( j + 0 ) % radialSegments ); meshIndex[l + 3] = irs1 + j; meshIndex[l + 4] = irs + ((j + 1) % radialSegments); meshIndex[l + 5] = irs1 + ((j + 1) % radialSegments); } } // capping const strip = [0]; for (let j = 1; j < radialSegments1 / 2; ++j) { strip.push(j); if (radialSegments - j !== j) { strip.push(radialSegments - j); } } // front cap l = n1 * radialSegments * 3 * 2; k = n * radialSegments; for (let j = 0; j < strip.length - 2; ++j) { if (j % 2 === 0) { meshIndex[l + j * 3 + 0] = k + strip[j + 0]; meshIndex[l + j * 3 + 1] = k + strip[j + 1]; meshIndex[l + j * 3 + 2] = k + strip[j + 2]; } else { meshIndex[l + j * 3 + 0] = k + strip[j + 2]; meshIndex[l + j * 3 + 1] = k + strip[j + 1]; meshIndex[l + j * 3 + 2] = k + strip[j + 0]; } } // back cap l = n1 * radialSegments * 3 * 2 + 3 * capTriangles; k = n * radialSegments + radialSegments; for (let j = 0; j < strip.length - 2; ++j) { if (j % 2 === 0) { meshIndex[l + j * 3 + 0] = k + strip[j + 0]; meshIndex[l + j * 3 + 1] = k + strip[j + 1]; meshIndex[l + j * 3 + 2] = k + strip[j + 2]; } else { meshIndex[l + j * 3 + 0] = k + strip[j + 2]; meshIndex[l + j * 3 + 1] = k + strip[j + 1]; meshIndex[l + j * 3 + 2] = k + strip[j + 0]; } } } }
JavaScript
class Pic extends Component { _handlePlaySoundAsync = async () => { await Audio.setIsEnabledAsync(true); let sound = new Audio.Sound(); await sound.loadAsync({ uri: 'http://cieloestrellado.xxxxxxxx.jp/coming/atos_3.mp3', }); await sound.playAsync(); }; constructor(props) { super(props); this.state = {uri:'http://www.pngmart.com/files/5/Snow-PNG-Transparent-Image.png'} this._changeLogo= this._changeLogo.bind(this) } judgeWinner(inputs) { return conditions.some(d => d.every(item => inputs.indexOf(item) !== -1)) } _changeLogo() { // this.setState(previousState => {return {uri: !previousState.uri }}); const { id } = this.props; this._handlePlaySoundAsync(); if( this.state.uri=='http://www.pngmart.com/files/5/Snow-PNG-Transparent-Image.png' ){ touch = true; // can touch }else{ touch = false; // can touch } if(touch==true){ if(round ===0) { round = 1 }else if(round ===1) { round = 2 } else if(round ===2) { round = 1 } if(round == 1){ this.setState(previousState => {return {uri: 'http://storage.googleapis.com/ix_choosemuse/uploads/2016/02/android-logo.png'}}); androidInputs = androidInputs.concat(id) let result = this.judgeWinner(androidInputs) if (result) { console.log("android win") } }else if(round ==2){ this.setState(previousState => {return {uri: 'https://tctechcrunch2011.files.wordpress.com/2014/06/apple_topic.png?w=220'}}); appleInputs = appleInputs.concat(id) let result = this.judgeWinner(appleInputs) if (result) { console.log("apple win") } } // console.log("android :" + androidInputs ) // console.log("apple :" + appleInputs ) } } render() { // let uri = this.state.uri ? 'http://storage.googleapis.com/ix_choosemuse/uploads/2016/02/android-logo.png' : 'https://tctechcrunch2011.files.wordpress.com/2014/06/apple_topic.png?w=220' let uri = this.state.uri return ( <TouchableHighlight onPress={this._changeLogo} underlayColor="#FF9999"> <View style={styles.button}> <Image source={{uri}} style={{width: 70, height: 70}}/> </View> </TouchableHighlight> ); } }
JavaScript
class PostFixedDepositAccountsRequest { /** * Constructs a new <code>PostFixedDepositAccountsRequest</code>. * PostFixedDepositAccountsRequest * @alias module:model/PostFixedDepositAccountsRequest */ constructor() { PostFixedDepositAccountsRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PostFixedDepositAccountsRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PostFixedDepositAccountsRequest} obj Optional instance to populate. * @return {module:model/PostFixedDepositAccountsRequest} The populated <code>PostFixedDepositAccountsRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PostFixedDepositAccountsRequest(); if (data.hasOwnProperty('clientId')) { obj['clientId'] = ApiClient.convertToType(data['clientId'], 'Number'); } if (data.hasOwnProperty('productId')) { obj['productId'] = ApiClient.convertToType(data['productId'], 'Number'); } if (data.hasOwnProperty('locale')) { obj['locale'] = ApiClient.convertToType(data['locale'], 'String'); } if (data.hasOwnProperty('dateFormat')) { obj['dateFormat'] = ApiClient.convertToType(data['dateFormat'], 'String'); } if (data.hasOwnProperty('submittedOnDate')) { obj['submittedOnDate'] = ApiClient.convertToType(data['submittedOnDate'], 'String'); } if (data.hasOwnProperty('depositAmount')) { obj['depositAmount'] = ApiClient.convertToType(data['depositAmount'], 'Number'); } if (data.hasOwnProperty('depositPeriod')) { obj['depositPeriod'] = ApiClient.convertToType(data['depositPeriod'], 'Number'); } if (data.hasOwnProperty('depositPeriodFrequencyId')) { obj['depositPeriodFrequencyId'] = ApiClient.convertToType(data['depositPeriodFrequencyId'], 'Number'); } } return obj; } }
JavaScript
class FirstPlot extends Component{ state={ ContractItems:[], } componentWillMount(){ fetch("http://localhost:8000/nba_package/Contracts/?format=json") .then(response => response.json()) .then(json => { this.setState({ ContractItems: json, }) }); } render(){ var player = this.props.player var data = this.state.ContractItems var contract = data.filter(function(item){ return item.player === player })[0]; if (contract !== undefined) { var ylist = [contract.number_2019_20, contract.number_2020_21, contract.number_2021_22, contract.number_2022_23, contract.number_2023_24]; } else { ylist = []; } return( <div className="Contract-data"> <Plot data={[ { x: ["2019-20","2020-21","2021-22","2022-23", "2023-24"], y: ylist, type: "bar", mode: "markers", marker: {color: "Blue"}, } ]} layout ={{ title: player + "'s Contract Obligations", autosize: false, width:750, height:410, yaxis:{ title: "Money Owed", range: [0, 50000000] }, xaxis: { title: "Year" }, }} /> </div> ) } }
JavaScript
class DomManager { /** * Initialization of the manager * * @param {object} config Configuration object */ constructor(config) { this._config = Object.assign({}, config); this.findVideo('local'); this.findVideo('remote'); } /** * Find video with the given type based on configuration * * @param {string} type One of video element types: 'local' or 'remote' * @private */ findVideo(type) { let container = document, found = null; if (this._config[type + 'VideoContainer'] instanceof Element) { container = this._config[type + 'VideoContainer']; } else if (typeof this._config[type + 'VideoContainer'] === 'string') { try { container = Finder.find(this._config[type + 'VideoContainer']); } catch (e) {} } if (this._config[type + 'Video'] instanceof Element) { found = this._config[type + 'Video']; } else if (typeof this._config[type + 'Video'] === 'string') { try { found = Finder.find(this._config[type + 'Video'], container, true); } catch (e) {} if(found === null) { try { found = Finder.find('video', container, true); } catch (e) {} } } if (found === null) { //found = Video.createVideo(type); } this._config[type + 'VideoContainer'] = container; this._config[type + 'Video'] = found; } /** * It sets the passed video element as local or remote * * @param {string} type Type of video: local or remote * @param {HTMLVideoElement} videoElement Video element */ setVideo(type, videoElement) { ValueChecker.check({ type, videoElement }, { "type": { "typeof": 'string', "inside": ['local', 'remote'], }, "videoElement": { "required": true, "typeof": "object", "instanceof": HTMLVideoElement } }); this._config[type + 'Video'] = videoElement; } /** * DOM element which contains local video * * @readonly * @type {Element} */ get localVideoContainer() { return this._config.localVideoContainer; } /** * Local video DOM element * * @readonly * @type {Element} */ get localVideo() { return this._config.localVideo; } /** * DOM element which contains remote video * * @readonly * @type {Element} */ get remoteVideoContainer() { return this._config.remoteVideoContainer; } /** * Remote video DOM element * * @readonly * @type {Element} */ get remoteVideo() { return this._config.remoteVideo; } /** * It clones video according to the given type and returns new DOM element * * @param type * @returns {Node} */ cloneVideo(type) { ValueChecker.check({ type }, { "type": { "typeof": 'string', "inside": ['local', 'remote'], } }); const baseElement = type === 'local' ? this.localVideo : this.remoteVideo; const clonedElement = baseElement.cloneNode(true); return clonedElement; } }
JavaScript
class DocumentScroll { /** * @param callback * @param ratio Use a ratio (0 = top, 1 = bottom) instead of an absolute value in pixels */ constructor(callback = null, useRatio = false) { this.m_callback = callback; this.m_useRatio = useRatio; this.m_scroll = 0; window.addEventListener('scroll', e => this.scrollEvent(e), false); window.addEventListener('resize', e => this.scrollEvent(e), false); this.scrollEvent(); } /** * Returns scroll in pixels * * @public * @returns {number} scroll */ getScroll() { return this.m_scroll; } /** * Called on scroll or window resize * * @private * @param e */ scrollEvent(e = null) { if (this.m_useRatio) { let scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; if (scroll === 0) this.m_scroll = 0; else this.m_scroll = scroll / (document.body.clientHeight - window.innerHeight); } else { this.m_scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; } if (this.m_callback !== null) this.m_callback(this.m_scroll); } }
JavaScript
class LoginForm extends Component { render() { return ( <div> <Message attached header='Welcome to our site!' content='Fill out the form below to login to your account' /> <Form className='attached fluid segment'> <Form.Input label='Username' placeholder='Username' type='text' /> <Form.Input label='Password' type='password' /> <Button color='blue'>Login</Button> </Form> <Message attached='bottom' warning> <Icon name='help' /> Don't registered yet?&nbsp;<a href='#'>Sign-Up here</a>&nbsp;instead. </Message> </div> ) } }
JavaScript
class Cart { /** * @private */ items = []; /** * @private */ listeners = []; /** * Add an item to the cart. * * @param {number} itemId The ID of the item * @param {number} amount The amount of items to be purchased * @returns {number} The cart item ID */ addItem(itemId, amount) { const id = this.items.reduce((acc, cartItem) => (cartItem.id > acc ? cartItem.id : acc), 0) + 1; this.items.push({ id: id, itemId: itemId, amount: amount }); this.notify(); return id; } /** * Remove an item from the cart. * * @param {number} id The ID of the cart item to be removed */ removeItem(id) { const cartItemIndex = this.items.indexOf((cartItem) => cartItem.id === id); this.items.splice(cartItemIndex, 1); this.notify(); } /** * Get the current Cart of the user. * * @returns {Array<{id: number, itemId: number, amount: number}>} The items array in the cart. */ getItems() { return [...this.items]; } /** * Checkout the cart and place an order. * * @returns {Promise} Promise for resolve/reject upon checkout */ checkout() { const self = this; const config = { url: "/orders", method: "POST", data: { order: self.items.map((cartItem) => ({ id: cartItem.itemId, amount: cartItem.amount })) } }; return new Promise((resolve, reject) => { utils.callApi(config) .then((data) => { self.items = []; self.notify(); resolve(data); }) .catch((error) => { reject(error); }); }); } /** * Add a new cart listener. * * @param {Function} callback The callback to be called upon cart changes */ addListener(callback) { for (let i = 0; i < this.listeners.length; i++) { if (this.listeners[i] === callback) { throw Error("Listener is already registered"); } } this.listeners.push(callback); } /** * Remove a cart listener. * * @param {Function} callback The callback to be removed from the listeners list */ removeListener(callback) { const removeIndex = this.listeners.indexOf(callback); if (removeIndex >= 0) { this.listeners.splice(removeIndex, 1); } else { throw Error("Listener to be removed is not registered"); } } /** * Notify the registered callbacks. */ notify() { for (let i = 0; i < this.listeners.length; i++) { this.listeners[i](this.getItems()); } } }
JavaScript
class DeleteGroup { /** * Constructor * * @param {string} groupId Group Id or Group object */ constructor(groupId) { this.groupId = String(groupId); } /** * Invoke command * * @param {Client} client Client * * @return {Promise} Promise for chaining */ invoke(client) { let options = { method: 'DELETE', url: `api/${client.username}/groups/${this.groupId}` }; return client.getTransport() .sendRequest(options) .then(() => true); } }
JavaScript
class CreateDialog extends React.Component { constructor(props) { super(props); this.state = { /** In case the input name is invalid, a meaningful error message is placed here */ error: null, filename: '', }; this.input = React.createRef(); } render() { const { directoryMode, configurationType } = this.props; const dialogMessage = directoryMode ? 'Folder' : configurationType.name + ' File'; return ( <Dialog focusOnShow={false} style={{ width: '400px' }} header={'Create ' + dialogMessage} modal={true} visible={this.props.visible} onHide={this.props.onHide} onShow={() => this.filenameChanged('')} footer={ <div> <Button label="Create" disabled={!this.canCreateFileOrFolder()} onClick={this.createFileOrFolder} /> <Button label="Cancel" className="p-button-secondary" onClick={this.props.onHide} /> </div> } > <div style={{ width: '100%', paddingBottom: '0.5em' }}> Create a {dialogMessage.toLowerCase()} in <b>{this.state.parentDirectoryName}</b>: </div> <div className="p-inputgroup" style={{ width: '100%' }}> <InputText ref={this.input} style={{ width: '100%' }} onKeyPress={this.onKeyPress} value={this.state.filename} placeholder={dialogMessage + ' Name'} onChange={(e) => this.filenameChanged(e.target.value)} /> {!this.props.directoryMode && <span className="p-inputgroup-addon">.yml</span>} </div> {this.state.error && ( <div style={{ width: '100%', paddingTop: '0.5em' }}> <Message style={{ width: '100%' }} severity="error" text={this.state.error}></Message> </div> )} </Dialog> ); } componentDidUpdate(prevProps) { if (!prevProps.visible && this.props.visible) { /**Timeout is needed for .focus() to be triggered correctly. */ setTimeout(() => { this.input.current.element.focus(); }, 0); const { filePath } = this.props; const fileObj = configurationUtils.getFile(this.props.files, filePath); const isDirectory = configurationUtils.isDirectory(fileObj); let parentDirectoryName = 'root'; if (filePath && isDirectory) { parentDirectoryName = '"' + filePath.split('/').slice(-1)[0] + '"'; } else if (filePath) { let parent = filePath.split('/').slice(-2)[0]; parentDirectoryName = parent ? '"' + parent + '"' : 'root'; } this.setState({ isDirectory, parentDirectoryName, }); } } onKeyPress = (e) => { if (e.key === 'Enter' && this.canCreateFileOrFolder()) { this.createFileOrFolder(); } }; filenameChanged = (name) => { let error = null; const existingFile = configurationUtils.getFile(this.props.files, this.getAbsolutePath(name)); if (existingFile) { if (configurationUtils.isDirectory(existingFile)) { error = 'A directory with the given name already exists'; } else { error = 'A file with the given name already exists'; } } this.setState({ filename: name, error: error, }); }; canCreateFileOrFolder = () => { return !this.state.error && !!this.state.filename; }; createFileOrFolder = () => { const { configurationType, createDirectory, directoryMode, writeFile, onHide } = this.props; const fullPath = this.getAbsolutePath(this.state.filename); if (directoryMode) { createDirectory(fullPath, true, true); } else { let content = ''; if (configurationType !== CONFIGURATION_TYPES.YAML) { const fileHeader = '# {"type": "' + configurationType.name + '"}\n'; const fileContent = yaml.dump(configurationType.template); content = fileHeader + fileContent; } writeFile(fullPath, content, true, true); } onHide(); }; /** * Returns the absolute path of the current filename relative to the selection */ getAbsolutePath = (filename) => { const { directoryMode, filePath } = this.props; const { isDirectory } = this.state; const suffix = directoryMode ? '' : '.yml'; if (!filePath) { return '/' + filename + suffix; } else if (isDirectory) { return filePath + '/' + filename + suffix; } else { const lastSlash = filePath.lastIndexOf('/'); return filePath.substring(0, lastSlash + 1) + filename + suffix; } }; }
JavaScript
class Cache { static get DIRECTORY () { return '.cache' } static get CACHE_TTL () { return 60 * 60 * 1000 // 1 hour in milliseconds } static getFile (link) { let cacheFile = '' let parsedURL = url.parse(link) if (parsedURL.hostname) { cacheFile += Cache.friendlyFile(parsedURL.hostname) } if (parsedURL.pathname) { cacheFile += Cache.friendlyFile(parsedURL.pathname) } return cacheFile.trim('_') } static read (cacheFilepath) { let abspath = path.join(Cache.DIRECTORY, cacheFilepath) if (!file.existsSync(abspath)) { throw new Error(`No cache to read`) } let currentTime = new Date().getTime() if (currentTime - file.statSync(abspath).mtime.getTime() > this.CACHE_TTL) { throw new Error(`Cache has expired`) } let content = file.readFileSync(abspath) if (content.length === 0) { throw new Error(`Empty file`) } return content } static write (cacheFilepath, content) { if (cacheFilepath.length === 0) { throw new Error(`Missing cache path`) } if (content.length === 0) { throw new Error(`Missing cache data`) } if (!file.existsSync(Cache.DIRECTORY)) { file.mkdirSync(Cache.DIRECTORY) } else if (!file.lstatSync(Cache.DIRECTORY).isDirectory()) { throw new Error(`Cannot create cache directory because a file with the same name already exists`) } let abspath = path.join(Cache.DIRECTORY, cacheFilepath) file.writeFileSync(abspath, content) } static readLink (link) { return Cache.read(Cache.getFile(link)) } static writeLink (link, data) { Cache.write(Cache.getFile(link), data) } static friendlyFile (filepath) { return filepath.replace(/[\W]/g, '_') } }
JavaScript
class ChatPage extends React.Component { render() { const {active, messages, userName} = this.props; const {onArrivalMessage} = this.props; return ( <Page name="chat" active={active}> <Messages messages={messages}/> <Socket autoStart={true} onMessage={onArrivalMessage} ref={socket => this.socket = socket}> <Form userName={userName}/> </Socket> </Page> ) } }
JavaScript
class FindAndReplace extends Plugin { /** * @inheritDoc */ static get requires() { return [ FindAndReplaceEditing, FindAndReplaceUI ]; } /** * @inheritDoc */ static get pluginName() { return 'FindAndReplace'; } init() { const ui = this.editor.plugins.get( 'FindAndReplaceUI' ); const findAndReplaceEditing = this.editor.plugins.get( 'FindAndReplaceEditing' ); /** * Delegate find next request. */ ui.on( 'findNext', ( event, data ) => { // Data is contained only for the "find" button. if ( data ) { findAndReplaceEditing.state.searchText = data.searchText; this.editor.execute( 'find', data.searchText, data ); } else { // Arrow button press. this.editor.execute( 'findNext' ); } } ); /** * Delegate find previous request */ ui.on( 'findPrevious', ( event, data ) => { if ( data && findAndReplaceEditing.state.searchText !== data.searchText ) { this.editor.execute( 'find', data.searchText ); } else { // Subsequent calls. this.editor.execute( 'findPrevious' ); } } ); /** * Delegate replace action. */ ui.on( 'replace', ( event, data ) => { if ( findAndReplaceEditing.state.searchText !== data.searchText ) { this.editor.execute( 'find', data.searchText ); } const highlightedResult = findAndReplaceEditing.state.highlightedResult; if ( highlightedResult ) { this.editor.execute( 'replace', data.replaceText, highlightedResult ); } } ); /** * Delegate replace all action. */ ui.on( 'replaceAll', ( event, data ) => { // The state hadn't been yet built for this search text. if ( findAndReplaceEditing.state.searchText !== data.searchText ) { this.editor.execute( 'find', data.searchText ); } this.editor.execute( 'replaceAll', data.replaceText, findAndReplaceEditing.state.results ); } ); ui.on( 'dropdown:closed', () => { findAndReplaceEditing.state.clear( this.editor.model ); findAndReplaceEditing.stop(); } ); if ( this.editor.ui ) { // We need to wait for the UI to be ready to have the toolbar dropdown available. // Otherwise the findAndReplace component is registered but not yet constructed. this.listenTo( this.editor.ui, 'ready', () => { const formView = ui.formView; // If the editor doesn't contain the findAndReplace button then there's no ui#formView property. if ( formView ) { const commands = this.editor.commands; formView.findNextButtonView.bind( 'isEnabled' ).to( commands.get( 'findNext' ), 'isEnabled' ); formView.findPrevButtonView.bind( 'isEnabled' ).to( commands.get( 'findPrevious' ), 'isEnabled' ); formView.replaceButtonView.unbind( 'isEnabled' ); formView.replaceButtonView.bind( 'isEnabled' ).to( commands.get( 'replace' ), 'isEnabled', formView, 'isSearching', ( commandEnabled, isSearching ) => { return commandEnabled && isSearching; } ); formView.replaceAllButtonView.unbind( 'isEnabled' ); formView.replaceAllButtonView.bind( 'isEnabled' ).to( commands.get( 'replaceAll' ), 'isEnabled', formView, 'isSearching', ( commandEnabled, isSearching ) => { return commandEnabled && isSearching; } ); } } ); } ui._setState( findAndReplaceEditing.state ); } }
JavaScript
class ArrayObservable extends Observable_1.Observable { /** * @param {?} array * @param {?=} scheduler */ constructor(array, scheduler) { super(); this.array = array; this.scheduler = scheduler; if (!scheduler && array.length === 1) { this._isScalar = true; this.value = array[0]; } } /** * @param {?} array * @param {?=} scheduler * @return {?} */ static create(array, scheduler) { return new ArrayObservable(array, scheduler); } /** * Creates an Observable that emits some values you specify as arguments, immediately one after the other, and then emits a complete notification. * <span class="informal">Emits the arguments you provide, then completes. </span> * <img src="./img/of.png" width="100%"> * This static operator is useful for creating a simple Observable that only emits the arguments given, and the complete notification thereafter. It can be used for composing with other Observables, such as with {@link concat}. By default, it uses a `null` Scheduler, which means the `next` notifications are sent synchronously, although with a different Scheduler it is possible to determine when those notifications will be delivered. * * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption> var numbers = Rx.Observable.of(10, 20, 30); var letters = Rx.Observable.of('a', 'b', 'c'); var interval = Rx.Observable.interval(1000); var result = numbers.concat(letters).concat(interval); result.subscribe(x => console.log(x)); * * @see {@link create} * @see {@link empty} * @see {@link never} * @see {@link throw} * the emissions of the `next` notifications. * @static true * @name of * @owner Observable * @param {...?} array * @return {?} */ static of(...array) { let /** @type {?} */ scheduler = (array[array.length - 1]); if (isScheduler_1.isScheduler(scheduler)) { array.pop(); } else { scheduler = null; } const /** @type {?} */ len = array.length; if (len > 1) { return new ArrayObservable(/** @type {?} */ (array), scheduler); } else if (len === 1) { return new ScalarObservable_1.ScalarObservable(/** @type {?} */ (array[0]), scheduler); } else { return new EmptyObservable_1.EmptyObservable(scheduler); } } /** * @param {?} state * @return {?} */ static dispatch(state) { const { array, index, count, subscriber } = state; if (index >= count) { subscriber.complete(); return; } subscriber.next(array[index]); if (subscriber.isUnsubscribed) { return; } state.index = index + 1; ((this)).schedule(state); } /** * @param {?} subscriber * @return {?} */ _subscribe(subscriber) { let /** @type {?} */ index = 0; const /** @type {?} */ array = this.array; const /** @type {?} */ count = array.length; const /** @type {?} */ scheduler = this.scheduler; if (scheduler) { return scheduler.schedule(ArrayObservable.dispatch, 0, { array, index, count, subscriber }); } else { for (let /** @type {?} */ i = 0; i < count && !subscriber.isUnsubscribed; i++) { subscriber.next(array[i]); } subscriber.complete(); } } static _tsickle_typeAnnotationsHelper() { /** @type {?} */ ArrayObservable.prototype.value; /** @type {?} */ ArrayObservable.prototype.array; /** @type {?} */ ArrayObservable.prototype.scheduler; } }
JavaScript
class Article extends Controller { static get targets() { return ["main"]; } connect() { loadDisqus(this.mainTarget, document.URL, true); } }
JavaScript
class NumberOutput extends Output { /** * displayed text, description, default=0 */ constructor(display, description, def="0") { super({ text: def, displayText: display, description, type: "number" }); } }
JavaScript
class Path { constructor(path) { // If the string contains favico.ico // replace it with an empty string this.path = path.replace('favicon.ico', ''); } /** * Determines if the string contains a locale * @param {String} str The string to determine * @return {Boolean} Returns true if the string contains a locale. */ isLocale(str) { str = str.toLowerCase().replace('-', '_'); // Compare the locales against cldr return _.contains(cldr.localeIds, str); } /** * Converts the path into an array. * @param {String} path The path to convert * @return {Array} The array that represents the path. */ toArray(path) { path = path ? path.split('/') : this.path.split('/'); var filtered = [], result = []; var version = /\d{1,2}(\.)\d{1,2}((\.)\d{1,2})?$/; if (path.length < 3) { // It's safe to say that path[0] will always be '' // so add the second '' and define it as the index if (path[1] === '') { result.push('index'); } else { // Make sure the path does not contain a locale // and maybe something does exist besides ''? (precaution) if (!this.isLocale(path[1])) result.push(path[1]); } } else { // For every item in the path // check to see if it contains a version or // if it's a regular name, then add it to the // filtered array _.forEach(path, function(item) { //Make sure the path does not contain a locale if (!this.isLocale(item)) if (item.match(version)) { // Prevent the version dots from being // interpreted as a dot notation filtered.push(item.replace('.', '*')); } else { filtered.push(item); } }, this); path = filtered; // Once we have filtered for (var count = 1; count < path.length; count++) { // Make sure the path does not contain a locale if (!this.isLocale(path[count])) if (count === 1) { if (path[count] === '') result.push('index'); else result.push(path[count]); } else { // Make sure nothing else is empty if (path[count] !== '') result.push(path[count]); } } } return result; } /** * Converts an array to a dotted path * @param {Array} array The array that contains the path * @return {String} The dotted path */ toDot(array) { array = array ? array : this.toArray(); if (array.length > 1) return array.join().replace(/,/g, '.'); else return array[0]; } }
JavaScript
class LogController extends Controller { constructor($interface, $logView, $editLogView) { super($interface); this.logView = new LogView($logView); this.editLogView = new EditLogView($editLogView); this.context = { currentView: -1, logEnabled: true }; //callback this.logViewContext = new Object(); this.editLogViewContext = new Object(); //calback interfaccia this.interfaceContext = new Object(); } init() { this.initCleanLogView(); this.initLogView(); this.viewLogView(); //views this.logViewContext["logController"] = this; this.logViewContext["onClick"] = this.logView_onClick; this.logView.$this.on("LogView_onClick", $.proxy(this.logViewContext.onClick, this.logViewContext)); this.editLogViewContext["logController"] = this; this.editLogViewContext["onClear"] = this.editLogView_onClear; this.editLogViewContext["onToggle"] = this.editLogView_onToggle; this.editLogView.$this.on("EditLogView_onClear", $.proxy(this.editLogViewContext.onClear, this.editLogViewContext)); this.editLogView.$this.on("EditLogView_onToggle", $.proxy(this.editLogViewContext.onToggle, this.editLogViewContext)); //Interfaccia this.interfaceContext["logController"] = this; this.interfaceContext["onLog"] = this.interface_onLog; this.on("Interface_onLog", $.proxy(this.interfaceContext.onLog, this.interfaceContext)); } logView_onClick(e, $this, index) { $this.hide(); $this.remove(); //this.logController.logView.list.splice(index, 1); } editLogView_onToggle(e, $button) { this.logController.context.logEnabled = $button.prop("checked"); } editLogView_onClear(e, $button) { //Ri-inizializzo il log cancellando tutto all' interno. this.logController.initLogView(); } interface_onLog(e, title, message, level) { if (this.logController.context.logEnabled) { this.logController.logView.log(title, message, level); } } toggleView(index) { switch (index) { case - 1: case 0: this.context.currentView = index; break; default: } switch (index) { case -1: { this.logView.hide(); break; } case 0: { this.logView.show(); break; } } } hideAll() { this.toggleView(-1); } initLogView() { this.logView.updateView(); } viewLogView() { this.toggleView(0); } initCleanLogView() { this.editLogView.updateView(); } }
JavaScript
class ContinousActions { constructor() { this.currentAction = null; } setCurrentAction(action) { this.currentAction = action; } clearCurrentAction() { this.currentAction = null; } isMoving() { return this.currentAction !== null && this.currentAction.type === Constants.ACTIONS.MOVE; } isEating() { return this.currentAction !== null && this.currentAction.type === Constants.ACTIONS.EAT; } }
JavaScript
class Juno60VoiceImplementation extends BaseVoiceImplementation { /** * Create a new instance of a Juno60-like voice. * @param {number} sampleRate - Samples-per-second for the current audio context. * @param {number} voiceIndex - Index of the voice. * @param {Object} patch - Object containing the instrument's initial patch. */ constructor(sampleRate, voiceIndex, patch) { this._dco=new Juno60Dco(sampleRate) this._noise=new Noise(sampleRate) this._lpf=new DiodeLadderFilter(sampleRate) this._modEnvelope=new Juno60Envelope(sampleRate) this._vcaEnvelope=new Juno60Envelope(sampleRate) super(sampleRate, voiceIndex, patch, [ this._vcaEnvelope, this._modEnvelope ]) } /** * Apply processing for a single tick of the audio clock. * @param {number} lfoValue - Current value of the LFO (-1.0 to +1.0). * @param {number} pitchBendValue - Current value of the pitch-bend. * @returns {number} - Output. */ process(lfoValue, pitchBendValue) { const vcaEnvValue=this._vcaEnvelope.process() if(!this._vcaEnvelope.isActive()) { return 0.0 } const filterEnvValue=this._modEnvelope.process() let output=this.dco.process(lfoValue, filterEnvValue, pitchBendValue) output+=this._noise.process() // TODO - add filter return output*vcaEnvValue } /** * Apply an update of the patch settings. * @override * @param {Object} patch - Object containing the instrument's new patch. * @param {string} patch.name - Name of the patch. * @param {number} patch.vca - Amplitude (between 0.0 and +1.0) of the voice. * @param {string} patch.vcaType - Envelope mode for the VCA ("gate" or "env") * @param {number} patch.dco.subAmount - Amount (between 0.0 and +1.0) of sub-oscilator audible within the voice. * @param {Object} patch.dco * @param {boolean} patch.dco.saw - True if the sawtooth-oscillator is audible. * @param {boolean} patch.dco.pulse - True if the pulse-oscillator is audible. * @param {boolean} patch.dco.sub - True if the sub-oscillator is audible. * @param {number} patch.dco.subAmount - Amount (between 0.0 and +1.0) of sub-oscilator audible within the voice. * @param {number} patch.dco.noise - Amount (between 0.0 and +1.0) of noise audible within the voice. * @param {number} patch.dco.pwm - Width (between 0.0 and +1.0) of the pulse-width. * @param {string} patch.dco.pwmMod - Type of modulation for the pulse-width ("l"=LFO, "e"=Envelope, "m"=Manual). * @param {number} patch.dco.lfo - Amount (between 0.0 and +1.0) that the LFO modulation the pitch of the voice. * @param {Object} patch.env * @param {number} patch.env.attack - Amount between 0.0 (fast-attack) and +1.0 (slow-attack) for the envelope. * @param {number} patch.env.decay - Amount between 0.0 (fast-decay) and +1.0 (slow-decay) for the envelope. * @param {number} patch.env.sustain - Amount (between 0.0 and +1.0) for the sustain-level of the envelope. * @param {number} patch.env.release - Amount between 0.0 (fast-release) and +1.0 (slow-release) for the envelope. */ update(patch) { super.update(patch) let changeDuration=this.vcaEnvelope.isActive()? 128.0/this.sampleRate:0.0 this.dco.note.linearRampToValueAtTime(this.noteNumber, changeDuration) const dco=patch.dco this.dco.pitchBendModDepth.linearRampToValueAtTime(0, changeDuration) // TODO - patches don't include this. this.dco.pitchLfoModDepth.linearRampToValueAtTime(dco.lfo, changeDuration) this.dco.pitchTranspose.linearRampToValueAtTime(0, changeDuration) // TODO - dco.range this.dco.pwmSource=dco.pwmMod this.dco.pwmWidth=dco.pwm*0.49 // Relative volumes of each source. let sawLevel=dco.saw? 0.2:0.0 let pulseLevel=dco.pulse? 0.2:0.0 let subLevel=dco.sub? dco.subAmount*0.195:0.0 let noiseLevel=dco.noise*0.21 // If multiple sources at same time then volume is reduced (max is 0.5). let mixFactor=sawLevel+pulseLevel+subLevel+noiseLevel if(mixFactor>0.3) { mixFactor=2.0-(mixFactor-0.3)*1.5 } else { mixFactor=2.0 } this.dco.sawLevel.linearRampToValueAtTime(sawLevel*mixFactor, changeDuration) this.dco.pulseLevel.linearRampToValueAtTime(pulseLevel*mixFactor, changeDuration) this.dco.subLevel.linearRampToValueAtTime(subLevel*mixFactor, changeDuration) this.noise.level.linearRampToValueAtTime(noiseLevel*mixFactor, changeDuration) const patchEnv=patch.env let attackDuration=0.001+(Math.exp(patchEnv.attack*5.0)-1)/(Math.exp(5.0)-1)*3.25 let decayDuration=0.002+(Math.exp(patchEnv.decay*4.0)-1)/(Math.exp(4.0)-1)*patchEnv.decay*19.78 let sustainLevel=patchEnv.sustain let releaseDuration=0.002+(Math.exp(patchEnv.release*4.0)-1)/(Math.exp(4.0)-1)*patchEnv.release*19.78 if(patch.vcaType==="gate") { this._vcaEnvelope.setValues(0.003, 1.0, 1.0, 0.006) if(this._vcaEnvelope.isActive()&&!this._vcaEnvelope.isReleased()) { this._vcaEnvelope.doTrigger() } } else { this._vcaEnvelope.setValues(attackDuration, decayDuration, sustainLevel, releaseDuration) } this._modEnvelope.setValues(attackDuration, decayDuration, sustainLevel, releaseDuration) } }
JavaScript
class WebProletarian { /** * Creates new WebProletarian, checking if worker provided is a function * and preparing WebWorker to communicating with the user. * @param {function} worker Function to exec into the WebWorker */ constructor(worker) { if (!Worker) throw new Error("WebProletarian Error: Current browser version does not support WebWorkers :("); if ({}.toString.call(worker) !== '[object Function]') throw new Error("WebProletarian Error: Worker function provided is not a function."); let raw = this.injectProletarian(worker); let blob = new Blob([ raw ], { type: "text/javascript" }); let url = window.URL.createObjectURL(blob); this.listeners = {} this.worker = new Worker(url); this.worker.addEventListener('message', e => this.handler(e)); } /** * Injects required code from Proletarian class into document body. * @private * @param {string} raw The user code */ injectProletarian(raw) { return [ `${ Proletarian };`, 'const proletarian = new Proletarian();', `(${ raw })();` ].join("\n\n"); } /** * Checks if current Proletarian has associated event listener to the incoming * event and exec it with data received as argument. * @private * @param {Object} e Contains event handler alias and data from workerk. */ handler(e) { let event = e.data.event; let data = e.data.data; if (Object.prototype.hasOwnProperty.call(this.listeners, event)) this.listeners[event](data); } /** * Register new event listener for current WebProletarian * @param {string} event Event handler alias * @param {function} func Event listener function */ read(event, func) { this.listeners[event] = func; } /** * Fire event to worker * @param {string} event Event handler alias to emit * @param {Object} data Data to emit */ fire(event, data) { this.worker.postMessage({ event, data }); } /** * Stop WebWorker associated to current WebProletarian */ stop() { this.worker.postMessage("terminate"); } }
JavaScript
class UserAlreadyLinkedException extends DeepFramework.Core.Exception.Exception { /** * @param accountId * @param userId */ constructor(accountId, userId) { super(`User: ${userId} already linked with account: ${accountId}`); } }
JavaScript
class AuthorizationError extends BaseError { /** * Creates a new AuthorizationError. * * @param {string} message - The error message. * @param {Error} inner - An optional error that caused the AuthenticationError. */ constructor(message, inner) { super(message, inner); this.name = 'AuthorizationError'; this.status = 403; this.statusCode = 403; } }
JavaScript
class GlobalNotificationService { constructor(crowi) { this.crowi = crowi; this.config = crowi.getConfig(); this.mailer = crowi.getMailer(); this.GlobalNotification = crowi.model('GlobalNotificationSetting'); this.User = crowi.model('User'); this.Config = crowi.model('Config'); this.appTitle = this.Config.appTitle(this.config); } notifyByMail(notification, mailOption) { this.mailer.send(Object.assign(mailOption, {to: notification.toEmail})); } notifyBySlack(notification, slackOption) { // send slack notification here } sendNotification(notifications, option) { notifications.forEach(notification => { if (notification.__t === 'mail') { this.notifyByMail(notification, option.mail); } else if (notification.__t === 'slack') { this.notifyBySlack(notification, option.slack); } }); } /** * send notification at page creation * @memberof GlobalNotification * @param {obejct} page */ async notifyPageCreate(page) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(page.path, 'pageCreate'); const lang = 'en-US'; //FIXME const option = { mail: { subject: `#pageCreate - ${page.creator.username} created ${page.path}`, template: `../../locales/${lang}/notifications/pageCreate.txt`, vars: { appTitle: this.appTitle, path: page.path, username: page.creator.username, } }, slack: {}, }; this.sendNotification(notifications, option); } /** * send notification at page edit * @memberof GlobalNotification * @param {obejct} page */ async notifyPageEdit(page) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(page.path, 'pageEdit'); const lang = 'en-US'; //FIXME const option = { mail: { subject: `#pageEdit - ${page.creator.username} edited ${page.path}`, template: `../../locales/${lang}/notifications/pageEdit.txt`, vars: { appTitle: this.appTitle, path: page.path, username: page.creator.username, } }, slack: {}, }; this.sendNotification(notifications, option); } /** * send notification at page deletion * @memberof GlobalNotification * @param {obejct} page */ async notifyPageDelete(page) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(page.path, 'pageDelete'); const lang = 'en-US'; //FIXME const option = { mail: { subject: `#pageDelete - ${page.creator.username} deleted ${page.path}`, //FIXME template: `../../locales/${lang}/notifications/pageDelete.txt`, vars: { appTitle: this.appTitle, path: page.path, username: page.creator.username, } }, slack: {}, }; this.sendNotification(notifications, option); } /** * send notification at page move * @memberof GlobalNotification * @param {obejct} page */ async notifyPageMove(page, oldPagePath, user) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(page.path, 'pageMove'); const lang = 'en-US'; //FIXME const option = { mail: { subject: `#pageMove - ${user.username} moved ${page.path} to ${page.path}`, //FIXME template: `../../locales/${lang}/notifications/pageMove.txt`, vars: { appTitle: this.appTitle, oldPath: oldPagePath, newPath: page.path, username: user.username, } }, slack: {}, }; this.sendNotification(notifications, option); } /** * send notification at page like * @memberof GlobalNotification * @param {obejct} page */ async notifyPageLike(page, user) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(page.path, 'pageLike'); const lang = 'en-US'; //FIXME const option = { mail: { subject: `#pageLike - ${user.username} liked ${page.path}`, template: `../../locales/${lang}/notifications/pageLike.txt`, vars: { appTitle: this.appTitle, path: page.path, username: page.creator.username, } }, slack: {}, }; this.sendNotification(notifications, option); } /** * send notification at page comment * @memberof GlobalNotification * @param {obejct} page * @param {obejct} comment */ async notifyComment(comment, path) { const notifications = await this.GlobalNotification.findSettingByPathAndEvent(path, 'comment'); const lang = 'en-US'; //FIXME const user = await this.User.findOne({_id: comment.creator}); const option = { mail: { subject: `#comment - ${user.username} commented on ${path}`, template: `../../locales/${lang}/notifications/comment.txt`, vars: { appTitle: this.appTitle, path: path, username: user.username, comment: comment.comment, } }, slack: {}, }; this.sendNotification(notifications, option); } }
JavaScript
class LifecycleBucketProcessor { /** * Constructor of LifecycleBucketProcessor * * @constructor * @param {Object} zkConfig - zookeeper config * @param {Object} kafkaConfig - kafka configuration object * @param {string} kafkaConfig.hosts - list of kafka brokers * as "host:port[,host:port...]" * @param {Object} [kafkaConfig.backlogMetrics] - param object to * publish kafka topic metrics to zookeeper (see {@link * BackbeatConsumer} constructor) * @param {Object} lcConfig - lifecycle config * @param {Object} lcConfig.lifecycle.auth - authentication info * @param {String} lcConfig.lifecycle.bucketTasksTopic - lifecycle bucket * topic name * @param {Object} lcConfig.lifecycle.bucketProcessor - kafka consumer * object * @param {String} lcConfig.lifecycle.bucketProcessor.groupId - kafka * consumer group id * @param {Object} repConfig - replication config * @param {String} repConfig.topic - kafka replication topic * @param {Object} repConfig.source - replication source * @param {Number} [lcConfig.bucketProcessor.concurrency] - number * of max allowed concurrent operations * @param {Object} s3Config - s3 config * @param {String} s3Config.host - host ip * @param {String} s3Config.port - port * @param {String} transport - http or https */ constructor(zkConfig, kafkaConfig, lcConfig, repConfig, s3Config, transport = 'http') { this._log = new Logger('Backbeat:Lifecycle:BucketProcessor'); this._zkConfig = zkConfig; this._kafkaConfig = kafkaConfig; this._lcConfig = lcConfig; this._repConfig = repConfig; this._s3Endpoint = `${transport}://${s3Config.host}:${s3Config.port}`; this._s3Config = s3Config; this._transport = transport; this._producer = null; this._kafkaBacklogMetrics = null; this._producerReady = false; this._consumerReady = false; if (transport === 'https') { this.s3Agent = new https.Agent({ keepAlive: true }); this.stsAgent = new https.Agent({ keepAlive: true }); } else { this.s3Agent = new http.Agent({ keepAlive: true }); this.stsAgent = new http.Agent({ keepAlive: true }); } this._stsConfig = null; this.s3Clients = {}; this.backbeatClients = {}; this.credentialsManager = new CredentialsManager('lifecycle', this._log); this.retryWrapper = new BackbeatTask(); // The task scheduler for processing lifecycle tasks concurrently. this._internalTaskScheduler = async.queue((ctx, cb) => { const { task, rules, value, s3target, backbeatMetadataProxy } = ctx; return this.retryWrapper.retry({ actionDesc: 'process bucket lifecycle entry', logFields: { value }, actionFunc: done => task.processBucketEntry( rules, value, s3target, backbeatMetadataProxy, done), shouldRetryFunc: err => err.retryable, log: this._log, }, cb); }, this._lcConfig.bucketProcessor.concurrency); // Listen for errors from any task being processed. this._internalTaskScheduler.drain(err => { if (err) { this._log.error('error occurred during task processing', { error: err, }); } }); } /** * Get the state variables of the current instance. * @return {Object} Object containing the state variables */ getStateVars() { return { producer: this._producer, bootstrapList: this._repConfig.destination.bootstrapList, enabledRules: this._lcConfig.rules, s3Endpoint: this._s3Endpoint, s3Auth: this._lcConfig.auth, bucketTasksTopic: this._lcConfig.bucketTasksTopic, objectTasksTopic: this._lcConfig.objectTasksTopic, kafkaBacklogMetrics: this._kafkaBacklogMetrics, log: this._log, }; } /** * Return an S3 client instance * @param {String} canonicalId - The canonical ID of the bucket owner. * @param {String} accountId - The account ID of the bucket owner . * @return {AWS.S3} The S3 client instance to make requests with */ _getS3Client(canonicalId, accountId) { const credentials = this.credentialsManager.getCredentials({ id: canonicalId, accountId, stsConfig: this._stsConfig, authConfig: this._lcConfig.auth, }); if (credentials === null) { return null; } const clientId = canonicalId; const client = this.s3Clients[clientId]; if (client) { return client; } this.s3Clients[clientId] = createS3Client({ transport: this._transport, port: this._s3Config.port, host: this._s3Config.host, credentials, agent: this.s3Agent, }); return this.s3Clients[clientId]; } /** * Return an backbeat client instance * @param {String} canonicalId - The canonical ID of the bucket owner. * @param {String} accountId - The account ID of the bucket owner . * @return {BackbeatClient} The S3 client instance to make requests with */ _getBackbeatClient(canonicalId, accountId) { const credentials = this.credentialsManager.getCredentials({ id: canonicalId, accountId, stsConfig: this._stsConfig, authConfig: this._lcConfig.auth, }); if (credentials === null) { return null; } const clientId = canonicalId; const client = this.backbeatClients[clientId]; if (client) { return new BackbeatMetadataProxy( `${this._transport}://${this._s3Config.host}:${this._s3Config.port}`, this._lcConfig.auth) .setBackbeatClient(client); } this.backbeatClients[clientId] = createBackbeatClient({ transport: this._transport, port: this._s3Config.port, host: this._s3Config.host, credentials, agent: this.s3Agent, }); return new BackbeatMetadataProxy( `${this._transport}://${this._s3Config.host}:${this._s3Config.port}`, this._lcConfig.auth) .setBackbeatClient(this.backbeatClients[clientId]); } /** * Determine whether the given config should be processed. * @param {Object} config - The bucket lifecycle configuration * @return {Boolean} Whether the config should be processed */ _shouldProcessConfig(config) { if (config.Rules.length === 0) { this._log.debug('bucket lifecycle config has no rules to process', { config, }); return false; } const { rules } = this._lcConfig; // Check if backbeat config has a lifecycle rule enabled for processing. const enabled = Object.keys(rules).some(rule => rules[rule].enabled); if (!enabled) { this._log.debug('no lifecycle rules enabled in backbeat config'); } return enabled; } /** * Process the given bucket entry, get the bucket's lifecycle configuration, * and schedule a task with the lifecycle configuration rules, if * applicable. * @param {Object} entry - The kafka entry containing the information for * performing a listing of the bucket's objects * @param {Object} entry.value - The value of the entry object * (see format of messages in lifecycle topic for bucket tasks) * @param {Function} cb - The callback to call * @return {undefined} */ _processBucketEntry(entry, cb) { const { error, result } = safeJsonParse(entry.value); if (error) { this._log.error('could not parse bucket entry', { value: entry.value, error }); return process.nextTick(() => cb(error)); } if (result.action !== PROCESS_OBJECTS_ACTION) { return process.nextTick(cb); } if (typeof result.target !== 'object') { this._log.error('malformed kafka bucket entry', { method: 'LifecycleBucketProcessor._processBucketEntry', entry: result, }); return process.nextTick(() => cb(errors.InternalError)); } const { bucket, owner, accountId } = result.target; if (!bucket || !owner || (!accountId && this._lcConfig.auth.type === authTypeAssumeRole)) { this._log.error('kafka bucket entry missing required fields', { method: 'LifecycleBucketProcessor._processBucketEntry', bucket, owner, accountId, }); return process.nextTick(() => cb(errors.InternalError)); } this._log.debug('processing bucket entry', { method: 'LifecycleBucketProcessor._processBucketEntry', bucket, owner, accountId, }); const s3 = this._getS3Client(owner, accountId); if (!s3) { return cb(errors.InternalError .customizeDescription('failed to obtain a s3 client')); } const backbeatMetadataProxy = this._getBackbeatClient(owner, accountId); if (!backbeatMetadataProxy) { return cb(errors.InternalError .customizeDescription('failed to obtain a backbeat client')); } const params = { Bucket: bucket }; return this._getBucketLifecycleConfiguration(s3, params, (err, config) => { if (err) { if (err.code === 'NoSuchLifecycleConfiguration') { this._log.debug('skipping non-lifecycled bucket', { bucket }); return cb(); } this._log.error('error getting bucket lifecycle config', { method: 'LifecycleBucketProcessor._processBucketEntry', bucket, owner, error: err, }); return cb(err); } if (!this._shouldProcessConfig(config)) { return cb(); } this._log.info('scheduling new task for bucket lifecycle', { method: 'LifecycleBucketProcessor._processBucketEntry', bucket, owner, details: result.details, }); return this._internalTaskScheduler.push({ task: new LifecycleTask(this), rules: config.Rules, value: result, s3target: s3, backbeatMetadataProxy, }, cb); }); } /** * Call AWS.S3.GetBucketLifecycleConfiguration in a retry wrapper. * @param {AWS.S3} s3 - the s3 client * @param {object} params - the parameters to pass to getBucketLifecycleConfiguration * @param {Function} cb - The callback to call * @return {undefined} */ _getBucketLifecycleConfiguration(s3, params, cb) { return this.retryWrapper.retry({ actionDesc: 'get bucket lifecycle', logFields: { params }, actionFunc: done => s3.getBucketLifecycleConfiguration(params, done), shouldRetryFunc: err => err.retryable, log: this._log, }, cb); } /** * Set up the backbeat producer with the given topic. * @param {Function} cb - The callback to call * @return {undefined} */ _setupProducer(cb) { const producer = new BackbeatProducer({ kafka: { hosts: this._kafkaConfig.hosts }, topic: this._lcConfig.objectTasksTopic, }); producer.once('error', err => { this._log.error('error setting up kafka producer', { error: err, method: 'LifecycleBucketProcesso::_setupProducer', }); process.exit(1); }); producer.once('ready', () => { this._log.debug('producer is ready', { kafkaConfig: this.kafkaConfig }); producer.removeAllListeners('error'); producer.on('error', err => { this._log.error('error from backbeat producer', { error: err, }); }); this._producerReady = true; this._producer = producer; return cb(); }); } /** * Set up the lifecycle consumer. * @param {function} cb - callback * @return {undefined} */ _setupConsumer(cb) { this._consumer = new BackbeatConsumer({ zookeeper: { connectionString: this._zkConfig.connectionString, }, kafka: { hosts: this._kafkaConfig.hosts, backlogMetrics: this._kafkaConfig.backlogMetrics, }, topic: this._lcConfig.bucketTasksTopic, groupId: this._lcConfig.bucketProcessor.groupId, concurrency: this._lcConfig.bucketProcessor.concurrency, queueProcessor: this._processBucketEntry.bind(this), }); this._consumer.on('error', err => { if (!this._consumerReady) { this._log.fatal('unable to start lifecycle consumer', { error: err, method: 'LifecycleBucketProcessor._setupConsumer', }); process.exit(1); } }); this._consumer.on('ready', () => { this._consumerReady = true; this._consumer.subscribe(); cb(); }); } /** * Set up the producers and consumers needed for lifecycle. * @param {function} done - callback * @return {undefined} */ start(done) { this._initSTSConfig(); this._initCredentialsManager(); async.series([ done => this._setupProducer(done), done => this._initKafkaBacklogMetrics(done), done => this._setupConsumer(done), ], done); } _initKafkaBacklogMetrics(cb) { this._kafkaBacklogMetrics = new KafkaBacklogMetrics( this._zkConfig.connectionString, this._kafkaConfig.backlogMetrics); this._kafkaBacklogMetrics.init(); this._kafkaBacklogMetrics.once('ready', () => { this._kafkaBacklogMetrics.removeAllListeners('error'); cb(); }); this._kafkaBacklogMetrics.once('error', err => { this._log.error('error setting up kafka topic metrics', { error: err, method: 'LifecycleBucketProcessor._initKafkaBacklogMetrics', }); process.exit(1); }); } _initSTSConfig() { if (this._lcConfig.auth.type === authTypeAssumeRole) { const { sts } = this._lcConfig.auth; this._stsConfig = { endpoint: `${this._transport}://${sts.host}:${sts.port}`, credentials: { accessKeyId: sts.accessKey, secretAccessKey: sts.secretKey, }, region: 'us-east-1', signatureVersion: 'v4', sslEnabled: this._transport === 'https', httpOptions: { agent: this.stsAgent, timeout: 0 }, maxRetries: 0, }; } } _initCredentialsManager() { this.credentialsManager.on('deleteCredentials', clientId => { delete this.s3Clients[clientId]; delete this.backbeatClients[clientId]; }); this._deleteInactiveCredentialsInterval = setInterval(() => { this.credentialsManager.removeInactiveCredentials(MAX_INACTIVE_DURATION); }, DELETE_INACTIVE_CREDENTIALS_INTERVAL); } /** * Close the lifecycle bucket processor * @param {function} cb - callback function * @return {undefined} */ close(cb) { if (this._deleteInactiveCredentialsInterval) { clearInterval(this._deleteInactiveCredentialsInterval); } async.parallel([ done => { this._log.debug('closing bucket tasks consumer'); this._consumer.close(done); }, done => { this._log.debug('closing producer'); this._producer.close(done); }, ], () => cb()); } isReady() { return this._producer && this._producer.isReady() && this._consumer && this._consumer.isReady(); } }
JavaScript
class Command extends LocateStrategy { constructor() { super(); this.strategy = Strategies.XPATH; } }