language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Fraction { constructor(f) { let fracIndex = f.indexOf('/'), decIndex = f.indexOf('.'); if (fracIndex > 0) { // we disallow inputs to start from / in our input box, so only need to check from index 1 let negNum; if (f[0] == '-') { this.sign = '-'; this.num = Number(f.slice(1, fracIndex)); negNum = -1; } else { this.sign = ''; this.num = Number(f.slice(0, fracIndex)); negNum = 1; } this.den = Number(f.slice(fracIndex + 1)); this.float = negNum * this.num / this.den; this.typeOf = 'f'; } else { // not a fraction let answer = handleDecimal(f); if (decIndex >= 0) { this.typeOf = 'd'; } else { this.typeOf = 'i'; } if (answer[0] == '-') { this.sign = '-'; this.num = Number(answer.slice(1)); this.den = 1; this.float = Number(answer); } else { this.sign = ''; this.num = Number(answer); this.den = 1; this.float = Number(answer); } } ; if (this.typeOf == 'f') { this.typeset = this.sign + '\\frac{' + this.num + '}{' + this.den + '}'; } else { this.typeset = this.sign + this.num; } } // methods simplify() { if (this.typeOf == 'f') { // only simplify fraction types let gcd = gcdY(this.num, this.den); if (gcd != 1 || this.den == 1) { // we can further simplify this.num = this.num / gcd; this.den = this.den / gcd; if (this.den == 1) { // no longer a fraction this.typeOf = 'i'; this.typeset = this.sign + this.num.toString(); } else { //typeset new fraction this.typeset = this.sign + '\\frac{' + this.num + '}{' + this.den + '}'; } } } } }
JavaScript
class StudentInput { constructor(typeOf, iD, varName = '', submitButton = '') { this.typeOf = typeOf; this.iD = iD; this.varName = varName; this.otherInput = []; this.otherRadio = []; this.submitButton = submitButton; this.inputID = 'input' + varName.toUpperCase(); this.katexID = varName + 'Equals'; this.validity = false; // initialized as false as input not received yet this.value = null; // initialized as false as input not received yet this.negativeID = ''; // only writes for 'i' case this.samsungWarningText = ''; // only writes the warning if we have typeOf 'i' this.fractionInstructions = ''; // only writes the instruction if we have typeOf 'fX' this.fractionID = ''; // only writes the instruction if we have typeOf 'fX' this.decimalID = ''; // only writes the instruction if we have typeOf 'fX' let innerHTML = "<span id='" + this.katexID + "'></span>"; if (typeOf[0] == 'i') { innerHTML += "<input id='" + this.inputID + "' type='number'></input>"; if (typeOf == 'i') { // negative allowed let checkboxID = 'negative' + varName.toUpperCase(); innerHTML += "<label class='left'><ons-checkbox input-id='" + checkboxID + "' id='" + checkboxID + "'></ons-checkbox></label><label for='" + checkboxID + "' class='center'>Make negative</label>"; this.samsungWarningText = '<p> Some Samsung devices may be unable to key in negative values. A check box is provided to modify the sign of your input. </p> <p> You can ignore the checkbox if you are able to key in negative values </p>'; this.negativeID = checkboxID; } } else { // fraction type this.fractionID = 'fractionExample' + varName.toUpperCase(); this.decimalID = 'decimalExample' + varName.toUpperCase(); this.fractionInstructions = "<ons-list-header>Instructions:<br>Key in your numerical answer(s).<br>For fractions like <span id='" + this.fractionID + "'></span>, key in <span id='" + this.decimalID + "'></span></ons-list-header>"; if (typeOf == 'f') { // allow negative innerHTML += "<input id='" + this.inputID + "' pattern='(\\d+|(?=.+\\.)\\d+\\.\\d{1,5}|(?=\\.)\\.\\d+|(?=.+/)\\d+/\\d{1,5})|[\\-](\\d+|(?=.+\\.)\\d+\\.\\d{1,5}|(?=\\.)\\.\\d{1,5}|(?=.+/)\\d+/\\d+)' class='fraction'></input>"; } else { innerHTML += "<input id='" + this.inputID + "' pattern='(\\d+|(?=.+\\.)\\d+\\.\\d{1,5}|(?=\\.)\\.\\d+|(?=.+/)\\d+/\\d{1,5})' class='fraction'></input>"; } } ; this.innerHTML = innerHTML; } // end of constructor // methods addToDOM() { document.getElementById(this.iD).innerHTML = this.innerHTML; katex.render(this.varName + '=', document.getElementById(this.katexID), { throwOnError: false }); let input_field = document.getElementById(this.inputID); if (this.typeOf[0] == 'f') { // prevents spaces input_field.addEventListener('textInput', function (e) { var char = e.data; var keyCode = char.charCodeAt(0); // Stop processing if spacebar is pressed if (keyCode == 32) { e.preventDefault(); return false; } return true; }); // end of spacebar prevention } // end of fraction if/else if (this.submitButton) { // add event listener to show submit button let self = this; input_field.addEventListener('input', function () { let validityArray = [self.updateValidity()]; self.otherInput.forEach(e => { validityArray.push(e.validity); }); self.otherRadio.forEach(e => { validityArray.push(e.selected); }); if (validityArray.every(e => e)) { document.getElementById(self.submitButton).style.display = 'block'; } else { document.getElementById(self.submitButton).style.display = 'none'; } }); } } updateValidity() { let inputElement = document.getElementById(this.inputID); let validityCheck = true; // if integer, no need to check validity if (this.typeOf[0] == 'f') { validityCheck = inputElement.validity.valid; } ; if (inputElement.value && validityCheck) { // valid this.validity = true; if (this.typeOf[0] == 'f') { // fraction this.value = new Fraction(inputElement.value); return true; } // else integer if (this.typeOf == 'i') { // potential negative let negativeCheckbox = document.getElementById(this.negativeID); if (negativeCheckbox.checked) { this.value = Number(inputElement.value) * -1; return true; } } // else positive integer this.value = Number(inputElement.value); return true; } else { // not valid this.validity = false; this.value = null; return false; } } insertFractionHeader(onsListID) { if (this.typeOf[0] == 'f') { let minusSign = ''; if (this.typeOf == 'f') { minusSign = '-'; } ; document.getElementById(onsListID).innerHTML += this.fractionInstructions; katex.render(minusSign + "\\frac{22}{7}", document.getElementById(this.fractionID), { throwOnError: false }); katex.render(minusSign + "22/7", document.getElementById(this.decimalID), { throwOnError: false }); } } set linkInput(s) { this.otherInput.push(s); s.otherInput.push(this); } set linkRadio(r) { this.otherRadio.push(r); r.otherInput.push(this); } }
JavaScript
class StudentRadio { constructor(optionsArray, iD, name = '', submitButton = '') { let innerHTML = "<ons-list>"; let numberWords = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']; let index; for (index = 0; index < optionsArray.length; index++) { let divString = "<div id='radio" + name + numberWords[index] + "'>"; divString += "<ons-list-item tappable style='background: rgb(0,0,0,0.07);'>"; divString += "<label class='left'>"; divString += "<ons-radio name='reason" + name + "' input-id='radio" + name + "-" + index + "' value='" + index + "' onclick='studentRadio" + name + ".click(this.value)'></ons-radio>"; divString += "</label>"; divString += "<label for='radio" + name + "-" + index + "' class='center'>"; divString += "<span id='reason" + name + numberWords[index] + "'></span>"; divString += "<span id='caret" + name + numberWords[index] + "' style='padding-left:10px; display:none'>"; divString += "<ons-icon icon='fa-caret-down'></ons-icon>"; divString += "</span></label></ons-list-item></div>"; innerHTML += divString; } ; innerHTML += "</ons-list>"; this.iD = iD; this.name = name; this.optionsArray = optionsArray; this.innerHTML = innerHTML; this.selected = false; // no options selected by default this.otherInput = []; this.otherRadio = []; this.submitButton = submitButton; this.option = -1; } // end of constructor // methods addToDOM() { document.getElementById(this.iD).innerHTML = this.innerHTML; let numberWords = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']; this.optionsArray.forEach((str, index) => { let reasonID = "reason" + this.name + numberWords[index]; katex.render(str, document.getElementById(reasonID), { throwOnError: false }); }); } click(indexString) { let iD = Number(indexString); let numberWords = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five'], index; let radioIds = [], caretIds = []; for (index = 0; index < this.optionsArray.length; index++) { radioIds.push("radio" + this.name + numberWords[index]); caretIds.push("caret" + this.name + numberWords[index]); } if (this.selected) { // option already selected: show all for reselection. Hide caret radioIds.forEach(function (radioString) { document.getElementById(radioString).style.display = 'block'; }); document.getElementById(caretIds[iD]).style.display = 'none'; this.selected = false; } else { // hide all but selection. Show caret radioIds.forEach(function (radioString, i) { if (i != iD) { document.getElementById(radioString).style.display = 'none'; } ; }); document.getElementById(caretIds[iD]).style.display = 'inline'; this.selected = true; } ; this.option = iD; // check for display of submit button if (this.submitButton) { let validityArray = [this.selected]; this.otherInput.forEach(e => { validityArray.push(e.validity); }); this.otherRadio.forEach(e => { validityArray.push(e.selected); }); if (validityArray.every(e => e)) { document.getElementById(this.submitButton).style.display = 'block'; } else { document.getElementById(this.submitButton).style.display = 'none'; } } } set linkInput(s) { this.otherInput.push(s); s.otherRadio.push(this); } set linkRadio(r) { this.otherRadio.push(r); r.otherRadio.push(this); } }
JavaScript
class MarkFraction { constructor(f1, f2) { this.correct = false; this.upToSimplified = false; this.upToSign = false; this.close = false; this.partial = false; // check if close if (f1.float.toPrecision(2) == f2.float.toPrecision(2)) { this.close = true; } if ((Math.abs(f1.float)).toPrecision(11) == (Math.abs(f2.float)).toPrecision(11)) { // check if accuracy is good (up to sign) this.upToSign = true; if (f1.float * f2.float >= 0) { // check if same sign (or 0) this.upToSimplified = true; if (isSimplified(f1) && isSimplified(f2)) { this.correct = true; } } } this.partial = this.upToSign || this.upToSimplified || this.close; } }
JavaScript
class BinarySearchTree { constructor() { this.theRoot = null; } root() { return this.theRoot; } add(data) { var newNode = new Node(data); if (!this.theRoot) { this.theRoot = newNode; } else { this.insertNode(this.theRoot, newNode); } } insertNode(node, newNode) { if (newNode.data < node.data) { if (!node.left) node.left = newNode; else this.insertNode(node.left, newNode); } else { if (!node.right) node.right = newNode; else this.insertNode(node.right, newNode); } } has(data) { var node = this.theRoot; if (!node) return null; else while (node) { if (data == node.data) return true; else if (data < node.data) node = node.left; else if (data > node.data) node = node.right; } return false; } find(data) { var node = this.theRoot; if (!node) return null; else while (node) { if (data == node.data) return node; else if (data < node.data) node = node.left; else if (data > node.data) node = node.right; } return null; } remove(data) { this.theRoot = this.removeNode(this.theRoot, data); } removeNode(node, key) { if (!node) return null; if (key < node.data) { node.left = this.removeNode(node.left, key); return node; } else if (key > node.data) { node.right = this.removeNode(node.right, key); return node; } else { if (!node.left && !node.right) { node = null; return node; } else if (!node.left) { node = node.right; return node; } else if (!node.right) { node = node.left; return node; } var aux = this.findMinNode(node.right); node.data = aux.data; node.right = this.removeNode(node.right, aux.data); return node; } } findMinNode(node) { if (node.left === null) return node; else return this.findMinNode(node.left); } min() { if (!this.theRoot) return null; var min = this.theRoot; while (min.left) { min = min.left; } return min.data; } max() { if (!this.theRoot) return null; var max = this.theRoot; while (max.right) { max = max.right; } return max.data; } }
JavaScript
class ColorsRandomizer extends Randomizer { /** * Create the box randomizer from min and max colors to randomize between. */ constructor (min, max) { super() this.min = min || new THREE.Color(0, 0, 0) this.max = max || new THREE.Color(1, 1, 1) } /** * Generate a random color. */ generate () { return Utils.getRandomColorBetween(this.min, this.max) } }
JavaScript
class PaginationResponse { /** * @type {number} * * @private */ totalItems = 0; /** * @type {number} */ currentPage = 1; /** * @type {number} */ perPage = 20; /** * @type {number} */ pageCount = 1; /** * Pagination constructor * * @param {JsonQuery} query * @param {number} count * * @return {undefined} */ constructor(query, count = 0) { /** * @private */ this.totalItems = count; /** * @private */ this.currentPage = query.getPage(); /** * @private */ this.perPage = query.getPerPage(); /** * @private */ this.pageCount = Math.ceil(this.totalItems / this.perPage); } /** * Get total items * * @return {number} */ getTotalItems = () => { return this.totalItems; }; /** * Get page count * * return {number} */ getPageCount = () => { return this.pageCount; }; /** * Get current page * * return {number} */ getCurrentPage = () => { return this.currentPage; }; /** * Get per page * * return {number} */ getPerPage = () => { return this.perPage; }; /** * Convert instance to json object * * @return {Object} */ toJSON() { return { currentPage: this.currentPage, perPage: this.perPage, pageCount: this.pageCount, totalItems: this.totalItems, }; } }
JavaScript
class SegmentInheritance extends Point2D { /** * Create a segment * @param {Point2D} initPoint * @param {Point2D} endPoint */ constructor(initPoint = new Point2D(), endPoint = new Point2D()) { super(initPoint.getAbscissa(), initPoint.getOrdinate()); this.endPoint_ = endPoint; } /** * The length of the segment * @return {number} Distance between this instance of Point2D and endPoint_ */ length() { return this.instanceDistance(this.endPoint_); } }
JavaScript
class Coordinate { /** * Create a SDR33 coordinate object * @param pName //Point name (max. 16 characters) * @param N //North value * @param E //East value * @param ele //elevation * @param desc //point description (max. 16 characters) */ constructor(pName, N, E, ele, desc) { this._typeCode = '08'; this._derivationCode = derivationCode_1.derivationCode.KeyboardInput; this.datalength = 84; //length in bytes this._pointId = pName; this._nothing = Number(N.toFixed(4)); this._easting = Number(E.toFixed(4)); this._elevation = Number(ele.toFixed(4)); this._description = desc; } /** * Get PointId bytes * @returns */ getPointIdBytes() { let len = 16; let Res = this._pointId; return sdr33Tools_1.fillUp(Res, len); } getNorthingBytes() { let len = 16; let Res = this._nothing.toString(10); return sdr33Tools_1.fillUp(Res, len); } getEastingBytes() { let len = 16; let Res = this._easting.toString(10); return sdr33Tools_1.fillUp(Res, len); } getEelvationBytes() { let len = 16; let Res = this._elevation.toString(10); return sdr33Tools_1.fillUp(Res, len); } getDescriptionBytes() { let len = 16; let Res = this._description; return sdr33Tools_1.fillUp(Res, len); } getMessage() { let m = ''; m += this._typeCode; m += this._derivationCode; m += this.getPointIdBytes(); m += this.getNorthingBytes(); m += this.getEastingBytes(); m += this.getEelvationBytes(); m += this.getDescriptionBytes(); return m; } }
JavaScript
class ReqData { constructor(type, URL, handler, body = {}) { this.type = type; this.URL = URL; this.handler = handler; this.body = body; } }
JavaScript
class UndoRedoReq { constructor(undoReqData, redoReqData) { this.undoReq = undoReqData; this.redoReq = redoReqData; } }
JavaScript
class ReqStack { constructor() { this.stack = []; } /** * pushes data onto stack. * * @param {Object} undoRedoReq UndoRedoReq object to be pushed onto stack */ push(undoRedoReq) { this.stack.push(undoRedoReq); } /** * pops an object of the top of the stack. */ pop() { // Maybe we will do stuff here return this.stack.pop(); } /** * Returns true if the stack is empty, false otherwise * * @returns {boolean} true if the stack is empty, false otherwise */ isEmpty() { return this.stack.length === 0; } /** * Clears the stack */ clear() { this.stack = []; } }
JavaScript
class UndoRedo { constructor() { this.undoStack = new ReqStack(); this.redoStack = new ReqStack(); } /** * An intermediary step for sending requests to the api. * Will store this request as a redoReq and create an inverse undoReq. * * @param {Object} reqData ReqData instance that contains data for request to send * @param {Object} inverseHandler the function to pass the response through when executing the reverse action */ sendAndAppend(reqData, inverseHandler = null) { return this.resAndInverse(reqData, inverseHandler).then( ({status, json, inverseData}) => { reqData.handler(status, json); if (status !== 201 && status !== 200) { // Handler should take care of this case return; } const undoRedoReq = new UndoRedoReq(inverseData, reqData); this.undoStack.push(undoRedoReq); updateUndoRedoButtons(); }); } /** * Handles the next undo and will add it to redo stack. Throws error if no undos. */ undo() { const undoRedoReq = this.undoStack.pop(); if (!undoRedoReq) { toast('Undo', 'Nothing to undo!', 'danger'); updateUndoRedoButtons(); throw "No undo's"; } return this.resAndInverse(undoRedoReq.undoReq).then( ({status, json, inverseData}) => { undoRedoReq.undoReq.handler(status, json); if (status !== 201 && status !== 200) { //Handler should take care of this case return; } this.redoStack.push( new UndoRedoReq(undoRedoReq.undoReq, inverseData)); toast('Undo', 'Undo successful'); updateUndoRedoButtons(); }); } /** * Handles the next redo and will add it to the undo stack. Throws error if no redos. */ redo() { const undoRedoReq = this.redoStack.pop(); if (!undoRedoReq) { toast('Redo', 'Nothing to redo!', 'danger'); updateUndoRedoButtons(); throw "No redos"; } return this.resAndInverse(undoRedoReq.redoReq).then( ({status, json, inverseData}) => { undoRedoReq.redoReq.handler(status, json); if (status !== 201 && status !== 200) { //Handler should take care of this case return; } this.undoStack.push( new UndoRedoReq(inverseData, undoRedoReq.redoReq)); toast('Redo', 'Redo successful'); updateUndoRedoButtons(); }); } /** * Generates a response by calling the appropriate fetch method and creates and * inverse data set to be used for undo/redo. * * @param {Object} reqData ReqData instance that contains data for request to send * @param {Object} inverseHandler the function to pass the response through when executing the reverse action */ resAndInverse(reqData, inverseHandler = null) { switch (reqData.type) { case requestTypes["TOGGLE"]: //Delete should toggle so its inverse is itself return put(reqData.URL, reqData.body).then(sponse => { return sponse.json().then(json => { return { status: sponse.status, json, inverseData: reqData }; }); }); case requestTypes["CREATE"]: //Send a post request with req data and generate a delete toggle inverseHandler = inverseHandler || reqData.handler; return post(reqData.URL, reqData.body).then(sponse => { return sponse.json().then(json => { const inverseData = new ReqData(requestTypes['TOGGLE'], `${reqData.URL}/${json}/delete`, inverseHandler); return {status: sponse.status, json, inverseData}; }); }); case requestTypes["UPDATE"]: return put(reqData.URL, reqData.body).then(sponse => { return sponse.json().then(json => { const inverseData = { ...reqData, body: json, }; return { status: sponse.status, json, inverseData, }; }); }); default: throw "Request type not found"; } } }
JavaScript
class PaintBox { /** * @param {string|Element|external:jQuery} container * @param {"fill"} type */ constructor(container, type, spinner) { const cur = curConfig[type === "fill" ? "initFill" : "initStroke"]; // set up gradients to be used for the buttons const svgdocbox = new DOMParser().parseFromString( `<svg xmlns="http://www.w3.org/2000/svg"> <ellipse fill="#${ cur.color }" stroke="#dfdfdf" stroke-width="2" cx="13" cy="14" rx="12" ry="12" opacity="${ cur.opacity }"></ellipse> <defs><linearGradient id="gradbox_${PaintBox.ctr++}"/></defs> </svg>`, "text/xml" ); this.noColor = $( "<div class='no-color' style='display:none'></div>" ).appendTo(container); let docElem = svgdocbox.documentElement; docElem = $(container)[0].appendChild(document.importNode(docElem, true)); docElem.setAttribute("width", 28); this.rect = docElem.firstElementChild; this.defs = docElem.getElementsByTagName("defs")[0]; this.grad = this.defs.firstElementChild; this.paint = new $.jGraduate.Paint({ solidColor: cur.color }); this.type = type; this.spinner = spinner; } setOpacity(v, apply, fromSpinner) { const paint = Object.assign({}, this.paint, {alpha: v}); this.setPaint(paint, apply, fromSpinner); } setPaint(paint, apply, fromSpinner) { this.paint = paint; const ptype = paint.type; const opac = paint.alpha / 100; if (!fromSpinner && this.spinner) { this.spinner.SpinButton(paint.alpha); } if (opac) { this.noColor.hide(); $(this.rect).show(); let fillAttr = "none"; switch (ptype) { case "solidColor": fillAttr = paint[ptype] !== "none" ? "#" + paint[ptype] : paint[ptype]; break; case "linearGradient": case "radialGradient": { this.grad.remove(); this.grad = this.defs.appendChild(paint[ptype]); const id = (this.grad.id = "gradbox_" + this.type); fillAttr = "url(#" + id + ")"; break; } } this.rect.setAttribute("fill", fillAttr); this.rect.setAttribute("opacity", opac); } else { this.noColor.show(); $(this.rect).hide(); } if (apply) { svgCanvas.setColor(this.type, this._paintColor, true); svgCanvas.setPaintOpacity(this.type, opac, true); } } /** * @param {boolean} apply * @returns {void} */ update(apply) { if (!selectedElement) { return; } const { type } = this; switch (selectedElement.tagName) { case "use": case "image": case "foreignObject": // These elements don't have fill or stroke, so don't change // the current value return; case "g": case "a": { const childs = selectedElement.getElementsByTagName("*"); let gPaint = null; for (let i = 0, len = childs.length; i < len; i++) { const elem = childs[i]; const p = elem.getAttribute(type); if (i === 0) { gPaint = p; } else if (gPaint !== p) { gPaint = null; break; } } if (gPaint === null) { // No common color, don't update anything this._paintColor = null; return; } this._paintColor = gPaint; this._paintOpacity = 1; break; } default: { this._paintOpacity = parseFloat( selectedElement.getAttribute(type + "-opacity") ); if (isNaN(this._paintOpacity)) { this._paintOpacity = 1.0; } const defColor = type === "fill" ? "black" : "none"; this._paintColor = selectedElement.getAttribute(type) || defColor; } } if (apply) { svgCanvas.setColor(type, this._paintColor, true); svgCanvas.setPaintOpacity(type, this._paintOpacity, true); } this._paintOpacity *= 100; const paint = getPaint(this._paintColor, this._paintOpacity, type); // update the rect inside #fill_color/#stroke_color this.setPaint(paint); } /** * @returns {void} */ prep() { const ptype = this.paint.type; switch (ptype) { case "linearGradient": case "radialGradient": { const paint = new $.jGraduate.Paint({ copy: this.paint }); svgCanvas.setPaint(this.type, paint); break; } } } }
JavaScript
class SandGrain extends EventEmitter { constructor() { super(); let name = this.constructor.name || 'SandGrain'; this.name = name[0].toLowerCase() + name.slice(1); this.env = SandGrain.getEnv(); this.config = this.config || {}; this.defaultConfig = this.defaultConfig || {}; this.version = 'unknown'; this.configName = this.name; } /** * Returns only select parameters when inspecting * * @returns {object} */ inspect() { "use strict"; return only(this, [ 'name', 'env', 'version' ]); } /** * Gets called when the process starts up, use this * to initialize your module * * @param {object|string} config - the config object or path to the config file * @param {function} done - Call this when done initializing * * @returns {SandGrain} */ init(config, done) { // Setup the logger try { var logger = Sand.Logger(this.name); } catch (e) { // Since Sand isn't loaded, lets load the fake logger logger = new (require('./FakeLogger'))(); } this.log = logger.log; this.warn = logger.warn; this.error = logger.error; // Load config this.loadConfig(config); if (typeof done === 'function') { done(); } return this; } /** * Run Start on Grain * * @param {Function} done * @returns {SandGrain} */ start(done) { if (typeof done === 'function') { done(); } return this; } /** * Loads the config * * @param {object|string} config - the config object or path to the config file */ loadConfig(config) { var passedInConfig; if (typeof config === 'object') { passedInConfig = config; } else if (typeof config === 'string') { // Must be a path passedInConfig = require(config); } if (passedInConfig) { if (!this.validateConfig(passedInConfig)) { this.log('Missing env ' + this.env + ' or all on the config object falling back to all'); } this.config = SandGrain.getConfig(passedInConfig, this.defaultConfig); } } /** * Gets called when process is shutting down * Use this method to cleanup your module * * @param {Function} done - Call this when done cleaning up * * @returns {SandGrain} */ shutdown(done) { if ('function' === typeof done) { done(); } return this; } /** * Checks to see if the config has an "env" member or "all" * * @param {object} config - the config object to check * * @returns {object} */ validateConfig(config) { // Default we check that it has environment or all return _.isPlainObject(config[this.env]) || _.isPlainObject(config['all']); } /** * Get the Config for the environment * * @param {object} config - The config to extract the real config from * @param {object} [defaultConfig] - The default config to merge with * * @returns {object} The merged object for the current environment */ static getConfig(config, defaultConfig) { var env = config[SandGrain.getEnv()] || {}; var all = config['all'] || {}; var obj = all || env ? {} : config; // Fallback to config if no all or env return _.merge({}, defaultConfig, all, env, obj); } /** * Get the currently running Environment * * @returns {string} */ static getEnv() { return typeof global.sand !== 'undefined' ? global.sand.env : (process.env.NODE_ENV || 'development'); } }
JavaScript
class PermRoleStore { constructor() { _defineProperty(this, "defineRole", (roleName, validationFunction) => { this.roleStore[roleName] = new _role.default(roleName, validationFunction); }); _defineProperty(this, "defineManyRoles", roleMap => { if (!(0, _isObject.default)(roleMap)) { throw new TypeError('Parameter "roleNames" name must be object'); } (0, _forEach.default)(roleMap, (validationFunction, roleName) => { this.defineRole(roleName, validationFunction); }); }); _defineProperty(this, "removeRoleDefinition", roleName => { delete this.roleStore[roleName]; }); _defineProperty(this, "hasRoleDefinition", roleName => { return !(0, _isUndefined.default)(this.roleStore[roleName]); }); _defineProperty(this, "getRoleDefinition", roleName => { return this.roleStore[roleName]; }); _defineProperty(this, "getStore", () => { return this.roleStore; }); _defineProperty(this, "clearStore", () => { this.roleStore = {}; }); this.roleStore = {}; } // let roleStore = {}; // this.defineRole = defineRole; // this.defineManyRoles = defineManyRoles; // this.getRoleDefinition = getRoleDefinition; // this.hasRoleDefinition = hasRoleDefinition; // this.removeRoleDefinition = removeRoleDefinition; // this.getStore = getStore; // this.clearStore = clearStore; /** * Allows to add single role definition to the store by providing it's name and validation function * @methodOf permission.PermRoleStore * * @param roleName {String} Name of defined role * @param [validationFunction] {Function|Array<String>} Function used to validate if role is valid or set of * permission names that has to be owned to have a role */ }
JavaScript
class Objectfield extends Parentfield { static TYPE = 'object'; /** @inheritdoc */ _children = {}; /** * The fields to display in the legend slot of the form. */ legendChildren = undefined; /** * The child that is currently open in the tabbed view. * @type {Field} */ activeChild = undefined; /** @inheritdoc */ init(id = '', args = {}) { args = Object.assign({children: {}, legendChildren: undefined}, args); this._children = args.children; this.legendChildren = args.legendChildren; return super.init(id, args); } /** * Called by Aurelia when this Objectfield is attached to the DOM. * This function is used for activating the first tab by default. */ attached() { // Is this a tabbed objectfield that has children? if (this.iterableChildren.length > 0 && this.format === 'tabs') { // Are there no active tabs? if ($(this.tabs).find('.tab-link.open').length === 0) { // Then activate the first tab. this.switchTab(this.iterableChildren[0]); } } } /** * Check if this object is empty. If all children are empty, then this field * is also considered to be empty. */ isEmpty() { for (const child of Object.values(this.allChildren)) { if (!child.isEmpty()) { return false; } } return true; } /** * @inheritdoc * @return {Object} The values of the children in an object. The keys are the * IDs of the children. */ getValue() { const value = {}; for (const [key, field] of Object.entries(this.allChildren)) { if (!field || !field.showValueInParent || !field.display) { continue; } else if (field.isEmpty() && field.hideValueIfEmpty) { continue; } value[key] = field.getValue(); } return value; } /** @inheritdoc */ revalidate(errorCollection) { const validation = super.revalidate(errorCollection); if (this.hasLegend) { for (const [index, child] of Object.entries(this.legendChildren)) { validation[index] = child.revalidate(errorCollection); if (!validation[index].valid || validation[index].childrenValid === false) { validation.childrenValid = false; } } } return validation; } /** @inheritdoc */ get allChildren() { return Object.assign({}, this.legendChildren, this._children); } /** @inheritdoc */ get iterableLegendChildren() { return this.legendChildren ? Object.values(this.legendChildren) : []; } /** @inheritdoc */ get hasLegend() { return this.legendChildren && this.iterableLegendChildren.length > 0; } /** * Set the values of the children of this field. * * @param {Object} value The values for the children with the ID of the child * as the object key. */ setValue(value) { this.onSetValue(value); for (const [key, field] of Object.entries(value)) { if (this._children.hasOwnProperty(key)) { this._children[key].setValue(field); } else if (this.legendChildren && this.legendChildren.hasOwnProperty(key)) { this.legendChildren[key].setValue(field); } } } /** * Add the given child to this object. * @param {Field} child The child to add. */ addChild(child) { this._children[child.id] = child; this.onChange(child); } /** * Switch to the tab of the given child element. * @param {Field} toChild The child whose tab to switch to. */ switchTab(toChild) { this.activeChild = toChild; const tabElem = $(`#tab-${toChild.path.replace(/\./g, '\\.')}`); tabElem.parent().find('.tab-link.open').removeClass('open'); tabElem.addClass('open'); } /** @inheritdoc */ clone(parent) { const clone = new Objectfield(); const clonedChildren = {}; for (const [key, field] of Object.entries(this._children)) { clonedChildren[key] = field.clone(clone); clonedChildren[key].parent = clone; } const clonedLegendChildren = {}; if (this.legendChildren) { for (const [key, field] of Object.entries(this.legendChildren)) { clonedLegendChildren[key] = field.clone(clone); clonedLegendChildren[key].parent = clone; } } clone.init(this.id, { format: this.format, columns: this.columns, collapsed: this.collapsed, parent: parent || this.parent, index: this.index, hideValueIfEmpty: this.hideValueIfEmpty, setValueListeners: this.setValueListeners, i18n: this.i18n, validation: this.validation, children: clonedChildren, legendChildren: clonedLegendChildren }); return clone; } /** @inheritdoc */ resolvePath(path) { const parentResolveResult = super.resolvePath(path); if (parentResolveResult) { return parentResolveResult; } if (this.hasLegend) { const elem = this.legendChildren[path[0]]; if (elem) { return elem.resolvePath(path.splice(1)); } } return undefined; } /** * @return {String} The name of the HTML file that displays the object with * the format specified in {@link #format}. * @private */ getViewStrategy() { if (this.format === 'tabs') { return 'resources/form/objectfield-tabbed.html'; } return 'resources/form/objectfield.html'; } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.state = { blogs: [], keyword: '' } this.searchHandler = this.searchHandler.bind(this); } /** * Changes keyword's state based on the search bar's content * @param {*} event handles search bar's onChange events */ searchHandler(event) { this.setState( {keyword: event.target.value}) } /** * Fetches data from the database upon loading */ componentDidMount() { fetch('http://localhost:8080/blogs') .then(res => res.json()) .then((data) => { this.setState({ blogs: data }) console.log(this.state.blogs) }) .catch(console.log) } /** * Handles the site layout and creates blog objects to the site */ render() { // Mapping blogs and all of their values const blogs = this.state.blogs.filter(searchFilter(this.state.keyword)) .map(blog => <Blog key={blog.id} id={blog.id}title={blog.title} body={blog.body} datetime={blog.datetime} comments={blog.comments} />) console.log(blogs); /** * Site's object structure */ return ( <div className="app"> <NavBar/> <Header/> <TextField className="searchbar" variant="outlined" type="text" label="Search for blogs" onChange={this.searchHandler} /> <div className="blogs"> {blogs} </div> <Footer/> </div> ); } }
JavaScript
class ZoomToBbox extends mixin(Control, ActivatableMixin) { /** * @param {g4uControlOptions} options */ constructor (options = {}) { options.element = $('<button>').get(0) options.className = options.className || 'g4u-zoom-to-bbox' options.singleButton = true super(options) this.classNameActive_ = this.className_ + '-active' /** * @type {StyleLike} * @private */ this.style_ = options.style || '#defaultStyle' this.setTitle(this.getTitle() || this.getLocaliser().localiseUsingDictionary('ZoomToBbox title') ) this.setTipLabel(this.getTipLabel() || this.getLocaliser().localiseUsingDictionary('ZoomToBbox tipLabel') ) this.get$Element() .addClass(this.className_) .addClass(cssClasses.mainButton) .html(this.getTitle()) addTooltip(this.get$Element(), this.getTipLabel()) this.get$Element().on('click', () => this.setActive(!this.getActive())) this.on('change:active', e => this.activeChangeHandler_(e)) } setMap (map) { if (this.getMap()) { this.removeInteraction(this.interaction_) } super.setMap(map) if (map) { this.interaction_ = new ExtentInteraction({ boxStyle: map.get('styling').getStyle(this.style_), pointerStyle: () => null, handleUpEvent: () => { this.setActive(false) return true } }) this.interaction_.setActive(false) map.addSupersedingInteraction('singleclick pointermove drag', this.interaction_) } } activeChangeHandler_ () { const active = this.getActive() this.get$Element().toggleClass(cssClasses.active, active) if (active) { this.interaction_.setActive(true) $(this.map_.getViewport()).addClass(cssClasses.crosshair) } else { this.map_.getView().fit(this.interaction_.getExtent()) $(this.map_.getViewport()).removeClass(cssClasses.crosshair) this.interaction_.setActive(false) this.interaction_.setExtent(null) } } }
JavaScript
class UnitDefinition { constructor({ name, base, units, aliases, conversion }) { assert(typeof name === 'string' && name, 'Definition has no name'); assert(typeof base === 'string' && base, 'Definition has no base unit : ' + name); assert(units && Object.keys(units).length, 'Definition has no units : ' + name); this.name = name; this.base = base; this.units = units; this.aliases = aliases || {}; this.conversion = conversion || {}; assert(this.base in this.units, 'Invalid base "' + this.base + '" in definition : ' + this.name); Object.keys(this.aliases).forEach(alias => { assert(typeof this.aliases[alias] === 'string', 'Invalid alias value for "' + alias + '" in definition : ' + this.name); assert(this.aliases[alias] in this.units, 'Invalid alias "' + alias + '" = "' + this.aliases[alias] + '" in definition : ' + this.name); }); if (this.conversion.converters) { Object.keys(this.conversion.converters).forEach(converterName => { const converterFn = this.conversion.converters[converterName]; assert(typeof converterFn === 'function', 'Converter should be a function : ' + converterName); }); } } /** Resolve the specified unit name. This method does not check whether the specified value is actually a valid unit name. @param unit {string} @return {string} */ resolveUnit(unit) { return this.aliases && this.aliases[unit] || unit; } /** Calculate the value from a given unit to another unit. For example: unitDef.calc(1, 'kilometer', 'meter') => 1000 @param value {number} @param fromUnit {string} @param toUnit {string} @return {number} */ calc(value, fromUnit, toUnit) { fromUnit = this.resolveUnit(fromUnit); toUnit = this.resolveUnit(toUnit); assert(fromUnit in this.units, 'Invalid unit "' + fromUnit + '" in definition : ' + this.name); assert(toUnit in this.units, 'Invalid unit "' + toUnit + '" in definition : ' + this.name); if (fromUnit !== toUnit) { if (typeof this.units[fromUnit].toBase === 'function' && fromUnit !== this.base) { value = this.units[fromUnit].toBase(Number(value)); } else { value *= this.units[fromUnit]; } if (typeof this.units[toUnit].fromBase === 'function' && toUnit !== this.base) { value = this.units[toUnit].fromBase(Number(value)); } else { value /= this.units[toUnit]; } } return value; } /** Calculate the value from a given unit to this definition's vase unit. @param value {number} @param unit {string} @return {number} */ calcBase(value, unit) { return this.calc(value, unit, this.base); } /** Check if any converter can convert the given type to the current type. @param type {string} @return {boolean} */ canConvert(type) { return !!(this.conversion.params && Object.keys(this.conversion.params).some(param => this.conversion.params[param] === type)); } /** Check that this unit type contains the specified converter. @param converter {string} @return {boolean} */ hasConverter(converter) { return this.conversion && this.conversion.converters && typeof this.conversion.converters[converter] === 'function'; } /** Call a converter given the specified converter name and params. If no converter match is found, an error will be thrown. If not all params as specified for the given converter, a value such as NaN may be returned. @param converter {string} the name of the converter to use @param params {object} an object of arguments. */ convert(converter, params) { assert(this.hasConverter(converter), 'Unknown or invalid converter "' + converter + '" in definition : ' + this.name); const fn = this.conversion.converters[converter] return fn.call(this, params || {}); } }
JavaScript
class WS2Server extends Server { /** * Spawns a new mock WS2 API server. Supported commands: * POST /send - body is parsed as JSON and sent to all clients * POST /config - body is parsed as JSON, and valid config keys are saved * * @param {Object} args * @param {number} args.apiPort - which port to listen on for ws clients * @param {number} args.cmdPort - which port to listen on for commands * @param {boolean} args.syncOnConnect - send snapshots to clients on connect * @param {boolean} args.listen - if true, listen() is called automatically */ constructor (args = { apiPort: 9997, cmdPort: 9996, syncOnConnect: true, listen: true }) { if (!args.cmdPort) args.cmdPort = 9996 super(args, path.join(__dirname, '../../data/ws2.json')) this._apiPort = args.apiPort || 9997 this._syncOnConnect = args.syncOnConnect === true this._cmdServer.post('/send', this._onSendCommand.bind(this)) this._cmdServer.post('/config', this._onConfigCommand.bind(this)) if (args.listen) { this.listen() } } /** * Returns server active status * * @return {boolean} open */ isOpen () { return !!this._wss } /** * @private */ _sendResponse (key, ws) { if (!this._responses.has(key)) { return ws.send(JSON.stringify({ error: 'no response configured' })) } const packets = this._prepareResponsePackets(key) if (packets === null) return // no response for (let i = 0; i < packets.length; i++) { ws.send(JSON.stringify(packets[i])) } } /** * @private */ _prepareResponsePackets (key) { const res = this._responses.get(key) if (!res || !res.packets || res.packets.length === 0) return null const responsePackets = [] let packet for (let i = 0; i < res.packets.length; i++) { if (!res.packets[i]) continue packet = res.packets[i] if (typeof packet === 'string') { // ref to another response const subResPackets = this._prepareResponsePackets(packet) if (subResPackets !== null) { subResPackets.forEach(p => responsePackets.push(p)) } } else { responsePackets.push(packet) } } return responsePackets } /** * Starts the API server listening on the configured port. This is a no-op if * the server is already up */ listen () { if (this._wss) return super.listen() this._wss = new WebSocket.Server({ perMessageDeflate: false, port: this._apiPort }) this._clients = [] this._wss.on('connection', this._onConnection.bind(this)) debug('ws2 api server listening on port %d', this._apiPort) } /** * Closes the API server if it is running; This is a no-op if it is not. * * @return {Promise} p - resolves/rejects on success/error */ close () { return super.close().then(() => { if (!this._wss) return null return this._wss.close((err) => { if (err) { console.error(err) return } debug('ws2 api server closed') this._wss = null }) }) } /** * Configures an event handler to be called once when the specified event is * emitted by the API server. No-op if the server is not yet up. * * @param {string} eventName * @param {Function} cb */ once (eventName, cb) { if (!this._wss) return this._wss.once(eventName, cb) } /** * @private */ _onConfigCommand (req, res) { let config try { config = JSON.parse(req.body) } catch (e) { return res.status(400).json({ error: 'invalid json config' }) } if (typeof config.syncOnConnect !== 'undefined') { this._syncOnConnect = config.syncOnConnect } res.send(200) } /** * @private */ _onSendCommand (req, res) { let packet try { packet = JSON.parse(req.body) } catch (e) { return res.status(400).json({ error: 'invalid json data' }) } this.send(packet) res.send(200) debug('sent packet to clients: %j', packet) } /** * Sends the provided packet to all connected clients * * @param {*} packet - stringifed before being sent */ send (packet) { const wsPacket = JSON.stringify(packet) this._clients.forEach(c => c.send(wsPacket)) } /** * @private */ _onConnection (ws) { this._clients.push(ws) ws.on('message', this._onClientMessage.bind(this, ws)) this._sendResponse('connect.res', ws) debug('client connected') } /** * @private */ _onClientMessage (ws, msgJSON) { const msg = JSON.parse(msgJSON) this.emit('message', ws, msg) if (msg.event === 'auth') { return this._handleAuthMessage(ws, msg) } else if (msg.event === 'subscribe') { return this._handleSubscribeMessage(ws, msg) } else if (Array.isArray(msg)) { if (msg[0] !== 0) return if (msg[1] === 'on') { return this._handleNewOrder(ws, msg) } else if (msg[1] === 'oc') { return this._handleCancelOrder(ws, msg) } else if (msg[1] === 'oc_multi') { return this._handleCancelMultipleOrders(ws, msg) } else if (msg[1] === 'ox_multi') { return this._handleOrderMultiOp(ws, msg) } else if (msg[1] === 'calc') { return this._handleCalc(ws, msg) } } return this._handleUnknownMessagw(ws, msg) } /** * @private */ _handleAuthMessage (ws, msg) { this._sendResponse('auth.res', ws) debug('client authenticated') if (this._syncOnConnect) { this._syncClient(ws) } } /** * @private */ _handleSubscribeMessage (ws, msg) { msg.event = 'subscribed' msg.chanId = Math.floor(Math.random() * 10000) ws.send(JSON.stringify(msg)) // this._sendResponse('subscribe.res', ws) debug('client subscribed to channel %s', msg.channel) } /** * @private */ _handleNewOrder (ws, msg) { this._sendResponse('on.res', ws) const o = msg[3] if (o) { debug( 'new order: gid %d, cid %d, %f @ %f %s', o.gid, o.cid, o.amount, o.price, o.type ) } else { debug('new order') } } /** * @private */ _handleCancelOrder (ws, msg) { this._sendResponse('oc.res', ws) const o = msg[3] if (o) { debug('canceled order id %d', o.id) } else { debug('canceled order') } } /** * @private */ _handleCancelMultipleOrders (ws, msg) { this._sendResponse('oc_multi.res', ws) } /** * @private */ _handleOrderMultiOp (ws, msg) { this._sendResponse('ox_multi.res', ws) } /** * @private */ _handleCalc (ws, msg) { this._sendResponse('calc.res', ws) } /** * @private */ _handleUnknownMessagw (ws, msg) {} /** * Send snapshot data to the client, usually after auth. * * @param {WebSocket} ws * @private */ _syncClient (ws) { this._sendResponse('ps', ws) this._sendResponse('ws', ws) this._sendResponse('os', ws) this._sendResponse('fos', ws) this._sendResponse('fcs', ws) this._sendResponse('fls', ws) this._sendResponse('ats', ws) } }
JavaScript
class Transmission { constructor({ host, port, username, password, }) { this.client = new TransmissionPromise({ host, port, username, password, }) } async all() { const { torrents } = await this.client.get(false) return torrents } async get(id) { const torrent = await this.client.get(id) return torrent } async parse(filename) { return { filename } // const buffer = await Drive.get(filename) // return parser(buffer) } async add(filename) { return { filename } // const buffer = await Drive.get(filename) // return parser(buffer) } }
JavaScript
class GravityStore extends BaseStore { constructor(dispatcher, state, stores) { super(dispatcher, stores); this.cursor = state.cursor(['GravityStore'], { gravity: 0 }); } handleAction({action, payload}) { const {configStore, gameStateStore} = this.stores; switch (action) { case RESTART: this.cursor(store => store.set('gravity', configStore.baseGravity)); break; case UPDATE: if (gameStateStore.state === PLAYING) { // The gravity will increase linearly by the base gravity every two minutes // (i. e. after two minutes of playing the gravity will be twice as strong). this.cursor(store => store.update('gravity', gravity => gravity + (payload.time * configStore.baseGravity) / 60 / 2)); } break; } } get gravity() { return this.cursor().get('gravity'); } }
JavaScript
class IndexPage extends React.Component { render() { return ( <Section> <Heading strong={false} align='center'> It Is Working! </Heading> <Columns alignContent='center'> <Box align='center' pad='medium' margin='small' colorIndex='light-2'> <Paragraph align='center'> Lorizzle you son of a bizzle dolor dang doggy, crazy adipiscing elizzle. Get down get down shiznit velit, shizzle my nizzle crocodizzle volutpizzle, suscipit check it out, gravida bow wow wow, the bizzle. Pellentesque check it out ass da bomb. In hac habitasse crazy dictumst. My shizz dapibizzle. Yo mamma tellus urna, shizzlin dizzle dawg, mattis hizzle, eleifend vitae, nunc. Yo suscipizzle. Integizzle semper crunk things brizzle. </Paragraph> </Box> <Box align='center' pad='medium' margin='small' colorIndex='light-2'> <Paragraph align='center'> Lorizzle you son of a bizzle dolor dang doggy, crazy adipiscing elizzle. Get down get down shiznit velit, shizzle my nizzle crocodizzle volutpizzle, suscipit check it out, gravida bow wow wow, the bizzle. Pellentesque check it out ass da bomb. In hac habitasse crazy dictumst. My shizz dapibizzle. Yo mamma tellus urna, shizzlin dizzle dawg, mattis hizzle, eleifend vitae, nunc. Yo suscipizzle. Integizzle semper crunk things brizzle. </Paragraph> </Box> </Columns> </Section> ); } }
JavaScript
class CSSStyling { constructor(chowsenStyle) { //finalStyles is the end point for storing dynamic styles that will be saved this.finalStyles = this.parseStyle(chowsenStyle); } /** * Parses CSS string into a list of objects that can be dynamically edited * @param {*} chowsenStyle is a string containing css data to be parsed */ parseStyle(chowsenStyle) { if ((typeof chowsenStyle == "string" && chowsenStyle != "") || (typeof chowsenStyle == "object" && chowsenStyle != null) || chowsenStyle != undefined) { this.listOfStyles = []; this.providedStyle = chowsenStyle.replaceAll("\t"," ").replaceAll(" "," ").trim(); if (typeof this.providedStyle == "string" && this.providedStyle != "" && this.listOfStyles != undefined) { while(this.providedStyle.length > 0){ let style = {}; let startIndex = this.providedStyle.indexOf('{'); let selectorPart = this.providedStyle.slice(0, startIndex).trim(); let endIndex = this.providedStyle.indexOf('}'); let styleBody = this.providedStyle.slice(startIndex + 1, endIndex - 1).trim(); let stylePrefs = styleBody.split(';'); let selector_sList = selectorPart.split(','); let selector_s = []; for(let selectorS in selector_sList){ selector_s.push(selector_sList[selectorS].trim()); } for(let stylePref = 0; stylePref < stylePrefs.length; stylePref++){ stylePrefs[stylePref] = stylePrefs[stylePref].trim(); if(stylePrefs[stylePref] != ""){ let prop_Val = stylePrefs[stylePref].split(':'); let prop_s = ""; prop_Val[0] = prop_Val[0].trim(); if(prop_Val.length == 2){ prop_Val[1] = prop_Val[1].trim(); if(prop_Val[1].slice(0,3).toLowerCase() == "rgb" || prop_Val[1].slice(0,3).toLowerCase() == "var" || prop_Val[1].slice(0,4).toLowerCase() == "rgba"){ prop_s = prop_Val[1]; style[prop_Val[0]] = [ prop_s ]; } else { prop_s = prop_Val[1].split(','); if(prop_s == prop_Val[1]){ prop_s = prop_Val[1].split(' '); if(prop_s == prop_Val[1]){ style[prop_Val[0]] = '-1'; } } for(let prop = 0; prop < prop_s.length; prop++){ prop_s[prop] = prop_s[prop].trim(); style[prop_Val[0]] = prop_s; } } } else if(prop_Val.length == 1) { style['o'] = prop_Val[0]; } } } this.listOfStyles.push({ selector: selector_s, selector_style:style }); this.providedStyle = this.providedStyle.slice(endIndex + 1, this.providedStyle.length); } } } return this.listOfStyles; } /** * * @param {*} obj is a JSON string that is converted to regular string * @returns string that parseStyle can understand */ JSONtoString(obj){ let objToProps = obj.slice(1,-1); let start = 0; let result = ""; for(let i = 0; i < objToProps.length; i++){ if(objToProps[i] == ',' && (i - 1 > 0 && (objToProps[i - 1] == '%' || objToProps[i - 1] >= '0' && objToProps[i - 1] <= '9' || objToProps[i - 1].toLowerCase() >= 'a' && objToProps[i - 1].toLowerCase() <= 'z'))|| ((objToProps[i] >= '0' && objToProps[i] <= '9' || objToProps[i].toLowerCase() >= 'a' && objToProps[i].toLowerCase() <= 'z') && (i - 1 > 0 && objToProps[i - 1] == ','))){ } else if(objToProps[i] == ',' || i == objToProps.length - 1){ if(start == 0){ result += `\t${ objToProps.slice(start, i).replaceAll("\"","") };`; } else { result += `\n\t${ objToProps.slice(start + 1, i).replaceAll("\"","") };`; } start = i; } } return `{\n${ result }\n}`; } /** * * @param {*} name is the name of selector or group of selectors that must display json object * @returns JSON object corresponding to name */ showStyle(name){ if(typeof name === "string" && this.finalStyles != undefined){ for(let i in this.finalStyles){ if(name == this.finalStyles[i].selector.join(', ')){ return this.finalStyles[i]; } } } return; } /** * * @param {*} obj1 JSON style object to change * @param {*} obj2 JSON style object to change to * @returns JSON object which specifies if difference has been made */ displayDifference(obj1, obj2){ let showDifference = "\n\t"; if(typeof obj1 != "undefined" && typeof obj2 != "undefined" && obj1 != undefined && obj2 != undefined && obj1 != null && obj2 != null){ if(Object.keys(obj1).length >= Object.keys(obj2[0].selector_style).length){ let showDifference = "\n\t"; for(let i in obj1){ for(let j in obj2[0].selector_style){ if(i == j){ if(obj1[i].length == obj2[0].selector_style[j].length){ if(obj1[i].length == 1){ if(obj1[i][0] != obj2[0].selector_style[j][0]){ showDifference += `${ i }:${ obj1[i] } -> ${ j }:${ obj2[0].selector_style[j] }\n\t`; } } else if(obj1[i].length > 1){ for(let k in obj2[0].selector_style[j]){ if(obj1[i][k] != obj2[0].selector_style[j][k]) { showDifference += `${ i }:${ obj1[i][k] } -> ${ j }:${ obj2[0].selector_style[j][k] }\n\t`; } } } } else if(obj1[i].length < obj2[0].selector_style[j].length || obj1[i].length > obj2[0].selector_style[j].length){ showDifference += `${ i }:${ obj1[i][k] } -> ${ j }:${ obj2[0].selector_style[j][k] }\n\t`; } } } } return { isDiff: (showDifference == "\n\t")?false:true, styleDiff:showDifference }; } else if(Object.keys(obj1).length < Object.keys(obj2[0].selector_style).length){ let showDifference = "\n\t"; for(let i in obj2[0].selector_style){ for(let j in obj1){ if(i == j){ if(obj2[i].length == obj1[0].selector_style[j].length){ if(obj2[i].length == 1){ if(obj2[i][0] != obj1[0].selector_style[j][0]){ showDifference += `${ i }:${ obj2[i] } -> ${ j }:${ obj1[0].selector_style[j] }\n\t`; } } else if(obj2[i].length > 1){ for(let k in obj1[0].selector_style[j]){ if(obj2[i][k] != obj1[0].selector_style[j][k]) { showDifference += `${ i }:${ obj2[i][k] } -> ${ j }:${ obj1[0].selector_style[j][k] }\n\t`; } } } } else if(obj2[i].length < obj1[0].selector_style[j].length || obj2[i].length > obj1[0].selector_style[j].length){ showDifference += `${ i }:${ obj2[i][k] } -> ${ j }:${ obj1[0].selector_style[j][k] }\n\t`; } } } } return { isDiff: (showDifference == "\n\t")?false:true, styleDiff:showDifference }; } } return { isDiff: false, styleDiff:"nothing done!" }; } /** * * @param {*} name name of selector or group of selectors * @param {*} obj json object to update to given selector name * @param {*} showMessage console log shows success message, default is true, may be set to false * @param {*} showDiff console log shows difference and is set to true by default, may be set to false * @returns nothing */ updateSelector(name, obj, showMessage = true, showDiff = true){ if(typeof name === "string" && obj != null && typeof obj == "string" && this.finalStyles != undefined){ let message = ""; let objReceived = this.parseStyle(`${ name } ${ this.JSONtoString(obj) }`); for(let i = 0; i < this.finalStyles.length; i++){ let foundSelector = this.finalStyles[i].selector.join(', '); if(name == foundSelector){ if(typeof showDiff == "boolean" && showDiff == true){ console.log(this.displayDifference(this.finalStyles[i].selector_style, objReceived).styleDiff); } this.finalStyles.splice(i, 1, { selector: [ name ], selector_style:objReceived[0].selector_style }); message = `\nSuccessfully applied Styling to ${ foundSelector }\n`; } } if(message == ""){ message = `\nFailed applying Styling, ${ name } could not be found!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * * @param {*} name Name of css selector to update * @param {*} obj JSON style object to update JSON object under name * @param {*} showMessage console log message for successful update * @param {*} showDiff console log message showing difference before update was made * @returns no value is returned */ updatePartOfSelector(name, obj, showMessage = true, showDiff = true){ if(typeof name === "string" && obj != null && typeof obj == "string" && this.finalStyles != undefined){ let message = ""; let objReceived = this.parseStyle(`${ name } ${ this.JSONtoString(obj) }`); for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector.includes(name) && selector.length > 1){ if(typeof showDiff == "boolean" && showDiff == true){ console.log(this.displayDifference(this.finalStyles[i].selector_style, objReceived).styleDiff); } this.finalStyles[i].selector.splice(this.finalStyles[i].selector.indexOf(name), 1); this.finalStyles.splice(i, 0, { selector: [ name ], selector_style:objReceived[0].selector_style }); message = `\nSuccessfully added ${ name } by applied Styling to ${ selector }\n`; } } if(message == ""){ message = `\nFailed applying Styling, ${ name } could not be found!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * * @param {*} name name of selector or part of it * @param {*} obj string representing property to change * @param {*} showMessage optionally lets hide the message, defaults to showing success message * @returns nothing is returned */ updateSelectorRule(name, obj, showMessage = true){ if(typeof name === "string" && obj != null && typeof obj == "string" && this.finalStyles != undefined){ let message = ""; let objReceived = this.JSONtoString(obj).slice(1,-1).split(';'); for(let i = 0; i < objReceived.length; i++){ if(objReceived[i] == '\n' || objReceived[i] == '\t' || objReceived[i] == '\r' || objReceived[i] == ''){ objReceived.splice(i,1); i--; } } if(objReceived.length == 1){ objReceived[0] = objReceived[0].replaceAll('\n','').replaceAll('\t','').replaceAll('\r',''); objReceived = objReceived[0].split(':'); } for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector.includes(name) || selector == name){ this.finalStyles[i].selector_style[objReceived[0]] = objReceived[1]; message = `\nSuccessfully updated property ${ objReceived[0] } for ${ name }\n`; } } if(message == ""){ message = `\nFailed applying property ${ objReceived[0] } for ${ name }!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * * @param {*} name name of selector or part of it * @param {*} propName string representing property to remove * @param {*} showMessage optionally lets hide the message, defaults to showing success message * @returns nothing is returned */ removeSelectorRule(name, propName, showMessage = true){ if(typeof name === "string" && propName != null && typeof propName == "string" && this.finalStyles != undefined){ let message = ""; for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector.includes(name) || selector == name){ if(this.finalStyles[i].selector_style[propName] != undefined){ delete this.finalStyles[i].selector_style[propName]; } message = `\nSuccessfully removed property ${ propName } from ${ name }\n`; } } if(message == ""){ message = `\nFailed to remove property ${ propName } from ${ name }!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * * @param {*} name name of selector or part of it * @param {*} obj string representing property to add * @param {*} showMessage optionally lets hide the message, defaults to showing success message * @returns nothing is returned */ addSelectorRule(name, obj, showMessage = true){ if(typeof name === "string" && obj != null && typeof obj == "string" && this.finalStyles != undefined){ let message = ""; let objReceived = this.JSONtoString(obj).slice(1,-1).split(';'); for(let i = 0; i < objReceived.length; i++){ if(objReceived[i] == '\n' || objReceived[i] == '\t' || objReceived[i] == '\r' || objReceived[i] == ''){ objReceived.splice(i,1); i--; } } if(objReceived.length == 1){ objReceived[0] = objReceived[0].replaceAll('\n','').replaceAll('\t','').replaceAll('\r',''); objReceived = objReceived[0].split(':'); } for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector.includes(name) || selector == name){ if(this.finalStyles[i].selector_style[objReceived[0]] == undefined){ this.finalStyles[i].selector_style[objReceived[0]] = objReceived[1]; } message = `\nSuccessfully property ${ objReceived[0] } for ${ name }\n`; } } if(message == ""){ message = `\nFailed to add property ${ objReceived[0] } for ${ name }!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * @param {*} name name of selector object to add * @param {*} obj string representing selector data to add * @param {*} showMessage optionally lets hide the message, defaults to showing success message * @returns nothing is returned */ addSelectorObject(name, obj, showMessage = true){ if(typeof name === "string" && obj != null && typeof obj == "string" && this.finalStyles != undefined){ let message = ""; let objReceived = this.parseStyle(`${ name } ${ this.JSONtoString(obj) }`); for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector.includes(name) || selector == name){ message = `\nFailed to add selector object ${ name }!\n`; return; } } this.finalStyles.push(objReceived[0]); message = `\nSuccessfully added selector object ${ name }\n`; if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** * * @param {*} name name of selector object to remove * @param {*} showMessage optionally lets hide the message, defaults to showing success message * @returns nothing is returned */ removeSelectorObject(name, showMessage = true){ if(typeof name === "string" && this.finalStyles != undefined){ let message = ""; for(let i = 0; i < this.finalStyles.length; i++){ let selector = this.finalStyles[i].selector.join(', '); if(selector == name){ this.finalStyles.splice(i,1); message = `\nSuccessfully removed selector object for ${ name }\n`; } } if(message == ""){ message = `\nFailed removing selector object ${ name }!\n`; } if(typeof showMessage == "boolean" && showMessage == true){ console.log(message); } } return; } /** Prints a professional string of CSS This method takes no parameters and returns a string for entire css file. @param {*} finalStyles is the parameter that determines smooth work. @returns No value returned if finalStyles is undefined */ toString(){ let final = "\t"; if(this.finalStyles != undefined){ let r = this.finalStyles; for(let i = 0; i < r.length; i++){ if(r[i].selector.length == 1){ final += r[i].selector[0]; } else if(r[i].selector.length > 1){ final += r[i].selector.join(', '); } final += '{'; for(let s in r[i].selector_style){ let style_s = r[i].selector_style[s]; if(typeof style_s == "string" && s != "o"){ if(s != "o"){ final += `\n\t\t${ s }:${ r[i].selector_style[s] };\t`; } else if(s == "o"){ final += `\n\t\t${ r[i].selector_style[s] };\t`; } } else if(Array.isArray(style_s)){ final += `\n\t\t${ s }:${ r[i].selector_style[s].join(', ') };\t`; } } final += '\n\t}\n\t\n\t'; } return final; } return; } }
JavaScript
class Matrix { static scalarMultiply(matrix1, matrix2) { const scalar1 = matrix1.reduce(function(a, b) { return a.concat(b); }); const scalar2 = matrix2.reduce(function(a, b) { return a.concat(b); }); let result = 0; for( let i=0; i < scalar1.length; ++i ) { result += scalar1[i] * scalar2[i]; } return result } static makeUnitMatrix(rows, columns) { const arr = []; for (let i = 0; i < rows; i++) { arr[i] = []; for (let j = 0; j < columns; j++) { arr[i][j] = 1; } } return arr; } static fromArray(arr, size) { const res = []; for (let i = 0; i < arr.length; i = i + size) res.push(arr.slice(i, i + size)); return res; } static T(matrix) { const m = matrix.length, n = matrix[0].length, AT = []; for (let i = 0; i < n; i++) { AT[i] = []; for (let j = 0; j < m; j++) AT[i][j] = matrix[j][i]; } return AT; } static unitMatrixMinus(matrix) { const unitMatrix = this.makeUnitMatrix(matrix.length, matrix[0].length); return this.subtract(unitMatrix, matrix); } static multiply(A, B) { const rowsA = A.length, colsA = A[0].length, rowsB = B.length, colsB = B[0].length, C = []; if (colsA !== rowsB) throw new Error('matrix multiply colsA !== rowsB'); for (let i = 0; i < rowsA; i++) C[i] = []; for (let k = 0; k < colsB; k++) { for (let i = 0; i < rowsA; i++) { let t = 0; for (let j = 0; j < rowsB; j++) t += A[i][j] * B[j][k]; C[i][k] = t; } } return C; }; static subtract(matrix1, matrix2) { const minusMatrix2 = this.multiplyNumber(-1, matrix2); return this.sum(matrix1, minusMatrix2); } static sum(matrix1, matrix2) { const m = matrix1.length, n = matrix1[0].length, C = []; for (let i = 0; i < m; i++) { C[i] = []; for (let j = 0; j < n; j++) { C[i][j] = matrix1[i][j] + matrix2[i][j]; } } return C; } static multiplyNumber(a, A) { const m = A.length, n = A[0].length, B = []; for (let i = 0; i < m; i++) { B[i] = []; for (let j = 0; j < n; j++) { B[i][j] = a * A[i][j]; } } return B; } static random(rows, columns) { const arr = []; for (let i = 0; i < rows; i++) { arr[i] = []; for (let j = 0; j < columns; j++) { arr[i][j] = Math.random() - 0.5; } } return arr; }; static forEachIn(matrix, func) { for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { matrix[i][j] = func(matrix[i][j]) } } return matrix; } }
JavaScript
class UserPreference { constructor(storageName, uiElementName, defaultValue) { this.storageName = storageName; this.uiElementName = uiElementName; this.value = defaultValue; } getUiElement() { return document.getElementById(this.uiElementName); } writeToLocalStorage() { window.localStorage.setItem(this.storageName, this.value); } }
JavaScript
class UserPreferences { constructor() { this.preferences = []; this.addPreference("removeDuplicateImages", "removeDuplicateImages", false); this.addPreference("includeImageSourceUrl", "includeImageSourceUrlCheckboxInput", true); this.addPreference("higestResolutionImages", "higestResolutionImagesCheckboxInput", true); this.addPreference("unSuperScriptAlternateTranslations", "unSuperScriptCheckboxInput", false); this.addPreference("styleSheet", "stylesheetInput", EpubMetaInfo.getDefaultStyleSheet()); this.addPreference("useSvgForImages", "useSvgForImagesInput", true); this.addPreference("advancedOptionsVisibleByDefault", "advancedOptionsVisibleByDefaultCheckbox", false); this.addPreference("writeErrorHistoryToFile", "writeErrorHistoryToFileCheckbox", false); this.addPreference("createEpub3", "createEpub3Checkbox", false); this.addPreference("chaptersPageInChapterList", "chaptersPageInChapterListCheckbox", false); this.observers = []; }; /** @private */ addPreference(storageName, uiElementName, defaultValue) { if (this[storageName] !== undefined) { throw new Error("Preference " + storageName + " already created."); } let preference = null; if (typeof(defaultValue) === "boolean") { preference = new BoolUserPreference(storageName, uiElementName, defaultValue) } else if (typeof(defaultValue) === "string") { preference = new StringUserPreference(storageName, uiElementName, defaultValue) } else { throw new Error("Unknown preference type"); } this.preferences.push(preference); this[storageName] = preference; } static readFromLocalStorage() { let newPreferences = new UserPreferences(); for(let p of newPreferences.preferences) { p.readFromLocalStorage(); } return newPreferences; } writeToLocalStorage() { for(let p of this.preferences) { p.writeToLocalStorage(); } } addObserver(observer) { this.observers.push(observer); this.notifyObserversOfChange(); } readFromUi() { for(let p of this.preferences) { p.readFromUi(); } this.writeToLocalStorage(); this.notifyObserversOfChange(); } notifyObserversOfChange() { let that = this; for(let observer of that.observers) { observer.onUserPreferencesUpdate(that); }; } writeToUi() { for(let p of this.preferences) { p.writeToUi(); } } hookupUi() { let readFromUi = this.readFromUi.bind(this); for(let p of this.preferences) { p.hookupUi(readFromUi); } this.notifyObserversOfChange(); } }
JavaScript
class JoyFeeling extends Ball { constructor(feelData, font) { super(feelData, new THREE.Vector3(THREE.Math.randFloatSpread(4), THREE.Math.randFloatSpread(4), 0), 3, 0xffeb03, font); this.material.opacity = 200; } runIt() { this.mouseOver(); this.flock(); this.updatePlaneCollision();//Move this? this.move(); this.special(); this.allGather(); }; flock() { this.separationBehavior(10); this.cohesionBehavior(0.002); this.alignBehavior(0.0005); }; move() { this.speed.add(this.acc); //ad acceleration to velocity(speed) this.speed.clampScalar(-3, 3); if (mousePressed && this.isOver) { this.tryToEscape(); } else if (this.isOver) { //Reduce velocity this.mesh.position.add(this.speed.divideScalar(1.2)); } else { //no reduction of speed this.mesh.position.add(this.speed); } //Move eractic this.acc.set(THREE.Math.randFloatSpread(.5), THREE.Math.randFloatSpread(.5), 0); //console.log('mesh pos x: '+this.mesh.position.x+' y: '+this.mesh.position.y); }; allGather() { if (gatherAll) { for (let i = 0; i < joyFeels.length; i++) { //walk through GeneralFeelings let steer = new THREE.Vector3(0, 0, 0); steer.subVectors(joyFeels[i].mesh.position, this.mesh.position); steer.normalize(); steer.multiplyScalar(0.01); this.acc.add(steer); this.separationBehavior(1); } } }; special() { let curiosity = false; let inside = false; let easing = 0.015; let targetX = mouse.x, targetY = mouse.y; let dx = targetX - this.mesh.position.x; // x catheter let dy = targetY - this.mesh.position.y; // y catheter if (Math.abs(mouse.x) > 0 && Math.abs(mouse.x) < maxwidth && Math.abs(mouse.y) > 0 && Math.abs(mouse.y) < maxheight) { inside = true; //Inside window } else { inside = false; } if (Math.abs(dx) > 1 && Math.abs(dx) < 190 && Math.abs(dy) > 1 && Math.abs(dy) < 190) { curiosity = true; } if ((inside) && (curiosity)) { this.mesh.position.x += dx * easing; this.mesh.position.y += dy * easing; this.mesh.position.z = 0; } } }
JavaScript
class FearFeeling extends Ball { constructor(feelData, font) { super(feelData,new THREE.Vector3(THREE.Math.randFloatSpread(2), THREE.Math.randFloatSpread(2), 0), 3, 0x03FFB1, font); } runIt() { this.mouseOver(); this.flock(); this.updatePlaneCollision();//Move this? this.move(); this.allGather(); }; flock() { this.separationBehavior(5); this.cohesionBehavior(0.4); this.alignBehavior(0); }; move() { this.speed.add(this.acc); //ad acceleration to velocity(speed) this.speed.clampScalar(-3, 3); if (mousePressed && this.isOver) { this.tryToEscape(); } else if (this.isOver) { //Reduce velocity this.mesh.position.add(this.speed.divideScalar(1.5)); } else { //no reduction of speed this.mesh.position.add(this.speed); } //Move eractic this.acc.set(THREE.Math.randFloatSpread(.5), THREE.Math.randFloatSpread(.5), 0); }; allGather() { if (gatherAll) { for (let i = 0; i < fearFeels.length; i++) { //walk through GeneralFeelings let steer = new THREE.Vector3(); steer.subVectors(fearFeels[i].mesh.position, this.mesh.position); steer.normalize(); steer.multiplyScalar(0.5); this.acc.add(steer); this.separationBehavior(15); } } }; }
JavaScript
class LoveFeeling extends Ball { constructor(feelData, font) { super(feelData, new THREE.Vector3(THREE.Math.randFloatSpread(6), THREE.Math.randFloatSpread(6), 0), 3, 0xcc0099, font); } runIt() { this.mouseOver(); this.flock(); this.updatePlaneCollision();//Move this? this.move(); this.allGather(); }; flock() { //console.log(this.mesh.userData.text); this.separationBehavior(1); this.cohesionBehavior(0.05); this.alignBehavior(0.00001); }; move() { this.speed.add(this.acc); //ad acceleration to velocity(speed) //TODO: set boundary for speed.... this.speed.clampScalar(-3, 3); if (mousePressed && this.isOver) { this.tryToEscape(); } else if (this.isOver) { //Reduce velocity this.mesh.position.add(this.speed.divideScalar(2)); } else { //no reduction of speed this.mesh.position.add(this.speed); } //Move eractic this.acc.set(THREE.Math.randFloatSpread(.5), THREE.Math.randFloatSpread(.5), 0); }; }
JavaScript
class GeneralFeeling extends Ball { constructor(feelData, font) { super(feelData, new THREE.Vector3(THREE.Math.randFloatSpread(3), THREE.Math.randFloatSpread(3), 0), 3, 0xffffff, font); } runIt() { this.mouseOver(); this.flock(); this.updatePlaneCollision();//Move this? this.move(); this.allGather(); }; flock() { //TODO: gathering while mouse button pressed! (mousePressed && this.isOver) ? gatherGeneral = true : gatherGeneral = false; if (gatherGeneral) { let steer = new THREE.Vector3(mouse.x, mouse.y, 0); steer.sub(this.mesh.position); steer.multiplyScalar(0.005); this.acc.add(steer); } //kör funktionerna separation, cohesion och align från klassen Boll //generella bollar har låg separation och cohesion för att mest glida omkring som en "normal" boll //de har även viss alignment för att ta efter andra bollars riktning //console.log(this.mesh.userData.text); this.separationBehavior(2); this.cohesionBehavior(0.004); this.alignBehavior(0.00001); }; move() { this.speed.add(this.acc); //ad acceleration to velocity(speed) //TODO: set boundary for speed.... this.speed.clampScalar(-3, 3); if (mousePressed && this.isOver) { this.tryToEscape(); } else if (this.isOver) { //Reduce velocity this.mesh.position.add(this.speed.divideScalar(2)); } else { //no reduction of speed this.mesh.position.add(this.speed); } //Move eractic this.acc.set(THREE.Math.randFloatSpread(.2), THREE.Math.randFloatSpread(.2), 0); }; //Om gatherAll är true så söker alla generella bollar sig till varandra allGather() { if (gatherAll) { for (let i = 0; i < generalFeels.length; i++) { //walk through GeneralFeelings let steer = new THREE.Vector3(); steer.subVectors(generalFeels[i].mesh.position, this.mesh.position); steer.normalize(); steer.multiplyScalar(0.05); this.acc.add(steer); this.separationBehavior(30); } } }; }
JavaScript
class Warrior { constructor(health,stamina) { this.health = health; this.stamina = stamina; } energy() { console.log('CLASS DECLARATION'); console.log(`Health: ${this.health}%`); console.log(`Stamina: ${this.stamina}%`); } }
JavaScript
class CDGContext { constructor () { this.init() } init () { this.hOffset = 0 this.vOffset = 0 this.keyColor = null // clut index this.bgColor = null // clut index this.clut = new Array(16).fill([0, 0, 0]) // color lookup table this.pixels = new Uint8ClampedArray(this.WIDTH * this.HEIGHT).fill(0) this.buffer = new Uint8ClampedArray(this.WIDTH * this.HEIGHT).fill(0) this.imageData = new ImageData(this.WIDTH, this.HEIGHT) // informational this.backgroundRGBA = [0, 0, 0, 0] this.contentBounds = [0, 0, 0, 0] // x1, y1, x2, y2 } setCLUTEntry (index, r, g, b) { this.clut[index] = [r, g, b].map(c => c * 17) } renderFrame ({ forceKey = false } = {}) { const [left, top, right, bottom] = [0, 0, this.WIDTH, this.HEIGHT] let [x1, y1, x2, y2] = [this.WIDTH, this.HEIGHT, 0, 0] // content bounds let isContent = false for (let y = top; y < bottom; y++) { for (let x = left; x < right; x++) { // Respect the horizontal and vertical offsets for grabbing the pixel color const px = ((x - this.hOffset) + this.WIDTH) % this.WIDTH const py = ((y - this.vOffset) + this.HEIGHT) % this.HEIGHT const pixelIndex = px + (py * this.WIDTH) const colorIndex = this.pixels[pixelIndex] const [r, g, b] = this.clut[colorIndex] const isKeyColor = colorIndex === this.keyColor || (forceKey && (colorIndex === this.bgColor || this.bgColor == null)) // Set the rgba values in the image data const offset = 4 * (x + (y * this.WIDTH)) this.imageData.data[offset] = r this.imageData.data[offset + 1] = g this.imageData.data[offset + 2] = b this.imageData.data[offset + 3] = isKeyColor ? 0x00 : 0xff // test content bounds if (!isKeyColor) { isContent = true if (x1 > x) x1 = x if (y1 > y) y1 = y if (x2 < x) x2 = x if (y2 < y) y2 = y } } } // report content bounds, with two tweaks: // 1) if there are no visible pixels, report [0,0,0,0] (isContent flag) // 2) account for size of the rightmost/bottommost pixels in 2nd coordinates (+1) this.contentBounds = isContent || !forceKey ? [x1, y1, x2 + 1, y2 + 1] : [0, 0, 0, 0] // report background status this.backgroundRGBA = this.bgColor === null ? [0, 0, 0, forceKey ? 0 : 1] : [...this.clut[this.bgColor], this.bgColor === this.keyColor || forceKey ? 0 : 1] } }
JavaScript
class VideoBuffer { constructor(numFrames) { this.numFrames = numFrames; } /** * Add a frame to the video buffer. * Should be called at 8 fps since that's what the model was trained for. * @param {Tensor} frame A tensor [128, 128, 3] representing the frame. */ updateWithFrame(frame) { // Add the frame if (frame == null) { return false; } if (this.frames == null) { this.frames = tf.keep(frame.expandDims(0)); } else { const oldFrames = this.frames; this.frames = tf.keep(oldFrames.concat(frame.expandDims(0), 0)); oldFrames.dispose(); } // Remove oldest frame if buffer is already full if (this.frames.shape[0] > this.numFrames) { const oldFrames = this.frames; this.frames = tf.keep(oldFrames.slice([1, 0, 0, 0], this.numFrames)) oldFrames.dispose(); } return this.frames.shape[0] == this.numFrames } }
JavaScript
class Editor { constructor(props = {}) { const { slices = [] } = props; this.props = props; this.state = { slices }; this.handleChop = this.handleChop.bind(this); this.updateChildren = this.updateChildren.bind(this); this.children = { canvas: new Canvas({ ...this.props, showMask: this.isShowCanvasMask(), onLoad: this.updateChildren }) }; this.el = this.render(); return this; } destroy() { Object.keys(this.children).forEach(key => { if (this.children[key].destroy) { this.children[key].destroy(); } }); } /** * Return true if mask should be visible. Based on at least once slice. * @returns {boolean} of mask state */ isShowCanvasMask() { return Boolean(this.props.slices.length); } /** * Handler for Chop Action */ handleChop() { const { image, files, onChop, slices } = this.props; const sliceRects = slices.map(slice => { if (slice.props.rect) { return slice.props.rect; } if (slice.getRect) { return slice.getRect(); } if (slice.rect) { return slice.rect; } }); if (image, onChop) { onChop(files, sliceRects); } } setState(state) { this.state = { ...this.state, ...state }; this.updateDOM(); } setProps(props) { this.props = { ...this.props, ...props } this.updateDOM(); } updateDOM() { this.children.canvas.setProps({ showMask: this.isShowCanvasMask() }); this.el = Respawn(this.el, this.render()); } updateChildren() { const { canvas } = this.children; this.children = { header: new Header({ ...this.props, onChop: this.handleChop }), canvas, sliceManager: new SliceManager({ ...this.props, canvas }) }; this.el = Respawn(this.el, this.render()); } render() { return Spawn({ className: 'editor', children: Object.keys(this.children).map(key => this.children[key].el) }); } }
JavaScript
class Store { constructor () { this.listeners = new Set([]); this.data = {}; } subscribe (listener) { this.listeners.add(listener); } unsubscribe (listener) { this.listeners.delete(listener); } notify (...args) { this.listeners.forEach(listener => { listener(...args); }); } /** * Conditionally update the data in state and notify subscribers. * * Can be forced to update and notify by passing force=<SOMETHING TRUTHY> * */ update ( data, force=false ) { if ( !this.deepEqual(data, this.data) || force == true ) { Object.assign(this.data, data); this.notify(); } else { // pass } } /** * Compare to objects for equality. * * Simple approach using JSON.stringify */ deepEqual (obj1, obj2) { const _obj1 = JSON.stringify(obj1, Object.keys(obj1).sort()); const _obj2 = JSON.stringify(obj2, Object.keys(obj1).sort()); return _obj1 === _obj2; } }
JavaScript
class PDP11Dbg extends Debugger { /** * PDP11Dbg(idMachine, idDevice, config) * * @this {PDP11Dbg} * @param {string} idMachine * @param {string} idDevice * @param {Config} [config] */ constructor(idMachine, idDevice, config) { super(idMachine, idDevice, config); this.opTable = PDP11Dbg.OPTABLE; this.aOpReserved = []; if (this.cpu.model < PDP11.MODEL_1140) { this.aOpReserved = this.aOpReserved.concat(PDP11Dbg.OP1140); } if (this.cpu.model < PDP11.MODEL_1145) { this.aOpReserved = this.aOpReserved.concat(PDP11Dbg.OP1145); } this.maxOpcodeLength = 6; } /** * unassemble(address, opcodes, annotation) * * Overrides Debugger's default unassemble() function with one that understands PDP-11 instructions. * * @this {PDP11Dbg} * @param {Address} address (advanced by the number of processed opcodes) * @param {Array.<number>} opcodes (each processed opcode is shifted out, reducing the size of the array) * @param {string} [annotation] (optional string to append to the final result) * @returns {string} */ unassemble(address, opcodes, annotation) { let sAddr = this.dumpAddress(address), sWords = ""; let sLabel = this.getSymbolName(address, Debugger.SYMBOL.LABEL); let sComment = this.getSymbolName(address, Debugger.SYMBOL.COMMENT); /** * toBaseWord(word) * * @param {number} word * @returns {string} */ let toBaseWord = (word) => this.toBase(word, 0, 16, ""); /** * getNextWord() * * @returns {number} */ let getNextWord = () => { let word = opcodes.shift() | (opcodes.shift() << 8); sWords += toBaseWord(word) + ' '; this.addAddress(address, 2); return word; }; /** * getOperand(opcode, type) * * If getOperand() returns an Array rather than a string, then the first element is the original * operand, and the second element is a comment containing additional information (eg, the target) * of the operand. * * @param {number} opcode * @param {number} type * @returns {string|Array.<string>} */ let getOperand = (opcode, type) => { /** * Take care of OP_OTHER opcodes first; then all we'll have to worry about * next are OP_SRC or OP_DST opcodes. */ let sOperand = ""; let disp; let addr; let typeOther = type & PDP11Dbg.OP_OTHER; if (typeOther == PDP11Dbg.OP_BRANCH) { disp = ((opcode & 0xff) << 24) >> 23; addr = (address.off + disp) & 0xffff; sOperand = toBaseWord(addr); } else if (typeOther == PDP11Dbg.OP_DSTOFF) { disp = (opcode & 0x3f) << 1; addr = (address.off - disp) & 0xffff; sOperand = toBaseWord(addr); } else if (typeOther == PDP11Dbg.OP_DSTNUM3) { disp = (opcode & 0x07); sOperand = this.toBase(disp, 0, 3, ""); } else if (typeOther == PDP11Dbg.OP_DSTNUM6) { disp = (opcode & 0x3f); sOperand = this.toBase(disp, 0, 6, ""); } else if (typeOther == PDP11Dbg.OP_DSTNUM8) { disp = (opcode & 0xff); sOperand = this.toBase(disp, 0, 8, ""); } else { /** * Isolate all OP_SRC or OP_DST bits from opcode in the mode variable. */ let mode = opcode & type; /** * Convert OP_SRC bits into OP_DST bits, since they use the same format. */ if (type & PDP11Dbg.OP_SRC) { mode >>= 6; type >>= 6; } if (type & PDP11Dbg.OP_DST) { let wIndex; let sTarget = null; let reg = mode & PDP11Dbg.OP_DSTREG; /** * Note that opcodes that specify only REG bits in the type mask (ie, no MOD bits) * will automatically default to OPMODE_REG below. */ switch((mode & PDP11Dbg.OP_DSTMODE)) { case PDP11.OPMODE.REG: // 0x0: REGISTER sOperand = getRegName(reg); break; case PDP11.OPMODE.REGD: // 0x1: REGISTER DEFERRED sOperand = '@' + getRegName(reg); sTarget = getTarget(this.cpu.regsGen[reg]); break; case PDP11.OPMODE.POSTINC: // 0x2: POST-INCREMENT if (reg < 7) { sOperand = '(' + getRegName(reg) + ")+"; } else { /** * When using R7 (aka PC), POST-INCREMENT is known as IMMEDIATE */ wIndex = getNextWord(); sOperand = '#' + toBaseWord(wIndex); } break; case PDP11.OPMODE.POSTINCD: // 0x3: POST-INCREMENT DEFERRED if (reg < 7) { sOperand = "@(" + getRegName(reg) + ")+"; } else { /** * When using R7 (aka PC), POST-INCREMENT DEFERRED is known as ABSOLUTE */ wIndex = getNextWord(); sOperand = "@#" + toBaseWord(wIndex); sTarget = getTarget(wIndex); } break; case PDP11.OPMODE.PREDEC: // 0x4: PRE-DECREMENT sOperand = "-(" + getRegName(reg) + ")"; break; case PDP11.OPMODE.PREDECD: // 0x5: PRE-DECREMENT DEFERRED sOperand = "@-(" + getRegName(reg) + ")"; break; case PDP11.OPMODE.INDEX: // 0x6: INDEX wIndex = getNextWord(); sOperand = toBaseWord(wIndex) + '(' + getRegName(reg) + ')'; if (reg == 7) { /** * When using R7 (aka PC), INDEX is known as RELATIVE. However, instead of displaying * such an instruction like this: * * 016156: 010167 001300 MOV R1,1300(PC) ; @017462 * * with the effective address display to the far right, let's display it like this instead: * * 016156: 010167 001300 MOV R1,017462 * * because you can still clearly see PC-relative offset (eg, 001300) as part of the disassembly. * * sOperand = [sOperand, toBaseWord((wIndex + address.off) & 0xffff)]; */ sOperand = toBaseWord(wIndex = (wIndex + address.off) & 0xffff); sTarget = getTarget(wIndex); } break; case PDP11.OPMODE.INDEXD: // 0x7: INDEX DEFERRED wIndex = getNextWord(); sOperand = '@' + toBaseWord(wIndex) + '(' + getRegName(reg) + ')'; if (reg == 7) { /** * When using R7 (aka PC), INDEX DEFERRED is known as RELATIVE DEFERRED. And for the same * reasons articulated above, we now display the effective address inline. * * sOperand = [sOperand, toBaseWord((wIndex + address.off) & 0xffff)]; */ sOperand = '@' + toBaseWord(wIndex = (wIndex + address.off) & 0xffff); sTarget = getTarget(this.cpu.readWordSafe(wIndex)); } break; default: this.assert(false); break; } if (sTarget) sOperand = [sOperand, sTarget]; } else { this.assert(false); } } return sOperand; }; /** * getRegName(iReg) * * @param {number} iReg (normally 0-7) * @returns {string} */ let getRegName = (iReg) => PDP11Dbg.REGNAMES[iReg] || "?"; /** * getTarget(addr) * * @param {number} addr * @returns {string|null} */ let getTarget = (addr) => { let a = this.cpu.getAddrInfo(addr); let addrPhysical = a[0]; // if (addrPhysical >= this.cpu.addrIOPage && addrPhysical < this.bus.addrIOPage) { // addrPhysical = (addrPhysical - this.cpu.addrIOPage) + this.bus.addrIOPage; // } return null; // TODO: this.bus.getAddrInfo(addrPhysical); }; let opcode = getNextWord(); let opDesc, opNames = PDP11Dbg.OPNAMES; for (let mask in this.opTable) { let opMasks = this.opTable[mask]; opDesc = opMasks[opcode & mask]; if (opDesc) break; } if (!opDesc) opDesc = PDP11Dbg.OPNONE; let opNum = opDesc[0]; if (this.aOpReserved.indexOf(opNum) >= 0) { opDesc = PDP11Dbg.OPNONE; opNum = opDesc[0]; } let sOpcode = opNames[opNum]; let sOperands = "", sTarget = ""; let cOperands = opDesc.length - 1; if (!opNum && !cOperands) sOperands = toBaseWord(opcode); for (let iOperand = 1; iOperand <= cOperands; iOperand++) { let type = opDesc[iOperand]; if (type == undefined) continue; let sOperand = getOperand(opcode, type); if (!sOperand || !sOperand.length) { sOperands = "INVALID"; break; } /** * If getOperand() returns an Array rather than a string, then the first element is the original * operand, and the second element contains additional information (eg, the target) of the operand. */ if (typeof sOperand != "string") { sTarget = sOperand[1]; sOperand = sOperand[0]; } if (sOperands.length > 0) sOperands += ','; sOperands += (sOperand || "???"); } let result = this.sprintf("%s %-21s %-7s %s", sAddr, sWords, sOpcode, sOperands); if (!annotation) { if (sComment) annotation = sComment; } else { if (sComment) annotation += " " + sComment; } if (annotation) result = this.sprintf("%-32s; %s", result, annotation); if (sLabel) result = sLabel + ":\n" + result; return result + "\n"; } }
JavaScript
class WebGLPointsLayer extends Layer { /** * @param {Options} options Options. */ constructor(options) { const baseOptions = assign({}, options); super(baseOptions); /** * @private * @type {import('../webgl/ShaderBuilder.js').StyleParseResult} */ this.parseResult_ = parseLiteralStyle(options.style); /** * @private * @type {boolean} */ this.hitDetectionDisabled_ = !!options.disableHitDetection; } /** * @inheritDoc */ createRenderer() { return new WebGLPointsLayerRenderer(this, { vertexShader: this.parseResult_.builder.getSymbolVertexShader(), fragmentShader: this.parseResult_.builder.getSymbolFragmentShader(), hitVertexShader: !this.hitDetectionDisabled_ && this.parseResult_.builder.getSymbolVertexShader(true), hitFragmentShader: !this.hitDetectionDisabled_ && this.parseResult_.builder.getSymbolFragmentShader(true), uniforms: this.parseResult_.uniforms, attributes: this.parseResult_.attributes }); } /** * * @inheritDoc */ disposeInternal() { this.renderer_.dispose(); super.disposeInternal(); } }
JavaScript
class NetplanConfigurator { /** * @description Netplan configurator object * @param {String} dirPath Path do netplan directory * @param {String} fileName File name with configuration */ constructor( dirPath = "/etc/netplan", fileName = "00-installer-config.yaml", applyCommand = "netplan apply" ) { this._dirPath = dirPath; this._fileName = fileName; this._interfaces = {}; this._applyCommand = applyCommand; } /** * @description Path do netplan directory */ get DirPath() { return this._dirPath; } /** * @description File name containing configuration */ get FileName() { return this._fileName; } /** * @description Interfaces from content */ get Interfaces() { return this._interfaces; } /** * @description Command invoked when applied settings */ get ApplyCommand() { return this._applyCommand; } /** * @description Method for loading all data from netplan config file - if file does not exists, content will remaing empty */ async Load() { await this._loadInterfaces(); } /** * @description Method for loading whole content from file to configurator and set interfaces based on this content */ async _loadInterfaces() { let content = await this._getContentFromFile(); //Clear interfaces this._interfaces = {}; //If content is proper - create,initialzie and add interface for every network ethernet if (content && content.network && content.network.ethernets) { let allNetworkEthernetNames = Object.keys(content.network.ethernets); for (let networkEthernetName of allNetworkEthernetNames) { let networkEthernetConfiguration = content.network.ethernets[networkEthernetName]; let networkNetplanConfiguration = new NetplanInterfaceConfiguration( networkEthernetName ); networkNetplanConfiguration.InitFromNetplanPayload( networkEthernetConfiguration ); this._interfaces[networkEthernetName] = networkNetplanConfiguration; } } } /** * @description Method for getting content from file - returns null if there is no file */ async _getContentFromFile() { //Exit stright away if there was no dir path specified if (!this.DirPath) return null; //Exit stright away if there was no file name if (!this.FileName) return null; //Exit stright away if dir does not exists let dirExists = await checkIfDirectoryExistsAsync(this.DirPath); if (!dirExists) return null; //Exit stright away if file does not exists let filePath = path.join(this.DirPath, this.FileName); let fileExists = await checkIfFileExistsAsync(filePath); if (!fileExists) return null; let yamlContent = await readFileAsync(filePath, "utf8"); return convertYamlToJSON(yamlContent); } /** * @description Method for saving all configuration to netplan config file */ async Save() { await this._saveInterfaces(); } /** * @description Method for saving all interface configurations to config file */ async _saveInterfaces() { let payload = this.NetplanPayload; let yamlPayload = convertJSONToYaml(payload); let filePath = path.join(this.DirPath, this.FileName); await writeFileAsync(filePath, yamlPayload, "utf8"); } /** * @description Method for applying changes to netplan - calls command "netplan appy" */ async ApplyChanges() { await execAsync(this.ApplyCommand); } /** * @description Payload of netplan file in JSON */ get NetplanPayload() { let payloadToReturn = { network: { version: 2, ethernets: {}, }, }; for (let netInterface of Object.values(this.Interfaces)) { payloadToReturn.network.ethernets[netInterface.Name] = netInterface.NetplanPayload; } return payloadToReturn; } /** * @description Payload of configuration object */ get Payload() { let payloadToReturn = { dirPath: this.DirPath, fileName: this.FileName, interfaces: Object.values(this.Interfaces).map( (netInterface) => netInterface.Payload ), }; return payloadToReturn; } /** * @description Method for validation if given payload is a valid netplan configurator payload * @param {JSON} payload Payload to check */ _validatePayload(payload) { return NetplanConfiguratorSchema.validate(payload, { abortEarly: true, }); } /** * @description Method for updating netplan configuration - DOES NOT CHANGE NETPLAN FILE AUTOMATICALLY, Throws if payload is invalid * @param {JSON} payload Payload to check */ Update(payload) { let validationResult = this._validatePayload(payload); if (validationResult.error) throw new Error(validationResult.error.message); let validatedPayload = validationResult.value; this._dirPath = validatedPayload.dirPath; this._fileName = validatedPayload.fileName; this._interfaces = {}; for (let netInterPayload of validatedPayload.interfaces) { let netInter = new NetplanInterfaceConfiguration(netInterPayload.name); netInter.InitFromPayload(netInterPayload); this._interfaces[netInter.Name] = netInter; } } }
JavaScript
class MaterialUtils { /** * Adds the provided material to the provided materials object if the material does not exists. * Use force override existing material. * * @param {object.<string, Material>} materialsObject * @param {Material} material * @param {string} materialName * @param {boolean} force * @param {boolean} [log] Log messages to the console */ static addMaterial( materialsObject, material, materialName, force, log ) { let existingMaterial; // ensure materialName is set material.name = materialName; if ( ! force ) { existingMaterial = materialsObject[ materialName ]; if ( existingMaterial ) { if ( existingMaterial.uuid !== existingMaterial.uuid ) { if ( log ) console.log( 'Same material name "' + existingMaterial.name + '" different uuid [' + existingMaterial.uuid + '|' + material.uuid + ']' ); } } else { materialsObject[ materialName ] = material; if ( log ) console.info( 'Material with name "' + materialName + '" was added.' ); } } else { materialsObject[ materialName ] = material; if ( log ) console.info( 'Material with name "' + materialName + '" was forcefully overridden.' ); } } /** * Transforms the named materials object to an object with named jsonified materials. * * @param {object.<string, Material>} * @returns {Object} Map of Materials in JSON representation */ static getMaterialsJSON ( materialsObject ) { const materialsJSON = {}; let material; for ( const materialName in materialsObject ) { material = materialsObject[ materialName ]; if ( typeof material.toJSON === 'function' ) { materialsJSON[ materialName ] = material.toJSON(); } } return materialsJSON; } /** * Clones a material according the provided instructions. * * @param {object.<String, Material>} materials * @param {object} materialCloneInstruction * @param {boolean} [log] */ static cloneMaterial ( materials, materialCloneInstruction, log ) { let material; if ( materialCloneInstruction ) { let materialNameOrg = materialCloneInstruction.materialNameOrg; materialNameOrg = ( materialNameOrg !== undefined && materialNameOrg !== null ) ? materialNameOrg : ''; const materialOrg = materials[ materialNameOrg ]; if ( materialOrg ) { material = materialOrg.clone(); Object.assign( material, materialCloneInstruction.materialProperties ); MaterialUtils.addMaterial( materials, material, materialCloneInstruction.materialProperties.name, true ); } else { if ( log ) console.info( 'Requested material "' + materialNameOrg + '" is not available!' ); } } return material; } }
JavaScript
class Dropdown extends PureComponent { static propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func, data: PropTypes.object.isRequired, className: PropTypes.string, style: PropTypes.object, isEnabled: PropTypes.bool }; static defaultProps = { className: '', style: {}, isEnabled: true, onChange: () => {} }; state = { hasFocus: false, isHovered: false }; _onMouseEnter = () => this.setState({isHovered: true}); _onMouseLeave = () => this.setState({isHovered: false}); _onFocus = () => this.setState({hasFocus: true}); _onBlur = () => this.setState({hasFocus: false}); _onChange = event => { const {onChange} = this.props; onChange(event.target.value); }; render() { const {theme, style, className, data, value, isEnabled} = this.props; const {height = theme.controlSize + theme.spacingTiny * 2} = style; const styleProps = { theme, height, hasFocus: this.state.hasFocus, isHovered: this.state.isHovered, isEnabled }; return ( <WrapperComponent className={className} userStyle={style.wrapper} {...styleProps}> <DropdownBorder userStyle={style.border} {...styleProps} onMouseEnter={this._onMouseEnter} onMouseLeave={this._onMouseLeave} > <DropdownInput userStyle={style.select} {...styleProps} tabIndex={isEnabled ? 0 : -1} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} value={value} > {Object.keys(data).map(key => ( <option key={key} value={key}> {data[key]} </option> ))} </DropdownInput> <DropdownIcon userStyle={style.icon} {...styleProps}> {style.iconArrow || <DefaultDropdownIcon />} </DropdownIcon> </DropdownBorder> </WrapperComponent> ); } }
JavaScript
class WAConnection extends _4_Events_1.WAConnection { constructor() { super(...arguments); /** * Query whether a given number is registered on WhatsApp * @param str phone number/jid you want to check for * @returns undefined if the number doesn't exists, otherwise the correctly formatted jid */ this.isOnWhatsApp = async (str) => { if (this.state !== 'open') { return this.isOnWhatsAppNoConn(str); } const { status, jid, biz } = await this.query({ json: ['query', 'exist', str], requiresPhoneConnection: false }); if (status === 200) return { exists: true, jid: Utils_1.whatsappID(jid), isBusiness: biz }; }; /** * Query whether a given number is registered on WhatsApp, without needing to open a WS connection * @param str phone number/jid you want to check for * @returns undefined if the number doesn't exists, otherwise the correctly formatted jid */ this.isOnWhatsAppNoConn = async (str) => { let phone = str.split('@')[0]; const url = `https://wa.me/${phone}`; const response = await this.fetchRequest(url, 'GET', undefined, undefined, undefined, false); const loc = response.headers.location; if (!loc) { this.logger.warn({ url, status: response.statusCode }, 'did not get location from request'); return; } const locUrl = new url_1.URL('', loc); if (!locUrl.pathname.endsWith('send/')) { return; } phone = locUrl.searchParams.get('phone'); return { exists: true, jid: `${phone}@s.whatsapp.net` }; }; /** * Tell someone about your presence -- online, typing, offline etc. * @param jid the ID of the person/group who you are updating * @param type your presence */ this.updatePresence = (jid, type) => this.sendBinary(['action', { epoch: this.msgCount.toString(), type: 'set' }, [['presence', { type: type, to: jid }, null]] ], [Constants_1.WAMetric.presence, Constants_1.WAFlag[type]], // weird stuff WA does undefined, true); /** Request an update on the presence of a user */ this.requestPresenceUpdate = async (jid) => this.query({ json: ['action', 'presence', 'subscribe', jid] }); } /** Query the status of the person (see groupMetadata() for groups) */ async getStatus(jid) { const status = await this.query({ json: ['query', 'Status', jid || this.user.jid], requiresPhoneConnection: false }); return status; } async setStatus(status) { const response = await this.setQuery([ [ 'status', null, Buffer.from(status, 'utf-8') ] ]); this.emit('contact-update', { jid: this.user.jid, status }); return response; } async updateProfileName(name) { const response = (await this.setQuery([ [ 'profile', { name }, null ] ])); if (response.status === 200) { this.user.name = response.pushname; this.emit('contact-update', { jid: this.user.jid, name }); } return response; } /** Get your contacts */ async getContacts() { const json = ['query', { epoch: this.msgCount.toString(), type: 'contacts' }, null]; const response = await this.query({ json, binaryTags: [Constants_1.WAMetric.queryContact, Constants_1.WAFlag.ignore], expect200: true, requiresPhoneConnection: true }); // this has to be an encrypted query return response; } /** Get the stories of your contacts */ async getStories() { const json = ['query', { epoch: this.msgCount.toString(), type: 'status' }, null]; const response = await this.query({ json, binaryTags: [Constants_1.WAMetric.queryStatus, Constants_1.WAFlag.ignore], expect200: true, requiresPhoneConnection: true }); if (Array.isArray(response[2])) { return response[2].map(row => { var _a, _b; return ({ unread: (_a = row[1]) === null || _a === void 0 ? void 0 : _a.unread, count: (_b = row[1]) === null || _b === void 0 ? void 0 : _b.count, messages: Array.isArray(row[2]) ? row[2].map(m => m[2]) : [] }); }); } return []; } /** Fetch your chats */ async getChats() { const json = ['query', { epoch: this.msgCount.toString(), type: 'chat' }, null]; return this.query({ json, binaryTags: [5, Constants_1.WAFlag.ignore], expect200: true }); // this has to be an encrypted query } /** Query broadcast list info */ async getBroadcastListInfo(jid) { return this.query({ json: ['query', 'contact', jid], expect200: true, requiresPhoneConnection: true }); } /** * Load chats in a paginated manner + gets the profile picture * @param before chats before the given cursor * @param count number of results to return * @param searchString optionally search for users * @returns the chats & the cursor to fetch the next page */ loadChats(count, before, options = {}) { var _a; const searchString = (_a = options.searchString) === null || _a === void 0 ? void 0 : _a.toLowerCase(); const chats = this.chats.paginated(before, count, options && (chat => { var _a, _b; return ((typeof (options === null || options === void 0 ? void 0 : options.custom) !== 'function' || (options === null || options === void 0 ? void 0 : options.custom(chat))) && (typeof searchString === 'undefined' || ((_a = chat.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchString)) || ((_b = chat.jid) === null || _b === void 0 ? void 0 : _b.includes(searchString)))); })); const cursor = (chats[chats.length - 1] && chats.length >= count) && this.chatOrderingKey.key(chats[chats.length - 1]); return { chats, cursor }; } /** * Update the profile picture * @param jid * @param img */ async updateProfilePicture(jid, img) { jid = Utils_1.whatsappID(jid); const data = await Utils_1.generateProfilePicture(img); const tag = this.generateMessageTag(); const query = [ 'picture', { jid: jid, id: tag, type: 'set' }, [ ['image', null, data.img], ['preview', null, data.preview] ] ]; const response = await this.setQuery([query], [Constants_1.WAMetric.picture, 136], tag); if (jid === this.user.jid) this.user.imgUrl = response.eurl; else if (this.chats.get(jid)) { this.chats.get(jid).imgUrl = response.eurl; this.emit('chat-update', { jid, imgUrl: response.eurl }); } return response; } /** * Add or remove user from blocklist * @param jid the ID of the person who you are blocking/unblocking * @param type type of operation */ async blockUser(jid, type = 'add') { const json = [ 'block', { type: type, }, [ ['user', { jid }, null] ], ]; const result = await this.setQuery([json], [Constants_1.WAMetric.block, Constants_1.WAFlag.ignore]); if (result.status === 200) { if (type === 'add') { this.blocklist.push(jid); } else { const index = this.blocklist.indexOf(jid); if (index !== -1) { this.blocklist.splice(index, 1); } } // Blocklist update event const update = { added: [], removed: [] }; let key = type === 'add' ? 'added' : 'removed'; update[key] = [jid]; this.emit('blocklist-update', update); } return result; } /** * Query Business Profile (Useful for VCards) * @param jid Business Jid * @returns profile object or undefined if not business account */ async getBusinessProfile(jid) { jid = Utils_1.whatsappID(jid); const { profiles: [{ profile, wid }] } = await this.query({ json: ["query", "businessProfile", [ { "wid": jid.replace('@s.whatsapp.net', '@c.us') } ], 84], expect200: true, requiresPhoneConnection: false, }); return { profile, jid: Utils_1.whatsappID(wid), }; } }
JavaScript
class LinearSegment{ constructor(ps, pe){ this.ps = ps; this.pe = pe; this.len = 0; this.points = [ps, pe]; this.lut = []; } length(){ if(!this.len) this.len = geom.distBetween(this.ps, this.pe); return this.len; } get(t){ t = Math.min(1, Math.max(0, t)); return geom.axpby(1 - t, this.ps, t, this.pe); } derivative(/* t, normalize */){ return geom.axpby(-1, this.ps, 1, this.pe); } tangent(/* t, normalize */){ return geom.unitVector(this.derivative()); } normal(t, normalize = false){ const tn = this.tangent(t, normalize); return geom.rightNormal(tn); } project({ x, y }){ // @see https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment const l2 = this.length() * this.length(); if(l2 == 0) return Object.assign({}, this.ps); const t = Math.max(0, Math.min(1, ((x - this.ps.x) * (this.pe.x - this.ps.x) + (y - this.ps.y) * (this.pe.y - this.ps.y)) / l2 )); const p = this.get(t); p.t = t; // to export t value (like BezierJS) return p; } bbox(){ const bbox = { x: { min: 0, max: 0 }, y: { min: 0, max: 0 } }; if(this.ps.x < this.pe.x){ bbox.x.min = this.ps.x; bbox.x.max = this.pe.x; } else { bbox.x.min = this.pe.x; bbox.x.max = this.ps.x; } if(this.ps.y < this.pe.y){ bbox.y.min = this.ps.y; bbox.y.max = this.pe.y; } else { bbox.y.min = this.pe.y; bbox.y.max = this.ps.y; } return bbox; } split(t1, t2){ assert(t1 !== undefined, 'Invalid arguments'); const p1 = this.get(t1); if(t2 === undefined){ return { left: new LinearSegment(this.ps, p1), right: new LinearSegment(p1, this.pe) }; } else { const p2 = this.get(t2); return new LinearSegment(p1, p2); } } intersects({ p1, p2 }){ // @see https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection const dx = p1.x - p2.x; const dy = p1.y - p2.y; const t_u = (this.ps.x - p1.x) * dy - (this.ps.y - p1.y) * dx; const t_l = (this.ps.x - this.pe.x) * dy - (this.ps.y - this.pe.y) * dx; if(Math.abs(t_l) < 1e-4) return []; // mostly parallel, count as no intersection const t = t_u / t_l; // note: segment is defined as P = this.ps - t * (Dx, Dy) if(geom.between(t, 0, 1)){ // check we are within the boundaries spanned by p1-p2 const mx = Math.min(p1.x, p2.x); const Mx = Math.max(p1.x, p2.x); const my = Math.min(p1.y, p2.y); const My = Math.max(p1.y, p2.y); const p = this.get(t); if(geom.between(p.x, mx, Mx) && geom.between(p.y, my, My)) return [ Math.max(0, Math.min(1, t)) ]; else return []; } else return []; } getLUT(steps = 100){ // same computation as in bezier.js if(this.lut.length === steps) return this.lut; else this.lut = []; steps--; for (let t = 0; t <= steps; t++) { this.lut.push(this.get(t / steps)); } return this.lut; } hull(/* t */){ assert.error('Hull not available on linear segments'); } }
JavaScript
class OptimizationsTransform extends Transform { constructor() { super({ objectMode: true }); this.tablesRegExp = {}; TABLES.forEach((table) => { this.tablesRegExp[table] = new RegExp(`([\\s\\(\\)]|^)${table}\\.([A-Za-z_][A-za-z0-9_]+)`, "g"); }); } /** * Transforms a file. * @param {Object} file The file to process. * @param {string} encoding The encoding of the file. * @param {Function} next A callback function. */ _transform(file, encoding, next) { if (file.isNull()) { return next(null, file); } if (file.isStream()) { streamToBuffer(file.contents, (err, contents) => { if (err) this.emit('error', err); else { const code = contents.toString(encoding); const optimizedCode = this.optimize(code); file.contents = Buffer.from(optimizedCode, encoding); next(null, file); } }); } if (file.isBuffer()) { const code = file.contents.toString(encoding); const optimizedCode = this.optimize(code); file.contents = Buffer.from(optimizedCode, encoding); next(null, file); } } optimize(code) { const locals = []; const memo = new Map(); const seenTables = new Map(); // Localize table members. Localized things are marginally faster. // The impact is especially noticeable inside rendering hooks. TABLES.forEach((table) => { const regexp = this.tablesRegExp[table]; code = code.replace(regexp, (_, whiteSpace, varName) => { const newVarName = `${table}_${varName}`; // Memoize the variable. // We don't need to redeclare it several times. if (!memo.has(newVarName)) { memo.set(newVarName, true); seenTables.set(table, true); locals.push(`local ${newVarName} = ${table}.${varName}`); } return whiteSpace + newVarName; }); }); // Localize whitelisted globals. // Same thing as above really, but slightly different. GLOBALS.forEach((global) => { if (code.indexOf(global) !== -1) { locals.push(`local ${global} = ${global}`); } }) if (locals.length > 0) { // Prepend seen tables. code = Array.from(seenTables.keys()) .map((table) => `local ${table} = ${table} or {}`) .join("\n") + "\n\n" + // Prepend the locals. locals.join("\n") + "\n\n" + code; } return code; } }
JavaScript
class Utils { static hash(input) { var hash = 0, i, chr; if (input.length === 0) return hash; for (i = 0; i < input.length; i++) { chr = input.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; } static typedArrayToGlType(typedArrayType) { return typedArrayToGlTypeMap.get(typedArrayType); } static glTypeToTypedArray(glType) { return glTypeToTypedArrayMap.get(glType) } /** * Converts the given 4x4 mat4 to an array */ static toArray(matrix) { var result = new Array(16); for (var i=0; i<16; i++) { result[i] = matrix[i]; } return result; } /** * Create a new GPU buffer, keep in mind that some extra attributes are being set on the returned GLBuffer object */ static createBuffer(gl, data, numElements, bufferType, components, srcStart, attribType, js_type) { // numElements -> Number of typed elements numElements = numElements || data.length; bufferType = bufferType || gl.ARRAY_BUFFER; components = components || 3; srcStart = srcStart || 0; const b = gl.createBuffer(); gl.bindBuffer(bufferType, b); var js_type = js_type ? js_type : data.constructor.name; const byteCount = numElements * window[js_type].BYTES_PER_ELEMENT; gl.bufferData(bufferType, data, gl.STATIC_DRAW, srcStart, numElements); b.byteSize = byteCount; b.N = numElements; b.gl_type = bufferType; b.js_type = js_type; b.attrib_type = attribType ? attribType : Utils.typedArrayToGlType(b.js_type); b.components = components; b.normalize = false; b.stride = 0; b.offset = 0; return b; } /** * Create a new GPU empty buffer, keep in mind that some extra attributes are being set on the returned GLBuffer object. * This method is usually used in order to create buffers that will be later be filled by calls to bufferSubData (via Utils.updateBuffer) */ static createEmptyBuffer(gl, numElements, bufferType, components, attribType, js_type) { const nrBytesRequired = numElements * window[js_type].BYTES_PER_ELEMENT; bufferType = bufferType || gl.ARRAY_BUFFER; components = components || 3; const b = gl.createBuffer(); gl.bindBuffer(bufferType, b); const byteCount = numElements * window[js_type].BYTES_PER_ELEMENT; // Read the WebGL documentation carefully on this, the interpretation of the size argument depends on the type of "data" gl.bufferData(bufferType, byteCount, gl.STATIC_DRAW); b.byteSize = byteCount; b.N = numElements; b.gl_type = bufferType; b.js_type = js_type; b.attrib_type = attribType ? attribType : Utils.typedArrayToGlType(b.js_type); b.components = components; b.normalize = false; b.stride = 0; b.offset = 0; b.writePosition = 0; return b; } /** * Update a GPU buffer */ static updateBuffer(gl, targetGlBuffer, data, pos, numElements) { gl.bindBuffer(targetGlBuffer.gl_type, targetGlBuffer); const byteCount = numElements * window[targetGlBuffer.js_type].BYTES_PER_ELEMENT; // Read the WebGL documentation carefully on this, the interpretation of the size argument depends on the type of "data" let size = numElements; // Ok for non-typed arrays if (data.constructor.name == "DataView") { size = byteCount; } gl.bufferSubData(targetGlBuffer.gl_type, targetGlBuffer.writePosition, data, pos, size); targetGlBuffer.writePosition += byteCount; } static createIndexBuffer(gl, data, n) { return Utils.createBuffer(gl, data, n, gl.ELEMENT_ARRAY_BUFFER); } static transformBounds(inputBounds, transformation) { var minVector = vec3.create(); var maxVector = vec3.create(); vec3.set(minVector, inputBounds[0], inputBounds[1], inputBounds[2]); vec3.set(maxVector, inputBounds[0] + inputBounds[3], inputBounds[1] + inputBounds[4], inputBounds[2] + inputBounds[5]); var normalizedMinVector = vec3.clone(minVector); var normalizedMaxVector = vec3.clone(maxVector); vec3.transformMat4(normalizedMinVector, normalizedMinVector, transformation); vec3.transformMat4(normalizedMaxVector, normalizedMaxVector, transformation); return [normalizedMinVector[0], normalizedMinVector[1], normalizedMinVector[2], normalizedMaxVector[0] - normalizedMinVector[0], normalizedMaxVector[1] - normalizedMinVector[1], normalizedMaxVector[2] - normalizedMinVector[2]]; } static unionAabb(a, b) { let r = new Float32Array(6); for (let i = 0; i < 6; ++i) { let fn = i < 3 ? Math.min : Math.max; r[i] = fn(a[i], b[i]); } return r; } static emptyAabb() { let i = Infinity; return new Float32Array([i,i,i,-i,-i,-i]); } static sortMapKeys(inputMap) { var sortedKeys = Array.from(inputMap.keys()).sort((a, b) => { // Otherwise a and b will be converted to string first... return a - b; }); var newMap = new Map(); for (var oid of sortedKeys) { newMap.set(oid, inputMap.get(oid)); } return newMap; } static request(options) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(options.method || "GET", options.url); if (options.binary) { xhr.responseType = "arraybuffer"; } xhr.onload = function () { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject(); } }; xhr.onerror = reject; xhr.send(null); }); } static calculateBytesUsed(settings, nrVertices, nrColors, nrIndices, nrNormals) { var bytes = 0; if (settings.quantizeVertices) { bytes += nrVertices * 2; } else { bytes += nrVertices * 4; } if (nrColors != null) { if (settings.quantizeColors) { bytes += nrColors; } else { bytes += nrColors * 4; } } // Pick buffers bytes += (nrVertices / 3) * 4; if (nrIndices < 65536 && settings.useSmallIndicesIfPossible) { bytes += nrIndices * 2; } else { bytes += nrIndices * 4; } if (settings.quantizeNormals) { bytes += nrNormals; } else { bytes += nrNormals * 4; } return bytes; } }
JavaScript
class NotBrackets extends Brackets { constructor() { super(...arguments); this["@instanceof"] = Symbol.for("NotBrackets"); } }
JavaScript
class ProtectedRoute extends Component { constructor(props) { super(props); this.state = { loading: true, isAuthenticated: false } } componentDidMount() { // this.verifyToken() auth.isAuthenticated(this.successCallback,this.failureCallback) } successCallback=()=>{ this.setState({ loading: false, isAuthenticated: true }) } failureCallback=()=>{ this.setState({loading: false}) } render() { const {loading, isAuthenticated} = this.state const {children, location} = this.props if (loading) { return <div>Loading</div> } console.log(children) return <Fragment> {isAuthenticated ? children : <Redirect to={{pathname: "/signin", state: {from: location}}}/> } </Fragment> } }
JavaScript
class JsavLinkedListObject{ /** * Class constructor * @param {JSAVpesudocodeobject} codeObject This object is used to show the student code in the slide show * @param {JSAV} av the JSAV object that is used to draw the visualizations */ constructor(codeObject, av) { this.JsavLinkedList = av.ds.list({ nodegap: 30, top: 40, left: codeObject.element.outerWidth() + 100 }); this.circular = false; this.size = 0; this.av = av; this.listOfNewNodesNotPartOfTheList = []; this.listOfNodesReferences = []; } /** * Create new node in the JSAV linked list. This node is not part of the list yet. * @param {Object} data the linked list node data * @returns the new JSAV linked list node */ newNode(data) { var newnode = this.JsavLinkedList.newNode(data); this.listOfNewNodesNotPartOfTheList.push(newnode); return newnode; } /** * Search for a node that is not in the linked list. * @param {Object} data The data will be used to find the requested node * @returns the linked list node */ getNodeNotPartOfTheListByData(data) { for (var i = 0; i < this.listOfNewNodesNotPartOfTheList.length; i++) if (this.listOfNewNodesNotPartOfTheList[i].value() === data) return this.listOfNewNodesNotPartOfTheList[i]; } /** * Creates and adds a new node at the first of the list. * @param {Object} data The created node data * @param {String} ref The created node memory reference. */ addFirst(data, ref) { this.JsavLinkedList.addFirst(data); this.listOfNodesReferences.splice(0, 0, ref.toString()); this.size++; } /** * Creates and adds a new node at the end on the list. * @param {Object} data The created node data * @param {String} ref The created node memory reference. */ addLast(data, ref) { this.JsavLinkedList.addLast(data); this.listOfNodesReferences.push(ref.toString()); this.size++; } /** * Creates and adds a new node at the specified index of the list. * @param {Integer} index The specified index on the list * @param {Object} data The created node data * @param {String} ref The created node memory reference. */ add(index, data, ref) { this.JsavLinkedList.add(index, data); this.listOfNodesReferences.splice(index, 0, ref.toString()); this.size++; } /** * returns the JSAV Linked list object. */ getJsavLinkedList() { return this.JsavLinkedList; } /** * returns the node at the specified index on the list. * @param {Integer} index The specified index of the list */ get(index) { return this.JsavLinkedList.get(index); } /** * removes the node at the specified index on the list. * @param {Integer} index The specified index of the list */ remove(index) { this.size--; return this.JsavLinkedList.remove(index); this.listOfNodesReferences.splice(index, 1); } /** * connects the last node with the first node * @param {JSAVNode} last * @param {JSAVNode} first */ CreateCircularArrow(last, first) { this.circularEdge = this.connection(last.element, first.element); this.circularEdge.hide(); } /** * Draws a link from obj1 to obj2 * @param {JSAVNode} obj1 * @param {JSAVNode} obj2 * @returns the new link */ connection(obj1, obj2) { var position = this.position(); //if (obj1 === obj2) { return; } var pos1 = obj1.offset(); var pos2 = obj2.offset(); var fx = pos1.left + obj1.outerWidth() / 2.0; var tx = pos2.left - obj2.outerWidth() / 2.0; var fy = position.top + obj1.outerHeight(); ///2.0 tx += 22; return this.av.g.path(["M", fx, fy, "h", 20, "v", 30, "h", (tx - fx - 30 - 20), "v", -30, "h", 20].join(","), { "arrow-end": "classic-wide-long", opacity: 0, "stroke-width": 2 }); } /** * Converts the list to Circular linked list */ convertToCircularList(toRef) { if(toRef === null){ this.CreateCircularArrow(this.get(this.size - 1), this.get(0)); } else{ var index = this.getNodeIndexByReference(toRef) this.CreateCircularArrow(this.get(this.size - 1), this.get(index)); } this.circularEdge.show(); this.last().next(this.first()); var edge = this.get(this.size - 1).edgeToNext(); edge.hide(); return true; } /** * redraw the JSAV linked list */ layout(toRef = null) { this.JsavLinkedList.layout(); if (this.circular) this.convertToCircularList(toRef); } /** * returns the size of the linked list */ size() { return this.JsavLinkedList.size(); } /** * returns the position of the JSAV linked list object */ position() { return this.JsavLinkedList.position(); } /** * returns the last JSAV node in the list */ last() { return this.JsavLinkedList.last(); } /** * returns the first JSAV node in the list */ first() { return this.JsavLinkedList.first(); } /** * Returns the index of the node with the given value * @param {Object} value the value that used to find the node index */ getNodeIndexByValue(value) { for (var i = 0; i < this.JsavLinkedList.size(); i++) if (this.JsavLinkedList.get(i).value() === value) return i; } /** * Returns the index of the node with the given reference * @param {String} reference the reference value that used to find the node index */ getNodeIndexByReference(reference) { for (var i = 0; i < this.listOfNodesReferences.length; i++) if (this.listOfNodesReferences[i] === reference.toString()) return i; } }
JavaScript
class AthleteName extends Component { constructor(props) { super(props); } render() { const name = this.props.athlete.name; const profilePic = this.props.athlete.profilepic; const userId = this.props.athlete.userid; const countryName = this.props.athlete.countryoforiginname; const age = this.props.athlete.age; const height = this.props.athlete.height; const weight = this.props.athlete.weight; const hidden = this.props.hidden; let textStyle = {}; let nameText = '+'; if(!hidden) { textStyle = { fontWeight: 700 }; nameText = '-'; } return ( <div> <div style={textStyle}>{nameText} {name}</div> {!hidden && <AthleteAttributes profilePic={profilePic} userId={userId} countryName={countryName} age={age} height={height} weight={weight} />} </div> ) } }
JavaScript
class AthleteAttributes extends Component { render() { let profilePic = this.props.profilePic; const userId = this.props.userId; let countryName = this.props.countryName; let age = this.props.age; let height = this.props.height; let weight = this.props.weight; console.log(userId); if(profilePic == "") { profilePic = "https://profilepicsbucket.crossfit.com/pukie.png"; } if(age == 0) age = ""; if(height != "") { height = height + " | " + weight; } else { height = ""; } var s = { flexFlow: 'row wrap', display: 'flex', alignItems: 'stretch' }; var imgStyles = { width: '70px', height: '70px', flexFlow: 'row wrap', } return ( <div style={s} className="bottom"> <img style={imgStyles} src={profilePic} /> <ul className="list-unstyled"> <li>{countryName}</li> <li>{age}</li> <li>{height}</li> {userId ? (<li><a href={'https://games.crossfit.com/athlete/' + userId} target="_blank">View Profile</a></li>) : ''} </ul> </div> ) } }
JavaScript
class Images extends React.Component { static propTypes = { ...viewPropTypes, /** * Specifies the external images in key-value pairs required for the shape source. * If you have an asset under Image.xcassets on iOS and the drawables directory on android * you can specify an array of string names with assets as the key `{ assets: ['pin'] }`. */ images: PropTypes.object, }; _getID() { if (!this.id) { this.id = `${ShapeSource.imageSourcePrefix}-${Math.random().toString(36).substr(2,9)}` } return this.id; } render() { const id = this._getID(); return ( <ShapeSource images={this.props.images} id={id} shape={{ "type": "FeatureCollection", "features": [] }} > {this.props.children} </ShapeSource> ); } }
JavaScript
class Dashboard extends Component { state = { selectedTab: 'unanswered' } // componentDidMount () { // this.props.dispatch(handleInitialCards()) // } render () { const { completedCards, uncompletedCards,loadingBar } = this.props return ( <Fragment> <MainMenu /> <div className="container"> <ul className='toggle-answers'> <li className={ this.state.selectedTab === 'unanswered' ? 'active' : 'li-hover'} onClick={() => {this.setState({ selectedTab: 'unanswered'})}}> Unanswered Questions </li> <li className={ this.state.selectedTab === 'answered' ? 'active' : 'li-hover'} onClick={() => {this.setState({ selectedTab: 'answered'})}}> Answered Questions </li> </ul> { !loadingBar.default && Object.keys(uncompletedCards).length === 0 && this.state.selectedTab === 'unanswered' ? <p className='no-results'>no results</p> : null } { !loadingBar.default && Object.keys(completedCards).length === 0 && this.state.selectedTab === 'answered' ? <p className='no-results'>no results</p> : null } { loadingBar.default ? <p className='loading'>Loading ...</p> : this.state.selectedTab === 'unanswered' && Object.keys(uncompletedCards).length !== 0 ? <div className='question-form margin'> {uncompletedCards.map((id) => ( <Card key={id} id={id}/> ))} </div> : this.state.selectedTab === 'answered' && Object.keys(completedCards).length !== 0 ? <div className='question-form margin'> {completedCards.map((id) => ( <Card key={id} id={id}/> ))} </div> : null } </div> </Fragment> ) } }
JavaScript
class PrivateProperties { /** * @constructor * @param {T} init Initialization of the private properties */ constructor(init) { // Initialize this._init = init; this._bag = {}; this._cache = new WeakMap(); // Loop through the initial object and define all properties for (const key in init) { if (!init.hasOwnProperty(key)) continue; this._bag[key] = new WeakMap(); } } /** * @methodOf PrivateProperties * Bind to the given parent on given property * @param {object} parent * @param {string} prop */ bind(parent, prop) { // Aliasing const _this = this; // Then define the property Object.defineProperty(parent, '_d', { get() { return _this.access(parent); } }); } /** * @methodOf PrivateProperties * Access the properties for given parent * @param {object} parent * @return {T} Property bag */ access(parent) { if (this._cache.has(parent)) return this._cache.get(parent); const accessor = {}; for (const key in this._bag) { const defaultValue = this._init[key]; /** * @type WeakMap<object, *> */ const bagMap = this._bag[key]; Object.defineProperty(accessor, key, { enumerable: true, get() { if (!bagMap.has(parent)) { const value = JSON.parse(JSON.stringify(defaultValue)); bagMap.set(parent, value); } return bagMap.get(parent); }, set(value) { bagMap.set(parent, value); }, }); } this._cache.set(parent, accessor); return accessor; } /** * @methodOf PrivateProperties * Destroy items for given parent * @param {object} parent */ destroy(parent) { this._cache.delete(parent); } }
JavaScript
class RobotVideo extends React.Component { constructor(props) { super(props); // Constants this.MAX_HEIGHT = "600px"; this.PLAY_TIMEOUT = 500; // play X ms after the video is loaded // Bind the functions this.loaded = this.loaded.bind(this); this.ended = this.ended.bind(this); // Refs this.videoRef = React.createRef(); } ended() { this.props.dispatch(displayState()); } loaded() { if (!this.props.video_loaded) { this.props.dispatch(playVideo()); setTimeout(() => { this.videoRef.current.play(); }, this.PLAY_TIMEOUT); } } render() { return ( <div className="row"> <div className="col"> <div className="view"> <div className={"embed-responsive embed-responsive-4by3" + ((!this.props.ax_selected_time && !!this.props.video_loaded) ? " visible" : " invisible")} style={{ maxHeight: this.MAX_HEIGHT }} key={this.props.video_loaded || !!this.props.ax_selected_time}> <video autoPlay={false} muted={true} className="embed-responsive-item" key={this.props.video_link} onEnded={this.ended} onCanPlayThrough={this.loaded} ref={this.videoRef}> <source src={this.props.video_link} /> </video> </div> <div className={"mask text-center" + ((!!this.props.ax_selected_time || !this.props.video_loaded) ? "" : " d-none")}> <h1 className="mb-5">Communicating with robot...</h1> <p className="text-primary"><FontAwesomeIcon icon={faSpinner} size="9x" pulse /></p> </div> </div> </div> </div> ); } }
JavaScript
class ModuleCollection extends Collection { /** * A collection of modules */ constructor() { super(); this.loadModules(); } /** * Load modules */ async loadModules() { try { const modules = await Module.find({ _state: config.state }).lean().exec(); for (const module of modules) { if (module.settings) { module.settings = jsonSchema.json2schema(module.settings); Server.schema.add({ [module.name.toLowerCase()]: module.settings, }); } this.set(module.name, module); } } catch (err) { throw new Error(err); } } }
JavaScript
class Field { /** * @hideconstructor */ constructor(fieldDataObject, connection, emitter) { /** * The UID of the current field is defined in the content type of the entry. * @type {string} */ this.uid = fieldDataObject.data.uid; /** * The data type of the current field is set using this method. * @type {string} */ this.data_type = fieldDataObject.data.schema.data_type; /** * The schema of the current field (schema of fields such as ‘Single Line Textbox’, ‘Number’, * and so on) is set using this method. * @type {Object} */ this.schema = fieldDataObject.data.schema; this._emitter = emitter; let separatedData = separateResolvedData(this, fieldDataObject.data.value); this._data = separatedData.unResolvedData; this._resolvedData = separatedData.resolvedData; this._connection = connection; this._self = fieldDataObject.data.self || false; const fieldObj = this; emitter.on('updateFields', (event) => { const path = fieldObj.uid.split('.'); let value = event.data; path.forEach((key) => { if (value) { value = value[key]; } }); if (fieldObj._data !== value) { fieldObj._data = value; } }); } /** * Sets the data for the current field. * @param {Object|string|number} data Data to be set on the field * @return {external:Promise} A promise object which is resolved when data is set for a field. Note: The data set by this function will only be saved when user saves the entry. */ setData(data) { const currentFieldObj = this; const dataObj = { data, uid: currentFieldObj.uid, self: currentFieldObj._self }; if (!currentFieldObj._self && ((excludedDataTypesForSetField.indexOf(currentFieldObj.data_type) !== -1) || !currentFieldObj.data_type)) { return Promise.reject(new Error('Cannot call set data for current field type')); } return this._connection.sendToParent('setData', dataObj).then(() => { this._data = data; return Promise.resolve(currentFieldObj); }).catch(e => Promise.reject(e)); } /** * Gets the data of the current field * @param {Object} options Options object for get Data method. * @param {boolean} options.resolved If the resolved parameter is set to true for the File field, then the method will return a resolved asset object along with all the field metadata, e.g. 'field.getData({resolved:true})'. * @return {Object|string|number} Returns the field data. */ getData({ resolved = false } = {}) { return resolved ? this._resolvedData : this._data; } /** * Sets the focus for a field when an extension is being used. This method shows user presence and highlights the extension field that the user is currently accessing in Contentstack UI. * @return {Object} A promise object which is resolved when Contentstack UI returns an acknowledgement of the focused state. */ setFocus() { return this._connection.sendToParent('focus'); } /** * This function is called when another extension programmatically changes data of this field using field.setData() function, only available for extension field, only support extensions of data type text, number, boolean or date. * @param {function} callback The function to be called when an entry is published. */ onChange(callback) { const fieldObj = this; if (callback && typeof (callback) === 'function') { fieldObj._emitter.on('extensionFieldChange', (event) => { this._data = event.data; this._resolvedData = event.data; callback(event.data); }); } else { throw Error('Callback must be a function'); } } }
JavaScript
class SwaggerContribCurrents { /** * Constructs a new <code>SwaggerContribCurrents</code>. * @alias module:model/SwaggerContribCurrents * @param p {String} * @param v {Number} * @param t {Number} * @param id {Number} * @param ig {Number} * @param is {Number} * @param ib {Number} */ constructor(p, v, t, id, ig, is, ib) { SwaggerContribCurrents.initialize(this, p, v, t, id, ig, is, ib); } /** * 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, p, v, t, id, ig, is, ib) { obj['p'] = p; obj['v'] = v; obj['t'] = t; obj['Id'] = id; obj['Ig'] = ig; obj['Is'] = is; obj['Ib'] = ib; } /** * Constructs a <code>SwaggerContribCurrents</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/SwaggerContribCurrents} obj Optional instance to populate. * @return {module:model/SwaggerContribCurrents} The populated <code>SwaggerContribCurrents</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new SwaggerContribCurrents(); if (data.hasOwnProperty('p')) { obj['p'] = ApiClient.convertToType(data['p'], 'String'); } if (data.hasOwnProperty('v')) { obj['v'] = ApiClient.convertToType(data['v'], 'Number'); } if (data.hasOwnProperty('t')) { obj['t'] = ApiClient.convertToType(data['t'], 'Number'); } if (data.hasOwnProperty('Id')) { obj['Id'] = ApiClient.convertToType(data['Id'], 'Number'); } if (data.hasOwnProperty('Ig')) { obj['Ig'] = ApiClient.convertToType(data['Ig'], 'Number'); } if (data.hasOwnProperty('Is')) { obj['Is'] = ApiClient.convertToType(data['Is'], 'Number'); } if (data.hasOwnProperty('Ib')) { obj['Ib'] = ApiClient.convertToType(data['Ib'], 'Number'); } } return obj; } }
JavaScript
class LegendItem extends React.Component { handleClick(e, key) { e.stopPropagation(); if (this.props.onSelectionChange) { this.props.onSelectionChange(key); } } handleHover(e, key) { if (this.props.onHighlightChange) { this.props.onHighlightChange(key); } } handleHoverLeave() { if (this.props.onHighlightChange) { this.props.onHighlightChange(null); } } renderLine(style) { const { symbolWidth, symbolHeight } = this.props; return ( <svg style={{ float: "left" }} width={symbolWidth} height={symbolHeight}> <line style={style} x1={0} y1={parseInt(symbolWidth / 2, 10)} x2={symbolWidth} y2={parseInt(symbolWidth / 2, 10)} stroke="black" strokeWidth="2" /> </svg> ); } renderSwatch(style) { const { symbolWidth, symbolHeight } = this.props; return ( <svg style={{ float: "left" }} width={symbolWidth} height={symbolHeight}> <rect style={style} x={2} y={2} width={symbolWidth - 4} height={symbolHeight - 4} rx={2} ry={2} /> </svg> ); } renderDot(style) { const { symbolWidth, symbolHeight } = this.props; const w = parseInt(symbolWidth / 2, 10); const h = parseInt(symbolHeight / 2, 10); const radius = w * 0.75; return ( <svg style={{ float: "left" }} width={symbolWidth} height={symbolHeight}> <circle style={style} cx={w} cy={h} r={radius} /> </svg> ); } render() { const { symbolStyle, labelStyle, valueStyle, itemKey, symbolType } = this.props; let symbol; switch (symbolType) { case "swatch": symbol = this.renderSwatch(symbolStyle); break; case "line": symbol = this.renderLine(symbolStyle); break; case "dot": symbol = this.renderDot(symbolStyle); break; default: //pass } // TODO: We shouldn't be adding interactions to a element like this. // The alternative it to put it on a <a> or something? return ( <Flexbox flexDirection="column" key={itemKey}> <div onClick={e => this.handleClick(e, itemKey)} onMouseMove={e => this.handleHover(e, itemKey)} onMouseLeave={() => this.handleHoverLeave()} > <Flexbox flexDirection="row"> <Flexbox width="20px">{symbol}</Flexbox> <Flexbox flexDirection="column"> <Flexbox> <div style={labelStyle}>{this.props.label}</div> </Flexbox> <Flexbox> <div style={valueStyle}>{this.props.value}</div> </Flexbox> </Flexbox> </Flexbox> </div> </Flexbox> ); } }
JavaScript
class UserContoller { constructor(){ this.validateLogin = this.validateLogin.bind(this) this.authenticate = this.authenticate.bind(this) } // user signup async signUp(req, res) { // validate user console.log(req.body) const { error } = validateUser(req.body); if (error) throw new CustomError(error.details[0].message) let { email, fullName, password } = req.body; fullName = fullName.trim() // Check user email exist if (await User.findOne({ email })) throw new CustomError("Email already exists"); let user = new User({ email, fullName, password }) const salt = await bcrypt.genSalt(10) const hash = await bcrypt.hash(user.password, salt) user.password = hash; user.save(user) const token = jwt.sign({ id: user._id }, jwtSecret, { expiresIn: 36000 }) const data = { token, uid: user.id, fullName: user.fullName, email: user.email, } res.status(201).json(response("User created", data, true)) } async authenticate(req, res) { const { error } = this.validateLogin(req.body); if (error) throw new CustomError(error.details[0].message); const user = await User.findOne({ email: req.body.email }); if (!user) throw new CustomError("Incorrect email or password"); const isCorrect = await bcrypt.compare(req.body.password, user.password) if (!isCorrect) throw new CustomError("Incorrect email or password"); const token = jwt.sign({ id: user._id }, jwtSecret, { expiresIn: 36000 }) const data = { uid: user._id, email: user.email, role: user.role, token }; res.status(200).json(response("User", data, true)) } async updateConfig(req, res) { console.log(req.body) const user = await User.findByIdAndUpdate({ _id: req.user._id }, { "$set": { config: req.body } }, { new: true, }); if (!user) throw new CustomError("user dosen't exist", 404); res.status(200).send(response("Configuration updated", user.config, true, req, res)); } validateLogin(req) { const schema = Joi.object({ email: Joi.string().required().email(), password: Joi.string().required() }); return schema.validate(req); } }
JavaScript
class Photo { constructor({ id, farm, owner, secret, server, title }) { this.id = id; this.farm = farm; this.owner = owner; this.secret = secret; this.server = server; this.title = title; } /* Property to link to a photo based on the flicker mask and photo data */ get link() { return `https://farm${this.farm}.staticflickr.com/${this.server}/${this.id}_${this.secret}_z.jpg`; } }
JavaScript
class Source { constructor({ page, pages, perpage, photo: images, total }) { this.page = page; this.pages = pages; this.perpage = perpage; this.total = total; this.hasImages = !!images && !!images.length; if(this.hasImages) { this.images = images.map(imageDTO => new Photo(imageDTO)); } } update({ page, photo: images }) { if(!images) { return; } images = images.map(imageDTO => new Photo(imageDTO)); this.images = [ ...this.images, ...images ]; } }
JavaScript
class UserHandler { /** * Get detailed profile information about the current user. * * @see https://developer.spotify.com/web-api/get-current-users-profile/ * * @public * @required {OAuth} * @return {Promise} User */ me() { return Client.instance.request(`/me`); } /** * Get public profile information about a Spotify user. * * @see https://developer.spotify.com/web-api/get-users-profile/ * * @public * @param {String} id User id to retrive * @required {OAuth} * @return {Promise} User */ get(id) { return Client.instance.request(`/users/${id}`); } /** * Get a list of the playlists owned or followed by a Spotify user. * * @see https://developer.spotify.com/web-api/get-list-users-playlists/ * * @public * @param {String} id User User id * @param {String} [playlistId] id to retrive playlists * @param {Object} [query] Query parameters. * @required {OAuth} * @return {Promise} playlistCollection */ playlists(id, playlistId, query) { if (playlistId) { return Client.instance.request(`/users/${id}/playlists/${playlistId}`, 'GET', query); } else { return Client.instance.request(`/users/${id}/playlists`, 'GET', query); } } /** * Check if a user follow an album, artist , track or user * @see https://developer.spotify.com/web-api/check-users-saved-albums/ * @see https://developer.spotify.com/web-api/check-current-user-follows/ * * @public * @required {OAuth} user-follow-read scope * @param {String} type artist, album or user * @param {Array} ids User id list * @return {Promise} JSON response */ contains(type, ids) { if (type === 'album') { return Client.instance.request( `/me/albums/contains`, 'GET', {ids: ids} ); } else if (type === 'track') { return Client.instance.request( `/me/tracks/contains`, 'GET', {ids: ids} ); } else { return Client.instance.request( `/me/following/contains`, 'GET', {ids: ids, type: type} ); } } /** * Get the current user’s top artists or tracks based on calculated affinity. * @see https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ * * @public * @required {OAuth} user-top-read * @param {String} type artists or tracks * @param {Object} query limit, offset or time_range(long_term, medium_term, short_term) * @return {Promise} JSON response */ top(type, query) { return Client.instance.request(`/me/top/${type}`, 'GET', query); } /** * Get the current user’s saved tracks. * @see https://developer.spotify.com/web-api/get-users-saved-tracks/ * * @public * @required {OAuth} * @return {Promise} Tracks saved */ tracks() { return Client.instance.request(`/me/tracks`); } /** * Get the current user’s saved albums. * @see https://developer.spotify.com/web-api/get-users-saved-albums/ * * @public * @required {OAuth} * @return {Promise} Albums saved */ albums() { return Client.instance.request(`/me/albums`); } /** * Convert a valid object to a User entity * * @public * @param {object} item Object to convert in entity * @return {Object} */ convert(item) { return new User(item); } }
JavaScript
class Accordion extends Component{ constructor(props) { super(props); this.onChangewinningamount = this.onChangewinningamount.bind(this); this.onChangenumberofwinners= this.onChangenumberofwinners.bind(this); this.onChangepercentage = this.onChangepercentage.bind(this); this.handlestartChange=this.handlestartChange.bind(this); this.handleendChange=this.handleendChange.bind(this); this.onChangeentryfee = this.onChangeentryfee.bind(this); this.onChangeamount1 = this.onChangeamount1.bind(this); this.onChangeamount2 = this.onChangeamount2.bind(this); this.onChangeamount3 = this.onChangeamount3.bind(this); this.onChangeamount4 = this.onChangeamount4.bind(this); this.onChangeamount5 = this.onChangeamount5.bind(this); this.onChangeamount6 = this.onChangeamount6.bind(this); this.onChangeamount7 = this.onChangeamount7.bind(this); this.onChangeamount8 = this.onChangeamount8.bind(this); this.onChangeamount9 = this.onChangeamount9.bind(this); this.onChangeamount10 = this.onChangeamount10.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { startDate:new Date(), endDate:new Date(), entryfee:'', winningamount:[], winning:[], numnberofwinners:'', percentage:'', amount1:'', amount2:'', amount3:'', amount4:'', amount5:'', amount6:'', amount7:'', amount8:'', amount9:'', amount10:'', trainer:[] } } onChangeentryfee(e) { this.setState({ entryfee: e.target.value }) } onChangewinningamount(e) { this.setState({ winningamount: e.target.value }) } onChangenumberofwinners(e) { this.setState({ numnberofwinners: e.target.value }) } onChangepercentage(e) { this.setState({ percentage: e.target.value }) } onChangeamount1(e) { this.setState({ amount1: e.target.value }) } onChangeamount2(e) { this.setState({ amount2: e.target.value }) } onChangeamount3(e) { this.setState({ amount3: e.target.value }) } onChangeamount4(e) { this.setState({ amount4: e.target.value }) } onChangeamount5(e) { this.setState({ amount5: e.target.value }) } onChangeamount6(e) { this.setState({ amount6: e.target.value }) } onChangeamount7(e) { this.setState({ amount7: e.target.value }) } onChangeamount8(e) { this.setState({ amount8: e.target.value }) } onChangeamount9(e) { this.setState({ amount9: e.target.value }) } onChangeamount10(e) { this.setState({ amount10: e.target.value }) } handlestartChange(date) { this.setState({ startDate: date }) } handleendChange(date) { this.setState({ endDate: date }) } onback(){ window.location='/#/dashboard/overview' } onSubmit(e) { e.preventDefault(); // this.state.winning={ // amount1:this.state.amount1, // amount2:this.state.amount2, // amount3:this.state.amount3, // amount4:this.state.amount4, // amount5:this.state.amount5, // amount6:this.state.amount6, // amount7:this.state.amount7, // amount8:this.state.amount8, // amount9:this.state.amount9, // amount10:this.state.amount10, // } this.state.winningamount=[this.state.amount1,this.state.amount2,this.state.amount3,this.state.amount4,this.state.amount5,this.state.amount6,this.state.amount7,this.state.amount8,this.state.amount9,this.state.amount10] const trainer = { startdate: this.state.startDate, enddate: this.state.endDate, winningamount:this.state.winningamount, numnberofwinners:this.state.numnberofwinners, percentage:this.state.percentage, entryfee:this.state.entryfee } axios.post('https://carrombackend.herokuapp.com/tournaments/add', trainer) .then(function(response){ if(response.data ==='Tournament added!'){ alert("successfully added tournament") window.location='/#/dashboard/overview' } }) } render(){ return( <div style={{marginTop:"50px"}}> <Card border="light" className="bg-white shadow-sm mb-4"> <Card.Body> <h5 className="mb-4">Tournament Information</h5> <Form onSubmit={this.onSubmit}> <Row> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> Start Date and Time</Form.Label> </Form.Group> </Col> <Col md={6} className="mb-3"> <DatePicker selected={this.state.startDate} onChange={this.handlestartChange} name="startDate" minDate={moment().toDate()} timeFormat="HH:mm" showTimeSelect timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" /> </Col> </Row> <Row className="align-items-center"> <Col md={6} className="mb-3"> <Form.Group id="firstName"> <Form.Label> End Date and Time</Form.Label> </Form.Group> </Col> <Col md={6} className="mb-3"> <DatePicker selected={this.state.endDate} onChange={this.handleendChange} name="endDate" minDate={moment().toDate()} timeFormat="HH:mm" showTimeSelect timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy h:mm aa" /> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="emal"> <Form.Label>Entry Fee</Form.Label> <Form.Control required type="number" max="1000000" placeholder="" value={this.state.entryfee} onChange={this.onChangeentryfee} /> </Form.Group> </Col> </Row> <Row> <Col md={6} className="mb-3"> <Form.Group id="phone"> <Form.Label>Number Of Winniers</Form.Label> <Form.Control required type="number" max="10" placeholder="" value={this.state.numnberofwinners } onChange={this.onChangenumberofwinners} /> </Form.Group> </Col> <Col md={6} className="mb-3"> <Form.Group id="percenta"> <Form.Label>Percentage</Form.Label> <Form.Control required type="number" placeholder="" value={this.state.percentage} onChange={this.onChangepercentage} max="100" /> </Form.Group> </Col> <h6>Winning Amount</h6> <div style={{border:"2px solid",width:"20%"}}> <Row> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount1</Form.Label> <Form.Control required style={{}} min="1" max="100000" type="number" placeholder="" value={this.state.amount1} onChange={this.onChangeamount1} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount2</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount2} onChange={this.onChangeamount2} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount3</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount3} onChange={this.onChangeamount3} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount4</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount4} onChange={this.onChangeamount4} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount5</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount5} onChange={this.onChangeamount5} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount6</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount6} onChange={this.onChangeamount6} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount7</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount7} onChange={this.onChangeamount7} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount8</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount8} onChange={this.onChangeamount8} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount9</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount9} onChange={this.onChangeamount9} /> </Form.Group> </Col> <Col md={12} className="mb-3"> <Form.Group id="emal"> <Form.Label style={{}}>Amount10</Form.Label> <Form.Control required style={{}} type="number" max="100000" placeholder="" value={this.state.amount10} onChange={this.onChangeamount10} /> </Form.Group> </Col> </Row> </div> </Row> <div className="mt-3"> <Button variant="primary" type="submit">Save </Button> </div> </Form> <div className="mt-3"> <Button variant="primary" type="submit" onClick={this.onback}>Back</Button> </div> </Card.Body> </Card> </div> ) } }
JavaScript
class IconBundler extends Bundler { /** * @inheritdoc */ async setup(options = {}) { options = Object.assign({}, options); let { input, output, root } = options; if (!input) { throw new Error(`missing "input" option for ${this.name}`); } if (!output) { throw new Error(`missing "output" option for ${this.name}`); } if (!Array.isArray(output)) { options.output = output = [output]; } if (typeof input === 'string') { options.input = new File(input); } options.output = output.map((file) => { if (typeof file === 'string') { return new File(file, input.cwd); } return file; }); if (typeof root === 'string') { options.root = new Directory(root); } else if (!root) { options.root = Project.getProject(input); } await super.setup(options); } /** * @inheritdoc */ async build(...invalidate) { await super.build(...invalidate); const { input, output = [], root } = this.options; if (!input.exists()) { throw new Error(`missing "input" file ${root.relative(input)} for ${this.name}`); } this.addResources(input.path); this.emit(IconBundler.BUNDLE_START, input); this.emit(IconBundler.BUILD_START, input); this.result = await Promise.all( output.map(async (iconDefinition) => { const image = await Jimp.read(input.path); if (iconDefinition.type === 'icon') { const { file, name, size, gutter, background } = iconDefinition; const gutterAlpha = image.hasAlpha() ? gutter : 0; const iconBuffer = new Jimp(size, size, colorToString(background || { r: 255, g: 255, b: 255, alpha: image.hasAlpha() ? 0 : 1 })); iconBuffer.composite(image.resize(size - (gutterAlpha || 0), size - (gutterAlpha || 0)), (gutterAlpha || 0) / 2, (gutterAlpha || 0) / 2); return { file, name, size, buffer: iconBuffer, }; } else if (iconDefinition.type === 'splash') { const { file, name, width, height, gutter, background } = iconDefinition; const gutterAlpha = image.hasAlpha() ? gutter : 0; const splashBackground = background || (() => { if (image.hasAlpha()) { return null; } let topLeftColor = image.getPixelColor(0, 0); let topRightColor = image.getPixelColor(image.bitmap.width - 1, 0); let bottomLeftColor = image.getPixelColor(0, image.bitmap.height - 1); let bottomRightColor = image.getPixelColor(image.bitmap.width - 1, image.bitmap.height - 1); if (topLeftColor === topRightColor && topLeftColor === bottomLeftColor && topLeftColor === bottomRightColor) { let color = Jimp.intToRGBA(topLeftColor); color.alpha = 1; return color; } return null; })() || { r: 255, g: 255, b: 255, alpha: 1 }; const size = Math.round(Math.min(height / 6, width / 6)) - (gutterAlpha || 0); const splashBuffer = new Jimp(width, height, colorToString(splashBackground)); splashBuffer.composite(image.resize(size, size), (width - size) / 2, (height - size) / 2); return { file, name, width, height, size, buffer: splashBuffer, }; } throw new Error(`invalid icon type: ${iconDefinition.type}`); }) ); this.emit(IconBundler.BUILD_END, input, null); this.emit(IconBundler.BUNDLE_END, this.result); return this.result; } /** * @inheritdoc */ async write() { this.emit(IconBundler.WRITE_START); const result = await Promise.all( this.result.map(async ({ file, buffer }) => { await buffer.writeAsync(file.path); this.emit(IconBundler.WRITE_PROGRESS, file); return file; }) ); this.emit(IconBundler.WRITE_END); await super.write(); return result; } }
JavaScript
class Animal { constructor(name, age, color, legs){ this.name = name; this.age = age; this.color = color; this.legs = legs; } eatingMethod(){ console.log(`${this.name} is eating`); } }
JavaScript
class Dog extends Animal{ latir(){ console.log(`${this.name} está latindo`); } }
JavaScript
class Bird extends Animal { constructor(name, age, color, legs, gender){ super(name, age, color, legs) this.gender = gender; } birdMethod(){ console.log(`${this.name} is ${this.gender}`) } }
JavaScript
class ImageTextRecUI extends Plugin { /** * @inheritDoc */ static get pluginName() { return 'ImageTextRecUI'; } /** * @inheritDoc */ init() { const editor = this.editor; const t = editor.t; // Add bold button to feature components. editor.ui.componentFactory.add( IMAGE_REC_UI, locale => { const view = new ButtonView( locale ); view.set( { label: "AI识字", icon: ai_icon, tooltip: true, isToggleable: false } ); // Execute command. view.on( 'execute', async () => { const imageUtils = editor.plugins.get( 'ImageUtils' ); const tableUtils = editor.plugins.get( 'TableUtils' ); const element = imageUtils.getClosestSelectedImageElement( editor.model.document.selection ); let base64 = element.getAttribute("src"); let params = new URLSearchParams({ "base64url": base64 }) let res = await axios.post(url, params, {timeout: 60000}); console.log(res); editor.model.change( writer => { // Create a table of 2 rows and 7 columns: res.data.TextDetections.forEach(text => { const textEle = writer.createText(text["DetectedText"]); editor.model.insertContent(textEle); }) }); } ); return view; } ); } }
JavaScript
class Calendar extends Component { constructor(props) { super(props) this.props.closePopper() } render() { const { events, classes } = this.props const eventsToShow = prepareEventsToCalendarEvents( events, this.props.shouldShowKuksaEventsAlso ) return ( <div className={ this.props.mobile ? classes.mobileCalendar : classes.calendar } > <BigCalendar localizer={localizer} events={eventsToShow} startAccessor="start" endAccessor="end" showMultiDayTimes views={['month', 'week', 'day']} components={{ event: CalendarEvent, toolbar: CalendarToolbar, }} eventPropGetter={eventStyleGetter} /> </div> ) } }
JavaScript
class Row { /** * @constructor * @param {int} size - The row capacity * @param {array} items - (Optional) The values to initialize this row. */ constructor(size, items) { this.capacity = size; this.items = items || []; } /** * Create a new box to this row and control the row capacity * @param {int} boxNumber - The new box number. * @param {int} afterNum - Place the new box after this box number. * @returns {int} Returns a box number in case of overflow and returns undefined when ok */ createBox(boxNumber, afterNumber) { // if afterNumber value was given if(afterNumber && afterNumber > 0) { // Insert the new boxNumber at the index position let index = this.items.indexOf(afterNumber); this.items.splice((index + 1), 0, boxNumber); } else { // Just insert at the begining this.items.unshift(boxNumber); } // Check if the row is over capacity if(this.items.length > this.capacity) { // I'm full, give this to another row please return this.items.pop(); } } }
JavaScript
class SpecialFunctions{ /** * Check for a special response to a roll argument * @param {string} expression the roll expression to check against the special functions */ getSpecial(expression){ if(expression && specialData.has(expression)){ return specialData.get(expression); } return null; } }
JavaScript
class Reply extends Component { constructor(props) { super(props); this.onMessageChange = this.onMessageChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onMessageChange(event, result) { const { value: msg } = result; this.props.messageToSendChanged(msg); } onFormSubmit() { const { messageToSend, identityId, match } = this.props; const msg = { message: messageToSend }; this.props.messageToSendChanged(''); const topic = `${topicFromParams(match.params)}/${identityId}`; IoT.publish(topic, JSON.stringify(msg)); } render() { return ( <Form onSubmit={this.onFormSubmit} > <Form.Group> <Form.Field> <Form.Input placeholder="message" value={this.props.messageToSend} onChange={this.onMessageChange} /> </Form.Field> <Button type="submit" disabled={this.props.messageToSend === ''} color="teal" > Reply </Button> </Form.Group> </Form> ); } }
JavaScript
class GadgetsGenerationAPI { /** * This method will return the AXIOS http client. * @returns httpClient */ getHTTPClient() { let httpClient = axios.create({ baseURL: appContext + '/apis', timeout: 300000, headers: { "Authorization": "Bearer " + AuthManager.getUser().SDID }, }); httpClient.defaults.headers.post['Content-Type'] = 'application/json'; return httpClient; } /** * Validates given widget name * @param widgetName */ validateWidgetName(widgetName) { return this.getHTTPClient().post(`/widgets/${widgetName}/validate`); } /** * Gets a list of available data providers */ getProvidersList() { return this.getHTTPClient().get('/data-provider/list'); } /** * Gets config for the given provider name * @param providerName */ getProviderConfiguration(providerName) { return this.getHTTPClient().get(`/data-provider/${providerName}/config`); } /** * Validates the provider with the given configuration, and returns metadata of the provider when valid * @param providerName * @param providerConfig */ getProviderMetadata(providerName, providerConfig) { return this.getHTTPClient().post(`/data-provider/${providerName}/validate`, providerConfig); } /** * Saves the gadget, with the given config * @param gadgetConfig */ addGadgetConfiguration(gadgetConfig) { return this.getHTTPClient().post('/widgets', gadgetConfig); } }
JavaScript
class SequentialHook extends RequestHook { constructor(...args) { super(...args); this.numRequests = 0; this.outstandingRequest = false; this.allRequestsSequential = true; } async onRequest() { this.numRequests += 1; if (this.outstandingRequest) { this.allRequestsSequential = false; } this.outstandingRequest = true; } async onResponse() { this.outstandingRequest = false; } haveRequestsBeenSequential() { return this.allRequestsSequential; } getNumRequests() { return this.numRequests; } }
JavaScript
class DeveloperToolCollection extends BaseCollection { constructor() { super('DeveloperTool', new SimpleSchema({ toolID: { type: SimpleSchema.RegEx.Id }, developerID: { type: SimpleSchema.RegEx.Id }, toolLevel: { type: String, allowedValues: skillAndToolLevels, optional: true }, })); } /** * Defines a new tuple. * @param tool {String} tool slug or ID. * @param developer {String} developer slug or ID. * @return {String} the ID of the new tuple. */ define({ tool, developer }) { const toolID = Tools.findIdBySlug(tool); const developerID = Developers.findIdBySlug(developer); return this._collection.insert({ toolID, developerID }); } /** * Updates the given tuple. * @param docID {String} the ID of the tuple to update. * @param tool {String} the new tool slug or ID (optional). * @param developer {String} the new developer slug or ID (optional). * @param toolLevel {String} the new toolLevel (optional). * @throws {Meteor.Error} if docID is not defined. */ update(docID, { tool, developer, toolLevel }) { this.assertDefined(docID); const updateData = {}; if (developer) { updateData.developerID = Developers.getID(developer); } if (tool) { updateData.toolID = Tools.getID(tool); } if (toolLevel) { updateData.toolLevel = toolLevel; } this._collection.update(docID, { $set: updateData }); } /** * Removes the tuple. * @param docID {String} the ID to remove. * @throws {Meteor.Error} if docID is not defined. */ removeIt(docID) { super.removeIt(docID); } /** * Removes all tuples for the given developer. * @param developer {String} the developer slug or ID. * @throws {Meteor.Error} if developer is not defined. */ removeDeveloper(developer) { const developerID = Developers.getID(developer); this._collection.remove({ developerID }); } /** * Removes all tuples for the given tool. * @param tool {String} the tool slug or ID. * @throws {Meteor.Error} if tool is not defined. */ removeTool(tool) { const toolID = Tools.getID(tool); this._collection.remove({ toolID }); } assertValidRoleForMethod(userId) { this.assertRole(userId, [ROLE.ADMIN, ROLE.DEVELOPER]); } }
JavaScript
class AddChannelToDatabase extends Handler { /** * Base class for bot commands * @param {Genesis} bot The bot object * @param {string} id The command's unique id * @param {string} event Event to trigger this handler */ constructor(bot) { super(bot, 'handlers.addChannel', Events.CHANNEL_CREATE); } /** * add the guild to teh Database * @param {Discord.Channel} channel channel to add to the database */ async execute(...[channel]) { this.logger.debug(`Running ${this.id} for ${this.event}`); if (channel.type === 'GUILD_VOICE') { return; } if (channel.type === 'GUILD_TEXT') { try { await this.settings.addGuildTextChannel(channel); this.logger.debug(`Text channel ${channel.name} (${channel.id}) created in guild ` + `${channel.guild.name} (${channel.guild.id})`); } catch (err) { await this.settings.addGuild(channel.guild); this.settings.addGuildTextChannel(channel); } } else { await this.settings.addDMChannel(channel); this.logger.debug(`DM channel with id ${channel.id} created`); } } }
JavaScript
class MemberExpression extends BaseSyntax { /** * The constructor of MemberExpression * * @constructor */ constructor(object, property) { super('MemberExpression'); this.object = object; this.property = property; } }
JavaScript
class Attachment { constructor(file, name) { this.file = null; this._attach(file, name); } /** * The name of the file * @type {?string} * @readonly */ get name() { return this.file.name; } /** * The file * @type {?BufferResolvable|Stream} * @readonly */ get attachment() { return this.file.attachment; } /** * Set the file of this attachment. * @param {BufferResolvable|Stream} file The file * @param {string} name The name of the file * @returns {Attachment} This attachment */ setAttachment(file, name) { this.file = { attachment: file, name }; return this; } /** * Set the file of this attachment. * @param {BufferResolvable|Stream} attachment The file * @returns {Attachment} This attachment */ setFile(attachment) { this.file.attachment = attachment; return this; } /** * Set the name of this attachment. * @param {string} name The name of the image * @returns {Attachment} This attachment */ setName(name) { this.file.name = name; return this; } /** * Set the file of this attachment. * @param {BufferResolvable|Stream} file The file * @param {string} name The name of the file * @private */ _attach(file, name) { if (file) { if (typeof file === 'string') this.file = file; else this.setAttachment(file, name); } } }
JavaScript
class SharedKeyManager { constructor(keyList) { this.keyList = keyList; setInterval(() => { this._initCheck(); }, 60 * 1000); } /** Check for shared keys and delete old shared keys - run every minute */ _initCheck() { chrome.storage.local.get('keys', (items) => { if (typeof items.keys !== 'object') { return; } this.keyList.keys = items.keys; const keys = []; for (let i = 0; i < this.keyList.keys.length; i++) { if (this.keyList.keys[i].key.priv) { keys.push(this.keyList.keys[i].key.pub); } } $.ajax({ url: 'https://grd.me/key/checkSharedKey', type: 'POST', data: { keys: keys, }, success: (data) => { if (data && data.status && data.status[0] && !data.status[0].code) { chrome.storage.local.get(['keys', 'acceptableSharedKeys'], (items) => { // Keys may not be an object when the keychain is encrypted if (typeof items.keys !== 'object') { return; } data.acceptableSharedKeys = items.acceptableSharedKeys; this.check(data); }); } }, error: (data) => { console.error('Error checking for shared keys:', data); }, }); }); } /** Get rid of duplicate elements in an array * @param arr The array to rid of duplicates */ _uniq(arr) { const seen = {}; const out = []; const len = arr.length; let j = 0; for (let i = 0; i < len; i++) { const item = JSON.stringify(arr[i]); if (seen[item] !== 1) { seen[item] = 1; out[j++] = JSON.parse(item); } } return out; } /** Post a notification of a key having been shared with the user * @param keys The array of keys that have been shared with the user */ notify(keys) { chrome.notifications.getPermissionLevel((level) => { if (level !== 'granted') { return; } const length = keys.length; chrome.notifications.create('GrdMeNewSharedKey', { type: 'basic', iconUrl: chrome.extension.getURL('icons/icon48.png'), title: 'New Shared Key' + (length > 1 ? 's' : ''), message: 'You have ' + length + ' new shared key' + (length > 1 ? 's' : '') + '!', }, () => {}); }); } /** Check to see if any new keys have been shared and if user's shared keys have been recieved * @param data Object with information about sent/recieved keys */ check(data) { chrome.storage.local.get('keys', (items) => { this.keyList.keys = items.keys; /* Handle receiving keys shared with this user */ const keyChain = this.keyList.keys; const originalLength = data.acceptableSharedKeys.length; let index; for (let i = 0; i < data.received.length; i++) { try { const sig = JSON.parse(data.received[i].sendSig); if (ecc.verify(data.received[i].fromKey, sig, data.received[i].sharedKey)) { for (let j = 0; j < keyChain.length; j++) { if (keyChain[j].key.priv) { try { const key = String(ecc.decrypt(keyChain[j].key.priv, data.received[i].sharedKey)).slice(0, 64); if (key) { let from = ''; let k; for (k = 0; k < keyChain.length; k++) { if (keyChain[k].key.pub === data.received[i].fromKey) { from = keyChain[k].description; break; } } data.acceptableSharedKeys.push({key: key, from: from}); data.acceptableSharedKeys = this._uniq(data.acceptableSharedKeys); for (k = 0; k < data.acceptableSharedKeys.length; k++) { if (data.acceptableSharedKeys[k].key === key && data.acceptableSharedKeys[k].from === from) { index = k; break; } } this.acknowledgeKey({ fromKey: data.received[i].fromKey, toKey: data.received[i].toKey, sharedKey: data.received[i].sharedKey, receiveSig: JSON.stringify(ecc.sign(keyChain[j].key.priv, data.received[i].sharedKey)), }, index); } } catch (e) { console.error('Error checking shared key', e); } } } } } catch (e) { console.error('Error checking shared key', e); } } // Notify user of acceptable keys data.acceptableSharedKeys = this._uniq(data.acceptableSharedKeys); if (data.acceptableSharedKeys.length !== originalLength) { this.notify(data.acceptableSharedKeys); chrome.storage.local.set({ acceptableSharedKeys: data.acceptableSharedKeys, }); } // Handle receiving acknowledgements of shared keys for (let i = 0; i < data.sent.length; i++) { try { const sig = JSON.parse(data.sent[i].receiveSig); if (ecc.verify(data.sent[i].toKey, sig, data.sent[i].sharedKey)) { this.deleteRequest({ fromKey: data.sent[i].fromKey, sharedKey: data.sent[i].sharedKey, }); } } catch (e) { console.error('Error checking shared key', e); } } }); } /** Make a request to delete a shared key * @param keyObj An object containing the sender's public key, the encrypted shared key and the random number */ deleteRequest(keyObj) { function error() { console.error('Error making delete shared key request'); } chrome.storage.local.get('randomMap', (items) => { const randomMap = items.randomMap; keyObj.rand = randomMap[keyObj.sharedKey]; $.ajax({ url: 'https://grd.me/key/deleteSharedKey', type: 'POST', data: keyObj, success: (data) => { if (!data || !data.status || !data.status[0] || data.status[0].code) { error(); } else { delete randomMap[keyObj.sharedKey]; chrome.storage.local.set({'randomMap': randomMap}); } }, error: error, }); }); } /** Acknowledge receiving a shared key * @param keyObj An object of the key data to send */ acknowledgeKey(keyObj) { $.ajax({ url: 'https://grd.me/key/acceptSharedKey', type: 'POST', data: keyObj, error: () => { console.error('Error acknowledging shared key received'); }, }); } }
JavaScript
class MediaBrowserContainer extends Component { static propTypes = { mediaSearchStore: PropTypes.object, history: PropTypes.object, intl: PropTypes.object, hubChannel: PropTypes.object, onMediaSearchResultEntrySelected: PropTypes.func, performConditionalSignIn: PropTypes.func, showNonHistoriedDialog: PropTypes.func.isRequired, scene: PropTypes.object.isRequired, store: PropTypes.object.isRequired }; state = { query: "", facets: [], showNav: true, selectNextResult: false, clearStashedQueryOnClose: false }; constructor(props) { super(props); this.state = this.getStoreAndHistoryState(props); this.props.mediaSearchStore.addEventListener("statechanged", this.storeUpdated); this.props.mediaSearchStore.addEventListener("sourcechanged", this.sourceChanged); } componentDidMount() {} componentWillUnmount() { this.props.mediaSearchStore.removeEventListener("statechanged", this.storeUpdated); this.props.mediaSearchStore.removeEventListener("sourcechanged", this.sourceChanged); } storeUpdated = () => { const newState = this.getStoreAndHistoryState(this.props); this.setState(newState); if (this.state.selectNextResult) { if (newState.result && newState.result.entries.length > 0) { this.selectEntry(newState.result.entries[0]); } else { this.close(); } } }; sourceChanged = () => { if (this.inputRef && !isMobile && !isMobileVR) { this.inputRef.focus(); } }; getUrlSource = searchParams => searchParams.get("media_source") || sluglessPath(this.props.history.location).substring(7); getStoreAndHistoryState = props => { const searchParams = new URLSearchParams(props.history.location.search); const result = props.mediaSearchStore.result; const newState = { result, query: this.state.query || searchParams.get("q") || "" }; const urlSource = this.getUrlSource(searchParams); newState.showNav = !!(searchParams.get("media_nav") !== "false"); newState.selectAction = searchParams.get("selectAction") || "spawn"; if (result && result.suggestions && result.suggestions.length > 0) { newState.facets = result.suggestions.map(s => { return { text: s, params: { q: s } }; }); } else { newState.facets = DEFAULT_FACETS[urlSource] || []; } return newState; }; handleQueryUpdated = (query, forceNow) => { this.setState({ result: null }); if (this._sendQueryTimeout) { clearTimeout(this._sendQueryTimeout); this._sendQueryTimeout = null; } if (forceNow) { this.props.mediaSearchStore.filterQueryNavigate("", query); } else { // Don't update search on every keystroke, but buffer for some ms. this._sendQueryTimeout = setTimeout(() => { // Drop filter for now, so entering text drops into "search all" mode this.props.mediaSearchStore.filterQueryNavigate("", query); this._sendQueryTimeout = null; }, 500); } this.setState({ query }); }; handleEntryClicked = (evt, entry) => { evt.preventDefault(); if (!entry.lucky_query) { this.selectEntry(entry); } else { // Entry has a pointer to another "i'm feeling lucky" query -- used for trending videos // // Also, mark the browser to clear the stashed query on close, since this is a temporary // query we are running to get the result we want. this.setState({ clearStashedQueryOnClose: true }); this.handleQueryUpdated(entry.lucky_query, true); } }; onShowSimilar = (id, name) => { this.handleFacetClicked({ params: { similar_to: id, similar_name: name } }); }; selectEntry = entry => { if (!this.props.onMediaSearchResultEntrySelected) return; this.props.onMediaSearchResultEntrySelected(entry, this.state.selectAction); this.close(); }; handleSourceClicked = source => { this.props.mediaSearchStore.sourceNavigate(source); }; handleFacetClicked = facet => { this.setState({ query: "" }, () => { const searchParams = this.getSearchClearedSearchParams(true, true, true); for (const [k, v] of Object.entries(facet.params)) { searchParams.set(k, v); } pushHistoryPath(this.props.history, this.props.history.location.pathname, searchParams.toString()); }); }; getSearchClearedSearchParams = (keepSource, keepNav, keepSelectAction) => { return this.props.mediaSearchStore.getSearchClearedSearchParams( this.props.history.location, keepSource, keepNav, keepSelectAction ); }; pushExitMediaBrowserHistory = (stashLastSearchParams = true) => { this.props.mediaSearchStore.pushExitMediaBrowserHistory(this.props.history, stashLastSearchParams); }; showCustomMediaDialog = source => { const { scene, store, hubChannel } = this.props; const isAvatarApiType = source === "avatars"; this.pushExitMediaBrowserHistory(!isAvatarApiType); if (source === "scenes") { this.props.showNonHistoriedDialog(SceneUrlModalContainer, { hubChannel }); } else if (isAvatarApiType) { this.props.showNonHistoriedDialog(AvatarUrlModalContainer, { scene, store }); } else { this.props.showNonHistoriedDialog(ObjectUrlModalContainer, { scene }); } }; close = () => { showFullScreenIfWasFullScreen(); const urlSource = this.getUrlSource(new URLSearchParams(this.props.history.location.search)); this.pushExitMediaBrowserHistory(urlSource !== "avatars" && urlSource !== "favorites"); if (this.state.clearStashedQueryOnClose) { this.props.mediaSearchStore.clearStashedQuery(); } }; handlePager = delta => { this.setState({ result: null }); this.props.mediaSearchStore.pageNavigate(delta); this.browserDiv.scrollTop = 0; }; handleCopyAvatar = (e, entry) => { e.preventDefault(); this.props.performConditionalSignIn( () => this.props.hubChannel.signedIn, async () => { await remixAvatar(entry.id, entry.name); this.handleFacetClicked({ params: { filter: "my-avatars" } }); }, SignInMessages.remixAvatar ); }; handleCopyScene = async (e, entry) => { e.preventDefault(); this.props.performConditionalSignIn( () => this.props.hubChannel.signedIn, async () => { await fetchReticulumAuthenticated("/api/v1/scenes", "POST", { parent_scene_id: entry.id }); this.handleFacetClicked({ params: { filter: "my-scenes" } }); }, SignInMessages.remixScene ); }; onCreateAvatar = () => { window.dispatchEvent(new CustomEvent("action_create_avatar")); }; processThumbnailUrl = (entry, thumbnailWidth, thumbnailHeight) => { if (entry.images.preview.type === "mp4") { return proxiedUrlFor(entry.images.preview.url); } else { return scaledThumbnailUrlFor(entry.images.preview.url, thumbnailWidth, thumbnailHeight); } }; render() { const intl = this.props.intl; const searchParams = new URLSearchParams(this.props.history.location.search); const urlSource = this.getUrlSource(searchParams); const isSceneApiType = urlSource === "scenes"; const isFavorites = urlSource === "favorites"; const showCustomOption = !isFavorites && (!isSceneApiType || this.props.hubChannel.canOrWillIfCreator("update_hub")); const entries = (this.state.result && this.state.result.entries) || []; const hideSearch = urlSource === "favorites"; const showEmptyStringOnNoResult = urlSource !== "avatars" && urlSource !== "scenes"; const facets = this.state.facets && this.state.facets.length > 0 ? this.state.facets : undefined; // Don't render anything if we just did a feeling lucky query and are waiting on result. if (this.state.selectNextResult) return <div />; const handleCustomClicked = urlSource => { const isAvatarApiType = urlSource === "avatars"; if (isAvatarApiType) { this.showCustomMediaDialog(urlSource); } else { this.props.performConditionalSignIn( () => !isSceneApiType || this.props.hubChannel.can("update_hub"), () => this.showCustomMediaDialog(urlSource), SignInMessages.changeScene ); } }; const activeFilter = searchParams.get("filter") || (searchParams.get("similar_to") && "similar") || (!searchParams.get("q") && ""); const meta = this.state.result && this.state.result.meta; const hasNext = !!(meta && meta.next_cursor); const hasPrevious = !!searchParams.get("cursor"); const customObjectType = this.state.result && isSceneApiType ? "scene" : urlSource === "avatars" ? "avatar" : "object"; let searchDescription; if (!hideSearch && urlSource !== "scenes" && urlSource !== "avatars" && urlSource !== "favorites") { searchDescription = ( <> {poweredByMessages[urlSource] ? intl.formatMessage(poweredByMessages[urlSource]) : ""} {poweredByMessages[urlSource] && PRIVACY_POLICY_LINKS[urlSource] ? " | " : ""} {PRIVACY_POLICY_LINKS[urlSource] && ( <a href={PRIVACY_POLICY_LINKS[urlSource]} target="_blank" rel="noreferrer noopener"> <FormattedMessage id="media-browser.privacy_policy" defaultMessage="Privacy Policy" /> </a> )} </> ); } else if (urlSource === "scenes") { searchDescription = ( <> {configs.feature("enable_spoke") && ( <> {intl.formatMessage(poweredByMessages.scenes, { editorName: ( <a href="/spoke" target="_blank" rel="noreferrer noopener"> {configs.translation("editor-name")} </a> ) })} </> )} {configs.feature("enable_spoke") && configs.feature("show_issue_report_link") && " | "} {configs.feature("show_issue_report_link") && ( <a target="_blank" rel="noopener noreferrer" href={configs.link("issue_report", "https://hubs.mozilla.com/docs/help.html")} > <FormattedMessage id="media-browser.report-issue" defaultMessage="Report Issue" /> </a> )} </> ); } return ( <MediaBrowser browserRef={r => (this.browserDiv = r)} onClose={this.close} searchInputRef={r => (this.inputRef = r)} autoFocusSearch={!isMobile && !isMobileVR} query={this.state.query} onChangeQuery={e => this.handleQueryUpdated(e.target.value)} onSearchKeyDown={e => { if (e.key === "Enter" && e.ctrlKey) { if (entries.length > 0 && !this._sendQueryTimeout) { this.handleEntryClicked(e, entries[0]); } else if (this.state.query.trim() !== "") { this.handleQueryUpdated(this.state.query, true); this.setState({ selectNextResult: true }); } else { this.close(); } } else if (e.key === "Escape" || (e.key === "Enter" && isMobile)) { e.target.blur(); } }} onClearSearch={() => this.handleQueryUpdated("", true)} mediaSources={urlSource === "favorites" ? undefined : SOURCES} selectedSource={urlSource} onSelectSource={this.handleSourceClicked} activeFilter={activeFilter} facets={facets} onSelectFacet={this.handleFacetClicked} searchPlaceholder={ searchPlaceholderMessages[urlSource] ? intl.formatMessage(searchPlaceholderMessages[urlSource]) : intl.formatMessage(searchPlaceholderMessages.default) } searchDescription={searchDescription} headerRight={ showCustomOption && ( <IconButton lg onClick={() => handleCustomClicked(urlSource)}> {["scenes", "avatars"].includes(urlSource) ? <LinkIcon /> : <UploadIcon />} <p>{intl.formatMessage(customObjectMessages[customObjectType])}</p> </IconButton> ) } hasNext={hasNext} hasPrevious={hasPrevious} onNextPage={() => this.handlePager(1)} onPreviousPage={() => this.handlePager(-1)} noResultsMessage={ emptyMessages[urlSource] ? intl.formatMessage(emptyMessages[urlSource]) : intl.formatMessage(emptyMessages.default) } > {this.props.mediaSearchStore.isFetching || this._sendQueryTimeout || entries.length > 0 || !showEmptyStringOnNoResult ? ( <> {urlSource === "avatars" && ( <CreateTile type="avatar" onClick={this.onCreateAvatar} label={<FormattedMessage id="media-browser.create-avatar" defaultMessage="Create Avatar" />} /> )} {urlSource === "scenes" && configs.feature("enable_spoke") && ( <CreateTile as="a" href="/spoke/new" rel="noopener noreferrer" target="_blank" type="scene" label={ <FormattedMessage id="media-browser.create-scene" defaultMessage="Create Scene with {editorName}" values={{ editorName: configs.translation("editor-name") }} /> } /> )} {entries.map((entry, idx) => { const isAvatar = entry.type === "avatar" || entry.type === "avatar_listing"; const isScene = entry.type === "scene" || entry.type === "scene_listing"; const onShowSimilar = entry.type === "avatar_listing" ? e => { e.preventDefault(); this.onShowSimilar(entry.id, entry.name); } : undefined; let onEdit; if (entry.type === "avatar") { onEdit = e => { e.preventDefault(); pushHistoryState(this.props.history, "overlay", "avatar-editor", { avatarId: entry.id }); }; } else if (entry.type === "scene") { onEdit = e => { e.preventDefault(); const spokeProjectUrl = getReticulumFetchUrl(`/spoke/projects/${entry.project_id}`); window.open(spokeProjectUrl); }; } let onCopy; if (isAvatar) { onCopy = e => this.handleCopyAvatar(e, entry); } else if (isScene) { onCopy = e => this.handleCopyScene(e, entry); } return ( <MediaTile key={`${entry.id}_${idx}`} entry={entry} processThumbnailUrl={this.processThumbnailUrl} onClick={e => this.handleEntryClicked(e, entry)} onEdit={onEdit} onShowSimilar={onShowSimilar} onCopy={onCopy} /> ); })} </> ) : null} </MediaBrowser> ); } }
JavaScript
class HoodSelector { constructor() { // Loads region boundaries unconditionally // this._regions = require(REL_PATH+REGION_FILE).features; this._regions = require('../Fixtures/indexed/bayAreaBoundaries.json').features; // These are all the other instance variables used: this._regionHoods = null; this._adjacentHoods = null; this._currentRegion = null; this._wasLastInBounds = false; // Set event hook functions, just like in Compass const EVENTS = [ 'onRegionWillLoad', 'onRegionDidLoad', 'onHoodChange', ]; for (let event of EVENTS) { this[event] = (func) => { if (typeof func === 'function') { this['_'+event] = func; } }; this['_'+event] = () => {}; } } // See bottom of file for detailed documentatoin on refresh() and _init() refresh(position) { const start = Date.now(); const point = toPoint(position); const lastHood = this._currentHood; this._wasLastInBounds = this._refresh(point); console.tron.log('REFRESH: '+(Date.now()-start)+'ms'); if (lastHood && this._currentHood !== lastHood) { this._onHoodChange({ newHood: this._currentHood, adjacentHoods: this._adjacentHoods }); } return this._wasLastInBounds; } _refresh(point) { if (!this._currentHood) return this._init(point); // 1 if (inside(point, this._currentHood)) return true; // 2 if ( this._setHood( this._selectHood(point, this._adjacentHoods) ) ) return true; // 3 if (!inside(point, this._currentRegion)) return this._init(point); // 4 return this._setHood (this._selectHood(point, this._regionHoods) ); // 5 } _init(point) { this._currentRegion = this._selectCurrentRegion(point); if (this._currentRegion === null) return false; // 1 this._regionHoods = this._loadRegionHoods(this._currentRegion); // 2 return this._setHood( this._selectHood(point, this._regionHoods) ); // 3 } _loadRegionHoods(region) { this._onRegionWillLoad(region); const start = Date.now(); const regionHoods = requireByIndex(region.properties.index).features; console.tron.log('Loaded '+region.properties.label+': '+(Date.now()-start).toFixed()+'ms'); this._onRegionDidLoad(regionHoods, region); return regionHoods; } // Sets current hood and adjacent hood; // It returns false if no hood, otherwise true _setHood(hood) { if (!hood) return false; this._currentHood = hood; this._adjacentHoods = this._selectAdjacentHoods(hood); return true; } _selectHood(point, hoods, context) { for (let hood of hoods) { if (inside(point, hood)) return hood; // await nextFrame(); // test this synchronously first } return null; } _selectCurrentRegion(point) { for (let region of this._regions) { if (inside(point, region)) return region; // await nextFrame(); } return null; } // This is a "dumb" synchronous function that simply pushes indexed adjacents to an array _selectAdjacentHoods(centerHood = this._currentHood) { const adjacentIndices = centerHood.properties.adjacents; const adjacentHoods = []; for (let adjacentIndex of adjacentIndices) { adjacentHoods.push(this._regionHoods[adjacentIndex]); } return adjacentHoods; } // These are the "dumb" public functions. // See notes on refresh() about this._wasLastInBounds getAdjacentHoods = () => (this._wasLastInBounds) ? this._adjacentHoods : null; getCurrentHood = () => (this._wasLastInBounds) ? this._currentHood : null; getCurrentRegion = () => this._currentRegion; }
JavaScript
class Disputes { constructor( arbitratorInstance = isRequired('arbitratorInstance'), arbitrableInstance = isRequired('arbitrableInstance'), storeProviderInstance = isRequired('storeProviderInstance') ) { this._ArbitratorInstance = arbitratorInstance this._ArbitrableInstance = arbitrableInstance this._StoreProviderInstance = storeProviderInstance this.disputeCache = {} } /** * Set arbitrator instance. * @param {object} arbitratorInstance - instance of an arbitrator contract. */ setArbitratorInstance = arbitratorInstance => { this._ArbitratorInstance = arbitratorInstance } /** * Set arbitrable instance. * @param {object} arbitrableInstance - instance of an arbitrable contract. */ setArbitrableInstance = arbitrableInstance => { this._ArbitrableInstance = arbitrableInstance } /** * Set store provider instance. * @param {object} storeProviderInstance - instance of store provider wrapper. */ setStoreProviderInstance = storeProviderInstance => { this._StoreProviderInstance = storeProviderInstance } // **************************** // // * Events * // // **************************** // /** * Method to register all dispute handlers to an EventListener. * @param {string} account - The address of the user. * @param {object} eventListener - The EventListener instance. See utils/EventListener.js. */ registerStoreUpdateEventListeners = ( account = isRequired('account'), eventListener = isRequired('eventListener') ) => { const eventHandlerMap = { DisputeCreation: [this._storeNewDisputeHandler] } for (let event in eventHandlerMap) { if (eventHandlerMap.hasOwnProperty(event)) { eventHandlerMap[event].forEach(handler => { eventListener.addEventHandler(this._ArbitratorInstance, event, args => handler(args, account) ) }) } } } /** * Event listener handler that stores dispute in store upon creation * @param {string} event - The event log. * @param {string} account - Account of user to update store data for */ _storeNewDisputeHandler = async (event, account) => { // There is no need to handle this event if we are not using the store const disputeID = event.args._disputeID.toNumber() const arbitratorAddress = this._ArbitratorInstance.getContractAddress() // arbitrator data const disputeData = await this._ArbitratorInstance.getDispute(disputeID) // arbitrable contract data await this._ArbitrableInstance.setContractInstance( disputeData.arbitrableContractAddress ) const arbitrableContractData = await this._ArbitrableInstance.getData( account ) if ( account === arbitrableContractData.partyA || account === arbitrableContractData.partyB ) { await this._StoreProviderInstance.updateDisputeProfile( account, arbitratorAddress, disputeID, { contractAddress: disputeData.arbitrableContractAddress, partyA: arbitrableContractData.partyA, partyB: arbitrableContractData.partyB, blockNumber: event.blockNumber } ) } } // **************************** // // * Internal * // // **************************** // /** * Add new data to the cache * @param {number} disputeID - The index of the dispute. Used as the key in cache * @param {object} newCacheData - Freeform data to cache. Will overwrite data with the same keys. */ _updateDisputeCache = (disputeID, newCacheData = {}) => { this.disputeCache[disputeID] = { ...this.disputeCache[disputeID], ...newCacheData } } /** * Get the block at which a dispute was created. Used to find timestamps for dispute. * The start block is cached after it has been found once as it will never change. * @param {number} disputeID - The index of the dispute. * @param {string} account - The address of the user. * @returns {number} The block number that the dispute was created. */ _getDisputeStartBlock = async (disputeID, account) => { const cachedDispute = this.disputeCache[disputeID] if (cachedDispute && cachedDispute.startBlock) return cachedDispute.startBlock const arbitratorAddress = this._ArbitratorInstance.getContractAddress() let blockNumber try { const userData = await this._StoreProviderInstance.getDispute( account, arbitratorAddress, disputeID ) blockNumber = userData.blockNumber // eslint-disable-next-line no-unused-vars } catch (err) {} // if block number is not stored we can look it up if (!blockNumber) { // Fetching a dispute will fail if it hasn't been added to the store yet. This is ok, we can just not return store data // see if we can get dispute start block from events const disputeCreationEvent = await this._ArbitratorInstance.getDisputeCreationEvent( disputeID ) if (disputeCreationEvent) { blockNumber = disputeCreationEvent.blockNumber } } // cache start block for dispute this._updateDisputeCache(disputeID, { startBlock: blockNumber }) return blockNumber } // **************************** // // * Public * // // **************************** // /** * Fetch the shared dispute data from the store. * @param {string} account - The users account. * @param {string} disputeID - The index of the dispute. * @returns {Promise} The dispute data in the store. */ getDisputeFromStore = async (account, disputeID) => { const arbitratorAddress = this._ArbitratorInstance.getContractAddress() return this._StoreProviderInstance.getDispute( account, arbitratorAddress, disputeID ) } /** * Get the dispute deadline for the appeal. * @param {number} disputeID - The index of the dispute. * @param {number} appeal - The appeal number. 0 if there have been no appeals. * @returns {number} timestamp of the appeal */ getDisputeDeadline = async (disputeID, appeal = 0) => { const cachedDispute = this.disputeCache[disputeID] || {} if (cachedDispute.appealDeadlines && cachedDispute.appealDeadlines[appeal]) return cachedDispute.appealDeadlines[appeal] const dispute = await this._ArbitratorInstance.getDispute(disputeID) const deadlineTimestamp = await this._ArbitratorInstance.getDisputeDeadlineTimestamp( dispute.firstSession + appeal ) if (deadlineTimestamp) { const currentDeadlines = cachedDispute.appealDeadlines || [] currentDeadlines[appeal] = deadlineTimestamp // cache the deadline for the appeal this._updateDisputeCache(disputeID, { appealDeadlines: currentDeadlines }) } return deadlineTimestamp } /** * Get the timestamp on when the dispute's ruling was finalized. * @param {number} disputeID - The index of the dispute. * @param {number} appeal - The appeal number. 0 if there have been no appeals. * @returns {number} timestamp of the appeal */ getAppealRuledAt = async (disputeID, appeal = 0) => { const cachedDispute = this.disputeCache[disputeID] if ( cachedDispute && cachedDispute.appealRuledAt && cachedDispute.appealRuledAt[appeal] ) return cachedDispute.appealRuledAt[appeal] const dispute = await this._ArbitratorInstance.getDispute(disputeID) const appealRuledAtTimestamp = await this._ArbitratorInstance.getAppealRuledAtTimestamp( dispute.firstSession + appeal ) // cache the deadline for the appeal if (appealRuledAtTimestamp) { const currentRuledAt = cachedDispute.appealRuledAt || [] currentRuledAt[appeal] = appealRuledAtTimestamp this._updateDisputeCache(disputeID, { appealRuledAt: currentRuledAt }) } return appealRuledAtTimestamp } /** * Get the timestamp on when the dispute's appeal was created * @param {number} disputeID - The index of the dispute. * @param {string} account - The users address. * @param {number} appeal - The appeal number. 0 if there have been no appeals. * @returns {number} timestamp of the appeal */ getAppealCreatedAt = async (disputeID, account, appeal = 0) => { const cachedDispute = this.disputeCache[disputeID] if ( cachedDispute && cachedDispute.appealCreatedAt && cachedDispute.appealCreatedAt[appeal] ) return cachedDispute.appealCreatedAt[appeal] const dispute = await this._ArbitratorInstance.getDispute(disputeID) let appealCreatedAtTimestamp = null if (appeal === 0) { const creationBlock = await this._getDisputeStartBlock(disputeID, account) if (creationBlock) { const timestampSeconds = await this._ArbitratorInstance._getTimestampForBlock( creationBlock ) appealCreatedAtTimestamp = timestampSeconds * 1000 } } else { appealCreatedAtTimestamp = await this._ArbitratorInstance.getAppealCreationTimestamp( dispute.firstSession + (appeal - 1) // appeal was created during previous session ) // cache the deadline for the appeal if (appealCreatedAtTimestamp) { const currentCreatedAt = cachedDispute.appealCreatedAt || [] currentCreatedAt[appeal] = appealCreatedAtTimestamp this._updateDisputeCache(disputeID, { appealCreatedAt: currentCreatedAt }) } } return appealCreatedAtTimestamp } /** * Get data for a dispute. This method provides data from the store as well as both * arbitrator and arbitrable contracts. Used to get all relevant data on a dispute. * @param {number} disputeID - The dispute's ID. * @param {string} account - The juror's address. * @returns {object} - Data object for the dispute that uses data from the contract and the store. */ getDataForDispute = async (disputeID, account) => { const arbitratorAddress = this._ArbitratorInstance.getContractAddress() // Get dispute data from contract. Also get the current session and period. const [dispute, period, session] = await Promise.all([ this._ArbitratorInstance.getDispute(disputeID, true), this._ArbitratorInstance.getPeriod(), this._ArbitratorInstance.getSession() ]) // Get arbitrable contract data and evidence const arbitrableContractAddress = dispute.arbitrableContractAddress await this._ArbitrableInstance.setContractInstance( arbitrableContractAddress ) const [metaEvidence, evidence, parties] = await Promise.all([ this._ArbitrableInstance.getMetaEvidence(), this._ArbitrableInstance.getEvidence(), this._ArbitrableInstance.getParties() ]) // Get dispute data from the store let appealDraws = [] // get draws if they have been added to store. try { const userData = await this._StoreProviderInstance.getDispute( account, arbitratorAddress, disputeID ) if (userData.appealDraws) appealDraws = userData.appealDraws || [] // eslint-disable-next-line no-unused-vars } catch (err) { // Dispute exists on chain but not in store. We have lost draws for past disputes. console.error('Dispute does not exist in store.') } const netPNK = await this._ArbitratorInstance.getNetTokensForDispute( disputeID, account ) // Build juror info and ruling arrays, indexed by appeal number const lastSession = dispute.firstSession + dispute.numberOfAppeals const appealJuror = [] const appealRulings = [] for (let appeal = 0; appeal <= dispute.numberOfAppeals; appeal++) { const isLastAppeal = dispute.firstSession + appeal === lastSession // Get appeal data const draws = appealDraws[appeal] || [] let canRule = false let canRepartition = false let canExecute = false let ruling const rulingPromises = [ this._ArbitratorInstance.currentRulingForDispute(disputeID, appeal) ] // Extra info for the last appeal if (isLastAppeal) { if (draws.length > 0) rulingPromises.push( this._ArbitratorInstance.canRuleDispute(disputeID, draws, account) ) if (session && period) canRepartition = lastSession <= session && // Not appealed to the next session period === arbitratorConstants.PERIOD.EXECUTE && // Executable period dispute.state === disputeConstants.STATE.OPEN // Open dispute canExecute = dispute.state === disputeConstants.STATE.EXECUTABLE // Executable state } // Wait for parallel requests to complete ;[ruling, canRule] = await Promise.all(rulingPromises) let jurorRuling = null // if can't rule that means they already did or they missed it if (!canRule) { jurorRuling = await this._ArbitratorInstance.getVoteForJuror( dispute.disputeID, appeal, account ) } const appealCreatedAt = await this.getAppealCreatedAt( dispute.disputeID, account, appeal ) const appealDeadline = await this.getDisputeDeadline( dispute.disputeID, appeal ) const appealRuledAt = await this.getAppealRuledAt( dispute.disputeID, appeal ) appealJuror[appeal] = { createdAt: appealCreatedAt, fee: dispute.arbitrationFeePerJuror.mul(draws.length), draws, jurorRuling, canRule } appealRulings[appeal] = { voteCounter: dispute.voteCounters[appeal], deadline: appealDeadline, ruledAt: appealRuledAt, ruling, canRepartition, canExecute } } return { // Arbitrable Contract Data arbitrableContractAddress, arbitratorAddress, parties, evidence, metaEvidence, // Dispute Data disputeID, firstSession: dispute.firstSession, lastSession, numberOfAppeals: dispute.numberOfAppeals, disputeState: dispute.state, disputeStatus: dispute.status, appealJuror, appealRulings, netPNK } } }
JavaScript
class QuestionPanel extends React.Component { // Create initial data constructor() { super(); this.state = {}; this.state.data = {}; this.loadQuestions = this.loadQuestions.bind(this); this.setQuestionType = this.setQuestionType.bind(this); this.updateTitle = this.updateTitle.bind(this); this.updateDescription = this.updateDescription.bind(this); } // Load questions in question list loadQuestions() { this.props.parent.loadQuestions(); } // Set the type of the question setQuestionType(e) { sendAjax( "PUT", '/setQuestionType', { _csrf: this.props.csrf, questionIndex: this.props.index, type: e.target.value, } ).then(this.loadQuestions) } // Update title of question updateTitle(title) { sendAjax( "PUT", '/updateQuestionTitle', { _csrf: this.props.csrf, index: this.props.index, title, } ).then(setMessageSaved); } // Update description of question updateDescription(content) { sendAjax( "PUT", '/updateQuestionContent', { _csrf: this.props.csrf, index: this.props.index, content, } ).then(setMessageSaved); } // Render question render() { const question = this.props.question; const questionTitleId = `questionTitle_${this.props.index}`; const questionDescriptionId = `questionDescription_${this.props.index}`; // Check if the question was loaded if (!question) { return ( <div>Question Not Loaded</div> ) } // Updates the question's title after the user has stopped typing for half a second. const titleUpdater = new DelayUpdateHandler( 500, () => { this.updateTitle($(`#${questionTitleId}`).val()) }, setMessageSaving ); // Updates the question's description after the user has stopped typing for half a second. const contentUpdater = new DelayUpdateHandler( 500, () => { this.updateDescription($(`#${questionDescriptionId}`).val()) }, setMessageSaving ); // Pick an answer panel based off the question type let answerPanel; switch (question.type) { // Multiple Choice question case "MultipleChoice": answerPanel = (<AnswerMultipleChoiceListPanel index={this.props.index} question={question} onChange={this.loadQuestions} csrf={this.props.csrf} />); break; // True/False question case "TrueFalse": answerPanel = (<AnswerTrueFalsePanel index={this.props.index} question={question} onChange={this.loadQuestions} csrf={this.props.csrf} />); break; // Numeric question case "Numeric": answerPanel = (<AnswerNumericPanel index={this.props.index} question={question} onChange={this.loadQuestions} csrf={this.props.csrf} />); break; // Text Question or default case default: case "Text": answerPanel = (<AnswerTextPanel index={this.props.index} question={question} onChange={this.loadQuestions} csrf={this.props.csrf} />); break; } return ( <div className="questionPanel"> <header> <span>Question {this.props.index + 1}: </span> {/* Lets user change the question type */} <select className="questionType" defaultValue={question.type} onChange={this.setQuestionType} > <option value="MultipleChoice">Multiple Choice</option> <option value="TrueFalse">True or False</option> <option value="Numeric">Numeric</option> <option value="Text">Text Answer</option> </select> {/* Delete question when clicked */} <input type="button" className="quizBuilderButton deleteQuestion" value="Delete Question" onClick={ () => this.props.parent.deleteQuestion(this.props.index) } /> </header> <hr /> <div> <label> Title: </label> {/* Let's the user change the title of the question */} <AutoExpandTextField id={questionTitleId} className="questionTitle" name="name" placeholder="Enter Title for Question" defaultValue={this.props.question.title} onChange={titleUpdater.update} /> </div> <div> <label>Question:</label> <br /> {/* Let's the user change the content of the question */} <AutoExpandTextArea id={questionDescriptionId} className="questionDescription" name="content" placeholder="Enter description" defaultValue={question.content} onChange={contentUpdater.update} /> <br /> </div> {/* Show answers */} {answerPanel} </div> ) } }
JavaScript
class SynthPad1 extends Tone.PolySynth { constructor(options = {}) { super( Object.assign( { maxPolyphony: 8, volume: 0, voice: Tone.MonoSynth, options: { oscillator: { voices: 3, detune: 1, type: "fatsawtooth", }, envelope: { attack: 1, decay: 0.5, sustain: 0.4, release: 1.5, }, filterEnvelope: { baseFrequency: 1100, attack: 0.8, decay: 0, sustain: 1, release: 1, }, }, }, options ) ); this.efx = { delay: new Tone.FeedbackDelay({ delayTime: "8n.", feedback: 0.3, wet: 0.2, }), reverb: new Tone.Reverb({ // convolver: this.efx.convolver, decay: 6, preDelay: 0.2, wet: 0.8, }), }; this.pattern = options.pattern || patterns.eternity; this.preEfxOut = this.output; this.noteIndex = 0; this.preEfxVolume = this.volume; this.playing = false; this.transport = options.transport || Tone.getTransport(); return this; } // async postInit() { // const postEfxVolume = new Tone.Volume(); // this.chain( // this.efx.distortion, // this.efx.delay, // this.efx.reverb, // postEfxVolume // ); // delete this.volume; // delete this.output; // this.output = postEfxVolume; // this.volume = postEfxVolume.volume; // await this.efx.reverb.generate(); // } repeater(time) { if (this.pleaseStop) { this.pleaseStop = false; return; } let note = this.pattern[this.noteIndex % this.pattern.length]; this.triggerAttackRelease(note, "4n", time); this.noteIndex++; } start() { this.pleaseStop = false; this.noteIndex = 0; this.nextEvent = this.transport.scheduleRepeat((time) => { this.repeater(time); }, "4n"); } stop() { this.pleaseStop = true; if (this.nextEvent) this.transport.cancel(this.nextEvent); } dispose() { for (const effect of Object.values(this.efx)) { effect.disposed || effect.dispose(); } this.disposed || super.dispose(); } }
JavaScript
class EventAggregator { /** * Contructor that initializes internal stuff. * @constructor */ constructor() { this.subscriptionsByTopic = {}; } /** * Registers a subscriber for a specific event topic. * @param {string} topic - name of the event type / topic. * @param {string} subscriberId - id the subscriber, must be unique. * @param {function(topic: string, sender: string, payload: Object)} onNotifyFn - callback * invoked upon when upon notification. * @param {Object} invokationScope - scope to be used when invoking callback, optional. */ subscribeTo(topic, subscriberId, onNotifyFn, invokationScope) { if (!this.subscriptionsByTopic[topic]) { this.subscriptionsByTopic[topic] = []; } this.subscriptionsByTopic[topic].push({ subscriber: subscriberId, callbackFn: onNotifyFn, invokationScope }); } // ToDo needs test /** * Unregisters a subscriber from a specific event topic. * @param {string} topic - name of the event type / topic. * @param {string} subscriber - id the unique subscriber. */ unsubscribeTo(topic, subscriber) { Object.keys(this.subscriptionsByTopic[topic]).forEach((j) => { if (this.subscriptionsByTopic[topic][j].subscriber === subscriber) { this.subscriptionsByTopic[topic].splice(j, 1); } }); } /** * Called to notify all subscribers of this topic * @param {string} topic - name of the event type / topic. * @param {string} sender - address of the sender. * @param {Object} payload - any data to pass to the subscriber. */ notify(topic, sender, payload) { if (!this.subscriptionsByTopic[topic]) { return; } Object.keys(this.subscriptionsByTopic[topic]).forEach((s2) => { let scope; if (this.subscriptionsByTopic[topic][s2].invokationScope) { scope = this.subscriptionsByTopic[topic][s2].invokationScope; } this.subscriptionsByTopic[topic][s2].callbackFn.apply(scope, [topic, sender, payload]); }); } }
JavaScript
class ClassOverview extends Component { constructor(props) { super(props); this.state = { data: {}, loading: true, fail: false }; } //Fetch the class with the corresponding url id componentDidMount(){ fetch(`./data/${this.props.classGroup}/${this.props.match.params.id}.json`) .then(res => res.json()) .then(fetchedData => this.setState({data: fetchedData, loading: false, fail: false})) .catch(err => this.setState({fail: true})); } //If url id changes, fetch and render the new class //When page updates, jump to anchor tag in url if there is one componentDidUpdate(prevProps, prevState){ if(prevProps.match.params.id !== this.props.match.params.id){ this.setState({loading: true}); fetch(`./data/${this.props.classGroup}/${this.props.match.params.id}.json`) .then(res => res.json()) .then(fetchedData => this.setState({data: fetchedData, loading: false, fail: false})) .catch(err => this.setState({fail: true})); }; if (window.location.hash) { const id = window.location.hash.replace("#", "").split("#"); const element = document.getElementById(id[1]); if(element){element.scrollIntoView();} }; } render() { const { loading, fail, data } = this.state ; return ( <div> <HeaderImage imageUrl={HeaderImageUrl.library}/> { loading ? <Container>{fail ? <h3>Looks like there was an error in the URL you entered, the page you are looking for may be moved or deleted.</h3> : ""}</Container> : <div> <Helmet> <title>{`${data.class} | Grandis Library`}</title> <meta content={data.meta} name="description"/> </Helmet> <Container> <ClassIntro data={data}/> {data.content.howToCreate && <ClassCreation classTitle={data.class} howToCreate={data.content.howToCreate}/>} {data.content.extraContent && <ClassExtraContent title={data.content.extraContent.title} content={data.content.extraContent.content}/>} <div id="skill"/> <SkillTab primary={data.skill.primary} fifth={data.skill.fifth} hyper={data.skill.hyper} hyperSkillBuild={data.content.hyperBuild} nodeInfo={data.content.nodeInfo}/> <hr/> <ClassOutro classGroup={data.content.classGroup} classTitle={data.class} moreInfo={data.content.moreInfo} credits={data.content.credits}/> </Container> </div> } </div> ); } }
JavaScript
class EyesWrappedElement { /** * Check if object could be wrapped with this class * @param {Object} object * @return {boolean} true - object could be wrapped with this class, otherwise - false */ static isCompatible(object) { throw new TypeError('The method is not implemented!') } /** * Compare two elements, these elements could be an instances of this class or compatible objects * @param {EyesWrappedElement|UnwrappedElement} leftElement * @param {EyesWrappedElement|UnwrappedElement} rightElement * @return {boolean} true - elements are equal, otherwise - false */ static equals(leftElement, rightElement) { throw new TypeError('The method is not implemented!') } /** * Extract element ID from this class instance or compatible object * @param {EyesWrappedElement|UnwrappedElement} element * @return {?string} if extraction is succeed returns ID of provided element, otherwise null */ static elementId(element) { throw new TypeError('The method is not implemented!') } /** * Returns ID of the wrapped element * @return {string} ID of the wrapped element */ get elementId() { throw new TypeError('The method is not implemented!') } /** * Returns unwrapped elements * @return {UnwrappedElement} unwrapped element */ get unwrapped() { throw new TypeError('The method is not implemented!') } /** * Returns element's rect related to context * @return {Promise<Region>} rect of the element */ async getRect() { throw new TypeError('The method is not implemented!') } /** * Returns element's bounds related to context * @return {Promise<Region>} bounds of the element */ async getBounds() { throw new TypeError('The method is not implemented!') } /** * Returns element's size * @return {Promise<RectangleSize>} size of the element */ async getSize() { throw new TypeError('The method is not implemented!') } /** * Returns element's location related to context * @return {Promise<Location>} location of the element */ async getLocation() { throw new TypeError('The method is not implemented!') } /** * Returns computed values for specified css properties * @param {...string} cssPropertyNames * @return {Promise<string[]|string>} returns array of css values if multiple properties were specified, * otherwise returns string */ async getCssProperty(...cssPropertyNames) { throw new TypeError('The method is not implemented!') } /** * Returns values for specified element's properties * @param {...string} propertyNames * @return {Promise<*[]|*>} returns array of values if multiple properties were specified, * otherwise returns value */ async getProperty(...propertyNames) { throw new TypeError('The method is not implemented!') } /** * Returns element's overflow from style attribute * @return {Promise<?string>} returns element's overflow if it was specified, otherwise returns null */ async getOverflow() { throw new TypeError('The method is not implemented!') } /** * Set overflow in element's style attribute * @param {?string} overflow * @return {Promise<void>} */ async setOverflow(overflow) { throw new TypeError('The method is not implemented!') } }
JavaScript
class howtoScene extends Phaser.Scene { /** * Constructor * @constructor */ constructor() { super({ key: 'Howto' }); } /** * Initialize the scene with some positions of the playing area, the grid size and get the menu music from the * previous scene * @param data */ init(data) { // parameters for the level drawing this.originLeft = {x: 10, y: 10}; // origin of the left side (top left) (px) this.originRight = {x: 630, y: this.originLeft.y}; // origin of the right side (top right) (px) this.gridSize = 12.5; // size of the grid to place objects (px) this.musicMenu = data.musicMenu; // get the menu music from the previous scene ("home" scene) } /** * Creates the "How to Play" scene with all of it's elements */ create() { // text styles this.styles = new TextStyle(); // add background this.add.image(0, 0, 'background').setOrigin(0, 0); // draw level (non-interactive as it is not used to play) this.level = new Levels(this.originLeft, this.originRight, this.gridSize); // create the level object this.level.createNonInteractiveLevel(this); // create a non-interactive level // add mirror indicator let indicator = this.add.image(485, 400, 'indicator').setOrigin(0.5); // add the mirror image this.mirrorPointer = this.add.sprite(indicator.x - indicator.width / 2 + 12, indicator.y + indicator.height / 2 - 14, 'pointer').setOrigin(0.5); // add the pointer of the mirror on the left side // add the inspector eyes this.eyes = this.add.sprite(485, 345, 'eyes', 0).setOrigin(0.5); // add the timer (set to 00:00) this.add.text(485, 445, '00:00', this.styles.get(2)).setOrigin(0.5); // Add keyboard inputs this.addKeys(); // Add a new frame object (for the "How to Play" explanations) this.frame = new Frame(this, 320, 240, 470, 290, 'Title','Text', this.styles); // Add highlighters to highlight aspects of the game (flashing (changing color) rectangles) this.highlighter = this.add.rectangle(8, 8, 304, 304).setOrigin(0).setDepth(1.5); // first highlighter this.highlighter.setStrokeStyle(4, 0x8cefb6); this.highlighterColors = [0x8cefb6, 0x474476, 0x6dbcb9, 0x4888b7]; // different highlighter colors which will change in a certain frequency this.highlighterCounter = 0; // counter to count which color is currently shown this.highlighter.setVisible(false); // make the highlighters invisible first this.highlighter2 = this.add.rectangle(8, 8, 304, 304).setOrigin(0).setDepth(1.5); // second highlighter (when two objects need to be highlighted) this.highlighter2.setStrokeStyle(4, 0x8cefb6); this.highlighter2.setVisible(false); // make the highlighters invisible first // timed event to change the color of the highlighter (make it flashing) this.time.addEvent({ delay: 300, repeat: -1, // -1 means it will repeat forever callback: function () { // change the color of the highlighter to the next color // increase the highlighter counter (which chooses the color) by one or reset it back to the first one if (this.highlighterCounter < this.highlighterColors.length - 1) { this.highlighterCounter++; // if it is not the last color, change to the next one } else { this.highlighterCounter = 0; // if it is the last color, change to the first one } // change the color of both frames based on the counter this.highlighter.setStrokeStyle(4, this.highlighterColors[this.highlighterCounter]); this.highlighter2.setStrokeStyle(4, this.highlighterColors[this.highlighterCounter]); }, callbackScope: this }); // add object array for different objects which are added to a certain part (stage) of the "How to Play" usually in the frames // this allows to destroy the objects in one action ("destroyAll" method) this.objectArray = []; // stage counter, which counts at which stage the player is in the "How to Play" this.stage = 0; // start first stage (by triggering the space key action) this.spaceEnterKey(); } update(time, delta) { } /** * Add keyboard input to the scene. */ addKeys() { // enter, space and backspace key this.input.keyboard.addKey('Enter').on('down', function() { this.spaceEnterKey() }, this); // next stage this.input.keyboard.addKey('Space').on('down', function() { this.spaceEnterKey() }, this); // next stage this.input.keyboard.addKey('Backspace').on('down', function() { this.backKey() }, this); // go back to home scene } /** * Action which happens when the enter or space key is pressed. The player(s) will be guided through the different * stages / parts / sections of the "How to Play". At the end it will jump back to the "Home" scene */ spaceEnterKey() { // based on the current stage a different instruction is shown // in this way the player(s) will be going through the instructions step-by-step (stage) switch(this.stage) { case 0: // Story, world description this.stage++; // make sure next stage is shown after this this.frame.changeText('Story', 'The Block universe is divided into 5879 sectors and ruled by the mighty Inspectors.'); // text this.objectArray.push(this.add.image(this.frame.x, this.frame.y + 10, 'eyes', 0).setDepth(3)); // add the inspector eyes break; case 1: // Story, sector description this.stage++; // make sure next stage is shown after this this.destroyAll(); // destroy all objects of the previous stage this.frame.changeText('Story', 'Each sector is inhabited by multiple blocks and contains one huge mirror.'); // text this.objectArray.push(this.add.image(this.frame.x - 50, this.frame.y + 10, 'block1', 1).setDepth(3)); // add the blocks this.objectArray.push(this.add.image(this.frame.x, this.frame.y + 10, 'block2', 1).setDepth(3)); this.objectArray.push(this.add.image(this.frame.x + 50, this.frame.y + 10, 'block3', 1).setDepth(3)); break; case 2: // Story, tasks description this.stage++; // make sure next stage is shown after this this.destroyAll(); // destroy all objects of the previous stage this.frame.changeText('Story', 'Every day the blocks get tasks from the Inspectors which they need to fulfil. ' + 'These tasks consist of visiting and touching the three holy pictures Tree, Rocket and Potato in a specific order. ' + 'While doing that they should not touch each other and the dangerous X blocks.'); // text this.objectArray.push(this.add.image(this.frame.x , this.frame.y + 23, 'checkpoint', 0).setDepth(3)); // add the checkpoints this.objectArray.push(this.add.image(this.frame.x + 50, this.frame.y + 23, 'checkpoint', 1).setDepth(3)); this.objectArray.push(this.add.image(this.frame.x + 100, this.frame.y + 23, 'checkpoint', 2).setDepth(3)); this.objectArray.push(this.add.image(this.frame.x + 50, this.frame.y + 57, 'danger', 0).setDepth(3)); // add the danger blocks break; case 3: // Story, penalty this.stage++; // make sure next stage is shown after this this.destroyAll(); // destroy all objects of the previous stage this.frame.changeText('Story', 'If the blocks do not fulfil their tasks, they will receive the maximum penalty: ' + 'They will be transformed into circles!'); // text this.objectArray.push(this.add.image(this.frame.x - 50, this.frame.y + 10, 'block1', 1).setDepth(3)); // add the blocks this.objectArray.push(this.add.image(this.frame.x, this.frame.y + 10, 'block2', 1).setDepth(3)); this.objectArray.push(this.add.image(this.frame.x + 50, this.frame.y + 10, 'block3', 1).setDepth(3)); let round = false; // switch to indicate if the blocks are round // change the blocks from square to round and back (timed event repeated infinitely) this.squareToRound = this.time.addEvent({ delay: 1000, repeat: -1, callback: function() { if (round) { this.objectArray[0].setFrame(1); // change to squares if they are round this.objectArray[1].setFrame(1); this.objectArray[2].setFrame(1); } else { this.objectArray[0].setFrame(2); // change to circles if they are not round this.objectArray[1].setFrame(2); this.objectArray[2].setFrame(2); } round = !round; // toggle swich }, callbackScope: this }); break; case 4: // Story, inspection description this.squareToRound.destroy(); // destroy timed event (square to round changes) this.stage++; // make sure next stage is shown after this this.destroyAll(); // destroy all objects of the previous stage this.frame.changeText('Story', 'However, there are not enough Inspectors to monitor all sectors every day and ' + 'each sector will be inspected for three days a year.'); // text break; case 5: // Story, detachment this.stage++; // make sure next stage is shown after this this.frame.changeText('Story', 'Sector 723 has always been a role model for all other sectors. ' + 'They performed their tasks always fast and without any errors.\n' + 'However, 13 days ago something strange happened! The mirror images of the blocks detached from their counterparts and started their own life. ' + 'All six blocks enjoyed the new freedom and celebrated it with wild parties!'); // text break; case 6: // Story, inspection day! this.stage++; // make sure next stage is shown after this this.frame.changeText('Story', 'However, today the Inspection Days start!\n\n' + 'The six blocks need to pretend that everything is normal for the next three days to pass the Inspection. ' + 'They need to fulfil their tasks and the mirror images and their real counterparts need to move in sync to each other...\nGood Luck!'); // text break; case 7: // How to Play, general description this.stage++; // make sure next stage is shown after this this.frame.changeText('How To Play', 'This is a cooperative 2 player game where you ' + 'need to work together to deceive the Inspector and maintain the freedom in Sector 723!'); // text break; case 8: // How to Play, player 1 side and controls this.stage++; // make sure next stage is shown after this this.highlighter.setPosition(8, 8).setSize(304, 304); // set highlighter for left playing area this.highlighter.setVisible(true); // make highlighter visible this.frame.setSize(479, 200); // change size of the frame this.frame.setPosition(380, 362) // change position of the frame (bottom right) this.frame.changeText('How To Play', 'Player 1 controls the real blocks on the left side by moving them with W, A, S, D ' + 'and changing between the blocks with SPACE.'); // text break; case 9: // How to Play, player 2 side and controls this.stage++; // make sure next stage is shown after this this.highlighter.setPosition(328, 8).setSize(304, 304); // move the highlighter to the right playing area this.frame.setPosition(260, 362) // change position of the frame (bottom left) this.frame.changeText('How To Play', 'Player 2 controls the mirror blocks on the right side by moving them with the Arrow Keys ' + 'and changing between the blocks with ENTER.'); // text break; case 10: // How to Play, pirate special movement this.stage++; // make sure next stage is shown after this // highlight the pirates this.highlighter.setPosition(8, 145.5).setSize(29, 29); // highlight left pirate this.highlighter2.setPosition(603, 145.5).setVisible(true).setSize(29, 29); // highlight right pirate this.frame.setPosition(320, 362); // change position of the frame (bottom middle) this.frame.changeText('How To Play', 'Watch out, the pirates move always in the opposite direction of what you tell them!'); // text this.objectArray.push(this.add.image(this.frame.x, this.frame.y + 10, 'block2', 1).setDepth(3)); // add pirate block into frame break; case 11: // How to Play, goal this.stage++; // make sure next stage is shown after this this.destroyAll(); // destroy all objects of the previous stage this.highlighter.setPosition(26, 328).setSize(265, 135); // highlight the tasks section this.highlighter.setVisible(true); // make first highlighter visible again (obsolete?) this.highlighter2.setVisible(false); // make second highlighter invisible (not used anymore) this.frame.setPosition(320, 150); // move frame (top middle) this.frame.changeText('How To Play', 'Fulfil all tasks of every block to pass the day. ' + 'Make sure the right side mirrors the movement on the left side so that the Inspector does not realize ' + 'that they are independent.'); // text break; case 12: // How to Play, mirror-o-meter this.stage++; // make sure next stage is shown after this this.highlighter.setPosition(350, 370).setSize(270, 60); // highlight the mirror-o-meter this.frame.changeText('How To Play', 'The Mirror-O-Meter and the music tell you how well you mirror the movements. ' + 'If the pointer moves too far right the Inspector will detect the deception and you will fail the Inspection.'); // text break; case 13: // How to Play, par time this.stage++; // make sure next stage is shown after this this.highlighter.setPosition(440, 430).setSize(90, 35); // highlight timer this.frame.changeText('How To Play', 'Try to beat the level and game as fast as possible and ' + 'beat the Par time (best time of the games developer).'); // text break; case 14: // Have fun this.stage++; // make sure next stage is shown after this this.highlighter.setVisible(false); // make highlighter invisible this.frame.setPosition(320, 240); // move frame to middle this.frame.setSize(470, 290); // make frame large again this.frame.changeText('Have Fun', 'You and your friend should now know everything to ' + 'save Sector 723. Good Luck, Sector 723 counts on you!'); // text this.frame.changePressText('\nPress [ENTER] or [SPACE] to go back to Main Menu'); // change the "press" text from default to back to main menu break; default: // if the last stage is reached go back to the main menu this.backKey(); // go back to the main menu by triggering the "backspace" action break; } } /** * Action which happens when the backspace key is pressed. Go back to the "Home" scene. */ backKey() { this.musicMenu.stop(); // stop the menu music this.scene.start('Home', {sequence: this.musicMenu.getSequence()}); // change to "home" scene and provide the current chord progression / sequence } /** * Destroys all objects of a stage, to simplify the destruction. */ destroyAll() { // destroy each object of the array for (let i in this.objectArray) { this.objectArray[i].destroy(); } // reinitialize the array this.objectArray = []; } }
JavaScript
class RegisterController { /** * Show a list of all registers. * GET registers * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index ({ request, response, view }) { } /** * Render a form to be used for creating a new register. * GET registers/create * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async create ({ request, response, view }) { return view.render('auth.register') } /** * Create/save a new register. * POST registers * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store ({ request, response, session }) { const rules = { email: 'required|email|unique:users,email', password: 'required|min:4|confirmed' } const validation = await validate(request.all(),rules) if (validation.fails()) { session.withErrors(validation.messages()).flashExcept(['password']) return response.redirect('back') } const user = await User.create({ email: request.input('email'), password: request.input('password') }) session.flash({ successMessage: 'Conta criada com sucesso' }) return response.redirect('/login') } /** * Display a single register. * GET registers/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show ({ params, request, response, view }) { } /** * Render a form to update an existing register. * GET registers/:id/edit * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async edit ({ params, request, response, view }) { } /** * Update register details. * PUT or PATCH registers/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update ({ params, request, response }) { } /** * Delete a register with id. * DELETE registers/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy ({ params, request, response }) { } }
JavaScript
class BaseCollection { /** * @constructor * @for BaseCollection */ constructor() { /** * Unigue string id that can be used to differentiate this model instance from another. * * @property _id * @type {string} * @private */ this._id = _uniqueId(); /** * @property _items * @type {array} * @default [] * @private */ this._items = []; } /** * Current length of the collection * * @property length * @return {number} */ get length() { return this._items.length; } /** * Initialize the model properties. Should be run on instantiation and, though not desired, * could be run multiple times after instantiation. * * This method may be called by the constructor or from a public fascade. * * @for BaseCollection * @method _init * @private */ _init() { throw new TypeError('BaseCollection#_init has not been implemented by the extending class'); } /** * Destory the current instance. * * When implemented by the inheriting class, this method should un-set all class properties * and remove any handlers. * * @for BaseCollection * @method destroy */ destroy() { throw new TypeError('BaseCollection#destroy has not been implemented by the extending class'); } }
JavaScript
class ToDo { constructor(name, dueDate, list){ this.name = name; this.dueDate = dueDate; this.list = list; } attachThestring(stringToAttach){ this.list.push(stringToAttach); } }
JavaScript
class GraphProfesion extends React.Component { componentDidMount() { this.mounted = true; fetch('https://censovenezolanoback.herokuapp.com/censos/estadisticas') .then(res => res.json()) .then(json => { let datos = json.estadisticas; let profesion_label = [ 'Ninguna', 'Cerrajero', 'Constructor', 'Medico', 'Astronauta', 'Guardia', 'Administrador', 'Actor', 'Bombero', 'Ejecutivo', 'Vendedor', 'Agricultor', 'Ingeniero', 'Enfermera', 'Educador', 'Plomero' ]; let profesion_datos = [ datos.profesion.ninguna, datos.profesion.cerrajero, datos.profesion.constructor, datos.profesion.medico, datos.profesion.astronauta, datos.profesion.guardia, datos.profesion.adminitrador, datos.profesion.actor, datos.profesion.bombero, datos.profesion.ejecutivo, datos.profesion.vendedor, datos.profesion.agricultor, datos.profesion.ingeniero, datos.profesion.enfermera, datos.profesion.educador, datos.profesion.plomero ]; if (this.mounted) { this.setState({ data: [ { x: profesion_label, y: profesion_datos, mode: 'markers', marker: { size: profesion_datos } } ], layout: { title: 'Profesiones', showlegend: false, height: 600, width: 800 }, frames: [], config: {} }); } }); } componentWillUnmount() { this.mounted = false; } constructor(props) { super(props); this.state = { data: [ { x: [], y: [], mode: 'markers', marker: { size: [] } } ], layout: { title: 'Profesiones', showlegend: false, height: 600, width: 800 }, frames: [], config: {} }; } render() { return ( <Plot data={this.state.data} layout={this.state.layout} frames={this.state.frames} config={this.state.config} onInitialized={figure => this.setState(figure)} onUpdate={figure => this.setState(figure)} /> ); } }
JavaScript
class TextPart extends Phaser.GameObjects.Text { constructor (scene, x = 0, y = 0, text = '', style = {}) { super(scene, x, y, '', (style instanceof TextStyle) ? style.toPhaserTextStyle() : style); this._printSpeed = 15; this._printedCount = 0; this._printText = text; this._elapsedMS = 0; this._isInitialized = false; this._isPrinting = false; } get isPrinting () { return this._isPrinting; } update (time, delta) { if (this._isInitialized == false) { this._isPrinting = this._isInitialized = true; this.emit('StartPrinting', this); } else if (this._isPrinting) { this._elapsedMS += delta; if (this._elapsedMS > this._printSpeed) { this._printedCount++; this.setText(this._printText.substr(0, this._printedCount)); this._elapsedMS = 0; if (this.text.length >= this._printText.length) { this._isPrinting = false; this.emit('DonePrinting', this); } } } } }
JavaScript
class BeforeGameOver extends Phaser.State { /** * Description * * @param {*} score, final score * @param {*} population, final city population */ init (score, population, gameData, game, config, utils, texts) { this.points = score this.population = population this.gameData = gameData this.game = game this.config = config this.utils = utils this.texts = texts } /** * Creates the elements shown in the menu. * The input field is added first so that its value can be read by the submit * button. */ create () { this.loadHighscoreToLocalStorage() this.menu = new MenuBuilder(this, 'gameover', this.camera.height * 5 / 9, this.gameData.config) this.stage.backgroundColor = 0x000000 var inputField = this.addInputFieldToMenu() this.addButtonsToMenu(inputField) } addInputFieldToMenu () { this.menu.createInputField({ padding: 8, borderWidth: 1, borderColor: '#000000', borderRadius: 6, placeHolder: this.texts.gameOverState.enterName }) this.menu.finishMenu() return this.menu.c.menuView.activeInputFields[0].inputField } addButtonsToMenu (inputField) { var toGameOverState = () => { this.state.start('GameOver', true, false, this.points, this.population, this.gameData, this.game, this.texts) } var sendScore = (name) => { this.utils.submitScore( {player: name, points: this.points}, this.config.gameSettings.scoreServer, new XMLHttpRequest() ) } this.menu.createButton('Lähetä tulos', () => { sendScore(inputField.value) toGameOverState() }) this.menu.createButton('Jatka', toGameOverState) this.menu.finishMenu() } loadHighscoreToLocalStorage () { // load highscore var highScore = 0 var loadScore = localStorage.getItem('biopeliHighScore') if (loadScore !== null) { highScore = parseInt(loadScore) } this.HighScore = highScore localStorage.setItem('biopeliHighScore', this.HighScore) } }
JavaScript
class SimpleCallOptionContract { constructor() { this.provider = new ethers.providers.Web3Provider(window.web3.currentProvider); this.contractAddress = "0x4Fc3Ba4585C6B3D85742B6E56B6250A4862A98D5"; this.contract = new ethers.Contract(this.contractAddress, SimpleCallOptionContractMeta.abi, this.provider.getSigner()); } async addNewOption(addr, name, price, year, rate) { let newTransaction = await this.contract.addOption(addr, name, price, year, rate); return newTransaction.hash } }
JavaScript
class Employee { constructor(name, id, email) { // Creates properties using the input this.name = name; this.id = id; this.email = email; } // Creates a method that returns the name getName () { return this.name; } // Creates a method that returns the id getId () { return this.id; } // Creates a method that returns the email getEmail () { return this.email; } // Creates a method that returns the role as Employee getRole () { return "Employee"; } }
JavaScript
class LoadForm extends Form { /** * creates loadForm * @param type */ constructor(type) { super(); } /** * returns data of loadForm * @return {*} */ getData() { const avatar = this.UploadInput.getFormData(); if (avatar === '') { return null; } return { avatar: avatar }; } /** * @return {HTMLDivElement} */ render() { this.UploadInput = new Input({ type: 'file', placeholder: '', id: 'loadImageInput' }, 'upload-input'); // this.UploadInput = new InputUpload(); this.UploadSubmit = new Input({ type: 'submit', value: 'Save picture', id: 'loadImageSubmit' }, 'upload-submit'); this.formElement.appendChild(this.UploadInput.render()); this.formElement.appendChild(this.UploadSubmit.render()); this.formElement.setAttribute('enctype', 'multipart/form-data'); this.formElement.setAttribute('name', 'form_loadFile'); this.formElement.classList.add('load-form'); return this.formElement; } setOnSubmit(callbackfn) { this.formElement.addEventListener('submit', (ev) => { ev.preventDefault(); callbackfn(); }); } }
JavaScript
class Reader { constructor(content) { this.idx = 0; this.content = content; this.len = content.length; } //> Returns the current character and moves the pointer one place farther. next() { const char = this.content[this.idx ++]; if (char === undefined) { this.idx = this.len; } return char; } //> Move the pointer back one place, undoing the last character read. // In practice, we never backtrack from index 0 -- we only use back() // to "un-read" a character we've read. So we don't check for negative cases here. back() { this.idx --; } //> Read up to a specified _contiguous_ substring, // but not including the substring. readUpto(substr) { const nextIdx = this.content.substr(this.idx).indexOf(substr); return this.toNext(nextIdx); } //> Read up to and including a _contiguous_ substring, or read until // the end of the template. readUntil(substr) { const nextIdx = this.content.substr(this.idx).indexOf(substr) + substr.length; return this.toNext(nextIdx); } //> Abstraction used for both `readUpto` and `readUntil` above. toNext(nextIdx) { const rest = this.content.substr(this.idx); if (nextIdx === -1) { this.idx = this.len; return rest; } else { const part = rest.substr(0, nextIdx); this.idx += nextIdx; return part; } } //> Remove some substring from the end of the template, if it ends in the substring. // This also returns whether the given substring was a valid ending substring. clipEnd(substr) { if (this.content.endsWith(substr)) { this.content = clipStringEnd(this.content, substr); return true; } return false; } }
JavaScript
class App extends React.Component { state = { account: "" } componentDidMount = async () => { try { // Use web3 to get the user's accounts. const account = await window.ethereum.request({ method: 'eth_accounts' }); this.setState({account: account[0]}) } catch (error) { // Catch any errors for any of the above operations. alert( `Failed to load web3, accounts, or contract. Check console for details.`, ); console.error(error); } } render() { return ( <Router> <Switch> <div> <Navbar account={this.state.account}/> <Route exact path='/'> <Main /> </Route> <Route exact path='/home'> <Main /> </Route> <Route exact path='/list-products'> <ListProducts /> </Route> <Route exact path='/my-products'> <MyProducts /> </Route> </div> </Switch> </Router> ); } }