query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Create a function to setup initial quiz screen html and show button that will start the quiz
function initialScreen() { $("body").html(`<div class = "jumbotron text-center"><div class = "Quiz"> <h1 class = title>State Capitals Trivia Quiz!</h1><br><button id = startButton>Play</button></div>`) $("#startButton").on("click", function(){ $("body").html(`<div class = "jumbotron text-center"> <div class = "Quiz"> <h1 class = "title">State Capitals Trivia Quiz!</h1> <p>Time Remaining: <span id = "timer">10</span></p> <p class = "question"></p> <p class = "choices"></p> <p class = "answer"></p> <p class = "result"></p> </div> </div>`) Quiz.displayQuestion(quizCounter); }) }
[ "function initiateQuiz() {\n startQuiz();\n renderFirstQuestion();\n answerChoice();\n renderNextQuestion();\n}", "function startQuiz() {\n // clear the start-view page when start-button is clicked\n $(\".score-and-question\").show();\n updateQuestion();\n generateForm();\n\n generateQuestion(STORE.currentQuestion);\n}", "function startQuizApp() {\n $('.js-start-button').click(function () {\n $('.start-page').hide();\n $('.question-page').show(); \n $('header').html(generateQuestionPageHeader());\n $('.js-question-number').text(1);\n renderQuestionInterface(STORE[questionNumber]);\n });\n}", "function initialPage() {\n\tstartScreen = \"<p class='text-center main-button-container'><a class='btn btn-primary btn-lg start-button' href='#' role='button'>Start Quiz</a></p>\";\n\t$(\".playArea\").html(startScreen);\n}", "function beginQuiz() {\n if (startQuiz) {\n header.style.display = 'none';\n quiz.style.display = 'block';\n createQuestions(mainQuestion);\n playTheme();\n }\n}", "function startQuiz() {\n $('#start').on('click', function(event){\n rendertheQuestion();\n }\n );\n }", "function startQuiz () {}", "function startQuiz() {\n homePage.hidden = true;\n questionElement.hidden = false;\n timerCountdown();\n getQuestion();\n}", "function startQuiz() {\n startButton.style.display = 'none';\n introText.style.display = 'none';\n questionHolder.style.display = '';\n displayQuestion(currentQuestion);\n}", "function renderStartQuizLayout() {\n $(\".js-quiz-form\").html(`<p>Test how much you know about the book series \"A Song of Ice and Fire\".</p><button type=\"submit\" class=\"js-quiz-start\">Start Quiz</button>`);\n }", "function initialScreen() {\n\tstartScreen = \"<p class='text-center main-button-container'>\";\n\tstartScreen += \"<a class='btn btn-primary btn-lg btn-block start-button' href='#' role='button'>Start Quiz</a></p>\";\n\t$(\".mainArea\").html(startScreen);\n\tclickStart.play();\n}", "function startQuiz() {\n introSectionEl.style.display = \"none\";\n questionSectionEl.style.display = \"block\";\n makeQuestion();\n timer();\n\n}", "function startQuiz(){\n\tif(!(accessValidation() )){\n\t\treturn;\n\t}\n\n\tif(document.getElementById(\"scoreTable\")){\n\t\tdocument.getElementById(\"scoreTable\").parentNode.removeChild(document.getElementById(\"scoreTable\"));\n\t}\n\n\tif(document.getElementById(\"accessScoresButton\")){\n\t\tdocument.getElementById(\"accessScoresButton\").parentNode.removeChild(document.getElementById(\"accessScoresButton\"));\n\t}\n\n\tvar h2Element = document.querySelector(\"h2\");\n\th2Element.innerHTML =\"\";\n\th2Element.style.display = \"none\";\n\tvar startedButton = document.getElementById(\"getStartedButton\");\n\tstartedButton.parentNode.removeChild(startedButton);\n\t\n\tvar changeQuestButtonText = document.createTextNode(\"Next Question\");\n\tvar changeQuestButtonElement = document.createElement(\"div\");\n\n\tchangeQuestButtonElement.appendChild(changeQuestButtonText);\n\tdocument.getElementById(\"actionButtons\").appendChild(changeQuestButtonElement);\n changeQuestButtonElement.classList.add(\"normalButton\");\n changeQuestButtonElement.id = \"nextQButton\";\n\tchangeQuestion();\n\t\n\t\n\tchangeQuestButtonElement.onclick = function(){changeQuestion(true)};\n}", "function initiateQuiz() {\r\n initializeQuiz();\r\n startQuiz();\r\n}", "function quizStarter() {\n startQuiz.style.display = 'none';\n newQuestion();\n}", "function startQuiz() {\n // hide the title screen,\n titleScreen.setAttribute(\"class\", \"hide\");\n // then show quiz questions, choices\n quizScreen.setAttribute(\"class\", \"show\");\n //starting timer at the end, instead of the beginning to be fair.\n setTime();\n}", "function startQuiz() {\n $(\".startquiz\").on(\"click\", function(event) {\n STORE.questionNumber = 0;\n STORE.score = 0;\n\n //render a question\n renderAQuestion(STORE.questionNumber);\n });\n }", "function quizPage() {\n\n const userName = localStorage.getItem(\"name\");\n if (!userName) {\n return;\n }\n\n const tempContent = document.importNode(templateEl.content, true);\n tempContent.querySelector('.welcome').textContent = `Welcome, ${userName}`;\n quizSection.append(tempContent);\n // Start timer\n startTimer(\"start\");\n // Next question event listener\n const nextBtn = quizSection.querySelector('.btn-next');\n nextBtn.addEventListener('click', nextQuestion);\n // Show question\n show(questionCount);\n}", "function startQuiz() {\n startPage.style.display = \"none\";\n quizPage.style.display = \"block\";\n countDown();\n giveQuestion(currentQuestion)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SET IDs IN DOM TO GLOBAL VARIABLES
function IDsToVars(){ var allElements = document.getElementsByTagName("*"); for (var q = 0; q<allElements.length; q++){ var el = allElements[q]; if (el.id){ window[el.id]=document.getElementById(el.id); } } }
[ "function idsToVars() {\n\t\t[].slice.call(document.querySelectorAll('*')).forEach(function(el) {\n\t\t\tif (el.id) window[el.id] = document.getElementById(el.id);\n\t\t});\n\t}", "function idsToVars() {\n [].slice.call(document.querySelectorAll('*')).forEach(function(el) {\n if (el.id) window[el.id] = document.getElementById(el.id);\n });\n}", "function IDsToVars(){\r\n var allElements = document.getElementsByTagName(\"*\");\r\n \r\n for (var q = 0; q<allElements.length; q++){\r\n var el = allElements[q];\r\n if (el.id){\r\n window[el.id]=document.getElementById(el.id);\r\n }\r\n }\r\n}", "function IDsToVars() {\n var allElements = document.getElementsByTagName(\"id\");\n\n for (var q = 0; q < allElements.length; q++) {\n var el = allElements[q];\n if (el.id) {\n window[el.id] = document.getElementById(el.id);\n }\n }\n}", "_setIds() {\n const that = this;\n\n if (!that.$.label.id) {\n that.$.label.id = that.id + 'Label';\n }\n\n if (!that.$.radixDisplayButton.id) {\n that.$.radixDisplayButton.id = that.id + 'RadixDisplayButton';\n }\n\n if (!that.$.unitDisplay.id) {\n that.$.unitDisplay.id = that.id + 'UnitDisplay';\n }\n\n if (!that.$.dropDown.id) {\n that.$.dropDown.id = that.id + 'DropDown';\n }\n\n if (!that.$.hint.id) {\n that.$.hint.id = that.id + 'Hint';\n }\n }", "_setIds() {\n const that = this;\n\n if (!that.$.label.id) {\n that.$.label.id = that.id + 'Label';\n }\n\n if (!that.$.input.id) {\n that.$.input.id = that.id + 'Input';\n }\n\n if (!that.$.calendarButton.id) {\n that.$.calendarButton.id = that.id + 'CalendarButton';\n }\n\n if (!that.$.dropDownContainer.id) {\n that.$.dropDownContainer.id = that.id + 'DropDownContainer';\n }\n\n if (!that.$.hint.id) {\n that.$.hint.id = that.id + 'Hint';\n }\n }", "function setIds() {\n let allArticles = document.querySelectorAll('.prod');\n for (var i = 0; i < allArticles.length; i++) {\n allArticles[i].setAttribute('id', i);\n }\n}", "function _assignUniqueIdsToDOM(doc) {\n var all = doc.body.getElementsByTagName(\"*\");\n for (var i = 0, max = all.length; i < max; i++) {\n all[i].setAttribute(\"id\", i);\n };\n return all.length;\n }", "function assignIds() {\n\t\tvar tiles = document.querySelectorAll(\".tile\");\n\t\tfor(var i = 0; i < tiles.length; i++) {\n\t\t\tvar row = parseInt(tiles[i].style.top) / tileSize;\n\t\t\tvar col = parseInt(tiles[i].style.left) / tileSize;\n\t\t\ttiles[i].id = \"tile_\" + row + \"_\" + col;\n\t\t}\n\t}", "function defineId() {\n _id = _dom.mainInput.id;\n if (!_id) {\n _id = (\"i\" + Math.round(Math.random() * 100000));\n _dom.mainInput.id = _id;\n }\n }", "function storeDomElements()\n\t{\n\t\tbp.CONF.els = {\n\t\t\twin : $(WIN),\n\t\t\tbody : $('body'),\n\t\t\tcontainer : $('#container'),\n\t\t\tageGate : $('#age-restricted'),\n\t\t\theader : $('header')\n\t\t};\n\n\t\t$.extend( bp.CONF.els, {\n\t\t\tsections : bp.CONF.els.container.find('section')\n\t\t});\n\t}", "function setInstances(dom) {\n let elements = {};\n [...dom.querySelectorAll(\"[identifier]\")].forEach(elem=>{\n let id = identifier(elem);\n let entry = elements[id];\n if (!entry) {\n entry = elements[id] = [];\n }\n entry.push(elem);\n });\n for (key in elements) {\n let seq=0;\n if (elements[key].length>1)\n elements[key].forEach(elem=>elem.setAttribute(\"instance\", ++seq));\n }\n }", "function setHtmlVars() {\n\tstatebox = $(\"#new_game_saver\");\n\tcurPlayBox = $(\"#game_currentplayer\");\n\tupdateForm = $('form.edit_game');\n\tsaverbox = $(\"#game_state\");\n\tcurPlayer = $('p')[0];\n}", "function setVariables(name) {\n $('#var_def').find(name).each(function() {\n var ths = $(this);\n ths.hide();\n var target = ths.attr('value');\n var element = ths.html();\n\n $('#var_container').find(name + '[value=\"' + target + '\"]').each(function() {\n $(this).append(element);\n });\n });\n}", "findUiElements() {\n this.config.uiElements = traverseObjectAndChange(this.config.uiElements, value => document.getElementById(value));\n }", "setIds(node) {\n // set ids\n const nodes = _.toArray(node.querySelectorAll('*:not([id])'));\n if (!node.getAttribute('id')) {\n nodes.unshift(node);\n }\n _(nodes).forEach(subnode => subnode.setAttribute('id', _.uniqueId(`${subnode.tagName}-`)));\n\n // set indexes on modules\n const moduleCells = node.querySelectorAll('cell[type=module]');\n for (let i = 0; i < moduleCells.length; i++) {\n moduleCells[i].setAttribute('module-index', i);\n }\n }", "function populate(elements)\n {\n for (const key of Object.keys(elements))\n {\n const id = key.replace(/_/g, \"-\");\n elements[key] = document.getElementById(id);\n }\n }", "function reloadVariables() {\n mainNote = document.querySelectorAll('.note');\n redButton = document.querySelectorAll('#sticky-btn-red');\n orangeButton = document.querySelectorAll('#sticky-btn-orange');\n yellowButton = document.querySelectorAll('#sticky-btn-yellow');\n greenButton = document.querySelectorAll('#sticky-btn-green');\n blueButton = document.querySelectorAll('#sticky-btn-blue');\n purpleButton = document.querySelectorAll('#sticky-btn-purple');\n deleteButton = document.querySelectorAll('#sticky-btn-delete');\n}", "function idGenerator() {\n $(\".slides__img\").each(function(index, el) {\n $(this).attr(\"id\", \"slide_\" + index);\n });\n $(\".dots__single\").each(function(index, el) {\n $(this).attr(\"id\", \"dot_\" + index);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor (low level) and fields Creates a new QR Code with the given version number, error correction level, data codeword bytes, and mask number. This is a lowlevel API that most users should not use directly. A midlevel API is the encodeSegments() function.
function QrCode( // The version number of this QR Code, which is between 1 and 40 (inclusive). // This determines the size of this barcode. version, // The error correction level used in this QR Code. errorCorrectionLevel, dataCodewords, msk) { (0,_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, QrCode); this.version = version; this.errorCorrectionLevel = errorCorrectionLevel; // The modules of this QR Code (false = light, true = dark). // Immutable after constructor finishes. Accessed through getModule(). this.modules = []; // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. this.isFunction = []; // Check scalar arguments if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) throw new RangeError('Version value out of range'); if (msk < -1 || msk > 7) throw new RangeError('Mask value out of range'); this.size = version * 4 + 17; // Initialize both grids to be size*size arrays of Boolean false var row = []; for (var i = 0; i < this.size; i++) row.push(false); for (var _i = 0; _i < this.size; _i++) { this.modules.push(row.slice()); // Initially all light this.isFunction.push(row.slice()); } // Compute ECC, draw modules this.drawFunctionPatterns(); var allCodewords = this.addEccAndInterleave(dataCodewords); this.drawCodewords(allCodewords); // Do masking if (msk == -1) { // Automatically choose best mask var minPenalty = 1000000000; for (var _i2 = 0; _i2 < 8; _i2++) { this.applyMask(_i2); this.drawFormatBits(_i2); var penalty = this.getPenaltyScore(); if (penalty < minPenalty) { msk = _i2; minPenalty = penalty; } this.applyMask(_i2); // Undoes the mask due to XOR } } assert(0 <= msk && msk <= 7); this.mask = msk; this.applyMask(msk); // Apply the final choice of mask this.drawFormatBits(msk); // Overwrite old format bits this.isFunction = []; }
[ "constructor(\n // The version number of this QR Code, which is between 1 and 40 (inclusive).\n // This determines the size of this barcode.\n version, \n // The error correction level used in this QR Code.\n errorCorrectionLevel, dataCodewords, \n // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).\n // Even if a QR Code is created with automatic masking requested (mask = -1),\n // the resulting object still has a mask value between 0 and 7.\n mask) {\n this.version = version;\n this.errorCorrectionLevel = errorCorrectionLevel;\n this.mask = mask;\n // The modules of this QR Code (false = white, true = black).\n // Immutable after constructor finishes. Accessed through getModule().\n this.modules = [];\n // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.\n this.isFunction = [];\n // Check scalar arguments\n if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)\n throw \"Version value out of range\";\n if (mask < -1 || mask > 7)\n throw \"Mask value out of range\";\n this.size = version * 4 + 17;\n // Initialize both grids to be size*size arrays of Boolean false\n let row = [];\n for (let i = 0; i < this.size; i++)\n row.push(false);\n for (let i = 0; i < this.size; i++) {\n this.modules.push(row.slice()); // Initially all white\n this.isFunction.push(row.slice());\n }\n // Compute ECC, draw modules\n this.drawFunctionPatterns();\n const allCodewords = this.addEccAndInterleave(dataCodewords);\n this.drawCodewords(allCodewords);\n // Do masking\n if (mask == -1) { // Automatically choose best mask\n let minPenalty = 1000000000;\n for (let i = 0; i < 8; i++) {\n this.applyMask(i);\n this.drawFormatBits(i);\n const penalty = this.getPenaltyScore();\n if (penalty < minPenalty) {\n mask = i;\n minPenalty = penalty;\n }\n this.applyMask(i); // Undoes the mask due to XOR\n }\n }\n if (mask < 0 || mask > 7)\n throw \"Assertion error\";\n this.mask = mask;\n this.applyMask(mask); // Apply the final choice of mask\n this.drawFormatBits(mask); // Overwrite old format bits\n this.isFunction = [];\n }", "function QRCode() {\n\n var undefined$1;\n /** Node.js global 检测. */\n\n var freeGlobal = (typeof global === \"undefined\" ? \"undefined\" : _typeof(global)) == 'object' && global && global.Object === Object && global;\n /** `self` 变量检测. */\n\n var freeSelf = (typeof self === \"undefined\" ? \"undefined\" : _typeof(self)) == 'object' && self && self.Object === Object && self;\n /** 全局对象检测. */\n\n var root = freeGlobal || freeSelf || Function('return this')();\n /** `exports` 变量检测. */\n\n var freeExports = (typeof exports === \"undefined\" ? \"undefined\" : _typeof(exports)) == 'object' && exports && !exports.nodeType && exports;\n /** `module` 变量检测. */\n\n var freeModule = freeExports && (typeof module === \"undefined\" ? \"undefined\" : _typeof(module)) == 'object' && module && !module.nodeType && module;\n var _QRCode = root.QRCode;\n var QRCode;\n\n function QR8bitByte(data, binary, utf8WithoutBOM) {\n this.mode = QRMode.MODE_8BIT_BYTE;\n this.data = data;\n this.parsedData = []; // Added to support UTF-8 Characters\n\n for (var i = 0, l = this.data.length; i < l; i++) {\n var byteArray = [];\n var code = this.data.charCodeAt(i);\n\n if (binary) {\n byteArray[0] = code;\n } else {\n if (code > 0x10000) {\n byteArray[0] = 0xf0 | (code & 0x1c0000) >>> 18;\n byteArray[1] = 0x80 | (code & 0x3f000) >>> 12;\n byteArray[2] = 0x80 | (code & 0xfc0) >>> 6;\n byteArray[3] = 0x80 | code & 0x3f;\n } else if (code > 0x800) {\n byteArray[0] = 0xe0 | (code & 0xf000) >>> 12;\n byteArray[1] = 0x80 | (code & 0xfc0) >>> 6;\n byteArray[2] = 0x80 | code & 0x3f;\n } else if (code > 0x80) {\n byteArray[0] = 0xc0 | (code & 0x7c0) >>> 6;\n byteArray[1] = 0x80 | code & 0x3f;\n } else {\n byteArray[0] = code;\n }\n }\n\n this.parsedData.push(byteArray);\n }\n\n this.parsedData = Array.prototype.concat.apply([], this.parsedData);\n\n if (!utf8WithoutBOM && this.parsedData.length != this.data.length) {\n this.parsedData.unshift(191);\n this.parsedData.unshift(187);\n this.parsedData.unshift(239);\n }\n }\n\n QR8bitByte.prototype = {\n getLength: function getLength(buffer) {\n return this.parsedData.length;\n },\n write: function write(buffer) {\n for (var i = 0, l = this.parsedData.length; i < l; i++) {\n buffer.put(this.parsedData[i], 8);\n }\n }\n };\n\n function QRCodeModel(typeNumber, errorCorrectLevel) {\n this.typeNumber = typeNumber;\n this.errorCorrectLevel = errorCorrectLevel;\n this.modules = null;\n this.moduleCount = 0;\n this.dataCache = null;\n this.dataList = [];\n }\n\n QRCodeModel.prototype = {\n addData: function addData(data, binary, utf8WithoutBOM) {\n var newData = new QR8bitByte(data, binary, utf8WithoutBOM);\n this.dataList.push(newData);\n this.dataCache = null;\n },\n isDark: function isDark(row, col) {\n if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {\n throw new Error(row + ',' + col);\n }\n\n return this.modules[row][col][0];\n },\n getEye: function getEye(row, col) {\n if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {\n throw new Error(row + ',' + col);\n }\n\n var block = this.modules[row][col]; // [isDark(ture/false), EyeOuterOrInner(O/I), Position(TL/TR/BL/A) ]\n\n if (block[1]) {\n var type = 'P' + block[1] + '_' + block[2]; //PO_TL, PI_TL, PO_TR, PI_TR, PO_BL, PI_BL\n\n if (block[2] == 'A') {\n type = 'A' + block[1]; // AI, AO\n }\n\n return {\n isDark: block[0],\n type: type\n };\n } else {\n return null;\n }\n },\n getModuleCount: function getModuleCount() {\n return this.moduleCount;\n },\n make: function make() {\n this.makeImpl(false, this.getBestMaskPattern());\n },\n makeImpl: function makeImpl(test, maskPattern) {\n this.moduleCount = this.typeNumber * 4 + 17;\n this.modules = new Array(this.moduleCount);\n\n for (var row = 0; row < this.moduleCount; row++) {\n this.modules[row] = new Array(this.moduleCount);\n\n for (var col = 0; col < this.moduleCount; col++) {\n this.modules[row][col] = []; // [isDark(ture/false), EyeOuterOrInner(O/I), Position(TL/TR/BL) ]\n }\n }\n\n this.setupPositionProbePattern(0, 0, 'TL'); // TopLeft, TL\n\n this.setupPositionProbePattern(this.moduleCount - 7, 0, 'BL'); // BotoomLeft, BL\n\n this.setupPositionProbePattern(0, this.moduleCount - 7, 'TR'); // TopRight, TR\n\n this.setupPositionAdjustPattern('A'); // Alignment, A\n\n this.setupTimingPattern();\n this.setupTypeInfo(test, maskPattern);\n\n if (this.typeNumber >= 7) {\n this.setupTypeNumber(test);\n }\n\n if (this.dataCache == null) {\n this.dataCache = QRCodeModel.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);\n }\n\n this.mapData(this.dataCache, maskPattern);\n },\n setupPositionProbePattern: function setupPositionProbePattern(row, col, posName) {\n for (var r = -1; r <= 7; r++) {\n if (row + r <= -1 || this.moduleCount <= row + r) continue;\n\n for (var c = -1; c <= 7; c++) {\n if (col + c <= -1 || this.moduleCount <= col + c) continue;\n\n if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) {\n this.modules[row + r][col + c][0] = true;\n this.modules[row + r][col + c][2] = posName; // Position\n\n if (r == -0 || c == -0 || r == 6 || c == 6) {\n this.modules[row + r][col + c][1] = 'O'; // Position Outer\n } else {\n this.modules[row + r][col + c][1] = 'I'; // Position Inner\n }\n } else {\n this.modules[row + r][col + c][0] = false;\n }\n }\n }\n },\n getBestMaskPattern: function getBestMaskPattern() {\n var minLostPoint = 0;\n var pattern = 0;\n\n for (var i = 0; i < 8; i++) {\n this.makeImpl(true, i);\n var lostPoint = QRUtil.getLostPoint(this);\n\n if (i == 0 || minLostPoint > lostPoint) {\n minLostPoint = lostPoint;\n pattern = i;\n }\n }\n\n return pattern;\n },\n createMovieClip: function createMovieClip(target_mc, instance_name, depth) {\n var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);\n var cs = 1;\n this.make();\n\n for (var row = 0; row < this.modules.length; row++) {\n var y = row * cs;\n\n for (var col = 0; col < this.modules[row].length; col++) {\n var x = col * cs;\n var dark = this.modules[row][col][0];\n\n if (dark) {\n qr_mc.beginFill(0, 100);\n qr_mc.moveTo(x, y);\n qr_mc.lineTo(x + cs, y);\n qr_mc.lineTo(x + cs, y + cs);\n qr_mc.lineTo(x, y + cs);\n qr_mc.endFill();\n }\n }\n }\n\n return qr_mc;\n },\n setupTimingPattern: function setupTimingPattern() {\n for (var r = 8; r < this.moduleCount - 8; r++) {\n if (this.modules[r][6][0] != null) {\n continue;\n }\n\n this.modules[r][6][0] = r % 2 == 0;\n }\n\n for (var c = 8; c < this.moduleCount - 8; c++) {\n if (this.modules[6][c][0] != null) {\n continue;\n }\n\n this.modules[6][c][0] = c % 2 == 0;\n }\n },\n setupPositionAdjustPattern: function setupPositionAdjustPattern(posName) {\n var pos = QRUtil.getPatternPosition(this.typeNumber);\n\n for (var i = 0; i < pos.length; i++) {\n for (var j = 0; j < pos.length; j++) {\n var row = pos[i];\n var col = pos[j];\n\n if (this.modules[row][col][0] != null) {\n continue;\n }\n\n for (var r = -2; r <= 2; r++) {\n for (var c = -2; c <= 2; c++) {\n if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) {\n this.modules[row + r][col + c][0] = true;\n this.modules[row + r][col + c][2] = posName; // Position\n\n if (r == -2 || c == -2 || r == 2 || c == 2) {\n this.modules[row + r][col + c][1] = 'O'; // Position Outer\n } else {\n this.modules[row + r][col + c][1] = 'I'; // Position Inner\n }\n } else {\n this.modules[row + r][col + c][0] = false;\n }\n }\n }\n }\n }\n },\n setupTypeNumber: function setupTypeNumber(test) {\n var bits = QRUtil.getBCHTypeNumber(this.typeNumber);\n\n for (var i = 0; i < 18; i++) {\n var mod = !test && (bits >> i & 1) == 1;\n this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3][0] = mod;\n }\n\n for (var i = 0; i < 18; i++) {\n var mod = !test && (bits >> i & 1) == 1;\n this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)][0] = mod;\n }\n },\n setupTypeInfo: function setupTypeInfo(test, maskPattern) {\n var data = this.errorCorrectLevel << 3 | maskPattern;\n var bits = QRUtil.getBCHTypeInfo(data);\n\n for (var i = 0; i < 15; i++) {\n var mod = !test && (bits >> i & 1) == 1;\n\n if (i < 6) {\n this.modules[i][8][0] = mod;\n } else if (i < 8) {\n this.modules[i + 1][8][0] = mod;\n } else {\n this.modules[this.moduleCount - 15 + i][8][0] = mod;\n }\n }\n\n for (var i = 0; i < 15; i++) {\n var mod = !test && (bits >> i & 1) == 1;\n\n if (i < 8) {\n this.modules[8][this.moduleCount - i - 1][0] = mod;\n } else if (i < 9) {\n this.modules[8][15 - i - 1 + 1][0] = mod;\n } else {\n this.modules[8][15 - i - 1][0] = mod;\n }\n }\n\n this.modules[this.moduleCount - 8][8][0] = !test;\n },\n mapData: function mapData(data, maskPattern) {\n var inc = -1;\n var row = this.moduleCount - 1;\n var bitIndex = 7;\n var byteIndex = 0;\n\n for (var col = this.moduleCount - 1; col > 0; col -= 2) {\n if (col == 6) col--;\n\n while (true) {\n for (var c = 0; c < 2; c++) {\n if (this.modules[row][col - c][0] == null) {\n var dark = false;\n\n if (byteIndex < data.length) {\n dark = (data[byteIndex] >>> bitIndex & 1) == 1;\n }\n\n var mask = QRUtil.getMask(maskPattern, row, col - c);\n\n if (mask) {\n dark = !dark;\n }\n\n this.modules[row][col - c][0] = dark;\n bitIndex--;\n\n if (bitIndex == -1) {\n byteIndex++;\n bitIndex = 7;\n }\n }\n }\n\n row += inc;\n\n if (row < 0 || this.moduleCount <= row) {\n row -= inc;\n inc = -inc;\n break;\n }\n }\n }\n }\n };\n QRCodeModel.PAD0 = 0xec;\n QRCodeModel.PAD1 = 0x11;\n\n QRCodeModel.createData = function (typeNumber, errorCorrectLevel, dataList) {\n var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel);\n var buffer = new QRBitBuffer();\n\n for (var i = 0; i < dataList.length; i++) {\n var data = dataList[i];\n buffer.put(data.mode, 4);\n buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber));\n data.write(buffer);\n }\n\n var totalDataCount = 0;\n\n for (var i = 0; i < rsBlocks.length; i++) {\n totalDataCount += rsBlocks[i].dataCount;\n }\n\n if (buffer.getLengthInBits() > totalDataCount * 8) {\n throw new Error('code length overflow. (' + buffer.getLengthInBits() + '>' + totalDataCount * 8 + ')');\n }\n\n if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {\n buffer.put(0, 4);\n }\n\n while (buffer.getLengthInBits() % 8 != 0) {\n buffer.putBit(false);\n }\n\n while (true) {\n if (buffer.getLengthInBits() >= totalDataCount * 8) {\n break;\n }\n\n buffer.put(QRCodeModel.PAD0, 8);\n\n if (buffer.getLengthInBits() >= totalDataCount * 8) {\n break;\n }\n\n buffer.put(QRCodeModel.PAD1, 8);\n }\n\n return QRCodeModel.createBytes(buffer, rsBlocks);\n };\n\n QRCodeModel.createBytes = function (buffer, rsBlocks) {\n var offset = 0;\n var maxDcCount = 0;\n var maxEcCount = 0;\n var dcdata = new Array(rsBlocks.length);\n var ecdata = new Array(rsBlocks.length);\n\n for (var r = 0; r < rsBlocks.length; r++) {\n var dcCount = rsBlocks[r].dataCount;\n var ecCount = rsBlocks[r].totalCount - dcCount;\n maxDcCount = Math.max(maxDcCount, dcCount);\n maxEcCount = Math.max(maxEcCount, ecCount);\n dcdata[r] = new Array(dcCount);\n\n for (var i = 0; i < dcdata[r].length; i++) {\n dcdata[r][i] = 0xff & buffer.buffer[i + offset];\n }\n\n offset += dcCount;\n var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);\n var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);\n var modPoly = rawPoly.mod(rsPoly);\n ecdata[r] = new Array(rsPoly.getLength() - 1);\n\n for (var i = 0; i < ecdata[r].length; i++) {\n var modIndex = i + modPoly.getLength() - ecdata[r].length;\n ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;\n }\n }\n\n var totalCodeCount = 0;\n\n for (var i = 0; i < rsBlocks.length; i++) {\n totalCodeCount += rsBlocks[i].totalCount;\n }\n\n var data = new Array(totalCodeCount);\n var index = 0;\n\n for (var i = 0; i < maxDcCount; i++) {\n for (var r = 0; r < rsBlocks.length; r++) {\n if (i < dcdata[r].length) {\n data[index++] = dcdata[r][i];\n }\n }\n }\n\n for (var i = 0; i < maxEcCount; i++) {\n for (var r = 0; r < rsBlocks.length; r++) {\n if (i < ecdata[r].length) {\n data[index++] = ecdata[r][i];\n }\n }\n }\n\n return data;\n };\n\n var QRMode = {\n MODE_NUMBER: 1 << 0,\n MODE_ALPHA_NUM: 1 << 1,\n MODE_8BIT_BYTE: 1 << 2,\n MODE_KANJI: 1 << 3\n };\n var QRErrorCorrectLevel = {\n L: 1,\n M: 0,\n Q: 3,\n H: 2\n };\n var QRMaskPattern = {\n PATTERN000: 0,\n PATTERN001: 1,\n PATTERN010: 2,\n PATTERN011: 3,\n PATTERN100: 4,\n PATTERN101: 5,\n PATTERN110: 6,\n PATTERN111: 7\n };\n var QRUtil = {\n PATTERN_POSITION_TABLE: [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170]],\n G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,\n G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,\n G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,\n getBCHTypeInfo: function getBCHTypeInfo(data) {\n var d = data << 10;\n\n while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {\n d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);\n }\n\n return (data << 10 | d) ^ QRUtil.G15_MASK;\n },\n getBCHTypeNumber: function getBCHTypeNumber(data) {\n var d = data << 12;\n\n while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {\n d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);\n }\n\n return data << 12 | d;\n },\n getBCHDigit: function getBCHDigit(data) {\n var digit = 0;\n\n while (data != 0) {\n digit++;\n data >>>= 1;\n }\n\n return digit;\n },\n getPatternPosition: function getPatternPosition(typeNumber) {\n return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];\n },\n getMask: function getMask(maskPattern, i, j) {\n switch (maskPattern) {\n case QRMaskPattern.PATTERN000:\n return (i + j) % 2 == 0;\n\n case QRMaskPattern.PATTERN001:\n return i % 2 == 0;\n\n case QRMaskPattern.PATTERN010:\n return j % 3 == 0;\n\n case QRMaskPattern.PATTERN011:\n return (i + j) % 3 == 0;\n\n case QRMaskPattern.PATTERN100:\n return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;\n\n case QRMaskPattern.PATTERN101:\n return i * j % 2 + i * j % 3 == 0;\n\n case QRMaskPattern.PATTERN110:\n return (i * j % 2 + i * j % 3) % 2 == 0;\n\n case QRMaskPattern.PATTERN111:\n return (i * j % 3 + (i + j) % 2) % 2 == 0;\n\n default:\n throw new Error('bad maskPattern:' + maskPattern);\n }\n },\n getErrorCorrectPolynomial: function getErrorCorrectPolynomial(errorCorrectLength) {\n var a = new QRPolynomial([1], 0);\n\n for (var i = 0; i < errorCorrectLength; i++) {\n a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));\n }\n\n return a;\n },\n getLengthInBits: function getLengthInBits(mode, type) {\n if (1 <= type && type < 10) {\n switch (mode) {\n case QRMode.MODE_NUMBER:\n return 10;\n\n case QRMode.MODE_ALPHA_NUM:\n return 9;\n\n case QRMode.MODE_8BIT_BYTE:\n return 8;\n\n case QRMode.MODE_KANJI:\n return 8;\n\n default:\n throw new Error('mode:' + mode);\n }\n } else if (type < 27) {\n switch (mode) {\n case QRMode.MODE_NUMBER:\n return 12;\n\n case QRMode.MODE_ALPHA_NUM:\n return 11;\n\n case QRMode.MODE_8BIT_BYTE:\n return 16;\n\n case QRMode.MODE_KANJI:\n return 10;\n\n default:\n throw new Error('mode:' + mode);\n }\n } else if (type < 41) {\n switch (mode) {\n case QRMode.MODE_NUMBER:\n return 14;\n\n case QRMode.MODE_ALPHA_NUM:\n return 13;\n\n case QRMode.MODE_8BIT_BYTE:\n return 16;\n\n case QRMode.MODE_KANJI:\n return 12;\n\n default:\n throw new Error('mode:' + mode);\n }\n } else {\n throw new Error('type:' + type);\n }\n },\n getLostPoint: function getLostPoint(qrCode) {\n var moduleCount = qrCode.getModuleCount();\n var lostPoint = 0;\n\n for (var row = 0; row < moduleCount; row++) {\n for (var col = 0; col < moduleCount; col++) {\n var sameCount = 0;\n var dark = qrCode.isDark(row, col);\n\n for (var r = -1; r <= 1; r++) {\n if (row + r < 0 || moduleCount <= row + r) {\n continue;\n }\n\n for (var c = -1; c <= 1; c++) {\n if (col + c < 0 || moduleCount <= col + c) {\n continue;\n }\n\n if (r == 0 && c == 0) {\n continue;\n }\n\n if (dark == qrCode.isDark(row + r, col + c)) {\n sameCount++;\n }\n }\n }\n\n if (sameCount > 5) {\n lostPoint += 3 + sameCount - 5;\n }\n }\n }\n\n for (var row = 0; row < moduleCount - 1; row++) {\n for (var col = 0; col < moduleCount - 1; col++) {\n var count = 0;\n if (qrCode.isDark(row, col)) count++;\n if (qrCode.isDark(row + 1, col)) count++;\n if (qrCode.isDark(row, col + 1)) count++;\n if (qrCode.isDark(row + 1, col + 1)) count++;\n\n if (count == 0 || count == 4) {\n lostPoint += 3;\n }\n }\n }\n\n for (var row = 0; row < moduleCount; row++) {\n for (var col = 0; col < moduleCount - 6; col++) {\n if (qrCode.isDark(row, col) && !qrCode.isDark(row, col + 1) && qrCode.isDark(row, col + 2) && qrCode.isDark(row, col + 3) && qrCode.isDark(row, col + 4) && !qrCode.isDark(row, col + 5) && qrCode.isDark(row, col + 6)) {\n lostPoint += 40;\n }\n }\n }\n\n for (var col = 0; col < moduleCount; col++) {\n for (var row = 0; row < moduleCount - 6; row++) {\n if (qrCode.isDark(row, col) && !qrCode.isDark(row + 1, col) && qrCode.isDark(row + 2, col) && qrCode.isDark(row + 3, col) && qrCode.isDark(row + 4, col) && !qrCode.isDark(row + 5, col) && qrCode.isDark(row + 6, col)) {\n lostPoint += 40;\n }\n }\n }\n\n var darkCount = 0;\n\n for (var col = 0; col < moduleCount; col++) {\n for (var row = 0; row < moduleCount; row++) {\n if (qrCode.isDark(row, col)) {\n darkCount++;\n }\n }\n }\n\n var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;\n lostPoint += ratio * 10;\n return lostPoint;\n }\n };\n var QRMath = {\n glog: function glog(n) {\n if (n < 1) {\n throw new Error('glog(' + n + ')');\n }\n\n return QRMath.LOG_TABLE[n];\n },\n gexp: function gexp(n) {\n while (n < 0) {\n n += 255;\n }\n\n while (n >= 256) {\n n -= 255;\n }\n\n return QRMath.EXP_TABLE[n];\n },\n EXP_TABLE: new Array(256),\n LOG_TABLE: new Array(256)\n };\n\n for (var i = 0; i < 8; i++) {\n QRMath.EXP_TABLE[i] = 1 << i;\n }\n\n for (var i = 8; i < 256; i++) {\n QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];\n }\n\n for (var i = 0; i < 255; i++) {\n QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;\n }\n\n function QRPolynomial(num, shift) {\n if (num.length == undefined$1) {\n throw new Error(num.length + '/' + shift);\n }\n\n var offset = 0;\n\n while (offset < num.length && num[offset] == 0) {\n offset++;\n }\n\n this.num = new Array(num.length - offset + shift);\n\n for (var i = 0; i < num.length - offset; i++) {\n this.num[i] = num[i + offset];\n }\n }\n\n QRPolynomial.prototype = {\n get: function get(index) {\n return this.num[index];\n },\n getLength: function getLength() {\n return this.num.length;\n },\n multiply: function multiply(e) {\n var num = new Array(this.getLength() + e.getLength() - 1);\n\n for (var i = 0; i < this.getLength(); i++) {\n for (var j = 0; j < e.getLength(); j++) {\n num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));\n }\n }\n\n return new QRPolynomial(num, 0);\n },\n mod: function mod(e) {\n if (this.getLength() - e.getLength() < 0) {\n return this;\n }\n\n var ratio = QRMath.glog(this.get(0)) - QRMath.glog(e.get(0));\n var num = new Array(this.getLength());\n\n for (var i = 0; i < this.getLength(); i++) {\n num[i] = this.get(i);\n }\n\n for (var i = 0; i < e.getLength(); i++) {\n num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);\n }\n\n return new QRPolynomial(num, 0).mod(e);\n }\n };\n\n function QRRSBlock(totalCount, dataCount) {\n this.totalCount = totalCount;\n this.dataCount = dataCount;\n }\n\n QRRSBlock.RS_BLOCK_TABLE = [[1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12, 7, 37, 13], [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16]];\n\n QRRSBlock.getRSBlocks = function (typeNumber, errorCorrectLevel) {\n var rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);\n\n if (rsBlock == undefined$1) {\n throw new Error('bad rs block @ typeNumber:' + typeNumber + '/errorCorrectLevel:' + errorCorrectLevel);\n }\n\n var length = rsBlock.length / 3;\n var list = [];\n\n for (var i = 0; i < length; i++) {\n var count = rsBlock[i * 3 + 0];\n var totalCount = rsBlock[i * 3 + 1];\n var dataCount = rsBlock[i * 3 + 2];\n\n for (var j = 0; j < count; j++) {\n list.push(new QRRSBlock(totalCount, dataCount));\n }\n }\n\n return list;\n };\n\n QRRSBlock.getRsBlockTable = function (typeNumber, errorCorrectLevel) {\n switch (errorCorrectLevel) {\n case QRErrorCorrectLevel.L:\n return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];\n\n case QRErrorCorrectLevel.M:\n return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];\n\n case QRErrorCorrectLevel.Q:\n return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];\n\n case QRErrorCorrectLevel.H:\n return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];\n\n default:\n return undefined$1;\n }\n };\n\n function QRBitBuffer() {\n this.buffer = [];\n this.length = 0;\n }\n\n QRBitBuffer.prototype = {\n get: function get(index) {\n var bufIndex = Math.floor(index / 8);\n return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) == 1;\n },\n put: function put(num, length) {\n for (var i = 0; i < length; i++) {\n this.putBit((num >>> length - i - 1 & 1) == 1);\n }\n },\n getLengthInBits: function getLengthInBits() {\n return this.length;\n },\n putBit: function putBit(bit) {\n var bufIndex = Math.floor(this.length / 8);\n\n if (this.buffer.length <= bufIndex) {\n this.buffer.push(0);\n }\n\n if (bit) {\n this.buffer[bufIndex] |= 0x80 >>> this.length % 8;\n }\n\n this.length++;\n }\n };\n var QRCodeLimitLength = [[17, 14, 11, 7], [32, 26, 20, 14], [53, 42, 32, 24], [78, 62, 46, 34], [106, 84, 60, 44], [134, 106, 74, 58], [154, 122, 86, 64], [192, 152, 108, 84], [230, 180, 130, 98], [271, 213, 151, 119], [321, 251, 177, 137], [367, 287, 203, 155], [425, 331, 241, 177], [458, 362, 258, 194], [520, 412, 292, 220], [586, 450, 322, 250], [644, 504, 364, 280], [718, 560, 394, 310], [792, 624, 442, 338], [858, 666, 482, 382], [929, 711, 509, 403], [1003, 779, 565, 439], [1091, 857, 611, 461], [1171, 911, 661, 511], [1273, 997, 715, 535], [1367, 1059, 751, 593], [1465, 1125, 805, 625], [1528, 1190, 868, 658], [1628, 1264, 908, 698], [1732, 1370, 982, 742], [1840, 1452, 1030, 790], [1952, 1538, 1112, 842], [2068, 1628, 1168, 898], [2188, 1722, 1228, 958], [2303, 1809, 1283, 983], [2431, 1911, 1351, 1051], [2563, 1989, 1423, 1093], [2699, 2099, 1499, 1139], [2809, 2213, 1579, 1219], [2953, 2331, 1663, 1273]];\n\n function _isSupportCanvas() {\n return typeof CanvasRenderingContext2D != 'undefined';\n } // android 2.x doesn't support Data-URI spec\n\n\n function _getAndroid() {\n var android = false;\n var sAgent = navigator.userAgent;\n\n if (/android/i.test(sAgent)) {\n // android\n android = true;\n var aMat = sAgent.toString().match(/android ([0-9]\\.[0-9])/i);\n\n if (aMat && aMat[1]) {\n android = parseFloat(aMat[1]);\n }\n }\n\n return android;\n } // Drawing in DOM by using Table tag\n\n\n var Drawing = !_isSupportCanvas() ? function () {\n var Drawing = function Drawing(el, htOption) {\n this._el = el;\n this._htOption = htOption;\n };\n /**\n * Draw the QRCode\n *\n * @param {QRCode} oQRCode\n */\n\n\n Drawing.prototype.draw = function (oQRCode) {\n var _htOption = this._htOption;\n var _el = this._el;\n var nCount = oQRCode.getModuleCount();\n var nWidth = Math.round(_htOption.width / nCount);\n var nHeight = Math.round((_htOption.height - _htOption.titleHeight) / nCount);\n\n if (nWidth <= 1) {\n nWidth = 1;\n }\n\n if (nHeight <= 1) {\n nHeight = 1;\n }\n\n this._htOption.width = nWidth * nCount;\n this._htOption.height = nHeight * nCount + _htOption.titleHeight;\n this._htOption.quietZone = Math.round(this._htOption.quietZone);\n var aHTML = [];\n var divStyle = '';\n var drawWidth = Math.round(nWidth * _htOption.dotScale);\n var drawHeight = Math.round(nHeight * _htOption.dotScale);\n\n if (drawWidth < 4) {\n drawWidth = 4;\n drawHeight = 4;\n }\n\n var nonRequiredColorDark = _htOption.colorDark;\n var nonRequiredcolorLight = _htOption.colorLight;\n\n if (_htOption.backgroundImage) {\n if (_htOption.autoColor) {\n _htOption.colorDark = \"rgba(0, 0, 0, .6);filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#99000000', EndColorStr='#99000000');\";\n _htOption.colorLight = \"rgba(255, 255, 255, .7);filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#B2FFFFFF', EndColorStr='#B2FFFFFF');\"; // _htOption.colorDark=\"rgba(0, 0, 0, .6)\";\n // _htOption.colorLight='rgba(255, 255, 255, .7)';\n } else {\n _htOption.colorLight = 'rgba(0,0,0,0)';\n }\n\n var backgroundImageEle = '<div style=\"display:inline-block; z-index:-10;position:absolute;\"><img src=\"' + _htOption.backgroundImage + '\" widht=\"' + (_htOption.width + _htOption.quietZone * 2) + '\" height=\"' + (_htOption.height + _htOption.quietZone * 2) + '\" style=\"opacity:' + _htOption.backgroundImageAlpha + ';filter:alpha(opacity=' + _htOption.backgroundImageAlpha * 100 + '); \"/></div>';\n aHTML.push(backgroundImageEle);\n }\n\n if (_htOption.quietZone) {\n divStyle = 'display:inline-block; width:' + (_htOption.width + _htOption.quietZone * 2) + 'px; height:' + (_htOption.width + _htOption.quietZone * 2) + 'px;background:' + _htOption.quietZoneColor + '; text-align:center;';\n }\n\n aHTML.push('<div style=\"font-size:0;' + divStyle + '\">');\n aHTML.push('<table style=\"font-size:0;border:0;border-collapse:collapse; margin-top:' + _htOption.quietZone + 'px;\" border=\"0\" cellspacing=\"0\" cellspadding=\"0\" align=\"center\" valign=\"middle\">');\n aHTML.push('<tr height=\"' + _htOption.titleHeight + '\" align=\"center\"><td style=\"border:0;border-collapse:collapse;margin:0;padding:0\" colspan=\"' + nCount + '\">');\n\n if (_htOption.title) {\n var c = _htOption.titleColor;\n var f = _htOption.titleFont;\n aHTML.push('<div style=\"width:100%;margin-top:' + _htOption.titleTop + 'px;color:' + c + ';font:' + f + ';background:' + _htOption.titleBackgroundColor + '\">' + _htOption.title + '</div>');\n }\n\n if (_htOption.subTitle) {\n aHTML.push('<div style=\"width:100%;margin-top:' + (_htOption.subTitleTop - _htOption.titleTop) + 'px;color:' + _htOption.subTitleColor + '; font:' + _htOption.subTitleFont + '\">' + _htOption.subTitle + '</div>');\n }\n\n aHTML.push('</td></tr>');\n\n for (var row = 0; row < nCount; row++) {\n aHTML.push('<tr style=\"border:0; padding:0; margin:0;\" height=\"7\">');\n\n for (var col = 0; col < nCount; col++) {\n var bIsDark = oQRCode.isDark(row, col);\n var eye = oQRCode.getEye(row, col); // { isDark: true/false, type: PO_TL, PI_TL, PO_TR, PI_TR, PO_BL, PI_BL };\n\n if (eye) {\n // Is eye\n bIsDark = eye.isDark;\n var type = eye.type; // PX_XX, PX, colorDark, colorLight\n\n var eyeColorDark = _htOption[type] || _htOption[type.substring(0, 2)] || nonRequiredColorDark;\n aHTML.push('<td style=\"border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;\">' + '<span style=\"width:' + nWidth + 'px;height:' + nHeight + 'px;background-color:' + (bIsDark ? eyeColorDark : nonRequiredcolorLight) + ';display:inline-block\"></span></td>');\n } else {\n // Timing Pattern\n var nowDarkColor = _htOption.colorDark;\n\n if (row == 6) {\n nowDarkColor = _htOption.timing_H || _htOption.timing || nonRequiredColorDark;\n aHTML.push('<td style=\"border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;background-color:' + (bIsDark ? nowDarkColor : nonRequiredcolorLight) + ';\"></td>');\n } else if (col == 6) {\n nowDarkColor = _htOption.timing_V || _htOption.timing || nonRequiredColorDark;\n aHTML.push('<td style=\"border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;background-color:' + (bIsDark ? nowDarkColor : nonRequiredcolorLight) + ';\"></td>');\n } else {\n aHTML.push('<td style=\"border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;\">' + '<div style=\"display:inline-block;width:' + drawWidth + 'px;height:' + drawHeight + 'px;background-color:' + (bIsDark ? nowDarkColor : _htOption.colorLight) + ';\"></div></td>');\n }\n }\n }\n\n aHTML.push('</tr>');\n }\n\n aHTML.push('</table>');\n aHTML.push('</div>');\n\n if (_htOption.logo) {\n // Logo Image\n var img = new Image();\n\n if (_htOption.crossOrigin != null) {\n img.crossOrigin = _htOption.crossOrigin;\n } // img.crossOrigin=\"Anonymous\";\n\n\n img.src = _htOption.logo;\n var imgW = _htOption.width / 3.5;\n var imgH = _htOption.height / 3.5;\n\n if (imgW != imgH) {\n imgW = imgH;\n }\n\n if (_htOption.logoWidth) {\n imgW = _htOption.logoWidth;\n }\n\n if (_htOption.logoHeight) {\n imgH = _htOption.logoHeight;\n }\n\n var imgDivStyle = 'position:relative; z-index:1;display:table-cell;top:-' + ((_htOption.height - _htOption.titleHeight) / 2 + imgH / 2 + _htOption.quietZone) + 'px;text-align:center; width:' + imgW + 'px; height:' + imgH + 'px;line-height:' + imgW + 'px; vertical-align: middle;';\n\n if (!_htOption.logoBackgroundTransparent) {\n imgDivStyle += 'background:' + _htOption.logoBackgroundColor;\n }\n\n aHTML.push('<div style=\"' + imgDivStyle + '\"><img src=\"' + _htOption.logo + '\" style=\"max-width: ' + imgW + 'px; max-height: ' + imgH + 'px;\" /> <div style=\" display: none; width:1px;margin-left: -1px;\"></div></div>');\n }\n\n if (_htOption.onRenderingStart) {\n _htOption.onRenderingStart(_htOption);\n }\n\n _el.innerHTML = aHTML.join(''); // Fix the margin values as real size.\n\n var elTable = _el.childNodes[0];\n var nLeftMarginTable = (_htOption.width - elTable.offsetWidth) / 2;\n var nTopMarginTable = (_htOption.height - elTable.offsetHeight) / 2;\n\n if (nLeftMarginTable > 0 && nTopMarginTable > 0) {\n elTable.style.margin = nTopMarginTable + 'px ' + nLeftMarginTable + 'px';\n }\n\n if (this._htOption.onRenderingEnd) {\n this._htOption.onRenderingEnd(this._htOption, null);\n }\n };\n /**\n * Clear the QRCode\n */\n\n\n Drawing.prototype.clear = function () {\n this._el.innerHTML = '';\n };\n\n return Drawing;\n }() : function () {\n // Drawing in Canvas\n function _onMakeImage() {\n if (this._htOption.drawer == 'svg') {\n var svgData = this._oContext.getSerializedSvg(true);\n\n this.dataURL = svgData;\n this._el.innerHTML = svgData;\n } else {\n // canvas\n // this._elImage.crossOrigin='Anonymous';\n try {\n // if (this._htOption.crossOrigin != null) {\n // this._elImage.crossOrigin = this._htOption.crossOrigin;\n // }\n var dataURL = this._elCanvas.toDataURL('image/png'); // this._elImage.src = dataURL;\n\n\n this.dataURL = dataURL; // this._elImage.style.display = \"inline\";\n // this._elCanvas.style.display = \"none\";\n } catch (e) {\n console.error(e);\n }\n }\n\n if (this._htOption.onRenderingEnd) {\n if (!this.dataURL) {\n console.error(\"Can not get base64 data, please check: 1. Published the page and image to the server 2. The image request support CORS 3. Configured `crossOrigin:'anonymous'` option\");\n }\n\n this._htOption.onRenderingEnd(this._htOption, this.dataURL);\n }\n } // Android 2.1 bug workaround\n // http://code.google.com/p/android/issues/detail?id=5141\n\n\n if (root._android && root._android <= 2.1) {\n var factor = 1 / window.devicePixelRatio;\n var drawImage = CanvasRenderingContext2D.prototype.drawImage;\n\n CanvasRenderingContext2D.prototype.drawImage = function (image, sx, sy, sw, sh, dx, dy, dw, dh) {\n if ('nodeName' in image && /img/i.test(image.nodeName)) {\n for (var i = arguments.length - 1; i >= 1; i--) {\n arguments[i] = arguments[i] * factor;\n }\n } else if (typeof dw == 'undefined') {\n arguments[1] *= factor;\n arguments[2] *= factor;\n arguments[3] *= factor;\n arguments[4] *= factor;\n }\n\n drawImage.apply(this, arguments);\n };\n }\n /**\n * Check whether the user's browser supports Data URI or not\n *\n * @private\n * @param {Function} fSuccess Occurs if it supports Data URI\n * @param {Function} fFail Occurs if it doesn't support Data URI\n */\n\n\n function _safeSetDataURI(fSuccess, fFail) {\n var self = this;\n self._fFail = fFail;\n self._fSuccess = fSuccess; // Check it just once\n\n if (self._bSupportDataURI === null) {\n var el = document.createElement('img');\n\n var fOnError = function fOnError() {\n self._bSupportDataURI = false;\n\n if (self._fFail) {\n self._fFail.call(self);\n }\n };\n\n var fOnSuccess = function fOnSuccess() {\n self._bSupportDataURI = true;\n\n if (self._fSuccess) {\n self._fSuccess.call(self);\n }\n };\n\n el.onabort = fOnError;\n el.onerror = fOnError;\n el.onload = fOnSuccess;\n el.src = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; // the Image contains 1px data.\n\n return;\n } else if (self._bSupportDataURI === true && self._fSuccess) {\n self._fSuccess.call(self);\n } else if (self._bSupportDataURI === false && self._fFail) {\n self._fFail.call(self);\n }\n }\n /**\n * Drawing QRCode by using canvas\n *\n * @constructor\n * @param {HTMLElement} el\n * @param {Object} htOption QRCode Options\n */\n\n\n var Drawing = function Drawing(el, htOption) {\n this._bIsPainted = false;\n this._android = _getAndroid();\n this._el = el;\n this._htOption = htOption;\n\n if (this._htOption.drawer == 'svg') {\n this._oContext = {};\n this._elCanvas = {};\n } else {\n // canvas\n this._elCanvas = document.createElement('canvas');\n\n this._el.appendChild(this._elCanvas);\n\n this._oContext = this._elCanvas.getContext('2d'); // this._elImage = document.createElement(\"img\");\n // this._elImage.alt = \"Scan me!\";\n // this._elImage.style.display = \"none\";\n // this._el.appendChild(this._elImage);\n }\n\n this._bSupportDataURI = null;\n this.dataURL = null;\n };\n /**\n * Draw the QRCode\n *\n * @param {QRCode} oQRCode\n */\n\n\n Drawing.prototype.draw = function (oQRCode) {\n // var _elImage = this._elImage;\n var _htOption = this._htOption;\n\n if (!_htOption.title && !_htOption.subTitle) {\n _htOption.height -= _htOption.titleHeight;\n _htOption.titleHeight = 0;\n }\n\n var nCount = oQRCode.getModuleCount();\n var nWidth = Math.round(_htOption.width / nCount);\n var nHeight = Math.round((_htOption.height - _htOption.titleHeight) / nCount);\n\n if (nWidth <= 1) {\n nWidth = 1;\n }\n\n if (nHeight <= 1) {\n nHeight = 1;\n }\n\n _htOption.width = nWidth * nCount;\n _htOption.height = nHeight * nCount + _htOption.titleHeight;\n _htOption.quietZone = Math.round(_htOption.quietZone);\n this._elCanvas.width = _htOption.width + _htOption.quietZone * 2;\n this._elCanvas.height = _htOption.height + _htOption.quietZone * 2;\n\n if (this._htOption.drawer != 'canvas') {\n // _elImage.style.display = \"none\";\n // } else {\n this._oContext = new C2S(this._elCanvas.width, this._elCanvas.height);\n }\n\n this.clear();\n var _oContext = this._oContext;\n _oContext.lineWidth = 0;\n _oContext.fillStyle = _htOption.colorLight;\n\n _oContext.fillRect(0, 0, this._elCanvas.width, this._elCanvas.height);\n\n var t = this;\n\n function drawQuietZoneColor() {\n if (_htOption.quietZone > 0 && _htOption.quietZoneColor) {\n // top\n _oContext.lineWidth = 0;\n _oContext.fillStyle = _htOption.quietZoneColor;\n\n _oContext.fillRect(0, 0, t._elCanvas.width, _htOption.quietZone); // left\n\n\n _oContext.fillRect(0, _htOption.quietZone, _htOption.quietZone, t._elCanvas.height - _htOption.quietZone * 2); // right\n\n\n _oContext.fillRect(t._elCanvas.width - _htOption.quietZone, _htOption.quietZone, _htOption.quietZone, t._elCanvas.height - _htOption.quietZone * 2); // bottom\n\n\n _oContext.fillRect(0, t._elCanvas.height - _htOption.quietZone, t._elCanvas.width, _htOption.quietZone);\n }\n }\n\n if (_htOption.backgroundImage) {\n // Background Image\n var bgImg = new Image();\n\n bgImg.onload = function () {\n _oContext.globalAlpha = 1;\n _oContext.globalAlpha = _htOption.backgroundImageAlpha;\n var imageSmoothingQuality = _oContext.imageSmoothingQuality;\n var imageSmoothingEnabled = _oContext.imageSmoothingEnabled;\n _oContext.imageSmoothingEnabled = true;\n _oContext.imageSmoothingQuality = 'high';\n\n _oContext.drawImage(bgImg, 0, _htOption.titleHeight, _htOption.width + _htOption.quietZone * 2, _htOption.height + _htOption.quietZone * 2 - _htOption.titleHeight);\n\n _oContext.imageSmoothingEnabled = imageSmoothingEnabled;\n _oContext.imageSmoothingQuality = imageSmoothingQuality;\n _oContext.globalAlpha = 1;\n drawQrcode.call(t, oQRCode);\n }; // bgImg.crossOrigin='Anonymous';\n\n\n if (_htOption.crossOrigin != null) {\n bgImg.crossOrigin = _htOption.crossOrigin;\n }\n\n bgImg.originalSrc = _htOption.backgroundImage;\n bgImg.src = _htOption.backgroundImage; // DoSomething\n } else {\n drawQrcode.call(t, oQRCode);\n }\n\n function drawQrcode(oQRCode) {\n if (_htOption.onRenderingStart) {\n _htOption.onRenderingStart(_htOption);\n }\n\n for (var row = 0; row < nCount; row++) {\n for (var col = 0; col < nCount; col++) {\n var nLeft = col * nWidth + _htOption.quietZone;\n var nTop = row * nHeight + _htOption.quietZone;\n var bIsDark = oQRCode.isDark(row, col);\n var eye = oQRCode.getEye(row, col); // { isDark: true/false, type: PO_TL, PI_TL, PO_TR, PI_TR, PO_BL, PI_BL };\n\n var nowDotScale = _htOption.dotScale;\n _oContext.lineWidth = 0; // Color handler\n\n var dColor;\n var lColor;\n\n if (eye) {\n dColor = _htOption[eye.type] || _htOption[eye.type.substring(0, 2)] || _htOption.colorDark;\n lColor = _htOption.colorLight;\n } else {\n if (_htOption.backgroundImage) {\n lColor = 'rgba(0,0,0,0)';\n\n if (row == 6) {\n // dColor = _htOption.timing_H || _htOption.timing || _htOption.colorDark;\n if (_htOption.autoColor) {\n dColor = _htOption.timing_H || _htOption.timing || _htOption.autoColorDark;\n lColor = _htOption.autoColorLight;\n } else {\n dColor = _htOption.timing_H || _htOption.timing || _htOption.colorDark;\n }\n } else if (col == 6) {\n // dColor = _htOption.timing_V || _htOption.timing || _htOption.colorDark;\n if (_htOption.autoColor) {\n dColor = _htOption.timing_V || _htOption.timing || _htOption.autoColorDark;\n lColor = _htOption.autoColorLight;\n } else {\n dColor = _htOption.timing_V || _htOption.timing || _htOption.colorDark;\n }\n } else {\n if (_htOption.autoColor) {\n dColor = _htOption.autoColorDark;\n lColor = _htOption.autoColorLight;\n } else {\n dColor = _htOption.colorDark;\n }\n }\n } else {\n if (row == 6) {\n dColor = _htOption.timing_H || _htOption.timing || _htOption.colorDark;\n } else if (col == 6) {\n dColor = _htOption.timing_V || _htOption.timing || _htOption.colorDark;\n } else {\n dColor = _htOption.colorDark;\n }\n\n lColor = _htOption.colorLight;\n }\n }\n\n _oContext.strokeStyle = bIsDark ? dColor : lColor;\n _oContext.fillStyle = bIsDark ? dColor : lColor;\n\n if (eye) {\n if (eye.type == 'AO') {\n nowDotScale = _htOption.dotScaleAO;\n } else if (eye.type == 'AI') {\n nowDotScale = _htOption.dotScaleAI;\n } else {\n nowDotScale = 1;\n }\n\n if (_htOption.backgroundImage && _htOption.autoColor) {\n dColor = (eye.type == 'AO' ? _htOption.AI : _htOption.AO) || _htOption.autoColorDark;\n lColor = _htOption.autoColorLight;\n } else {\n dColor = (eye.type == 'AO' ? _htOption.AI : _htOption.AO) || dColor;\n } // Is eye\n\n\n bIsDark = eye.isDark;\n\n _oContext.fillRect(nLeft + nWidth * (1 - nowDotScale) / 2, _htOption.titleHeight + nTop + nHeight * (1 - nowDotScale) / 2, nWidth * nowDotScale, nHeight * nowDotScale);\n } else {\n if (row == 6) {\n // Timing Pattern\n nowDotScale = _htOption.dotScaleTiming_H;\n\n _oContext.fillRect(nLeft + nWidth * (1 - nowDotScale) / 2, _htOption.titleHeight + nTop + nHeight * (1 - nowDotScale) / 2, nWidth * nowDotScale, nHeight * nowDotScale);\n } else if (col == 6) {\n // Timing Pattern\n nowDotScale = _htOption.dotScaleTiming_V;\n\n _oContext.fillRect(nLeft + nWidth * (1 - nowDotScale) / 2, _htOption.titleHeight + nTop + nHeight * (1 - nowDotScale) / 2, nWidth * nowDotScale, nHeight * nowDotScale);\n } else {\n if (_htOption.backgroundImage) {\n _oContext.fillRect(nLeft + nWidth * (1 - nowDotScale) / 2, _htOption.titleHeight + nTop + nHeight * (1 - nowDotScale) / 2, nWidth * nowDotScale, nHeight * nowDotScale);\n } else {\n _oContext.fillRect(nLeft + nWidth * (1 - nowDotScale) / 2, _htOption.titleHeight + nTop + nHeight * (1 - nowDotScale) / 2, nWidth * nowDotScale, nHeight * nowDotScale);\n }\n }\n }\n\n if (_htOption.dotScale != 1 && !eye) {\n _oContext.strokeStyle = _htOption.colorLight;\n }\n }\n }\n\n if (_htOption.title) {\n _oContext.fillStyle = _htOption.titleBackgroundColor;\n\n _oContext.fillRect(0, 0, this._elCanvas.width, _htOption.titleHeight + _htOption.quietZone);\n\n _oContext.font = _htOption.titleFont;\n _oContext.fillStyle = _htOption.titleColor;\n _oContext.textAlign = 'center';\n\n _oContext.fillText(_htOption.title, this._elCanvas.width / 2, +_htOption.quietZone + _htOption.titleTop);\n }\n\n if (_htOption.subTitle) {\n _oContext.font = _htOption.subTitleFont;\n _oContext.fillStyle = _htOption.subTitleColor;\n\n _oContext.fillText(_htOption.subTitle, this._elCanvas.width / 2, +_htOption.quietZone + _htOption.subTitleTop);\n }\n\n function generateLogoImg(img) {\n var imgContainerW = Math.round(_htOption.width / 3.5);\n var imgContainerH = Math.round(_htOption.height / 3.5);\n\n if (imgContainerW !== imgContainerH) {\n imgContainerW = imgContainerH;\n }\n\n if (_htOption.logoMaxWidth) {\n imgContainerW = Math.round(_htOption.logoMaxWidth);\n } else if (_htOption.logoWidth) {\n imgContainerW = Math.round(_htOption.logoWidth);\n }\n\n if (_htOption.logoMaxHeight) {\n imgContainerH = Math.round(_htOption.logoMaxHeight);\n } else if (_htOption.logoHeight) {\n imgContainerH = Math.round(_htOption.logoHeight);\n }\n\n var nw;\n var nh;\n\n if (typeof img.naturalWidth == 'undefined') {\n // IE 6/7/8\n nw = img.width;\n nh = img.height;\n } else {\n // HTML5 browsers\n nw = img.naturalWidth;\n nh = img.naturalHeight;\n }\n\n if (_htOption.logoMaxWidth || _htOption.logoMaxHeight) {\n if (_htOption.logoMaxWidth && nw <= imgContainerW) {\n imgContainerW = nw;\n }\n\n if (_htOption.logoMaxHeight && nh <= imgContainerH) {\n imgContainerH = nh;\n }\n\n if (nw <= imgContainerW && nh <= imgContainerH) {\n imgContainerW = nw;\n imgContainerH = nh;\n }\n }\n\n var imgContainerX = (_htOption.width + _htOption.quietZone * 2 - imgContainerW) / 2;\n var imgContainerY = (_htOption.height + _htOption.titleHeight + _htOption.quietZone * 2 - imgContainerH) / 2;\n var imgScale = Math.min(imgContainerW / nw, imgContainerH / nh);\n var imgW = nw * imgScale;\n var imgH = nh * imgScale;\n\n if (_htOption.logoMaxWidth || _htOption.logoMaxHeight) {\n imgContainerW = imgW;\n imgContainerH = imgH;\n imgContainerX = (_htOption.width + _htOption.quietZone * 2 - imgContainerW) / 2;\n imgContainerY = (_htOption.height + _htOption.titleHeight + _htOption.quietZone * 2 - imgContainerH) / 2;\n } // Did Not Use Transparent Logo Image\n\n\n if (!_htOption.logoBackgroundTransparent) {\n //if (!_htOption.logoBackgroundColor) {\n //_htOption.logoBackgroundColor = '#ffffff';\n //}\n _oContext.fillStyle = _htOption.logoBackgroundColor;\n\n _oContext.fillRect(imgContainerX, imgContainerY, imgContainerW, imgContainerH);\n }\n\n var imageSmoothingQuality = _oContext.imageSmoothingQuality;\n var imageSmoothingEnabled = _oContext.imageSmoothingEnabled;\n _oContext.imageSmoothingEnabled = true;\n _oContext.imageSmoothingQuality = 'high';\n\n _oContext.drawImage(img, imgContainerX + (imgContainerW - imgW) / 2, imgContainerY + (imgContainerH - imgH) / 2, imgW, imgH);\n\n _oContext.imageSmoothingEnabled = imageSmoothingEnabled;\n _oContext.imageSmoothingQuality = imageSmoothingQuality;\n drawQuietZoneColor();\n _this._bIsPainted = true;\n\n _this.makeImage();\n }\n\n if (_htOption.logo) {\n // Logo Image\n var img = new Image();\n\n var _this = this;\n\n img.onload = function () {\n generateLogoImg(img);\n };\n\n img.onerror = function (e) {\n console.error(e);\n }; // img.crossOrigin=\"Anonymous\";\n\n\n if (_htOption.crossOrigin != null) {\n img.crossOrigin = _htOption.crossOrigin;\n }\n\n img.originalSrc = _htOption.logo;\n img.src = _htOption.logo;\n } else {\n drawQuietZoneColor();\n this._bIsPainted = true;\n this.makeImage();\n }\n }\n };\n /**\n * Make the image from Canvas if the browser supports Data URI.\n */\n\n\n Drawing.prototype.makeImage = function () {\n if (this._bIsPainted) {\n _safeSetDataURI.call(this, _onMakeImage);\n }\n };\n /**\n * Return whether the QRCode is painted or not\n *\n * @return {Boolean}\n */\n\n\n Drawing.prototype.isPainted = function () {\n return this._bIsPainted;\n };\n /**\n * Clear the QRCode\n */\n\n\n Drawing.prototype.clear = function () {\n this._oContext.clearRect(0, 0, this._elCanvas.width, this._elCanvas.height);\n\n this._bIsPainted = false;\n };\n\n Drawing.prototype.remove = function () {\n this._oContext.clearRect(0, 0, this._elCanvas.width, this._elCanvas.height);\n\n this._bIsPainted = false;\n this._el.innerHTML = '';\n };\n /**\n * @private\n * @param {Number} nNumber\n */\n\n\n Drawing.prototype.round = function (nNumber) {\n if (!nNumber) {\n return nNumber;\n }\n\n return Math.floor(nNumber * 1000) / 1000;\n };\n\n return Drawing;\n }();\n /**\n * Get the type by string length\n *\n * @private\n * @param {String} sText\n * @param {Number} nCorrectLevel\n * @return {Number} type\n */\n\n function _getTypeNumber(sText, _htOption) {\n var nCorrectLevel = _htOption.correctLevel;\n var nType = 1;\n\n var length = _getUTF8Length(sText);\n\n for (var i = 0, len = QRCodeLimitLength.length; i < len; i++) {\n var nLimit = 0;\n\n switch (nCorrectLevel) {\n case QRErrorCorrectLevel.L:\n nLimit = QRCodeLimitLength[i][0];\n break;\n\n case QRErrorCorrectLevel.M:\n nLimit = QRCodeLimitLength[i][1];\n break;\n\n case QRErrorCorrectLevel.Q:\n nLimit = QRCodeLimitLength[i][2];\n break;\n\n case QRErrorCorrectLevel.H:\n nLimit = QRCodeLimitLength[i][3];\n break;\n }\n\n if (length <= nLimit) {\n break;\n } else {\n nType++;\n }\n }\n\n if (nType > QRCodeLimitLength.length) {\n throw new Error('Too long data. the CorrectLevel.' + ['M', 'L', 'H', 'Q'][nCorrectLevel] + ' limit length is ' + nLimit);\n }\n\n if (_htOption.version != 0) {\n if (nType <= _htOption.version) {\n nType = _htOption.version;\n _htOption.runVersion = nType;\n } else {\n console.warn('QR Code version ' + _htOption.version + ' too small, run version use ' + nType);\n _htOption.runVersion = nType;\n }\n }\n\n return nType;\n }\n\n function _getUTF8Length(sText) {\n var replacedText = encodeURI(sText).toString().replace(/\\%[0-9a-fA-F]{2}/g, 'a');\n return replacedText.length + (replacedText.length != sText.length ? 3 : 0);\n }\n\n QRCode = function QRCode(el, vOption) {\n this._htOption = {\n width: 256,\n height: 256,\n typeNumber: 4,\n colorDark: '#000000',\n colorLight: '#ffffff',\n correctLevel: QRErrorCorrectLevel.H,\n dotScale: 1,\n // For body block, must be greater than 0, less than or equal to 1. default is 1\n dotScaleTiming: 1,\n // Dafault for timing block , must be greater than 0, less than or equal to 1. default is 1\n dotScaleTiming_H: undefined$1,\n // For horizontal timing block, must be greater than 0, less than or equal to 1. default is 1\n dotScaleTiming_V: undefined$1,\n // For vertical timing block, must be greater than 0, less than or equal to 1. default is 1\n dotScaleA: 1,\n // Dafault for alignment block, must be greater than 0, less than or equal to 1. default is 1\n dotScaleAO: undefined$1,\n // For alignment outer block, must be greater than 0, less than or equal to 1. default is 1\n dotScaleAI: undefined$1,\n // For alignment inner block, must be greater than 0, less than or equal to 1. default is 1\n quietZone: 0,\n quietZoneColor: 'rgba(0,0,0,0)',\n title: '',\n titleFont: 'normal normal bold 16px Arial',\n titleColor: '#000000',\n titleBackgroundColor: '#ffffff',\n titleHeight: 0,\n // Title Height, Include subTitle\n titleTop: 30,\n // draws y coordinates. default is 30\n subTitle: '',\n subTitleFont: 'normal normal normal 14px Arial',\n subTitleColor: '#4F4F4F',\n subTitleTop: 60,\n // draws y coordinates. default is 0\n logo: undefined$1,\n logoWidth: undefined$1,\n logoHeight: undefined$1,\n logoMaxWidth: undefined$1,\n logoMaxHeight: undefined$1,\n logoBackgroundColor: '#ffffff',\n logoBackgroundTransparent: false,\n // === Posotion Pattern(Eye) Color\n PO: undefined$1,\n // Global Posotion Outer color. if not set, the defaut is `colorDark`\n PI: undefined$1,\n // Global Posotion Inner color. if not set, the defaut is `colorDark`\n PO_TL: undefined$1,\n // Posotion Outer - Top Left\n PI_TL: undefined$1,\n // Posotion Inner - Top Left\n PO_TR: undefined$1,\n // Posotion Outer - Top Right\n PI_TR: undefined$1,\n // Posotion Inner - Top Right\n PO_BL: undefined$1,\n // Posotion Outer - Bottom Left\n PI_BL: undefined$1,\n // Posotion Inner - Bottom Left\n // === Alignment Color\n AO: undefined$1,\n // Alignment Outer. if not set, the defaut is `colorDark`\n AI: undefined$1,\n // Alignment Inner. if not set, the defaut is `colorDark`\n // === Timing Pattern Color\n timing: undefined$1,\n // Global Timing color. if not set, the defaut is `colorDark`\n timing_H: undefined$1,\n // Horizontal timing color\n timing_V: undefined$1,\n // Vertical timing color\n // ==== Backgroud Image\n backgroundImage: undefined$1,\n // Background Image\n backgroundImageAlpha: 1,\n // Background image transparency, value between 0 and 1. default is 1.\n autoColor: false,\n // Automatic color adjustment(for data block)\n autoColorDark: 'rgba(0, 0, 0, .6)',\n // Automatic color: dark CSS color\n autoColorLight: 'rgba(255, 255, 255, .7)',\n // Automatic color: light CSS color\n // ==== Event Handler\n onRenderingStart: undefined$1,\n onRenderingEnd: undefined$1,\n // ==== Versions\n version: 0,\n // The symbol versions of QR Code range from Version 1 to Version 40. default 0 means automatically choose the closest version based on the text length.\n // ==== Tooltip\n tooltip: false,\n // Whether set the QRCode Text as the title attribute value of the image\n // ==== Binary(hex) data mode\n binary: false,\n // Whether it is binary mode, default is text mode.\n // ==== Drawing method\n drawer: 'canvas',\n // Drawing method: canvas, svg(Chrome, FF, IE9+)\n // ==== CORS\n crossOrigin: null,\n // String which specifies the CORS setting to use when retrieving the image. null means that the crossOrigin attribute is not set.\n // UTF-8 without BOM\n utf8WithoutBOM: true\n };\n\n if (typeof vOption === 'string') {\n vOption = {\n text: vOption\n };\n } // Overwrites options\n\n\n if (vOption) {\n for (var i in vOption) {\n this._htOption[i] = vOption[i];\n }\n }\n\n if (this._htOption.version < 0 || this._htOption.version > 40) {\n console.warn(\"QR Code version '\" + this._htOption.version + \"' is invalidate, reset to 0\");\n this._htOption.version = 0;\n }\n\n if (this._htOption.dotScale < 0 || this._htOption.dotScale > 1) {\n console.warn(this._htOption.dotScale + ' , is invalidate, dotScale must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScale = 1;\n }\n\n if (this._htOption.dotScaleTiming < 0 || this._htOption.dotScaleTiming > 1) {\n console.warn(this._htOption.dotScaleTiming + ' , is invalidate, dotScaleTiming must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleTiming = 1;\n }\n\n if (this._htOption.dotScaleTiming_H) {\n if (this._htOption.dotScaleTiming_H < 0 || this._htOption.dotScaleTiming_H > 1) {\n console.warn(this._htOption.dotScaleTiming_H + ' , is invalidate, dotScaleTiming_H must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleTiming_H = 1;\n }\n } else {\n this._htOption.dotScaleTiming_H = this._htOption.dotScaleTiming;\n }\n\n if (this._htOption.dotScaleTiming_V) {\n if (this._htOption.dotScaleTiming_V < 0 || this._htOption.dotScaleTiming_V > 1) {\n console.warn(this._htOption.dotScaleTiming_V + ' , is invalidate, dotScaleTiming_V must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleTiming_V = 1;\n }\n } else {\n this._htOption.dotScaleTiming_V = this._htOption.dotScaleTiming;\n }\n\n if (this._htOption.dotScaleA < 0 || this._htOption.dotScaleA > 1) {\n console.warn(this._htOption.dotScaleA + ' , is invalidate, dotScaleA must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleA = 1;\n }\n\n if (this._htOption.dotScaleAO) {\n if (this._htOption.dotScaleAO < 0 || this._htOption.dotScaleAO > 1) {\n console.warn(this._htOption.dotScaleAO + ' , is invalidate, dotScaleAO must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleAO = 1;\n }\n } else {\n this._htOption.dotScaleAO = this._htOption.dotScaleA;\n }\n\n if (this._htOption.dotScaleAI) {\n if (this._htOption.dotScaleAI < 0 || this._htOption.dotScaleAI > 1) {\n console.warn(this._htOption.dotScaleAI + ' , is invalidate, dotScaleAI must greater than 0, less than or equal to 1, now reset to 1. ');\n this._htOption.dotScaleAI = 1;\n }\n } else {\n this._htOption.dotScaleAI = this._htOption.dotScaleA;\n }\n\n if (this._htOption.backgroundImageAlpha < 0 || this._htOption.backgroundImageAlpha > 1) {\n console.warn(this._htOption.backgroundImageAlpha + ' , is invalidate, backgroundImageAlpha must between 0 and 1, now reset to 1. ');\n this._htOption.backgroundImageAlpha = 1;\n }\n\n this._htOption.height = this._htOption.height + this._htOption.titleHeight;\n\n if (typeof el == 'string') {\n el = document.getElementById(el);\n }\n\n if (!this._htOption.drawer || this._htOption.drawer != 'svg' && this._htOption.drawer != 'canvas') {\n this._htOption.drawer = 'canvas';\n }\n\n this._android = _getAndroid();\n this._el = el;\n this._oQRCode = null;\n var _htOptionClone = {};\n\n for (var i in this._htOption) {\n _htOptionClone[i] = this._htOption[i];\n }\n\n this._oDrawing = new Drawing(this._el, _htOptionClone);\n\n if (this._htOption.text) {\n this.makeCode(this._htOption.text);\n }\n };\n /**\n * Make the QRCode\n *\n * @param {String} sText link data\n */\n\n\n QRCode.prototype.makeCode = function (sText) {\n this._oQRCode = new QRCodeModel(_getTypeNumber(sText, this._htOption), this._htOption.correctLevel);\n\n this._oQRCode.addData(sText, this._htOption.binary, this._htOption.utf8WithoutBOM);\n\n this._oQRCode.make();\n\n if (this._htOption.tooltip) {\n this._el.title = sText;\n }\n\n this._oDrawing.draw(this._oQRCode); // this.makeImage();\n\n };\n /**\n * Make the Image from Canvas element\n * - It occurs automatically\n * - Android below 3 doesn't support Data-URI spec.\n *\n * @private\n */\n\n\n QRCode.prototype.makeImage = function () {\n if (typeof this._oDrawing.makeImage == 'function' && (!this._android || this._android >= 3)) {\n this._oDrawing.makeImage();\n }\n };\n /**\n * Clear the QRCode\n */\n\n\n QRCode.prototype.clear = function () {\n this._oDrawing.remove();\n };\n /**\n * Resize the QRCode\n */\n\n\n QRCode.prototype.resize = function (width, height) {\n this._oDrawing._htOption.width = width;\n this._oDrawing._htOption.height = height;\n\n this._oDrawing.draw(this._oQRCode);\n };\n /**\n * No Conflict\n * @return QRCode object\n */\n\n\n QRCode.prototype.noConflict = function () {\n if (root.QRCode === this) {\n root.QRCode = _QRCode;\n }\n\n return QRCode;\n };\n /**\n * @name QRCode.CorrectLevel\n */\n\n\n QRCode.CorrectLevel = QRErrorCorrectLevel;\n /*--------------------------------------------------------------------------*/\n // Export QRCode\n // AMD & CMD Compatibility\n\n if (typeof define == 'function' && (define.amd || define.cmd)) {\n // 1. Define an anonymous module\n define([], function () {\n return QRCode;\n });\n } // CommonJS Compatibility(include NodeJS)\n else if (freeModule) {\n // Node.js\n (freeModule.exports = QRCode).QRCode = QRCode; // Other CommonJS\n\n freeExports.QRCode = QRCode;\n } else {\n // Export Global\n root.QRCode = QRCode;\n }\n}", "function QR() {\n var typeNumber = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6;\n var errorCorrectLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : errorCorrectLevel_1.ErrorCorrectLevel.L;\n\n _classCallCheck(this, QR);\n\n if (!numberHelper_1.NumberHelper.isInteger(typeNumber) || typeNumber < 0 || typeNumber > 40) {\n throw Error(\"The typeNumber parameter should be a number >= 0 and <= 40\");\n }\n\n this._typeNumber = typeNumber;\n this._errorCorrectLevel = errorCorrectLevel;\n this._qrData = [];\n this._moduleCount = 0;\n this._modules = [];\n mathHelper_1.MathHelper.initialize();\n }", "function initQRCode(numInputBytes, ecLevel, mode, qrCode) {\n qrCode.setECLevel(ecLevel);\n qrCode.setMode(mode);\n\n // In the following comments, we use numbers of Version 7-H.\n for( var versionNum = 1; versionNum <= 40; versionNum++ ) {\n var version = Version.getVersionForNumber(versionNum);\n // numBytes = 196\n var numBytes = version.getTotalCodewords();\n // getNumECBytes = 130\n var ecBlocks = version.getECBlocksForLevel(ecLevel);\n var numEcBytes = ecBlocks.getTotalECCodewords();\n // getNumRSBlocks = 5\n var numRSBlocks = ecBlocks.getNumBlocks();\n // getNumDataBytes = 196 - 130 = 66\n var numDataBytes = numBytes - numEcBytes;\n // We want to choose the smallest version which can contain data of \"numInputBytes\" + some\n // extra bits for the header (mode info and length info). The header can be three bytes\n // (precisely 4 + 16 bits) at most. Hence we do +3 here.\n if( numDataBytes >= numInputBytes + 3 ) {\n // Yay, we found the proper rs block info!\n qrCode.setVersion(versionNum);\n qrCode.setNumTotalBytes(numBytes);\n qrCode.setNumDataBytes(numDataBytes);\n qrCode.setNumRSBlocks(numRSBlocks);\n // getNumECBytes = 196 - 66 = 130\n qrCode.setNumECBytes(numEcBytes);\n // matrix width = 21 + 6 * 4 = 45\n qrCode.setMatrixWidth(version.getDimensionForVersion());\n return;\n }\n }\n throw new Error(\"Cannot find proper rs block info (input data too big?)\");\n }", "function QRCodeManager() {}", "GenerateQRCode(imagePath) {\n let description = document.getElementById('description').value;\n let address = document.getElementById('address').value;\n let defaultcheckinlength = document.getElementById('defaultcheckinlength').value;\n let locationtype = +document.getElementById('locationtype').value;\n\n let locationData = new proto.CWALocationData();\n locationData.setVersion(1);\n locationData.setType(locationtype);\n locationData.setDefaultcheckinlengthinminutes(+defaultcheckinlength);\n\n let crowdNotifierData = new proto.CrowdNotifierData();\n crowdNotifierData.setVersion(1);\n crowdNotifierData.setPublickey('gwLMzE153tQwAOf2MZoUXXfzWTdlSpfS99iZffmcmxOG9njSK4RTimFOFwDh6t0Tyw8XR01ugDYjtuKwjjuK49Oh83FWct6XpefPi9Skjxvvz53i9gaMmUEc96pbtoaA');\n\n let seed = new Uint8Array(16);\n crypto.getRandomValues(seed);\n crowdNotifierData.setCryptographicseed(seed);\n\n let traceLocation = new proto.TraceLocation();\n traceLocation.setVersion(1);\n traceLocation.setDescription(description);\n traceLocation.setAddress(address);\n\n if (locationtype >= 9 || locationtype === 2) {\n let startdate = document.getElementById('starttime-date').value.split('.');\n let starttime = document.getElementById('starttime-time').value;\n traceLocation.setStarttimestamp(moment(startdate.reverse().join('-') + ' ' + starttime).format('X'));\n\n let enddate = document.getElementById('endtime-date').value.split('.');\n let endtime = document.getElementById('endtime-time').value;\n traceLocation.setEndtimestamp(moment(enddate.reverse().join('-') + ' ' + endtime).format('X'));\n }\n\n let payload = new proto.QRCodePayload();\n payload.setLocationdata(traceLocation);\n payload.setCrowdnotifierdata(crowdNotifierData);\n payload.setVendordata(locationData.serializeBinary());\n payload.setVersion(1);\n\n let qrContent = encode(payload.serializeBinary()).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n let canvas = document.getElementById('eventqrcode');\n let ctx = canvas.getContext('2d');\n QRCode.toDataURL('https://e.coronawarn.app?v=1#' + qrContent, {\n margin: 0,\n width: 1100\n }, function (err, qrUrl) {\n if (err) {\n console.error(err);\n return;\n }\n\n let img = new Image();\n img.onload = function() {\n ctx.width = 1654;\n ctx.height = 2339;\n canvas.width = 1654;\n canvas.height = 2339;\n canvas.style.maxWidth = \"100%\"\n\n ctx.drawImage(img, 0, 0);\n let qrImg = new Image();\n qrImg.onload = function() {\n ctx.drawImage(qrImg, 275, 230);\n ctx.font = \"30px sans-serif\";\n ctx.fillStyle = \"black\";\n ctx.fillText(description, 225, 1460);\n ctx.fillText(address, 225, 1510);\n }\n qrImg.src = qrUrl;\n }\n img.src = '/assets/img/pt-poster-1.0.0.png';\n //added\n if(imagePath) img.src = imagePath;\n });\n }", "function makeCode() {\n // Grab url input\n elementText = document.getElementById(\"text\");\n url = elementText.value;\n\n // Check for non-empty url\n if (!url) {\n alert(\"Error: empty input\");\n elementText.focus();\n return;\n }\n\n // // Pad URL since we want more density\n // maxLength = 40;\n // if (url.length < maxLength) {\n // url += \"?/\" + \"0\".repeat(maxLength - url.length);\n // }\n\n // Generate URL bits\n qrcode.makeCode(url);\n\n // Manually draw canvas\n QRMatrix = qrcode._oQRCode.modules;\n QRLength = QRMatrix.length;\n\n // Form canvas\n canvas = document.getElementById(\"myCanvas\");\n ctx = canvas.getContext(\"2d\");\n\n // QR code sizing\n bitLength = 10;\n canvasLength = bitLength * (QRLength + borderSizeValue * 2);\n canvas.width = canvasLength;\n canvas.height = canvasLength;\n\n // Set background of canvas\n if (document.getElementById(\"whitebackground\").checked) {\n ctx.fillStyle = \"#FFFFFF\";\n ctx.fillRect(0, 0, canvasLength, canvasLength);\n }\n\n // Set image of code\n if (img) {\n ctx.drawImage(\n img,\n bitLength * borderSizeValue,\n bitLength * borderSizeValue,\n bitLength * QRLength,\n bitLength * QRLength\n );\n }\n\n // Colors of true and false bits\n black = \"#000000\";\n white = \"#FFFFFF\";\n\n // Populate canvas with bits\n for (let i = 0; i < QRLength; i++) {\n for (let j = 0; j < QRLength; j++) {\n if (QRMatrix[i][j]) {\n ctx.fillStyle = black;\n } else {\n ctx.fillStyle = white;\n }\n drawShape(\n ctx,\n j + borderSizeValue,\n i + borderSizeValue,\n bitLength,\n radiusRatio,\n QRLength\n );\n }\n }\n}", "function mainQrCode() {\n console.log(\"okay\")\n const generateBtn = document.querySelector(\".buttonQRcodeSend\");\n const dataBox = document.getElementById(\"linkQrcode\");\n const qrcode = document.getElementById(\"qrcode\");\n const qrdiv = document.getElementById(\"qrdiv\");\n\n const errorClassName = \"error\";\n const shakeClassName = \"shake\";\n const dataBoxClassName = \"dataBox\";\n const toHideClassName = \"hide\";\n const qrdivClassName = \"qrdiv\";\n\n var QR_CODE = new QRCode(\"qrcode\", {\n width: 260,\n height: 260,\n colorDark: \"#000000\",\n colorLight: \"#ffffff\",\n correctLevel: QRCode.CorrectLevel.H,\n });\n\n const data = dataBox.value;\n if (data) {\n generateQRCode(data);\n } else {\n markDataBoxError();\n }\n\n dataBox.onfocus = function(e) {\n const classList = dataBox.classList;\n\n if (classList.contains(errorClassName)) {\n // Removing error class\n dataBox.className = dataBoxClassName;\n }\n };\n\n\n function markDataBoxError() {\n const prevClassName = dataBox.className;\n dataBox.className =\n prevClassName + \" \" + errorClassName + \" \" + shakeClassName;\n vibrate();\n setTimeout(() => {\n // Reset class\n dataBox.className = prevClassName + \" \" + errorClassName;\n }, 500);\n }\n\n function generateQRCode(data) {\n QR_CODE.clear();\n QR_CODE.makeCode(data);\n // Show QRCode div\n qrdiv.className = qrdivClassName;\n setTimeout(() => {\n let data =qrcode.getElementsByTagName('img')[0].src\n fabric.Image.fromURL(data, function(img) {\n var oImg = img.set({\n left: canvas.getWidth() / 2,\n top: canvas.getHeight() / 2,\n scaleX: 0.2,\n scaleY: 0.2,\n originX: 'center',\n originY: 'center',\n });\n oImg.setControlsVisibility({\n br: false,\n ml: false,\n mt: false,\n mr: false,\n mb: false,\n mtr: false\n });\n canvas.add(oImg).renderAll();\n canvas.setActiveObject(oImg);\n\n });\n\n }, 500);\n }\n\n function vibrate() {\n if (Boolean(window.navigator.vibrate)) {\n window.navigator.vibrate([100, 100, 100]);\n }\n }\n}", "_encodeQRCodeData(data) {\n try {\n const jsonString = JSON.stringify(data);\n return this._compressAndBase32Encode(jsonString);\n } catch (encodeJSONError) {\n console.error(encodeJSONError);\n throw new Error(\"Unable to create QR code (JSON encode error).\");\n }\n }", "function QREncoder() {\n var bitMatrix = qrEncoder.encode(\"HTTPS://QR1.CH/Q/8452D30565044CMP9OI4CC7D47938DF\", 3);\n}", "function generateFrame(data, options) {\n\tvar MODES = {'numeric': MODE_NUMERIC, 'alphanumeric': MODE_ALPHANUMERIC,\n\t\t'octet': MODE_OCTET};\n\tvar ECCLEVELS = {'L': ECCLEVEL_L, 'M': ECCLEVEL_M, 'Q': ECCLEVEL_Q,\n\t\t'H': ECCLEVEL_H};\n\n\toptions = options || {};\n\tvar ver = options.version || -1;\n\tvar ecclevel = ECCLEVELS[(options.eccLevel || 'L').toUpperCase()];\n\tvar mode = options.mode ? MODES[options.mode.toLowerCase()] : -1;\n\tvar mask = 'mask' in options ? options.mask : -1;\n\n\tif (mode < 0) {\n\t\tif (typeof data === 'string') {\n\t\t\tif (data.match(NUMERIC_REGEXP)) {\n\t\t\t\tmode = MODE_NUMERIC;\n\t\t\t} else if (data.match(ALPHANUMERIC_OUT_REGEXP)) {\n\t\t\t\t// while encode supports case-insensitive encoding, we restrict the data to be uppercased when auto-selecting the mode.\n\t\t\t\tmode = MODE_ALPHANUMERIC;\n\t\t\t} else {\n\t\t\t\tmode = MODE_OCTET;\n\t\t\t}\n\t\t} else {\n\t\t\tmode = MODE_OCTET;\n\t\t}\n\t} else if (!(mode == MODE_NUMERIC || mode == MODE_ALPHANUMERIC ||\n\t\tmode == MODE_OCTET)) {\n\t\tthrow 'invalid or unsupported mode';\n\t}\n\n\tdata = validatedata(mode, data);\n\tif (data === null)\n\t\tthrow 'invalid data format';\n\n\tif (ecclevel < 0 || ecclevel > 3)\n\t\tthrow 'invalid ECC level';\n\n\tif (ver < 0) {\n\t\tfor (ver = 1; ver <= 40; ++ver) {\n\t\t\tif (data.length <= getmaxdatalen(ver, mode, ecclevel))\n\t\t\t\tbreak;\n\t\t}\n\t\tif (ver > 40)\n\t\t\tthrow 'too large data for the Qr format';\n\t} else if (ver < 1 || ver > 40) {\n\t\tthrow 'invalid Qr version! should be between 1 and 40';\n\t}\n\n\tif (mask != -1 && (mask < 0 || mask > 8))\n\t\tthrow 'invalid mask';\n\t//console.log('version:', ver, 'mode:', mode, 'ECC:', ecclevel, 'mask:', mask )\n\treturn generate(data, ver, mode, ecclevel, mask);\n}", "function generateFrame(data, options) {\n\t\t\tvar MODES = {'numeric': MODE_NUMERIC, 'alphanumeric': MODE_ALPHANUMERIC,\n\t\t\t\t'octet': MODE_OCTET};\n\t\t\tvar ECCLEVELS = {'L': ECCLEVEL_L, 'M': ECCLEVEL_M, 'Q': ECCLEVEL_Q,\n\t\t\t\t'H': ECCLEVEL_H};\n\n\t\t\toptions = options || {};\n\t\t\tvar ver = options.version || -1;\n\t\t\tvar ecclevel = ECCLEVELS[(options.eccLevel || 'L').toUpperCase()];\n\t\t\tvar mode = options.mode ? MODES[options.mode.toLowerCase()] : -1;\n\t\t\tvar mask = 'mask' in options ? options.mask : -1;\n\n\t\t\tif (mode < 0) {\n\t\t\t\tif (typeof data === 'string') {\n\t\t\t\t\tif (data.match(NUMERIC_REGEXP)) {\n\t\t\t\t\t\tmode = MODE_NUMERIC;\n\t\t\t\t\t} else if (data.match(ALPHANUMERIC_OUT_REGEXP)) {\n\t\t\t\t\t\t// while encode supports case-insensitive encoding, we restrict the data to be uppercased when auto-selecting the mode.\n\t\t\t\t\t\tmode = MODE_ALPHANUMERIC;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmode = MODE_OCTET;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmode = MODE_OCTET;\n\t\t\t\t}\n\t\t\t} else if (!(mode == MODE_NUMERIC || mode == MODE_ALPHANUMERIC ||\n\t\t\t\t\tmode == MODE_OCTET)) {\n\t\t\t\tthrow 'invalid or unsupported mode';\n\t\t\t}\n\n\t\t\tdata = validatedata(mode, data);\n\t\t\tif (data === null) throw 'invalid data format';\n\n\t\t\tif (ecclevel < 0 || ecclevel > 3) throw 'invalid ECC level';\n\n\t\t\tif (ver < 0) {\n\t\t\t\tfor (ver = 1; ver <= 40; ++ver) {\n\t\t\t\t\tif (data.length <= getmaxdatalen(ver, mode, ecclevel)) break;\n\t\t\t\t}\n\t\t\t\tif (ver > 40) throw 'too large data for the Qr format';\n\t\t\t} else if (ver < 1 || ver > 40) {\n\t\t\t\tthrow 'invalid Qr version! should be between 1 and 40';\n\t\t\t}\n\n\t\t\tif (mask != -1 && (mask < 0 || mask > 8)) throw 'invalid mask';\n\t //console.log('version:', ver, 'mode:', mode, 'ECC:', ecclevel, 'mask:', mask )\n\t\t\treturn generate(data, ver, mode, ecclevel, mask);\n\t\t}", "function doSegmentDemo() {\n appendHeading(\"Segment\");\n let qr;\n let segs;\n const QrCode = qrcodegen.QrCode; // Abbreviation\n const QrSegment = qrcodegen.QrSegment; // Abbreviation\n // Illustration \"silver\"\n const silver0 = \"THE SQUARE ROOT OF 2 IS 1.\";\n const silver1 = \"41421356237309504880168872420969807856967187537694807317667973799\";\n qr = QrCode.encodeText(silver0 + silver1, QrCode.Ecc.LOW);\n qr.drawCanvas(10, 3, appendCanvas(\"sqrt2-monolithic-QR\"));\n segs = [\n QrSegment.makeAlphanumeric(silver0),\n QrSegment.makeNumeric(silver1)\n ];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(10, 3, appendCanvas(\"sqrt2-segmented-QR\"));\n // Illustration \"golden\"\n const golden0 = \"Golden ratio \\u03C6 = 1.\";\n const golden1 = \"6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374\";\n const golden2 = \"......\";\n qr = QrCode.encodeText(golden0 + golden1 + golden2, QrCode.Ecc.LOW);\n qr.drawCanvas(8, 5, appendCanvas(\"phi-monolithic-QR\"));\n segs = [\n QrSegment.makeBytes(toUtf8ByteArray(golden0)),\n QrSegment.makeNumeric(golden1),\n QrSegment.makeAlphanumeric(golden2)\n ];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(8, 5, appendCanvas(\"phi-segmented-QR\"));\n // Illustration \"Madoka\": kanji, kana, Cyrillic, full-width Latin, Greek characters\n const madoka = \"\\u300C\\u9B54\\u6CD5\\u5C11\\u5973\\u307E\\u3069\\u304B\\u2606\\u30DE\\u30AE\\u30AB\\u300D\\u3063\\u3066\\u3001\\u3000\\u0418\\u0410\\u0418\\u3000\\uFF44\\uFF45\\uFF53\\uFF55\\u3000\\u03BA\\u03B1\\uFF1F\";\n qr = QrCode.encodeText(madoka, QrCode.Ecc.LOW);\n qr.drawCanvas(9, 4, appendCanvas(\"madoka-utf8-QR\"));\n const kanjiCharBits = [\n 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1,\n 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1,\n 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,\n 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1,\n 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n ];\n segs = [new QrSegment(QrSegment.Mode.KANJI, kanjiCharBits.length / 13, kanjiCharBits)];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(9, 4, appendCanvas(\"madoka-kanji-QR\"));\n }", "function QrSegment(\n // The mode indicator of this segment.\n mode,\n // The length of this segment's unencoded data. Measured in characters for\n // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.\n // Always zero or positive. Not the same as the data's bit length.\n numChars,\n // The data bits of this segment. Accessed through getData().\n bitData) {\n (0,_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(this, QrSegment);\n this.mode = mode;\n this.numChars = numChars;\n this.bitData = bitData;\n if (numChars < 0) throw new RangeError('Invalid argument');\n this.bitData = bitData.slice(); // Make defensive copy\n }", "creerQRCodeEnsemble(){\n return new QRCodeEnsemble();\n }", "function doMaskDemo() {\n appendHeading(\"Mask\");\n let qr;\n let segs;\n const QrCode = qrcodegen.QrCode; // Abbreviation\n // Project Nayuki URL\n segs = qrcodegen.QrSegment.makeSegments(\"https://www.nayuki.io/\");\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.HIGH, QrCode.MIN_VERSION, QrCode.MAX_VERSION, -1, true); // Automatic mask\n qr.drawCanvas(8, 6, appendCanvas(\"project-nayuki-automask-QR\"));\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.HIGH, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 3, true); // Force mask 3\n qr.drawCanvas(8, 6, appendCanvas(\"project-nayuki-mask3-QR\"));\n // Chinese text as UTF-8\n segs = qrcodegen.QrSegment.makeSegments(\"\\u7DAD\\u57FA\\u767E\\u79D1\\uFF08Wikipedia\\uFF0C\\u8046\\u807Di/\\u02CCw\\u026Ak\\u1D7B\\u02C8pi\\u02D0di.\\u0259/\\uFF09\\u662F\\u4E00\"\n + \"\\u500B\\u81EA\\u7531\\u5167\\u5BB9\\u3001\\u516C\\u958B\\u7DE8\\u8F2F\\u4E14\\u591A\\u8A9E\\u8A00\\u7684\\u7DB2\\u8DEF\\u767E\\u79D1\\u5168\\u66F8\\u5354\\u4F5C\\u8A08\\u756B\");\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 0, true); // Force mask 0\n qr.drawCanvas(10, 3, appendCanvas(\"unicode-mask0-QR\"));\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 1, true); // Force mask 1\n qr.drawCanvas(10, 3, appendCanvas(\"unicode-mask1-QR\"));\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 5, true); // Force mask 5\n qr.drawCanvas(10, 3, appendCanvas(\"unicode-mask5-QR\"));\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 7, true); // Force mask 7\n qr.drawCanvas(10, 3, appendCanvas(\"unicode-mask7-QR\"));\n }", "function drawQrcode () {\n var qrcode = new QRCode(\"qrcode\", {\n text: 'http://' + host,\n colorDark : \"#000\",\n colorLight : \"#fff\"\n });\n }", "leerDatosQR() {\n this.isCodigoQrValido = true;\n console.log('codigo escaneado', this.codQR);\n // let _codQr = '';\n // try {\n const _codQr = this.codQR.split('-');\n this.isCodigoQrValido = _codQr[0].toString() === '369' ? true : false;\n console.log('_codQr', _codQr);\n console.log('_codQr', _codQr[1]);\n if (!this.isCodigoQrValido) {\n return;\n }\n this.codeScanSucces.emit(_codQr[1]);\n // } catch (error) {\n // this.resValidQR(false);\n // return;\n // }\n // const isValidKeyQR = _codQr[0] === 'keyQrPwa' ? true : false;\n // if ( !isValidKeyQR ) {\n // this.isDemo = _codQr[0] === 'keyQrPwaDemo' ? true : false;\n // }\n // // no se encuentra el key no es qr valido\n // if ( !isValidKeyQR && !this.isDemo) {\n // this.resValidQR(isValidKeyQR);\n // return;\n // }\n // // const dataQr = this.codQR.split('|');\n // const dataQr = _codQr[1].split('|');\n // const m = dataQr[0];\n // const s = dataQr[2];\n // const o = dataQr[3];\n // // -1 = solo llevar // activa ubicacion\n // this.isSoloLLevar = m === '-1' ? true : false;\n // this.isDelivery = m === '-2' ? true : false;\n // const dataSend = {\n // m: m,\n // s: s\n // };\n // // consultar si sede requiere geolocalizacion\n // const dataHeader = {\n // idsede: s\n // };\n // this.crudService.postFree(dataHeader, 'ini', 'info-sede-gps', false)\n // .subscribe((res: any) => {\n // this.isSedeRequiereGPS = res.data[0].pwa_requiere_gps === '0' ? false : true;\n // this.isSedeRequiereGPS = this.isSoloLLevar ? true : this.isSedeRequiereGPS;\n // this.isSedeRequiereGPS = this.isDelivery ? false : this.isSedeRequiereGPS;\n // // setear idsede en clienteSOcket\n // this.verifyClientService.getDataClient();\n // if ( !this.isSoloLLevar ) { this.verifyClientService.setMesa(m); }\n // this.verifyClientService.setIdSede(s);\n // this.verifyClientService.setQrSuccess(true);\n // this.verifyClientService.setIsSoloLLevar(this.isSoloLLevar);\n // this.verifyClientService.setIsDelivery(this.isDelivery);\n // if ( this.isDelivery ) {\n // // this.infoTokenService.converToJSON();\n // // this.infoTokenService.infoUsToken.isDelivery = true;\n // // this.infoTokenService.set();\n // this.verifyClientService.setIdOrg(o);\n // this.getInfoEstablecimiento(s);\n // }\n // // this.verifyClientService.setDataClient();\n // const position = dataQr[1].split(':');\n // const localPos = { lat: parseFloat(position[0]), lng: parseFloat(position[1]) };\n // const isPositionCorrect = true;\n // if ( this.isSedeRequiereGPS ) {\n // // this.getPosition();\n // // isPositionCorrect = this.isDemo ? true : this.arePointsNear(localPos, this.divicePos, 1);\n // this.openDialogPOS(localPos);\n // } else {\n // this.resValidQR(isPositionCorrect);\n // }\n // });\n }", "drawCodewords(data) {\n if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))\n throw \"Invalid argument\";\n let i = 0; // Bit index into the data\n // Do the funny zigzag scan\n for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair\n if (right == 6)\n right = 5;\n for (let vert = 0; vert < this.size; vert++) { // Vertical counter\n for (let j = 0; j < 2; j++) {\n const x = right - j; // Actual x coordinate\n const upward = ((right + 1) & 2) == 0;\n const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate\n if (!this.isFunction[y][x] && i < data.length * 8) {\n this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));\n i++;\n }\n // If this QR Code has any remainder bits (0 to 7), they were assigned as\n // 0/false/white by the constructor and are left unchanged by this method\n }\n }\n }\n if (i != data.length * 8)\n throw \"Assertion error\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be threadsafe. We have no pointers in JS, so keep tables separate
function $tTA8$var$fixedtables(state) { if ($tTA8$var$virgin) { var sym; $tTA8$var$lenfix = new $tTA8$var$utils.Buf32(512); $tTA8$var$distfix = new $tTA8$var$utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } $tTA8$var$inflate_table($tTA8$var$LENS, state.lens, 0, 288, $tTA8$var$lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } $tTA8$var$inflate_table($tTA8$var$DISTS, state.lens, 0, 32, $tTA8$var$distfix, 0, state.work, { bits: 5 }); /* do this just once */ $tTA8$var$virgin = false; } state.lencode = $tTA8$var$lenfix; state.lenbits = 9; state.distcode = $tTA8$var$distfix; state.distbits = 5; }
[ "function constructFixedTables() {\n\t\tvar lengths = new Array();\n\t\t// literal/length table\n\t\tfor(var symbol = 0; symbol < 144; symbol++) lengths[symbol] = 8;\n\t\tfor(; symbol < 256; symbol++) lengths[symbol] = 9;\n\t\tfor(; symbol < 280; symbol++) lengths[symbol] = 7;\n\t\tfor(; symbol < FIXLCODES; symbol++) lengths[symbol] = 8;\n\t\tconstruct(lencode, lengths, FIXLCODES);\n\t\tfor(symbol = 0; symbol < MAXDCODES; symbol++) lengths[symbol] = 5;\n\t\tconstruct(distcode, lengths, MAXDCODES);\n\t}", "function inflate_table(state, type)\n{\n var MAXBITS = 15;\n var table = state.next;\n var bits = (type == DISTS ? state.distbits : state.lenbits);\n var work = state.work;\n var lens = state.lens;\n var lens_offset = (type == DISTS ? state.nlen : 0);\n var state_codes = state.codes;\n var codes;\n if(type == LENS)\n codes = state.nlen;\n else if(type == DISTS)\n codes = state.ndist;\n else // CODES\n codes = 19;\n\n var len; /* a code's length in bits */\n var sym; /* index of code symbols */\n var min, max; /* minimum and maximum code lengths */\n var root; /* number of index bits for root table */\n var curr; /* number of index bits for current table */\n var drop; /* code bits to drop for sub-table */\n var left; /* number of prefix codes available */\n var used; /* code entries in table used */\n var huff; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var here; /* table entry for duplication */\n var next; /* next available space in table */\n var base; /* base value table to use */\n var base_offset;\n var extra; /* extra bits table to use */\n var extra_offset;\n var end; /* use base and extra for symbol > end */\n var count = new Array(MAXBITS+1); /* number of codes of each length */\n var offs = new Array(MAXBITS+1); /* offsets in table for each length */\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++)\n count[len] = 0;\n for (sym = 0; sym < codes; sym++)\n count[lens[lens_offset + sym]]++;\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n\n for (max = MAXBITS; max >= 1; max--)\n if (count[max] != 0) break;\n if (root > max) root = max;\n if (max == 0) {\n /* no symbols to code at all */\n /* invalid code marker */\n here = {op:64, bits:1, val:0};\n state_codes[table++] = here; /* make a table to force an error */\n state_codes[table++] = here;\n if(type == DISTS) state.distbits = 1; else state.lenbits = 1; // *bits = 1;\n state.next = table;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++)\n if (count[min] != 0) break;\n if (root < min) root = min;\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) return -1; /* over-subscribed */\n }\n if (left > 0 && (type == CODES || max != 1)) {\n state.next = table;\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++)\n offs[len + 1] = offs[len] + count[len];\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++)\n if (lens[lens_offset + sym] != 0) work[offs[lens[lens_offset + sym]]++] = sym;\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n switch (type) {\n case CODES:\n base = extra = work; /* dummy value--not used */\n base_offset = 0;\n extra_offset = 0;\n end = 19;\n break;\n case LENS:\n base = inflate_table_lbase;\n base_offset = -257; // base -= 257;\n extra = inflate_table_lext;\n extra_offset = -257; // extra -= 257;\n end = 256;\n break;\n default: /* DISTS */\n base = inflate_table_dbase;\n extra = inflate_table_dext;\n base_offset = 0;\n extra_offset = 0;\n end = -1;\n }\n\n /* initialize state for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type == LENS && used >= ENOUGH_LENS) ||\n (type == DISTS && used >= ENOUGH_DISTS)) {\n state.next = table;\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here = {op:0, bits:len - drop, val:0};\n if (work[sym] < end) {\n here.val = work[sym];\n }\n else if (work[sym] > end) {\n here.op = extra[extra_offset + work[sym]];\n here.val = base[base_offset + work[sym]];\n }\n else {\n here.op = 32 + 64; /* end of block */\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n state_codes[next + (huff >>> drop) + fill] = here;\n } while (fill != 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr)\n incr >>>= 1;\n if (incr != 0) {\n huff &= incr - 1;\n huff += incr;\n }\n else\n huff = 0;\n\n /* go to next symbol, update count, len */\n sym++;\n if (--(count[len]) == 0) {\n if (len == max) break;\n len = lens[lens_offset + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) != low) {\n /* if first time, transition to sub-tables */\n if (drop == 0)\n drop = root;\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = (1 << curr);\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) break;\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type == LENS && used >= ENOUGH_LENS) ||\n (type == DISTS && used >= ENOUGH_DISTS)) {\n state.next = table;\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n state_codes[table + low] = {op:curr, bits:root, val:next - table};\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff != 0) {\n state_codes[next + huff] = {op:64, bits:len - drop, val:0};\n }\n\n /* set return parameters */\n state.next = table + used;\n if(type == DISTS) state.distbits = root; else state.lenbits = root; //*bits = root;\n return 0;\n}", "function h$initInfoTables ( depth // depth in the base chain\n , funcs // array with all entry functions\n , objects // array with all the global heap objects\n , lbls // array with non-haskell labels\n , infoMeta // packed info\n , infoStatic\n ) {\n TRACE_META(\"decoding info tables\");\n var n, i, j, o, pos = 0, info;\n function code(c) {\n if(c < 34) return c - 32;\n if(c < 92) return c - 33;\n return c - 34;\n }\n function next() {\n var c = info.charCodeAt(pos);\n if(c < 124) {\n TRACE_META(\"pos: \" + pos + \" decoded: \" + code(c));\n pos++;\n return code(c);\n }\n if(c === 124) {\n pos+=3;\n var r = 90 + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n TRACE_META(\"pos: \" + (pos-3) + \" decoded: \" + r);\n return r;\n }\n if(c === 125) {\n pos+=4;\n var r = 8190 + 8100 * code(info.charCodeAt(pos-3))\n + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n TRACE_META(\"pos: \" + (pos-4) + \" decoded: \" + r);\n return r;\n }\n throw (\"h$initInfoTables: invalid code in info table: \" + c + \" at \" + pos)\n }\n function nextCh() {\n return next(); // fixme map readable chars\n }\n function nextInt() {\n var n = next();\n var r;\n if(n === 0) {\n var n1 = next();\n var n2 = next();\n r = n1 << 16 | n2;\n } else {\n r = n - 12;\n }\n TRACE_META(\"decoded int: \" + r);\n return r;\n }\n function nextSignificand() {\n var n = next();\n var n1, n2, n3, n4, n5;\n var r;\n if(n < 2) {\n n1 = next();\n n2 = next();\n n3 = next();\n n4 = next();\n n5 = n1 * 281474976710656 + n2 * 4294967296 + n3 * 65536 + n4;\n r = n === 0 ? -n5 : n5;\n } else {\n r = n - 12;\n }\n TRACE_META(\"decoded significand:\" + r);\n return r;\n }\n function nextEntry(o) { return nextIndexed(\"nextEntry\", h$entriesStack, o); }\n function nextObj(o) { return nextIndexed(\"nextObj\", h$staticsStack, o); }\n function nextLabel(o) { return nextIndexed(\"nextLabel\", h$labelsStack, o); }\n function nextIndexed(msg, stack, o) {\n var n = (o === undefined) ? next() : o;\n var i = depth;\n while(n >= stack[i].length) {\n n -= stack[i].length;\n i--;\n if(i < 0) throw (msg + \": cannot find item \" + n + \", stack length: \" + stack.length + \" depth: \" + depth);\n }\n return stack[i][n];\n }\n function nextArg() {\n var o = next();\n var n, n1, n2, d0, d1, d2, d3;\n var isString = false;\n switch(o) {\n case 0:\n TRACE_META(\"bool arg: false\");\n return false;\n case 1:\n TRACE_META(\"bool arg: true\");\n return true;\n case 2:\n TRACE_META(\"int constant: 0\");\n return 0;\n case 3:\n TRACE_META(\"int constant: 1\");\n return 1;\n case 4:\n TRACE_META(\"int arg\");\n return nextInt();\n case 5:\n TRACE_META(\"literal arg: null\");\n return null;\n case 6:\n TRACE_META(\"double arg\");\n n = next();\n switch(n) {\n case 0:\n return -0.0;\n case 1:\n return 0.0;\n case 2:\n return 1/0;\n case 3:\n return -1/0;\n case 4:\n return 0/0;\n case 5:\n n1 = nextInt();\n var ns = nextSignificand();\n if(n1 > 600) {\n return ns * Math.pow(2,n1-600) * Math.pow(2,600);\n } else if(n1 < -600) {\n return ns * Math.pow(2,n1+600) * Math.pow(2,-600);\n } else {\n return ns * Math.pow(2, n1);\n }\n default:\n n1 = n - 36;\n return nextSignificand() * Math.pow(2, n1);\n }\n case 7:\n TRACE_META(\"string arg\");\n isString = true;\n // no break, strings are null temrinated UTF8 encoded binary with\n case 8:\n TRACE_META(\"binary arg\");\n n = next();\n var ba = h$newByteArray(isString ? (n+1) : n);\n var b8 = ba.u8;\n if(isString) b8[n] = 0;\n var p = 0;\n while(n > 0) {\n switch(n) {\n case 1:\n d0 = next();\n d1 = next();\n b8[p] = ((d0 << 2) | (d1 >> 4));\n break;\n case 2:\n d0 = next();\n d1 = next();\n d2 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p] = ((d1 << 4) | (d2 >> 2));\n break;\n default:\n d0 = next();\n d1 = next();\n d2 = next();\n d3 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p++] = ((d1 << 4) | (d2 >> 2));\n b8[p++] = ((d2 << 6) | d3);\n break;\n }\n n -= 3;\n }\n return ba;\n case 9:\n var isFun = next() === 1;\n var lbl = nextLabel();\n return h$initPtrLbl(isFun, lbl);\n case 10:\n var c = { f: nextEntry(), d1: null, d2: null, m: 0 };\n var n = next();\n var args = [];\n while(n--) {\n args.push(nextArg());\n }\n return h$init_closure(c, args);\n default:\n TRACE_META(\"object arg: \" + (o-11));\n return nextObj(o-11);\n }\n }\n info = infoMeta; pos = 0;\n for(i=0;i<funcs.length;i++) {\n o = funcs[i];\n var ot;\n var oa = 0;\n var oregs = 256; // one register no skip\n switch(next()) {\n case 0: // thunk\n ot = 0;\n break;\n case 1: // fun\n ot = 1;\n var arity = next();\n var skipRegs = next()-1;\n if(skipRegs === -1) throw \"h$initInfoTables: unknown register info for function\";\n var skip = skipRegs & 1;\n var regs = skipRegs >>> 1;\n oregs = (regs << 8) | skip;\n oa = arity + ((regs-1+skip) << 8);\n break;\n case 2: // con\n ot = 2;\n oa = next();\n break;\n case 3: // stack frame\n ot = -1;\n oa = 0;\n oregs = next() - 1;\n if(oregs !== -1) oregs = ((oregs >>> 1) << 8) | (oregs & 1);\n break;\n default: throw (\"h$initInfoTables: invalid closure type\")\n }\n var size = next() - 1;\n var nsrts = next();\n var srt = null;\n if(nsrts > 0) {\n srt = [];\n for(var j=0;j<nsrts;j++) {\n srt.push(nextObj());\n }\n }\n\n // h$log(\"result: \" + ot + \" \" + oa + \" \" + oregs + \" [\" + srt + \"] \" + size);\n // h$log(\"orig: \" + o.t + \" \" + o.a + \" \" + o.r + \" [\" + o.s + \"] \" + o.size);\n // if(ot !== o.t || oa !== o.a || oregs !== o.r || size !== o.size) throw \"inconsistent\";\n\n o.t = ot;\n o.i = [];\n o.n = \"\";\n o.a = oa;\n o.r = oregs;\n o.s = srt;\n o.m = 0;\n o.size = size;\n }\n info = infoStatic;\n pos = 0;\n for(i=0;i<objects.length;i++) {\n TRACE_META(\"start iteration\");\n o = objects[i];\n // traceMetaObjBefore(o);\n var nx = next();\n TRACE_META(\"static init object: \" + i + \" tag: \" + nx);\n switch(nx) {\n case 0: // no init, could be a primitive value (still in the list since others might reference it)\n // h$log(\"zero init\");\n break;\n case 1: // staticfun\n o.f = nextEntry();\n TRACE_META(\"staticFun\");\n n = next();\n TRACE_META(\"args: \" + n);\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n\n break;\n case 2: // staticThunk\n TRACE_META(\"staticThunk\");\n o.f = nextEntry();\n n = next();\n TRACE_META(\"args: \" + n);\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n h$addCAF(o);\n break;\n case 3: // staticPrim false, no init\n TRACE_META(\"staticBool false\");\n break;\n case 4: // staticPrim true, no init\n TRACE_META(\"staticBool true\");\n break;\n case 5:\n TRACE_META(\"staticInt\");\n break;\n case 6: // staticString\n TRACE_META(\"staticDouble\");\n break;\n case 7: // staticBin\n TRACE_META(\"staticBin: error unused\");\n n = next();\n var b = h$newByteArray(n);\n for(j=0;j>n;j++) {\n b.u8[j] = next();\n }\n break;\n case 8: // staticEmptyList\n TRACE_META(\"staticEmptyList\");\n o.f = HS_NIL_CON;\n break;\n case 9: // staticList\n TRACE_META(\"staticList\");\n n = next();\n var hasTail = next();\n var c = (hasTail === 1) ? nextObj() : HS_NIL;\n TRACE_META(\"list length: \" + n);\n while(n--) {\n c = MK_CONS(nextArg(), c);\n }\n o.f = c.f;\n o.d1 = c.d1;\n o.d2 = c.d2;\n break;\n case 10: // staticData n args\n TRACE_META(\"staticData\");\n n = next();\n TRACE_META(\"args: \" + n);\n o.f = nextEntry();\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n break;\n case 11: // staticData 0 args\n TRACE_META(\"staticData0\");\n o.f = nextEntry();\n break;\n case 12: // staticData 1 args\n TRACE_META(\"staticData1\");\n o.f = nextEntry();\n o.d1 = nextArg();\n break;\n case 13: // staticData 2 args\n TRACE_META(\"staticData2\");\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = nextArg();\n break;\n case 14: // staticData 3 args\n TRACE_META(\"staticData3\");\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg()};\n break;\n case 15: // staticData 4 args\n TRACE_META(\"staticData4\");\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg() };\n break;\n case 16: // staticData 5 args\n TRACE_META(\"staticData5\");\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg() };\n break;\n case 17: // staticData 6 args\n TRACE_META(\"staticData6\");\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg(), d5: nextArg() };\n break;\n default:\n throw (\"invalid static data initializer: \" + nx);\n }\n }\n h$staticDelayed = null;\n}", "function woff2otfFactory() {\n\n // Begin tinyInflate\n var tinyInflate = function () {\n var module = {};\n var TINF_OK = 0;\n var TINF_DATA_ERROR = -3;\n\n function Tree() {\n this.table = new Uint16Array(16); /* table of code length counts */\n this.trans = new Uint16Array(288); /* code -> symbol translation table */\n }\n\n function Data(source, dest) {\n this.source = source;\n this.sourceIndex = 0;\n this.tag = 0;\n this.bitcount = 0;\n\n this.dest = dest;\n this.destLen = 0;\n\n this.ltree = new Tree(); /* dynamic length/symbol tree */\n this.dtree = new Tree(); /* dynamic distance tree */\n }\n\n /* --------------------------------------------------- *\n * -- uninitialized global data (static structures) -- *\n * --------------------------------------------------- */\n\n var sltree = new Tree();\n var sdtree = new Tree();\n\n /* extra bits and base tables for length codes */\n var length_bits = new Uint8Array(30);\n var length_base = new Uint16Array(30);\n\n /* extra bits and base tables for distance codes */\n var dist_bits = new Uint8Array(30);\n var dist_base = new Uint16Array(30);\n\n /* special ordering of code length codes */\n var clcidx = new Uint8Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n\n /* used by tinf_decode_trees, avoids allocations every call */\n var code_tree = new Tree();\n var lengths = new Uint8Array(288 + 32);\n\n /* ----------------------- *\n * -- utility functions -- *\n * ----------------------- */\n\n /* build extra bits and base tables */\n function tinf_build_bits_base(bits, base, delta, first) {\n var i, sum;\n\n /* build bits table */\n for (i = 0; i < delta; ++i) {\n bits[i] = 0;\n }for (i = 0; i < 30 - delta; ++i) {\n bits[i + delta] = i / delta | 0;\n } /* build base table */\n for (sum = first, i = 0; i < 30; ++i) {\n base[i] = sum;\n sum += 1 << bits[i];\n }\n }\n\n /* build the fixed huffman trees */\n function tinf_build_fixed_trees(lt, dt) {\n var i;\n\n /* build fixed length tree */\n for (i = 0; i < 7; ++i) {\n lt.table[i] = 0;\n }lt.table[7] = 24;\n lt.table[8] = 152;\n lt.table[9] = 112;\n\n for (i = 0; i < 24; ++i) {\n lt.trans[i] = 256 + i;\n }for (i = 0; i < 144; ++i) {\n lt.trans[24 + i] = i;\n }for (i = 0; i < 8; ++i) {\n lt.trans[24 + 144 + i] = 280 + i;\n }for (i = 0; i < 112; ++i) {\n lt.trans[24 + 144 + 8 + i] = 144 + i;\n } /* build fixed distance tree */\n for (i = 0; i < 5; ++i) {\n dt.table[i] = 0;\n }dt.table[5] = 32;\n\n for (i = 0; i < 32; ++i) {\n dt.trans[i] = i;\n }\n }\n\n /* given an array of code lengths, build a tree */\n var offs = new Uint16Array(16);\n\n function tinf_build_tree(t, lengths, off, num) {\n var i, sum;\n\n /* clear code length count table */\n for (i = 0; i < 16; ++i) {\n t.table[i] = 0;\n } /* scan symbol lengths, and sum code length counts */\n for (i = 0; i < num; ++i) {\n t.table[lengths[off + i]]++;\n }t.table[0] = 0;\n\n /* compute offset table for distribution sort */\n for (sum = 0, i = 0; i < 16; ++i) {\n offs[i] = sum;\n sum += t.table[i];\n }\n\n /* create code->symbol translation table (symbols sorted by code) */\n for (i = 0; i < num; ++i) {\n if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i;\n }\n }\n\n /* ---------------------- *\n * -- decode functions -- *\n * ---------------------- */\n\n /* get one bit from source stream */\n function tinf_getbit(d) {\n /* check if tag is empty */\n if (!d.bitcount--) {\n /* load next tag */\n d.tag = d.source[d.sourceIndex++];\n d.bitcount = 7;\n }\n\n /* shift bit out of tag */\n var bit = d.tag & 1;\n d.tag >>>= 1;\n\n return bit;\n }\n\n /* read a num bit value from a stream and add base */\n function tinf_read_bits(d, num, base) {\n if (!num) return base;\n\n while (d.bitcount < 24) {\n d.tag |= d.source[d.sourceIndex++] << d.bitcount;\n d.bitcount += 8;\n }\n\n var val = d.tag & 0xffff >>> 16 - num;\n d.tag >>>= num;\n d.bitcount -= num;\n return val + base;\n }\n\n /* given a data stream and a tree, decode a symbol */\n function tinf_decode_symbol(d, t) {\n while (d.bitcount < 24) {\n d.tag |= d.source[d.sourceIndex++] << d.bitcount;\n d.bitcount += 8;\n }\n\n var sum = 0,\n cur = 0,\n len = 0;\n var tag = d.tag;\n\n /* get more bits while code value is above sum */\n do {\n cur = 2 * cur + (tag & 1);\n tag >>>= 1;\n ++len;\n\n sum += t.table[len];\n cur -= t.table[len];\n } while (cur >= 0);\n\n d.tag = tag;\n d.bitcount -= len;\n\n return t.trans[sum + cur];\n }\n\n /* given a data stream, decode dynamic trees from it */\n function tinf_decode_trees(d, lt, dt) {\n var hlit, hdist, hclen;\n var i, num, length;\n\n /* get 5 bits HLIT (257-286) */\n hlit = tinf_read_bits(d, 5, 257);\n\n /* get 5 bits HDIST (1-32) */\n hdist = tinf_read_bits(d, 5, 1);\n\n /* get 4 bits HCLEN (4-19) */\n hclen = tinf_read_bits(d, 4, 4);\n\n for (i = 0; i < 19; ++i) {\n lengths[i] = 0;\n } /* read code lengths for code length alphabet */\n for (i = 0; i < hclen; ++i) {\n /* get 3 bits code length (0-7) */\n var clen = tinf_read_bits(d, 3, 0);\n lengths[clcidx[i]] = clen;\n }\n\n /* build code length tree */\n tinf_build_tree(code_tree, lengths, 0, 19);\n\n /* decode code lengths for the dynamic trees */\n for (num = 0; num < hlit + hdist;) {\n var sym = tinf_decode_symbol(d, code_tree);\n\n switch (sym) {\n case 16:\n /* copy previous code length 3-6 times (read 2 bits) */\n var prev = lengths[num - 1];\n for (length = tinf_read_bits(d, 2, 3); length; --length) {\n lengths[num++] = prev;\n }\n break;\n case 17:\n /* repeat code length 0 for 3-10 times (read 3 bits) */\n for (length = tinf_read_bits(d, 3, 3); length; --length) {\n lengths[num++] = 0;\n }\n break;\n case 18:\n /* repeat code length 0 for 11-138 times (read 7 bits) */\n for (length = tinf_read_bits(d, 7, 11); length; --length) {\n lengths[num++] = 0;\n }\n break;\n default:\n /* values 0-15 represent the actual code lengths */\n lengths[num++] = sym;\n break;\n }\n }\n\n /* build dynamic trees */\n tinf_build_tree(lt, lengths, 0, hlit);\n tinf_build_tree(dt, lengths, hlit, hdist);\n }\n\n /* ----------------------------- *\n * -- block inflate functions -- *\n * ----------------------------- */\n\n /* given a stream and two trees, inflate a block of data */\n function tinf_inflate_block_data(d, lt, dt) {\n while (1) {\n var sym = tinf_decode_symbol(d, lt);\n\n /* check for end of block */\n if (sym === 256) {\n return TINF_OK;\n }\n\n if (sym < 256) {\n d.dest[d.destLen++] = sym;\n } else {\n var length, dist, offs;\n var i;\n\n sym -= 257;\n\n /* possibly get more bits from length code */\n length = tinf_read_bits(d, length_bits[sym], length_base[sym]);\n\n dist = tinf_decode_symbol(d, dt);\n\n /* possibly get more bits from distance code */\n offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);\n\n /* copy match */\n for (i = offs; i < offs + length; ++i) {\n d.dest[d.destLen++] = d.dest[i];\n }\n }\n }\n }\n\n /* inflate an uncompressed block of data */\n function tinf_inflate_uncompressed_block(d) {\n var length, invlength;\n var i;\n\n /* unread from bitbuffer */\n while (d.bitcount > 8) {\n d.sourceIndex--;\n d.bitcount -= 8;\n }\n\n /* get length */\n length = d.source[d.sourceIndex + 1];\n length = 256 * length + d.source[d.sourceIndex];\n\n /* get one's complement of length */\n invlength = d.source[d.sourceIndex + 3];\n invlength = 256 * invlength + d.source[d.sourceIndex + 2];\n\n /* check length */\n if (length !== (~invlength & 0x0000ffff)) return TINF_DATA_ERROR;\n\n d.sourceIndex += 4;\n\n /* copy block */\n for (i = length; i; --i) {\n d.dest[d.destLen++] = d.source[d.sourceIndex++];\n } /* make sure we start next block on a byte boundary */\n d.bitcount = 0;\n\n return TINF_OK;\n }\n\n /* inflate stream from source to dest */\n function tinf_uncompress(source, dest) {\n var d = new Data(source, dest);\n var bfinal, btype, res;\n\n do {\n /* read final block flag */\n bfinal = tinf_getbit(d);\n\n /* read block type (2 bits) */\n btype = tinf_read_bits(d, 2, 0);\n\n /* decompress block */\n switch (btype) {\n case 0:\n /* decompress uncompressed block */\n res = tinf_inflate_uncompressed_block(d);\n break;\n case 1:\n /* decompress block with fixed huffman trees */\n res = tinf_inflate_block_data(d, sltree, sdtree);\n break;\n case 2:\n /* decompress block with dynamic huffman trees */\n tinf_decode_trees(d, d.ltree, d.dtree);\n res = tinf_inflate_block_data(d, d.ltree, d.dtree);\n break;\n default:\n res = TINF_DATA_ERROR;\n }\n\n if (res !== TINF_OK) throw new Error('Data error');\n } while (!bfinal);\n\n if (d.destLen < d.dest.length) {\n if (typeof d.dest.slice === 'function') return d.dest.slice(0, d.destLen);else return d.dest.subarray(0, d.destLen);\n }\n\n return d.dest;\n }\n\n /* -------------------- *\n * -- initialization -- *\n * -------------------- */\n\n /* build fixed huffman trees */\n tinf_build_fixed_trees(sltree, sdtree);\n\n /* build extra bits and base tables */\n tinf_build_bits_base(length_bits, length_base, 4, 3);\n tinf_build_bits_base(dist_bits, dist_base, 2, 1);\n\n /* fix a special case */\n length_bits[28] = 0;\n length_base[28] = 258;\n\n module.exports = tinf_uncompress;\n\n return module.exports;\n }();\n // End tinyInflate\n\n // Begin woff2otf.js\n /*\n Copyright 2012, Steffen Hanikel (https://github.com/hanikesn)\n Modified by Artemy Tregubenko, 2014 (https://github.com/arty-name/woff2otf)\n Modified by Jason Johnston, 2019 (pako --> tiny-inflate)\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n A tool to convert a WOFF back to a TTF/OTF font file, in pure Javascript\n */\n\n function convert_streams(bufferIn, tinyInflate) {\n var dataViewIn = new DataView(bufferIn);\n var offsetIn = 0;\n\n function read2() {\n var uint16 = dataViewIn.getUint16(offsetIn);\n offsetIn += 2;\n return uint16;\n }\n\n function read4() {\n var uint32 = dataViewIn.getUint32(offsetIn);\n offsetIn += 4;\n return uint32;\n }\n\n function write2(uint16) {\n dataViewOut.setUint16(offsetOut, uint16);\n offsetOut += 2;\n }\n\n function write4(uint32) {\n dataViewOut.setUint32(offsetOut, uint32);\n offsetOut += 4;\n }\n\n var WOFFHeader = {\n signature: read4(),\n flavor: read4(),\n length: read4(),\n numTables: read2(),\n reserved: read2(),\n totalSfntSize: read4(),\n majorVersion: read2(),\n minorVersion: read2(),\n metaOffset: read4(),\n metaLength: read4(),\n metaOrigLength: read4(),\n privOffset: read4(),\n privLength: read4()\n };\n\n var entrySelector = 0;\n while (Math.pow(2, entrySelector) <= WOFFHeader.numTables) {\n entrySelector++;\n }\n entrySelector--;\n\n var searchRange = Math.pow(2, entrySelector) * 16;\n var rangeShift = WOFFHeader.numTables * 16 - searchRange;\n\n var offset = 4 + 2 + 2 + 2 + 2;\n var TableDirectoryEntries = [];\n for (var i = 0; i < WOFFHeader.numTables; i++) {\n TableDirectoryEntries.push({\n tag: read4(),\n offset: read4(),\n compLength: read4(),\n origLength: read4(),\n origChecksum: read4()\n });\n offset += 4 * 4;\n }\n\n var arrayOut = new Uint8Array(4 + 2 + 2 + 2 + 2 + TableDirectoryEntries.length * (4 + 4 + 4 + 4) + TableDirectoryEntries.reduce(function (acc, entry) {\n return acc + entry.origLength + 4;\n }, 0));\n var bufferOut = arrayOut.buffer;\n var dataViewOut = new DataView(bufferOut);\n var offsetOut = 0;\n\n write4(WOFFHeader.flavor);\n write2(WOFFHeader.numTables);\n write2(searchRange);\n write2(entrySelector);\n write2(rangeShift);\n\n TableDirectoryEntries.forEach(function (TableDirectoryEntry) {\n write4(TableDirectoryEntry.tag);\n write4(TableDirectoryEntry.origChecksum);\n write4(offset);\n write4(TableDirectoryEntry.origLength);\n\n TableDirectoryEntry.outOffset = offset;\n offset += TableDirectoryEntry.origLength;\n if (offset % 4 != 0) {\n offset += 4 - offset % 4;\n }\n });\n\n var size;\n\n TableDirectoryEntries.forEach(function (TableDirectoryEntry) {\n var compressedData = bufferIn.slice(TableDirectoryEntry.offset, TableDirectoryEntry.offset + TableDirectoryEntry.compLength);\n\n if (TableDirectoryEntry.compLength != TableDirectoryEntry.origLength) {\n var uncompressedData = new Uint8Array(TableDirectoryEntry.origLength);\n tinyInflate(new Uint8Array(compressedData, 2), //skip deflate header\n uncompressedData);\n } else {\n uncompressedData = new Uint8Array(compressedData);\n }\n\n arrayOut.set(uncompressedData, TableDirectoryEntry.outOffset);\n offset = TableDirectoryEntry.outOffset + TableDirectoryEntry.origLength;\n\n var padding = 0;\n if (offset % 4 != 0) {\n padding = 4 - offset % 4;\n }\n arrayOut.set(new Uint8Array(padding).buffer, TableDirectoryEntry.outOffset + TableDirectoryEntry.origLength);\n\n size = offset + padding;\n });\n\n return bufferOut.slice(0, size);\n }\n\n // End woff2otf.js\n\n return function (buffer) {\n return convert_streams(buffer, tinyInflate);\n };\n }", "function BuildHuffmanTable(root_table,root_table_off,\n root_bits,\n code_lengths,code_lengths_off,\n code_lengths_size,\n count,count_off) {\n var code=new HuffmanCode(); /* current table entry */\n var table=new Array(new HuffmanCode());//* /* next available space in table */\n var table_off=0;\n var len; /* current code length */\n var symbol; /* symbol index in original or sorted table */\n var key; /* reversed prefix code */\n var step; /* step size to replicate values in current table */\n var low; /* low bits for current root entry */\n var mask; /* mask for low bits */\n var table_bits; /* key length of current table */\n var table_size; /* size of current table */\n var total_size; /* sum of root table size and 2nd level table sizes */\n /* symbols sorted by code length */\n var sorted=new mallocArr(code_lengths_size,0);\n /* offsets in sorted table for each length */\n var offset=new mallocArr(kHuffmanMaxLength + 1,0);\n var max_length = 1;\n\n /* generate offsets into sorted symbol table by code length */\n {\n var sum = 0;\n for (len = 1; len <= kHuffmanMaxLength; len++) {\n offset[len] = sum;\n if (count[len]) {\n sum = (sum + count[len]);\n max_length = len;\n }\n }\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (symbol = 0; symbol < code_lengths_size; symbol++) {\n if (code_lengths[symbol] != 0) {\n sorted[offset[code_lengths[symbol]]++] = symbol;\n }\n }\n\n table = root_table;\n table_off = root_table_off;\n table_bits = root_bits;\n table_size = 1 << table_bits;\n total_size = table_size;\n\n /* special case code with only one value */\n if (offset[kHuffmanMaxLength] == 1) {\n code.bits = 0;\n code.value = (sorted[0]);\n for (key = 0; key < total_size; ++key) {\n table[table_off+key] = code;\n }\n return total_size;\n }\n\n /* fill in root table */\n /* let's reduce the table size to a smaller size if possible, and */\n /* create the repetitions by memcpy if possible in the coming loop */\n if (table_bits > max_length) {\n table_bits = max_length;\n table_size = 1 << table_bits;\n }\n key = 0;\n symbol = 0;\n code.bits = 1;\n step = 2;\n do {\n for (; count[code.bits] != 0; --count[code.bits]) {\n code.value = (sorted[symbol++]);\n ReplicateValue(table,table_off+key, step, table_size, code);\n key = GetNextKey(key, code.bits);\n }\n step <<= 1;\n } while (++code.bits <= table_bits);\n\n /* if root_bits != table_bits we only created one fraction of the */\n /* table, and we need to replicate it now. */\n while (total_size != table_size) {\n //memcpy(&table[table_size], &table[0], table_size * sizeof(table[0]));\n\tfor(var i=0;i<table_size;++i) {\n\t\ttable[table_off+table_size+i].bits=table[table_off+0+i].bits;\n\t\ttable[table_off+table_size+i].value=table[table_off+0+i].value;\n\t}\n table_size <<= 1;\n }\n\n /* fill in 2nd level tables and add pointers to root table */\n mask = total_size - 1;\n low = -1;\n for (len = root_bits + 1, step = 2; len <= max_length; ++len, step <<= 1) {\n for (; count[len] != 0; --count[len]) {\n if ((key & mask) != low) {\n table_off += table_size;\n table_bits = NextTableBitSize(count, len, root_bits);\n table_size = 1 << table_bits;\n total_size += table_size;\n low = key & mask;\n root_table[root_table_off+low].bits = (table_bits + root_bits);\n root_table[root_table_off+low].value =\n ((table_off - root_table_off) - low);\n }\n code.bits = (len - root_bits);\n code.value = (sorted[symbol++]);\n ReplicateValue(table,table_off+(key >> root_bits), step, table_size, code);\n key = GetNextKey(key, len);\n }\n }\n\n return total_size;\n}", "function computeMappingTables() {\n\t\tvar table,\n\t\t\tsizes = [],\n\t\t\toffset = 0;\n\n\t\ttables = {};\n\n\t\tsizes[0] = mappingTables.computeSuperBlockSizes(header.flbw, header.flbh);\n\t\tsizes[1] = mappingTables.computeSuperBlockSizes(header.fcbw, header.fcbh);\n\t\tsizes[2] = sizes[1];\n\t\ttables.superBlockSizes = sizes[0].concat(sizes[1]).concat(sizes[2]);\n\n\t\ttable = mappingTables.computeBlockToSuperBlockTable(header.flbw, header.flbh, sizes[0], offset);\n\n\t\toffset += sizes[0].length;\n\t\ttable.push.apply(table,\n\t\t\t\t\t\tmappingTables.computeBlockToSuperBlockTable(header.fcbw, header.fcbh, sizes[1], offset));\n\n\t\toffset += sizes[1].length;\n\t\ttable.push.apply(table,\n\t\t\t\t\t\tmappingTables.computeBlockToSuperBlockTable(header.fcbw, header.fcbh, sizes[2], offset));\n\n\t\ttables.biToSbi = table;\n\n\t\toffset = 0;\n\t\ttable = mappingTables.computeRasterToCodedOrderMappingTable(\n\t\t\theader.flbw,\n\t\t\theader.flbh,\n\t\t\ttables.biToSbi,\n\t\t\ttables.superBlockSizes,\n\t\t\toffset\n\t\t);\n\n\t\toffset += header.nlbs;\n\t\ttable.push.apply(table, mappingTables.computeRasterToCodedOrderMappingTable(\n\t\t\theader.fcbw,\n\t\t\theader.fcbh,\n\t\t\ttables.biToSbi,\n\t\t\ttables.superBlockSizes,\n\t\t\toffset\n\t\t));\n\n\t\toffset += header.ncbs;\n\t\ttable.push.apply(table, mappingTables.computeRasterToCodedOrderMappingTable(\n\t\t\theader.fcbw,\n\t\t\theader.fcbh,\n\t\t\ttables.biToSbi,\n\t\t\ttables.superBlockSizes,\n\t\t\toffset\n\t\t));\n\n\t\ttables.rasterToCodedOrder = table;\n\t\ttables.codedToRasterOrder = util.arrayFlip(table);\n\n\t\ttable = mappingTables.computeMacroBlockMappingTables(\n\t\t\theader.fmbw,\n\t\t\theader.fmbh,\n\t\t\theader.pf,\n\t\t\ttables.rasterToCodedOrder\n\t\t);\n\n\t\ttables.biToMbi = table[0];\n\t\ttables.mbiToBi = table[1];\n\t}", "function StateTable1() {\n var entryData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var lookupType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16;\n\n var ClassLookupTable = new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Struct({\n version: function version() {\n return 8;\n },\n // simulate LookupTable\n firstGlyph: restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16,\n values: new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Array(restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint8, restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16)\n });\n\n var entry = Object.assign({\n newStateOffset: restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16,\n // convert offset to stateArray index\n newState: function newState(t) {\n return (t.newStateOffset - (t.parent.stateArray.base - t.parent._startOffset)) / t.parent.nClasses;\n },\n flags: restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16\n }, entryData);\n\n var Entry = new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Struct(entry);\n var StateArray = new UnboundedArray(new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Array(restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint8, function (t) {\n return t.nClasses;\n }));\n\n var StateHeader1 = new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Struct({\n nClasses: restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16,\n classTable: new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Pointer(restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16, ClassLookupTable),\n stateArray: new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Pointer(restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16, StateArray),\n entryTable: new restructure__WEBPACK_IMPORTED_MODULE_0___default.a.Pointer(restructure__WEBPACK_IMPORTED_MODULE_0___default.a.uint16, new UnboundedArray(Entry))\n });\n\n return StateHeader1;\n}", "function StateTable1() {\n var entryData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var lookupType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16;\n\n var ClassLookupTable = new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Struct({\n version: function version() {\n return 8;\n },\n // simulate LookupTable\n firstGlyph: __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16,\n values: new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Array(__WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint8, __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16)\n });\n\n var entry = Object.assign({\n newStateOffset: __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16,\n // convert offset to stateArray index\n newState: function newState(t) {\n return (t.newStateOffset - (t.parent.stateArray.base - t.parent._startOffset)) / t.parent.nClasses;\n },\n flags: __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16\n }, entryData);\n\n var Entry = new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Struct(entry);\n var StateArray = new UnboundedArray(new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Array(__WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint8, function (t) {\n return t.nClasses;\n }));\n\n var StateHeader1 = new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Struct({\n nClasses: __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16,\n classTable: new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Pointer(__WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16, ClassLookupTable),\n stateArray: new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Pointer(__WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16, StateArray),\n entryTable: new __WEBPACK_IMPORTED_MODULE_0_restructure___default.a.Pointer(__WEBPACK_IMPORTED_MODULE_0_restructure___default.a.uint16, new UnboundedArray(Entry))\n });\n\n return StateHeader1;\n}", "function TableCompiler() {\n\tvar b64vlq = B64VLQ();\n\tvar fs = require(\"fs\");\n\n\tfunction compile(src) {\n\t\tvar table = {},\n\t\t\t\tdata = null,\n\t\t\t\tjson = null;\n\t\t\t\tsources = {},\n\t\t\t\ttmp = null;\n\n\t\tdata = fs.readFileSync(src, \"utf8\");\n\t\tjson = JSON.parse(data);\n\n\t\tvar i = 0;\n\t\tjson.sourcesContent.forEach(function (s) {\n\t\t\tsources[i] = {source: s, lines: []};\n\t\t\tsources[i].lines = sources[i].source.split(/\\n/);\n\t\t\ti++;\n\t\t});\n\t\t\n\t\ttmp = json.mappings.split(\";\");\n\t\tvar line = 1;\n\t\tvar base = [1, 0, 0, 0, 0];\n\t\tvar prev = 0;\n\t\ttmp.forEach(function (m) {\n\t\t\tvar positions = m.split(\",\");\n\t\t\tpositions.forEach(function (p) {\n\t\t\t\tvar dcmp = b64vlq.decompress(p);\n\t\t\t\tfor(var i = 0; i < dcmp.length; ++i) {\n\t\t\t\t\tbase[i] += dcmp[i];\n\t\t\t\t}\n\t\t\t\ttable[(line).toString() + \":\" + (base[0] - prev)] = \"\" + json.sources[base[1]] + \":\" + base[2];\n\t\t\t});\n\t\t\tprev = base[0] - 1;\n\t\t\tline++;\n\t\t});\n\t\t//console.log(table);\n\t\treturn table;\n\t}\n\n\n\treturn {\n\t\tcompile: compile\n\t}\n}", "function createMarkerCodeTable() {\n // Code assignments\n codes = new Map([\n // SOF markers, non-differential, Huffman-coding \n [0xC0, \"SOF0\"], // Baseline DCT\n [0xC1, \"SOF1\"], // Extended sequential DCT\n [0xC2, \"SOF2\"], // Progressive DCT\n [0xC3, \"SOF3\"], // Lossless (sequential)\n // SOF markers, differential, Huffman-coding\n [0xC5, \"SOF5\"], // Differential sequenctial DCT\n [0xC6, \"SOF6\"], // Differential progressive DCT\n [0xC7, \"SOF7\"], // Differential lossless (sequential)\n // SOF markers, non-differential, arithmetic coding\n [0xC8, \"JPG\"], // (Reserved)\n [0xC9, \"SOF9\"], // Extended sequential DCT\n [0xCA, \"SOF10\"], // Progressive DCT\n [0xCB, \"SOF11\"], // Lossless (sequential)\n // SOF markers, differential, arithmetic coding\n [0xCD, \"SOF13\"], // Differential sequential DCT\n [0xCE, \"SOF14\"], // Differential progressive DCT\n [0xCF, \"SOF15\"], // Differential lossless (sequential)\n // Huffman table spec\n [0xC4, \"DHT\"], // Define Huffman table(s)\n // Arithmetic coding conditioning spec\n [0xCC, \"DAC\"], // Define arithmetic coding conditioning(s)\n // Other markers\n [0xD8, \"SOI*\"], // Start of image\n [0xD9, \"EOI*\"], // End of image\n [0xDA, \"SOS\"], // Start of sequence\n [0xDB, \"DQT\"], // Define quantization table\n [0xDC, \"DNL\"], // Define number of lines\n [0xDD, \"DRI\"], // Define restart interval\n [0xDE, \"DHP\"], // Define hierarchical progression\n [0xDF, \"EXP\"], // Expand reference component(s)\n [0xFE, \"COM\"], // Comment\n // Reserved markers\n [0x01, \"TEM*\"], // For temp private in arithmetic coding\n ]);\n // Restart interval termination\n for (let i = 0; i < 8; i++) {\n codes.set(0xD0 + i, \"RST\" + i); // Restart with modulo 8 count 'm'\n }\n // Reserved for application segmentation\n for (let i = 0; i <= 0xF; i++) {\n codes.set(0xE0 + i, \"APP\" + i.toString(16).toUpperCase());\n }\n // Reserved for JPEG extensions\n for (let i = 0; i <= 0xD; i++) {\n codes.set(0xF0 + i, \"JPG\" + i.toString(16).toUpperCase());\n }\n // Reserved\n for (let i = 2; i <= 0xBF; i++) {\n codes.set(0x00 + i, \"RES\");\n }\n return codes;\n}", "function codeGeneration() {\n //Reset machine code array and pointers\n machineCode = [];\n machineCodeStrings = [];\n ncount = 0;\n heapcount = 255;\n jumpcount = 0;\n //Empty code section of old codes\n document.getElementById('hex-code').innerHTML = \"\";\n //Empty static and jump tables\n staticTable = [];\n jumpTable = [];\n //Assignment (From Var): AD T1 XX 8D T0 XX\n //Add: EE\n //256 bytes of 00 in the array - all blank\n for (var b = 0; b < 257; b++) {\n machineCode.push(\"00\");\n }\n //Traverse AST, write 6502 codes into array\n writeCodes(AST.root);\n //Codes are now done and are stored in machineCode.\n machineCode[ncount] = \"00\"; //finish code with an 00\n //Static space starts here, increment counter\n ncount++;\n //Can now backpatch.\n for (var i = 0; i < staticTable.length; i++) {\n //For each variable, set up an address at the next available space.\n staticTable[i].setAddress(ncount.toString(16));\n //Add starting 0 if needed.\n if (ncount.toString(16).length === 1) {\n staticTable[i].setAddress(\"0\" + ncount.toString(16));\n }\n //Next space.\n ncount++;\n }\n //For all the hex code... backpatch it\n for (var y = 0; y < 257; y++) {\n if (y !== 256) {\n //Memory location is two bytes\n var memLoc = machineCode[y] + machineCode[y + 1];\n //Traverse static table\n for (var j = 0; j < staticTable.length; j++) {\n //If a recognized temporary placeholder like T0XX is found...\n if (memLoc === staticTable[j].temp) {\n //Set it to the real static address stored in the table\n machineCode[y] = staticTable[j].address;\n machineCode[y + 1] = \"00\"; //this address space is never used\n }\n }\n //Traverse jump table\n for (var k = 0; k < jumpTable.length; k++) {\n //If a recognized jump placeholder like J0 is found...\n if (machineCode[y] === jumpTable[k].temp) {\n //Set its actual distance\n jumpTable[k].setDistance(jumpTable[k].distance);\n if (jumpTable[k].distance.length === 1) {\n jumpTable[k].setDistance(\"0\" + jumpTable[k].distance);\n }\n machineCode[y] = jumpTable[k].distance;\n }\n }\n }\n }\n //One line of 8 bytes\n var codeStr = \"\";\n //Keeps track of bytes\n var byteCounter = 0;\n //For each byte...\n for (var b = 0; b < 257; b++) {\n //Put in a line and increment counter\n codeStr += \" \" + machineCode[b];\n byteCounter++;\n //When multiple of 8 reached...\n if (byteCounter % 8 === 0) {\n //Create a line with 8 bytes of code\n machineCodeStrings.push(codeStr.toUpperCase());\n //Reset for the next line\n codeStr = \"\";\n }\n }\n //For each line, write it into the code section with a line break\n for (var e = 0; e < machineCodeStrings.length; e++) {\n document.getElementById('hex-code').innerHTML += machineCodeStrings[e] + \"<br />\";\n }\n} //code gen end", "buildCodes() {\n let nextCode = new Int32Array(this.maxLength);\n let code = 0;\n this.codes = new Int16Array(this.freqs.length);\n for (let bits = 0; bits < this.maxLength; bits++) {\n nextCode[bits] = code;\n code += this.bitLengthCounts[bits] << (15 - bits);\n }\n for (let i = 0; i < this.numCodes; i++) {\n let bits = this.length[i];\n if (bits > 0) {\n this.codes[i] = DeflaterHuffman.bitReverse(nextCode[bits - 1]);\n nextCode[bits - 1] += 1 << (16 - bits);\n }\n }\n }", "function computeFloat16OffsetTable() {\n const offsetTable = new Uint32Array(64);\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n return offsetTable;\n}", "function h$initInfoTables ( depth // depth in the base chain\n , funcs // array with all entry functions\n , objects // array with all the global heap objects\n , lbls // array with non-haskell labels\n , infoMeta // packed info\n , infoStatic\n ) {\n ;\n var n, i, j, o, pos = 0, info;\n function code(c) {\n if(c < 34) return c - 32;\n if(c < 92) return c - 33;\n return c - 34;\n }\n function next() {\n var c = info.charCodeAt(pos);\n if(c < 124) {\n ;\n pos++;\n return code(c);\n }\n if(c === 124) {\n pos+=3;\n var r = 90 + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n if(c === 125) {\n pos+=4;\n var r = 8190 + 8100 * code(info.charCodeAt(pos-3))\n + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n throw (\"h$initInfoTables: invalid code in info table: \" + c + \" at \" + pos)\n }\n function nextCh() {\n return next(); // fixme map readable chars\n }\n function nextInt() {\n var n = next();\n var r;\n if(n === 0) {\n var n1 = next();\n var n2 = next();\n r = n1 << 16 | n2;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextSignificand() {\n var n = next();\n var n1, n2, n3, n4, n5;\n var r;\n if(n < 2) {\n n1 = next();\n n2 = next();\n n3 = next();\n n4 = next();\n n5 = n1 * 281474976710656 + n2 * 4294967296 + n3 * 65536 + n4;\n r = n === 0 ? -n5 : n5;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextEntry(o) { return nextIndexed(\"nextEntry\", h$entriesStack, o); }\n function nextObj(o) { return nextIndexed(\"nextObj\", h$staticsStack, o); }\n function nextLabel(o) { return nextIndexed(\"nextLabel\", h$labelsStack, o); }\n function nextIndexed(msg, stack, o) {\n var n = (o === undefined) ? next() : o;\n var i = depth;\n while(n > stack[i].length) {\n n -= stack[i].length;\n i--;\n if(i < 0) throw (msg + \": cannot find item \" + n + \", stack length: \" + stack.length + \" depth: \" + depth);\n }\n return stack[i][n];\n }\n function nextArg() {\n var o = next();\n var n, n1, n2, d0, d1, d2, d3;\n var isString = false;\n switch(o) {\n case 0:\n ;\n return false;\n case 1:\n ;\n return true;\n case 2:\n ;\n return 0;\n case 3:\n ;\n return 1;\n case 4:\n ;\n return nextInt();\n case 5:\n ;\n return null;\n case 6:\n ;\n n = next();\n switch(n) {\n case 0:\n return -0.0;\n case 1:\n return 0.0;\n case 2:\n return 1/0;\n case 3:\n return -1/0;\n case 4:\n return 0/0;\n case 5:\n n1 = nextInt();\n var ns = nextSignificand();\n if(n1 > 600) {\n return ns * Math.pow(2,n1-600) * Math.pow(2,600);\n } else if(n1 < -600) {\n return ns * Math.pow(2,n1+600) * Math.pow(2,-600);\n } else {\n return ns * Math.pow(2, n1);\n }\n default:\n n1 = n - 36;\n return nextSignificand() * Math.pow(2, n1);\n }\n case 7:\n ;\n isString = true;\n // no break, strings are null temrinated UTF8 encoded binary with\n case 8:\n ;\n n = next();\n var ba = h$newByteArray(isString ? (n+1) : n);\n var b8 = ba.u8;\n if(isString) b8[n] = 0;\n var p = 0;\n while(n > 0) {\n switch(n) {\n case 1:\n d0 = next();\n d1 = next();\n b8[p] = ((d0 << 2) | (d1 >> 4));\n break;\n case 2:\n d0 = next();\n d1 = next();\n d2 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p] = ((d1 << 4) | (d2 >> 2));\n break;\n default:\n d0 = next();\n d1 = next();\n d2 = next();\n d3 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p++] = ((d1 << 4) | (d2 >> 2));\n b8[p++] = ((d2 << 6) | d3);\n break;\n }\n n -= 3;\n }\n return ba;\n case 9:\n var isFun = next() === 1;\n var lbl = nextLabel();\n return h$initPtrLbl(isFun, lbl);\n case 10:\n var c = { f: nextEntry(), d1: null, d2: null, m: 0 };\n var n = next();\n var args = [];\n while(n--) {\n args.push(nextArg());\n }\n return h$init_closure(c, args);\n default:\n ;\n return nextObj(o-11);\n }\n }\n info = infoMeta; pos = 0;\n for(i=0;i<funcs.length;i++) {\n o = funcs[i];\n var ot;\n var oa = 0;\n var oregs = 256; // one register no skip\n switch(next()) {\n case 0: // thunk\n ot = 0;\n break;\n case 1: // fun\n ot = 1;\n var arity = next();\n var skipRegs = next()-1;\n if(skipRegs === -1) throw \"h$initInfoTables: unknown register info for function\";\n var skip = skipRegs & 1;\n var regs = skipRegs >>> 1;\n oregs = (regs << 8) | skip;\n oa = arity + ((regs-1+skip) << 8);\n break;\n case 2: // con\n ot = 2;\n oa = next();\n break;\n case 3: // stack frame\n ot = -1;\n oa = 0;\n oregs = next() - 1;\n if(oregs !== -1) oregs = ((oregs >>> 1) << 8) | (oregs & 1);\n break;\n default: throw (\"h$initInfoTables: invalid closure type\")\n }\n var size = next() - 1;\n var nsrts = next();\n var srt = null;\n if(nsrts > 0) {\n srt = [];\n for(var j=0;j<nsrts;j++) {\n srt.push(nextObj());\n }\n }\n\n // h$log(\"result: \" + ot + \" \" + oa + \" \" + oregs + \" [\" + srt + \"] \" + size);\n // h$log(\"orig: \" + o.t + \" \" + o.a + \" \" + o.r + \" [\" + o.s + \"] \" + o.size);\n // if(ot !== o.t || oa !== o.a || oregs !== o.r || size !== o.size) throw \"inconsistent\";\n\n o.t = ot;\n o.i = [];\n o.n = \"\";\n o.a = oa;\n o.r = oregs;\n o.s = srt;\n o.m = 0;\n o.size = size;\n }\n info = infoStatic;\n pos = 0;\n for(i=0;i<objects.length;i++) {\n ;\n o = objects[i];\n // traceMetaObjBefore(o);\n var nx = next();\n ;\n switch(nx) {\n case 0: // no init, could be a primitive value (still in the list since others might reference it)\n // h$log(\"zero init\");\n break;\n case 1: // staticfun\n o.f = nextEntry();\n ;\n n = next();\n ;\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n\n break;\n case 2: // staticThunk\n ;\n o.f = nextEntry();\n n = next();\n ;\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n h$addCAF(o);\n break;\n case 3: // staticPrim false, no init\n ;\n break;\n case 4: // staticPrim true, no init\n ;\n break;\n case 5:\n ;\n break;\n case 6: // staticString\n ;\n break;\n case 7: // staticBin\n ;\n n = next();\n var b = h$newByteArray(n);\n for(j=0;j>n;j++) {\n b.u8[j] = next();\n }\n break;\n case 8: // staticEmptyList\n ;\n o.f = h$ghczmprimZCGHCziTypesziZMZN_con_e;\n break;\n case 9: // staticList\n ;\n n = next();\n var hasTail = next();\n var c = (hasTail === 1) ? nextObj() : h$ghczmprimZCGHCziTypesziZMZN;\n ;\n while(n--) {\n c = (h$c2(h$ghczmprimZCGHCziTypesziZC_con_e, (nextArg()), (c)));\n }\n o.f = c.f;\n o.d1 = c.d1;\n o.d2 = c.d2;\n break;\n case 10: // staticData n args\n ;\n n = next();\n ;\n o.f = nextEntry();\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n break;\n case 11: // staticData 0 args\n ;\n o.f = nextEntry();\n break;\n case 12: // staticData 1 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n break;\n case 13: // staticData 2 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = nextArg();\n break;\n case 14: // staticData 3 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg()};\n break;\n case 15: // staticData 4 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg() };\n break;\n case 16: // staticData 5 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg() };\n break;\n case 17: // staticData 6 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg(), d5: nextArg() };\n break;\n default:\n throw (\"invalid static data initializer: \" + nx);\n }\n }\n h$staticDelayed = null;\n}", "function h$initInfoTables ( depth // depth in the base chain\n , funcs // array with all entry functions\n , objects // array with all the global heap objects\n , lbls // array with non-haskell labels\n , infoMeta // packed info\n , infoStatic\n ) {\n ;\n var n, i, j, o, pos = 0, info;\n function code(c) {\n if(c < 34) return c - 32;\n if(c < 92) return c - 33;\n return c - 34;\n }\n function next() {\n var c = info.charCodeAt(pos);\n if(c < 124) {\n ;\n pos++;\n return code(c);\n }\n if(c === 124) {\n pos+=3;\n var r = 90 + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n if(c === 125) {\n pos+=4;\n var r = 8190 + 8100 * code(info.charCodeAt(pos-3))\n + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n throw (\"h$initInfoTables: invalid code in info table: \" + c + \" at \" + pos)\n }\n function nextCh() {\n return next(); // fixme map readable chars\n }\n function nextInt() {\n var n = next();\n var r;\n if(n === 0) {\n var n1 = next();\n var n2 = next();\n r = n1 << 16 | n2;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextSignificand() {\n var n = next();\n var n1, n2, n3, n4, n5;\n var r;\n if(n < 2) {\n n1 = next();\n n2 = next();\n n3 = next();\n n4 = next();\n n5 = n1 * 281474976710656 + n2 * 4294967296 + n3 * 65536 + n4;\n r = n === 0 ? -n5 : n5;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextEntry(o) { return nextIndexed(\"nextEntry\", h$entriesStack, o); }\n function nextObj(o) { return nextIndexed(\"nextObj\", h$staticsStack, o); }\n function nextLabel(o) { return nextIndexed(\"nextLabel\", h$labelsStack, o); }\n function nextIndexed(msg, stack, o) {\n var n = (o === undefined) ? next() : o;\n var i = depth;\n while(n > stack[i].length) {\n n -= stack[i].length;\n i--;\n if(i < 0) throw (msg + \": cannot find item \" + n + \", stack length: \" + stack.length + \" depth: \" + depth);\n }\n return stack[i][n];\n }\n function nextArg() {\n var o = next();\n var n, n1, n2;\n switch(o) {\n case 0:\n ;\n return false;\n case 1:\n ;\n return true;\n case 2:\n ;\n return 0;\n case 3:\n ;\n return 1;\n case 4:\n ;\n return nextInt();\n case 5:\n ;\n return null;\n case 6:\n ;\n n = next();\n switch(n) {\n case 0:\n return -0.0;\n case 1:\n return 0.0;\n case 2:\n return 1/0;\n case 3:\n return -1/0;\n case 4:\n return 0/0;\n case 5:\n n1 = nextInt();\n return nextSignificand() * Math.pow(2, n1)\n default:\n n1 = n - 36;\n return nextSignificand() * Math.pow(2, n1);\n }\n case 7:\n ;\n // no break, strings are UTF8 encoded binary\n case 8:\n ;\n n = next();\n var ba = h$newByteArray(n);\n var b8 = ba.u8;\n var p = 0;\n while(n > 0) {\n switch(n) {\n case 1:\n d0 = next();\n d1 = next();\n b8[p] = ((d0 << 2) | (d1 >> 4));\n break;\n case 2:\n d0 = next();\n d1 = next();\n d2 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p] = ((d1 << 4) | (d2 >> 2));\n break;\n default:\n d0 = next();\n d1 = next();\n d2 = next();\n d3 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p++] = ((d1 << 4) | (d2 >> 2));\n b8[p++] = ((d2 << 6) | d3);\n break;\n }\n n -= 3;\n }\n return ba;\n case 9:\n var isFun = next() === 1;\n var lbl = nextLabel();\n return h$initPtrLbl(isFun, lbl);\n case 10:\n var c = { f: nextEntry(), d1: null, d2: null, m: 0 };\n var n = next();\n var args = [];\n while(n--) {\n args.push(nextArg());\n }\n return h$init_closure(c, args);\n default:\n ;\n return nextObj(o-11);\n }\n }\n info = infoMeta; pos = 0;\n for(i=0;i<funcs.length;i++) {\n o = funcs[i];\n var ot;\n var oa = 0;\n var oregs = 256; // one register no skip\n switch(next()) {\n case 0: // thunk\n ot = 0;\n break;\n case 1: // fun\n ot = 1\n var arity = next();\n var skipRegs = next()-1;\n if(skipRegs === -1) throw \"h$initInfoTables: unknown register info for function\";\n var skip = skipRegs & 1;\n var regs = skipRegs >>> 1;\n oregs = (regs << 8) | skip;\n oa = arity + ((regs-1+skip) << 8);\n break;\n case 2: // con\n ot = 2;\n oa = next();\n break;\n case 3: // stack frame\n ot = -1;\n oa = 0;\n oregs = next() - 1;\n if(oregs !== -1) oregs = ((oregs >>> 1) << 8) | (oregs & 1);\n break;\n default: throw (\"h$initInfoTables: invalid closure type\")\n }\n var size = next() - 1;\n var nsrts = next();\n var srt = null;\n if(nsrts > 0) {\n srt = [];\n for(var j=0;j<nsrts;j++) {\n srt.push(nextObj());\n }\n }\n\n // h$log(\"result: \" + ot + \" \" + oa + \" \" + oregs + \" [\" + srt + \"] \" + size);\n // h$log(\"orig: \" + o.t + \" \" + o.a + \" \" + o.r + \" [\" + o.s + \"] \" + o.size);\n // if(ot !== o.t || oa !== o.a || oregs !== o.r || size !== o.size) throw \"inconsistent\";\n\n o.t = ot;\n o.i = [];\n o.n = \"\";\n o.a = oa;\n o.r = oregs;\n o.s = srt;\n o.m = 0;\n o.size = size;\n }\n info = infoStatic;\n pos = 0;\n for(i=0;i<objects.length;i++) {\n ;\n o = objects[i];\n // traceMetaObjBefore(o);\n var nx = next();\n ;\n switch(nx) {\n case 0: // no init, could be a primitive value (still in the list since others might reference it)\n // h$log(\"zero init\");\n break;\n case 1: // staticfun\n o.f = nextEntry();\n ;\n break;\n case 2: // staticThunk\n ;\n o.f = nextEntry();\n h$CAFs.push(o);\n h$CAFsReset.push(o.f);\n break;\n case 3: // staticPrim false, no init\n ;\n break;\n case 4: // staticPrim true, no init\n ;\n break;\n case 5:\n ;\n break;\n case 6: // staticString\n ;\n break;\n case 7: // staticBin\n ;\n n = next();\n var b = h$newByteArray(n);\n for(j=0;j>n;j++) {\n b.u8[j] = next();\n }\n break;\n case 8: // staticEmptyList\n ;\n o.f = h$ghczmprimZCGHCziTypesziZMZN_con_e;\n break;\n case 9: // staticList\n ;\n n = next();\n var hasTail = next();\n var c = (hasTail === 1) ? nextObj() : h$ghczmprimZCGHCziTypesziZMZN;\n ;\n while(n--) {\n c = (h$c2(h$ghczmprimZCGHCziTypesziZC_con_e, (nextArg()), (c)));\n }\n o.f = c.f;\n o.d1 = c.d1;\n o.d2 = c.d2;\n break;\n case 10: // staticData n args\n ;\n n = next();\n ;\n o.f = nextEntry();\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n break;\n case 11: // staticData 0 args\n ;\n o.f = nextEntry();\n break;\n case 12: // staticData 1 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n break;\n case 13: // staticData 2 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = nextArg();\n break;\n case 14: // staticData 3 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg()};\n break;\n case 15: // staticData 4 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg() };\n break;\n case 16: // staticData 5 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg() };\n break;\n case 17: // staticData 6 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg(), d5: nextArg() };\n break;\n default:\n throw (\"invalid static data initializer: \" + nx);\n }\n }\n h$staticDelayed = null;\n}", "function h$initInfoTables ( depth // depth in the base chain\n , funcs // array with all entry functions\n , objects // array with all the global heap objects\n , lbls // array with non-haskell labels\n , infoMeta // packed info\n , infoStatic\n ) {\n ;\n var n, i, j, o, pos = 0, info;\n function code(c) {\n if(c < 34) return c - 32;\n if(c < 92) return c - 33;\n return c - 34;\n }\n function next() {\n var c = info.charCodeAt(pos);\n if(c < 124) {\n ;\n pos++;\n return code(c);\n }\n if(c === 124) {\n pos+=3;\n var r = 90 + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n if(c === 125) {\n pos+=4;\n var r = 8190 + 8100 * code(info.charCodeAt(pos-3))\n + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n throw (\"h$initInfoTables: invalid code in info table: \" + c + \" at \" + pos)\n }\n function nextCh() {\n return next(); // fixme map readable chars\n }\n function nextInt() {\n var n = next();\n var r;\n if(n === 0) {\n var n1 = next();\n var n2 = next();\n r = n1 << 16 | n2;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextSignificand() {\n var n = next();\n var n1, n2, n3, n4, n5;\n var r;\n if(n < 2) {\n n1 = next();\n n2 = next();\n n3 = next();\n n4 = next();\n n5 = n1 * 281474976710656 + n2 * 4294967296 + n3 * 65536 + n4;\n r = n === 0 ? -n5 : n5;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextEntry(o) { return nextIndexed(\"nextEntry\", h$entriesStack, o); }\n function nextObj(o) { return nextIndexed(\"nextObj\", h$staticsStack, o); }\n function nextLabel(o) { return nextIndexed(\"nextLabel\", h$labelsStack, o); }\n function nextIndexed(msg, stack, o) {\n var n = (o === undefined) ? next() : o;\n var i = depth;\n while(n > stack[i].length) {\n n -= stack[i].length;\n i--;\n if(i < 0) throw (msg + \": cannot find item \" + n + \", stack length: \" + stack.length + \" depth: \" + depth);\n }\n return stack[i][n];\n }\n function nextArg() {\n var o = next();\n var n, n1, n2;\n switch(o) {\n case 0:\n ;\n return false;\n case 1:\n ;\n return true;\n case 2:\n ;\n return 0;\n case 3:\n ;\n return 1;\n case 4:\n ;\n return nextInt();\n case 5:\n ;\n return null;\n case 6:\n ;\n n = next();\n switch(n) {\n case 0:\n return -0.0;\n case 1:\n return 0.0;\n case 2:\n return 1/0;\n case 3:\n return -1/0;\n case 4:\n return 0/0;\n case 5:\n n1 = nextInt();\n return nextSignificand() * Math.pow(2, n1)\n default:\n n1 = n - 36;\n return nextSignificand() * Math.pow(2, n1);\n }\n case 7:\n ;\n throw \"string arg\";\n return \"\"; // fixme haskell string\n case 8:\n ;\n n = next();\n var ba = h$newByteArray(n);\n var b8 = ba.u8;\n var p = 0;\n while(n > 0) {\n switch(n) {\n case 1:\n d0 = next();\n d1 = next();\n b8[p] = ((d0 << 2) | (d1 >> 4));\n break;\n case 2:\n d0 = next();\n d1 = next();\n d2 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p] = ((d1 << 4) | (d2 >> 2));\n break;\n default:\n d0 = next();\n d1 = next();\n d2 = next();\n d3 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p++] = ((d1 << 4) | (d2 >> 2));\n b8[p++] = ((d2 << 6) | d3);\n break;\n }\n n -= 3;\n }\n return ba;\n case 9:\n var isFun = next() === 1;\n var lbl = nextLabel();\n return h$initPtrLbl(isFun, lbl);\n case 10:\n var c = { f: nextEntry(), d1: null, d2: null, m: 0 };\n var n = next();\n var args = [];\n while(n--) {\n args.push(nextArg());\n }\n return h$init_closure(c, args);\n default:\n ;\n return nextObj(o-11);\n }\n }\n info = infoMeta; pos = 0;\n for(i=0;i<funcs.length;i++) {\n o = funcs[i];\n var ot;\n var oa = 0;\n var oregs = 256; // one register no skip\n switch(next()) {\n case 0: // thunk\n ot = 0;\n break;\n case 1: // fun\n ot = 1\n var arity = next();\n var skipRegs = next()-1;\n if(skipRegs === -1) throw \"h$initInfoTables: unknown register info for function\";\n var skip = skipRegs & 1;\n var regs = skipRegs >>> 1;\n oregs = (regs << 8) | skip;\n oa = arity + ((regs-1+skip) << 8);\n break;\n case 2: // con\n ot = 2;\n oa = next();\n break;\n case 3: // stack frame\n ot = -1;\n oa = 0;\n oregs = next() - 1;\n if(oregs !== -1) oregs = ((oregs >>> 1) << 8) | (oregs & 1);\n break;\n default: throw (\"h$initInfoTables: invalid closure type\")\n }\n var size = next() - 1;\n var nsrts = next();\n var srt = null;\n if(nsrts > 0) {\n srt = [];\n for(var j=0;j<nsrts;j++) {\n srt.push(nextObj());\n }\n }\n\n // h$log(\"result: \" + ot + \" \" + oa + \" \" + oregs + \" [\" + srt + \"] \" + size);\n // h$log(\"orig: \" + o.t + \" \" + o.a + \" \" + o.r + \" [\" + o.s + \"] \" + o.size);\n // if(ot !== o.t || oa !== o.a || oregs !== o.r || size !== o.size) throw \"inconsistent\";\n\n o.t = ot;\n o.i = [];\n o.n = \"\";\n o.a = oa;\n o.r = oregs;\n o.s = srt;\n o.m = 0;\n o.size = size;\n }\n info = infoStatic;\n pos = 0;\n for(i=0;i<objects.length;i++) {\n ;\n o = objects[i];\n // traceMetaObjBefore(o);\n var nx = next();\n ;\n switch(nx) {\n case 0: // no init, could be a primitive value (still in the list since others might reference it)\n // h$log(\"zero init\");\n break;\n case 1: // staticfun\n o.f = nextEntry();\n ;\n break;\n case 2: // staticThunk\n ;\n o.f = nextEntry();\n h$CAFs.push(o);\n h$CAFsReset.push(o.f);\n break;\n case 3: // staticPrim false, no init\n ;\n break;\n case 4: // staticPrim true, no init\n ;\n break;\n case 5:\n ;\n break;\n case 6: // staticString\n ;\n break;\n case 7: // staticBin\n ;\n n = next();\n var b = h$newByteArray(n);\n for(j=0;j>n;j++) {\n b.u8[j] = next();\n }\n break;\n case 8: // staticEmptyList\n ;\n o.f = h$ghczmprimZCGHCziTypesziZMZN.f;\n break;\n case 9: // staticList\n ;\n n = next();\n var hasTail = next();\n var c = (hasTail === 1) ? nextObj() : h$ghczmprimZCGHCziTypesziZMZN;\n ;\n while(n--) {\n c = h$c2(h$ghczmprimZCGHCziTypesziZC_con_e, nextArg(), c);\n }\n o.f = c.f;\n o.d1 = c.d1;\n o.d2 = c.d2;\n break;\n case 10: // staticData n args\n ;\n n = next();\n ;\n o.f = nextEntry();\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n break;\n case 11: // staticData 0 args\n ;\n o.f = nextEntry();\n break;\n case 12: // staticData 1 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n break;\n case 13: // staticData 2 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = nextArg();\n break;\n case 14: // staticData 3 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg()};\n break;\n case 15: // staticData 4 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg() };\n break;\n case 16: // staticData 5 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg() };\n break;\n case 17: // staticData 6 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg(), d5: nextArg() };\n break;\n default:\n throw (\"invalid static data initializer: \" + nx);\n }\n }\n h$staticDelayed = null;\n}", "function h$initInfoTables ( depth // depth in the base chain\n , funcs // array with all entry functions\n , objects // array with all the global heap objects\n , lbls // array with non-haskell labels\n , infoMeta // packed info\n , infoStatic\n ) {\n ;\n var n, i, j, o, pos = 0, info;\n function code(c) {\n if(c < 34) return c - 32;\n if(c < 92) return c - 33;\n return c - 34;\n }\n function next() {\n var c = info.charCodeAt(pos);\n if(c < 124) {\n ;\n pos++;\n return code(c);\n }\n if(c === 124) {\n pos+=3;\n var r = 90 + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n if(c === 125) {\n pos+=4;\n var r = 8190 + 8100 * code(info.charCodeAt(pos-3))\n + 90 * code(info.charCodeAt(pos-2))\n + code(info.charCodeAt(pos-1));\n ;\n return r;\n }\n throw (\"h$initInfoTables: invalid code in info table: \" + c + \" at \" + pos)\n }\n function nextCh() {\n return next(); // fixme map readable chars\n }\n function nextInt() {\n var n = next();\n var r;\n if(n === 0) {\n var n1 = next();\n var n2 = next();\n r = n1 << 16 | n2;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextSignificand() {\n var n = next();\n var n1, n2, n3, n4, n5;\n var r;\n if(n < 2) {\n n1 = next();\n n2 = next();\n n3 = next();\n n4 = next();\n n5 = n1 * 281474976710656 + n2 * 4294967296 + n3 * 65536 + n4;\n r = n === 0 ? -n5 : n5;\n } else {\n r = n - 12;\n }\n ;\n return r;\n }\n function nextEntry(o) { return nextIndexed(\"nextEntry\", h$entriesStack, o); }\n function nextObj(o) { return nextIndexed(\"nextObj\", h$staticsStack, o); }\n function nextLabel(o) { return nextIndexed(\"nextLabel\", h$labelsStack, o); }\n function nextIndexed(msg, stack, o) {\n var n = (o === undefined) ? next() : o;\n var i = depth;\n while(n > stack[i].length) {\n n -= stack[i].length;\n i--;\n if(i < 0) throw (msg + \": cannot find item \" + n + \", stack length: \" + stack.length + \" depth: \" + depth);\n }\n return stack[i][n];\n }\n function nextArg() {\n var o = next();\n var n, n1, n2, d0, d1, d2, d3;\n var isString = false;\n switch(o) {\n case 0:\n ;\n return false;\n case 1:\n ;\n return true;\n case 2:\n ;\n return 0;\n case 3:\n ;\n return 1;\n case 4:\n ;\n return nextInt();\n case 5:\n ;\n return null;\n case 6:\n ;\n n = next();\n switch(n) {\n case 0:\n return -0.0;\n case 1:\n return 0.0;\n case 2:\n return 1/0;\n case 3:\n return -1/0;\n case 4:\n return 0/0;\n case 5:\n n1 = nextInt();\n var ns = nextSignificand();\n if(n1 > 600) {\n return ns * Math.pow(2,n1-600) * Math.pow(2,600);\n } else if(n1 < -600) {\n return ns * Math.pow(2,n1+600) * Math.pow(2,-600);\n } else {\n return ns * Math.pow(2, n1);\n }\n default:\n n1 = n - 36;\n return nextSignificand() * Math.pow(2, n1);\n }\n case 7:\n ;\n isString = true;\n // no break, strings are null temrinated UTF8 encoded binary with\n case 8:\n ;\n n = next();\n var ba = h$newByteArray(isString ? (n+1) : n);\n var b8 = ba.u8;\n if(isString) b8[n] = 0;\n var p = 0;\n while(n > 0) {\n switch(n) {\n case 1:\n d0 = next();\n d1 = next();\n b8[p] = ((d0 << 2) | (d1 >> 4));\n break;\n case 2:\n d0 = next();\n d1 = next();\n d2 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p] = ((d1 << 4) | (d2 >> 2));\n break;\n default:\n d0 = next();\n d1 = next();\n d2 = next();\n d3 = next();\n b8[p++] = ((d0 << 2) | (d1 >> 4));\n b8[p++] = ((d1 << 4) | (d2 >> 2));\n b8[p++] = ((d2 << 6) | d3);\n break;\n }\n n -= 3;\n }\n return ba;\n case 9:\n var isFun = next() === 1;\n var lbl = nextLabel();\n return h$initPtrLbl(isFun, lbl);\n case 10:\n var c = { f: nextEntry(), d1: null, d2: null, m: 0 };\n var n = next();\n var args = [];\n while(n--) {\n args.push(nextArg());\n }\n return h$init_closure(c, args);\n default:\n ;\n return nextObj(o-11);\n }\n }\n info = infoMeta; pos = 0;\n for(i=0;i<funcs.length;i++) {\n o = funcs[i];\n var ot;\n var oa = 0;\n var oregs = 256; // one register no skip\n switch(next()) {\n case 0: // thunk\n ot = 0;\n break;\n case 1: // fun\n ot = 1;\n var arity = next();\n var skipRegs = next()-1;\n if(skipRegs === -1) throw \"h$initInfoTables: unknown register info for function\";\n var skip = skipRegs & 1;\n var regs = skipRegs >>> 1;\n oregs = (regs << 8) | skip;\n oa = arity + ((regs-1+skip) << 8);\n break;\n case 2: // con\n ot = 2;\n oa = next();\n break;\n case 3: // stack frame\n ot = -1;\n oa = 0;\n oregs = next() - 1;\n if(oregs !== -1) oregs = ((oregs >>> 1) << 8) | (oregs & 1);\n break;\n default: throw (\"h$initInfoTables: invalid closure type\")\n }\n var size = next() - 1;\n var nsrts = next();\n var srt = null;\n if(nsrts > 0) {\n srt = [];\n for(var j=0;j<nsrts;j++) {\n srt.push(nextObj());\n }\n }\n // h$log(\"result: \" + ot + \" \" + oa + \" \" + oregs + \" [\" + srt + \"] \" + size);\n // h$log(\"orig: \" + o.t + \" \" + o.a + \" \" + o.r + \" [\" + o.s + \"] \" + o.size);\n // if(ot !== o.t || oa !== o.a || oregs !== o.r || size !== o.size) throw \"inconsistent\";\n o.t = ot;\n o.i = [];\n o.n = \"\";\n o.a = oa;\n o.r = oregs;\n o.s = srt;\n o.m = 0;\n o.size = size;\n }\n info = infoStatic;\n pos = 0;\n for(i=0;i<objects.length;i++) {\n ;\n o = objects[i];\n // traceMetaObjBefore(o);\n var nx = next();\n ;\n switch(nx) {\n case 0: // no init, could be a primitive value (still in the list since others might reference it)\n // h$log(\"zero init\");\n break;\n case 1: // staticfun\n o.f = nextEntry();\n ;\n n = next();\n ;\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n break;\n case 2: // staticThunk\n ;\n o.f = nextEntry();\n n = next();\n ;\n if(n === 0) {\n o.d1 = null;\n o.d2 = null;\n } else if(n === 1) {\n o.d1 = nextArg();\n o.d2 = null;\n } else if(n === 2) {\n o.d1 = nextArg();\n o.d2 = nextArg();\n } else {\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n }\n h$addCAF(o);\n break;\n case 3: // staticPrim false, no init\n ;\n break;\n case 4: // staticPrim true, no init\n ;\n break;\n case 5:\n ;\n break;\n case 6: // staticString\n ;\n break;\n case 7: // staticBin\n ;\n n = next();\n var b = h$newByteArray(n);\n for(j=0;j>n;j++) {\n b.u8[j] = next();\n }\n break;\n case 8: // staticEmptyList\n ;\n o.f = h$ghczmprimZCGHCziTypesziZMZN_con_e;\n break;\n case 9: // staticList\n ;\n n = next();\n var hasTail = next();\n var c = (hasTail === 1) ? nextObj() : h$ghczmprimZCGHCziTypesziZMZN;\n ;\n while(n--) {\n c = (h$c2(h$ghczmprimZCGHCziTypesziZC_con_e, (nextArg()), (c)));\n }\n o.f = c.f;\n o.d1 = c.d1;\n o.d2 = c.d2;\n break;\n case 10: // staticData n args\n ;\n n = next();\n ;\n o.f = nextEntry();\n for(j=0;j<n;j++) {\n h$setField(o, j, nextArg());\n }\n break;\n case 11: // staticData 0 args\n ;\n o.f = nextEntry();\n break;\n case 12: // staticData 1 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n break;\n case 13: // staticData 2 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = nextArg();\n break;\n case 14: // staticData 3 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg()};\n break;\n case 15: // staticData 4 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n // should be the correct order\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg() };\n break;\n case 16: // staticData 5 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg() };\n break;\n case 17: // staticData 6 args\n ;\n o.f = nextEntry();\n o.d1 = nextArg();\n o.d2 = { d1: nextArg(), d2: nextArg(), d3: nextArg(), d4: nextArg(), d5: nextArg() };\n break;\n default:\n throw (\"invalid static data initializer: \" + nx);\n }\n }\n h$staticDelayed = null;\n}", "decode(bitstreamTable) {\n this.bitTypes = []; // Fill this in as we go\n var x = this.bitPt[0];\n var y = this.bitPt[1];\n var nf = 0;\n for (var bitnum = 0; bitnum < 8; bitnum++) {\n var bit = bitstreamTable[x + bitnum][y + 7];\n this.bitTypes.push([x + bitnum, y + 7, BITTYPE.lut]);\n if (bit) {\n nf |= 1 << [1, 0, 2, 3, 5, 4, 6, 7][bitnum]; // Ordering of LUT is irregular\n }\n }\n this.configNf = nf;\n var fin1 = bitstreamTable[x + 7][y + 6] ? 'A' : 'B';\n var fin2 = bitstreamTable[x + 6][y + 6] ? 'B' : 'C';\n var fin3 = 'Q';\n if (bitstreamTable[x + 1][y + 6]) {\n fin3 = 'C';\n } else if ( bitstreamTable[x + 0][y + 6]) {\n fin3 = 'D';\n }\n this.bitTypes.push([x + 7, y + 6, BITTYPE.clb], [x + 6, y + 6, BITTYPE.clb], [x + 1, y + 6, BITTYPE.clb], [x + 0, y + 6, BITTYPE.clb]);\n\n var ng = 0;\n for (var bitnum = 0; bitnum < 8; bitnum++) {\n bit = bitstreamTable[x + bitnum + 10][y + 7];\n this.bitTypes.push([x + bitnum + 10, y + 7, BITTYPE.lut]);\n if (bit) {\n ng |= 1 << [7, 6, 4, 5, 3, 2, 0, 1][bitnum]; // Ordering of LUT is irregular\n }\n }\n this.configNg = ng;\n var gin1 = bitstreamTable[x + 11][y + 6] ? 'A' : 'B';\n var gin2 = bitstreamTable[x + 12][y + 6] ? 'B' : 'C';\n this.bitTypes.push([x + 11, y + 6, BITTYPE.clb], [x + 12, y + 6, BITTYPE.clb]);\n var gin3 = 'Q';\n if ( bitstreamTable[x + 16][y + 6]) {\n gin3 = 'C';\n } else if ( bitstreamTable[x + 17][y + 6]) {\n gin3 = 'D';\n }\n\n var str;\n var fname = 'F'; // The F output used internally; renamed to M for Base FGM.\n var gname = 'G';\n this.bitTypes.push([x + 9, y + 7, BITTYPE.clb]);\n if (bitstreamTable[x + 9][y + 7] != 1) {\n if (fin1 == gin1 && fin2 == gin2 && fin3 == gin3) {\n this.configBase = 'F';\n this.configF = fin1 + ':B:' + fin2 + ':' + fin3;\n this.configG = '';\n gname = 'F'; // NO G\n // F,G combined\n this.configFormulaF = formula4((nf << 8) | ng, fin1, fin2, fin3, 'B');\n str = 'F = ' + this.configFormulaF;\n } else {\n // MUX\n this.configBase = 'FGM';\n this.configF = fin1 + ':' + fin2 + ':' + fin3;\n this.configG = gin1 + ':' + gin2 + ':' + gin3;\n fname = 'M';\n gname = 'M';\n this.configFormulaF = formula3(nf, fin1, fin2, fin3);\n this.configFormulaG = formula3(ng, gin1, gin2, gin3);\n str = 'F = B*(' + this.configFormulaF +\n ') + ~B*(' + this.configFormalaG + ')';\n }\n } else {\n // F, G separate\n this.configBase = 'FG';\n this.configF = fin1 + ':' + fin2 + ':' + fin3;\n this.configG = gin1 + ':' + gin2 + ':' + gin3;\n this.configFormulaF = formula3(nf, fin1, fin2, fin3);\n this.configFormulaG = formula3(ng, gin1, gin2, gin3);\n str = 'F = ' + this.configFormulaF;\n str += '<br/>G = ' + this.configFormulaG;\n }\n\n // Select one of four values based on two index bits\n function choose4(bit1, bit0, [val0, val1, val2, val3]) {\n if (bit1) {\n return bit0 ? val3 : val2;\n } else {\n return bit0 ? val1 : val0;\n }\n }\n \n // Decode X input\n this.configX = choose4(bitstreamTable[x + 11][y + 5], bitstreamTable[x + 10][y + 5], ['Q', fname, gname, 'UNDEF']);\n this.bitTypes.push([x + 11, y + 5, BITTYPE.clb], [x + 10, y + 5, BITTYPE.clb]);\n this.configY = choose4(bitstreamTable[x + 13][y + 5], bitstreamTable[x + 12][y + 5], ['Q', gname, fname, 'UNDEF']);\n this.bitTypes.push([x + 13, y + 5, BITTYPE.clb], [x + 12, y + 5, BITTYPE.clb]);\n this.configQ = bitstreamTable[x + 9][y + 5] ? 'LATCH': 'FF';\n this.bitTypes.push([x + 9, y + 5, BITTYPE.clb]);\n\n // Figure out flip flop type and clock source. This seems a bit messed up.\n let clkInvert = bitstreamTable[x + 5][y + 4]; // Invert flag\n this.bitTypes.push([x + 5, y + 4, BITTYPE.clb]);\n if (bitstreamTable[x + 9][y + 5]) {\n clkInvert = !clkInvert; // LATCH flips the clock\n }\n if (bitstreamTable[x + 6][y + 4] == 0) {\n // No clock\n this.configClk = '';\n } else {\n if (bitstreamTable[x + 4][y + 4] == 1) {\n this.configClk = 'C';\n } else {\n // K or G inverted. This seems like a bug in XACT?\n // Assume not inverted?\n if (clkInvert) {\n clkInvert = 0;\n this.configClk = gname;\n } else {\n this.configClk = 'K';\n }\n }\n }\n this.bitTypes.push([x + 6, y + 4, BITTYPE.clb]);\n this.bitTypes.push([x + 4, y + 4, BITTYPE.clb]);\n if (clkInvert) { // Add NOT, maybe with colon separator.\n if (this.configClk != '') {\n this.configClk += ':NOT';\n } else {\n this.configClk += 'NOT';\n }\n }\n\n this.configSet = choose4(bitstreamTable[x + 3][y + 5], bitstreamTable[x + 2][y + 5], ['A', '', fname, 'BOTH?']);\n this.bitTypes.push([x + 3, y + 5, BITTYPE.clb], [x + 2, y + 5, BITTYPE.clb]);\n this.configRes = choose4(bitstreamTable[x + 1][y + 5], bitstreamTable[x + 0][y + 5], ['', 'G?', 'D', gname]);\n this.bitTypes.push([x + 1, y + 5, BITTYPE.clb], [x + 0, y + 5, BITTYPE.clb]);\n this.configString = 'X:' + this.configX + ' Y:' + this.configY + ' F:' + this.configF + ' G:' + this.configG + ' Q:' + this.configQ +\n ' SET:' + this.configSet + ' RES:' + this.configRes + ' CLK:' + this.configClk;\n }", "function computeFloat16OffsetTable() {\n var offsetTable = new Uint32Array(64);\n for (var i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n return offsetTable;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contract: bridge contract prover: eprover/hprover
constructor(web3, contract, prover) { this.web3 = web3; this.contract = contract; this.prover = prover; }
[ "async function deployContract(){\n\n let abiPath = path.join(__dirname + '/bin/DataStorageEvent.abi');\n let binPath = path.join(__dirname + '/bin/DataStorageEvent.bin');\n\n console.log(chalk.green(abiPath));\n console.log(chalk.green(binPath));\n\n let abi = fs.readFileSync(abiPath);\n // let bin = '0x' + fs.readFileSync(binPath); updated version of ganache-cli does not need 'Ox' to be added to depict hexadecimal.\n let bin = fs.readFileSync(binPath);\n\n\n let contract = new web3.eth.Contract(JSON.parse(abi));\n\n console.log()\n // Returns an object of abstract contract.\n let status = await contract.deploy({\n data: bin,\n arguments: [100]\n }).send({\n from: '0x96b6E861698DfBA5721a3Ccd9AfBCa808e360bf3',\n gasPrice: 1000,\n gas: 300000\n })\n\n console.log(chalk.red('Address of Contract Deployed : ' + status.options.address));\n}", "static async deployAuthenticationContract({voterList = [], voterConstituencyList = [], votingAddress}) {\n const accounts = await web3.eth.getAccounts();\n const authenticationContract = new web3.eth.Contract(authenticationABI);\n return authenticationContract.deploy({\n data: authenticationJSON.bytecode,\n arguments: [\n voterList.map(name => web3.utils.asciiToHex(name)),\n voterConstituencyList.map(constituency => web3.utils.asciiToHex(constituency)),\n votingAddress\n ]\n }).send({\n from: accounts[1],\n gas: 4700000\n }, (error, transactionHash) => {\n if(error != null) console.log(error);\n }).then(contractInstance => contractInstance.options.address);\n }", "_initContract () {\n if (this.contract) return\n this.contract = new this.web3.eth.Contract(plasmaChainCompiled.abi)\n this.registryContract = new this.web3.eth.Contract(\n registryCompiled.abi,\n this.options.registryAddress\n )\n }", "async function deployContract() {\n let abi = metadata.abi\n let bytecode = metadata.bytecode\n provider = await getProvider()\n let signer = await provider.getSigner()\n var el = document.querySelector(\"[class^='ctor']\")\n let factory = await new ethers.ContractFactory(abi, bytecode, signer)\n el.replaceWith(bel`<div class=${css.deploying}>Publishing to Ethereum network ${loadingAnimation(colors)}</div>`)\n try {\n var allArgs = getArgs(el, 'inputContainer')\n let args = allArgs.args\n var instance\n if (allArgs.overrides) { instance = await factory.deploy(...args, allArgs.overrides) }\n else { instance = await factory.deploy(...args) }\n // instance = await factory.deploy(...args)\n contract = instance\n let deployed = await contract.deployed()\n topContainer.innerHTML = ''\n topContainer.appendChild(makeDeployReceipt(provider, contract, false))\n activateSendTx(contract)\n } catch (e) {\n let loader = document.querySelector(\"[class^='deploying']\")\n loader.replaceWith(ctor)\n }\n }", "static async deployVotingContract({candidateList = [], constituencyList = []}) {\n const accounts = await web3.eth.getAccounts();\n const votingContract = new web3.eth.Contract(votingABI);\n return votingContract.deploy({\n data: votingJSON.bytecode,\n arguments: [\n candidateList.map(name => web3.utils.asciiToHex(createHash('sha256').update(name).digest('hex'))),\n constituencyList.map(constituency => web3.utils.asciiToHex(constituency))\n ]\n }).send({\n from: accounts[0],\n gas: 4700000\n }, (error, transactionHash) => {\n if(error != null) console.log(error);\n }).then(contractInstance => contractInstance.options.address);\n }", "function deployContractCB(err, contract) {\n if (err) console.log(err);\n console.log(contract);\n if (contract) {\n if (contract.address) {\n console.log(contract);\n console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);\n cb(null, contract.address);\n }\n }\n }", "function initContract() {\n\tconsole.log(\"Load contract at : \"+contractAddress);\n\ttry {\n\t\thelloContract = new web3.eth.Contract(proposableHelloABI, contractAddress);\n\t}\n\tcatch(error) {\n\t\tconsole.error(\"Error loading contract : \"+error);\n\t}\n}", "function Deploy(myaddress, myprivatekey, mygasfee, nodeToCall, networkToCall, contract_script, storage = 0x00, returntype = '05', par = '') {\n\n if(returntype.length == 1)\n returntype = returntype[0]; // remove array if single element\n\n\n if(contract_script == \"\")\n {\n\talert(\"ERROR (DEPLOY): Empty script (avm)!\");\n \treturn;\n }\n\n var contract_scripthash = getScriptHashFromAVM(contract_script);\n\n //Notify user if contract exists\n getContractState(contract_scripthash, true);\n if(contract_scripthash == \"\" || !Neon.default.is.scriptHash(contract_scripthash))\n {\n\talert(\"ERROR (DEPLOY): Contract scripthash \" + contract_scripthash + \" is not being recognized as a scripthash.\");\n \treturn;\n }\n\n const sb = Neon.default.create.scriptBuilder();\n sb.emitPush(Neon.u.str2hexstring('appdescription')) // description\n .emitPush(Neon.u.str2hexstring('email')) // email\n .emitPush(Neon.u.str2hexstring('author')) // author\n .emitPush(Neon.u.str2hexstring('v1.0')) // code_version\n .emitPush(Neon.u.str2hexstring('appname')) // name\n .emitPush(storage) // storage: {none: 0x00, storage: 0x01, dynamic: 0x02, storage+dynamic:0x03}\n .emitPush(returntype) // expects hexstring (_emitString) // usually '05'\n .emitPush(par) // expects hexstring (_emitString) // usually '0710'\n .emitPush(contract_script) //script\n .emitSysCall('Neo.Contract.Create');\n\n const config = {\n net: networkToCall,\n url: nodeToCall,\n script: sb.str,\n address: myaddress, //'AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y',//'ARCvt1d5qAGzcHqJCWA2MxvhTLQDb9dvjQ',\n privateKey: myprivatekey, //'1dd37fba80fec4e6a6f13fd708d8dcb3b29def768017052f6c930fa1c5d90bbb',//'4f0d41eda93941d106d4a26cc90b4b4fddc0e03b396ac94eb439c5d9e0cd6548',\n gas: mygasfee //0\n }\n\n Neon.default.doInvoke(config).then(res => {\n \tconsole.log(res);\n\n if(typeof(res.response.result) == \"boolean\") // 2.X\n createNotificationOrAlert(\"Deploy\",\"Response: \" + res.response.result, 7000);\n else // 3.X\n createNotificationOrAlert(\"Deploy\",\"Response: \" + res.response.result.succeed + \" Reason:\" + res.response.result.reason + \" id \" + res.tx.hash, 7000);\n\n if(res.response.result) {\n if(typeof(res.response.result) == \"boolean\") // 2.X\n updateVecRelayedTXsAndDraw(res.response.txid, \"Deploy\", $(\"#contracthashjs\").val(),\"DeployParams\");\n else // 3.X\n updateVecRelayedTXsAndDraw(res.tx.hash, \"Deploy\", $(\"#contracthashjs\").val(),\"DeployParams\");\n }\n\n }).catch(err => {\n \tconsole.log(err);\n\tcreateNotificationOrAlert(\"Deploy ERROR\",\"Response: \" + err, 5000);\n });\n\n document.getElementById('divNetworkRelayed').scrollIntoView();\n}", "getContract(props) {\n return this.contract;\n }", "loadContract() {\r\n try {\r\n this.contract = new this.web3.eth.Contract(this.ABI, this.address);\r\n } catch (error) {\r\n console.error(error);\r\n throw new Error('Error loading contract.');\r\n }\r\n }", "async function deployContract() {\n let abi = solcMetadata.output.abi\n let bytecode = opts.metadata.bytecode\n provider = await getProvider()\n let signer = await provider.getSigner()\n let element = document.querySelector(\"[class^='ctor']\")\n let factory = await new ethers.ContractFactory(abi, bytecode, signer)\n let instance = await factory.deploy(getArgs(element, 'inputFields'))\n contract = instance\n deployingNotice()\n let deployed = await contract.deployed()\n createDeployStats(contract)\n activateSendTx(contract)\n }", "createContractInstance() {\n // replace me :)\n debugger;\n App.contracts.deployed().then(function(instance){\n console.log('inside deployeed');\n debugger;\n \n });\n let instance;\n App.contractInstance = instance;\n App.contractInstance.setProvider(App.web3Provider);\n //Storage.deployed().then(instance => instance.get.call()).then(result => storeData = result)\n }", "_checkEscrowContract() {\n let promiseOfPayment = this._checkPromiseOfPayment()\n const escrowContractPacket = {\n header: {\n signature: this._metaData.escrowContract.messageSignature,\n ephemeralPublicKey: this._metaData.escrowContract.senderEphemeralPublicKey,\n ephemeralPublicKeyCertificate: this._metaData.escrowContract.senderEphemeralPublicKeyCertificate,\n identityPublicKey: this._identities.server\n },\n body: {\n promiseOfPaymentSig: this._metaData.promiseOfPayment.messageSignature,\n promiseOfPayment: promiseOfPayment.readMessage()\n }\n }\n\n // implicitly verify packet by constructing new received packet\n return new EscrowContract({type: 'receive', packet: escrowContractPacket})\n }", "async propose() {\n await this.setStage(0)\n\n const proposal = { name: \"\", policies: FLAG, valid: true};\n if (process.env.CHEAT) {\n return this.contract.propose(this.walletAddress, proposal)\n }\n \n const sig = \"propose(address,(string,string,bool))\"\n let abiEncoded = this.contract.interface.encodeFunctionData(\"propose\", [this.walletAddress, proposal])\n let abiEncodedFull = abiEncoded; // keep a backup just incase\n // strip the call from the function signature\n console.log(\"Signature\", '0x' + abiEncoded.slice(2, 10))\n abiEncoded = abiEncoded.slice(10)\n // strip the address from the call\n console.log(\"Candidate\", '0x' + abiEncoded.slice(24, 64))\n abiEncoded = abiEncoded.slice(64)\n console.log(\"Rest\", abiEncoded)\n // Since we want to have an (address, Proposal), we will skip up to the msg.sender\n // part of the call, and then use the first 32 bytes as the `value` of the transfer\n // and the rest as the `data` field. These will hopefully get put back together\n // in the correct way, so that a call to `propose` is made\n let value = abiEncoded.slice(0, 66)\n let data = '0x' + abiEncoded.slice(66)\n // abi.encodeWithSignature(customFallback, msg.sender, value, data)\n const contractSees = await this.contract.helper(sig, this.walletAddress, value, data)\n console.log(\"Contract\\n\", contractSees)\n console.log(\"Us\\n\", abiEncodedFull)\n\n // get us the missing funds\n await this.mint(value)\n\n await this.call(\n sig,\n value,\n data,\n )\n }", "function send_contract() {\n console.log(\"Sending contract\");\n\n // get hash of contract to enable reopening later if needed\n previous_contract_hash = consumer.commitmentTx._getHash();\n previous_contract_hash = reverse_array(previous_contract_hash);\n console.log('previous_contract_hash: ');\n print_array(previous_contract_hash);\n\n // TODO: handle edge case where first payment is also last\n var sigtype = Signature.SIGHASH_ANYONECANPAY | Signature.SIGHASH_SINGLE;\n consumer.incrementPaymentBy(min_initial_payment, sigtype);\n last_increment = min_initial_payment;\n var signature_buffer = get_payment_update_signature(sigtype);\n refund_amount = consumer.paymentTx.outputs[0].satoshis;\n //console.log(\"contract hash: \" + consumer.commitmentTx.id);\n console.log(\"paymentTx.paid = \" + consumer.paymentTx.paid);\n console.log(\"refund_amount: \" + refund_amount);\n\n /*\n console.log(\"refund_amount: \" + refund_amount);\n// console.log(\"multisig script: \" + consumer.commitmentTx.outscript.toHex());\n console.log(\"paymentTx: \" + consumer.paymentTx.id);\n console.log(\"changeAddress: \" + consumer.paymentTx.changeAddress.toString());\n console.log(\"changeScript: \" + consumer.paymentTx._changeScript.toString());\n //console.log(\"commitment_script: \" + consumer.commitmentTx.outputs[0].script.toString());\n */\n var msg = new Message({\n \"type\": Message.MessageType.PROVIDE_CONTRACT,\n \"provide_contract\": {\n \"tx\": consumer.commitmentTx.toBuffer(),\n \"initial_payment\": {\n \"client_change_value\": refund_amount,\n \"signature\": signature_buffer\n }\n }\n });\n send_message(msg);\n set_channel_state(CHANNEL_STATES.SENT_CONTRACT);\n}", "async function deploySmartContracts() {\n DAI = await hre.ethers.getContractFactory(\"DAI\")\n WBTC = await hre.ethers.getContractFactory(\"WBTC\")\n CDP = await hre.ethers.getContractFactory(\"CDP\")\n\n console.log(\"Deploy the DAI contract\")\n dai = await DAI.deploy()\n DAI_TOKEN = dai.address\n\n console.log(\"Deploy the WBTC contract\")\n wbtc = await WBTC.deploy()\n WBTC_TOKEN = wbtc.address\n\n console.log(\"Deploy the CDP contract\")\n cdp = await CDP.deploy(DAI_TOKEN, WBTC_TOKEN)\n CDP_ADDRESS = cdp.address\n //await cdp.deployed()\n\n console.log(\"=== DAI ===\", DAI_TOKEN)\n console.log(\"=== WBTC ===\", WBTC_TOKEN)\n console.log(\"=== CDP ===\", CDP_ADDRESS)\n}", "async connectToContract(){\n\n await this.auctionContract.connect( App.provider.getSigner(), this.auctionContract.contractAddress);\n this.auctionContract.registerToEvents(sellerUI);\n }", "async deploy(nome_file,args,address,URL)\r\n {\r\n const web3 = new Web3(URL)\r\n const [abi,bytecode] = compila(nome_file)\r\n let contract = new web3.eth.Contract(abi).deploy({data:bytecode,arguments:args})\r\n contract=await contract.send({from:address});\r\n return contract\r\n }", "function loadContract() {\n\thello = web3.eth.contract(helloWorldABI).at(helloContractAddress);\n\tconsole.log(\"Contract loaded at \"+helloContractAddress);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make the timeline draggable
function _dragableTimeline() { var selected = null, x_pos = 0, x_elem = 0; // Will be called when user starts dragging an element function _drag_init(elem) { selected = elem; x_elem = x_pos - selected.offsetLeft; } // Will be called when user dragging an element function _move_elem(e) { x_pos = document.all ? window.event.clientX : e.pageX; if (selected !== null) { selected.style.left = (x_pos - x_elem) + 'px'; } } // Destroy the object when we are done function _stop_move() { if (selected) { // active the closest elem var linePos = $el.find('.' + options.className + '-vertical-line').offset().left; var closestDotYear = null; var diff = 99999999999999999999999; children.parent().find('.' + options.className + '-timeblock:not(.inactive) .' + options.className + '-dot').each(function (index) { var currDotPos = $(this).offset().left; var currDiff = Math.abs(currDotPos - linePos); if (currDiff < diff) { console.log($(this).attr('data-year')); closestDotYear = $(this).attr('data-year'); diff = currDiff; } }); $el.find('.' + options.className + '-dot[data-year=' + closestDotYear + ']').trigger('click'); selected = null; } } // Bind the functions... $el.first().on('mousedown', function() { _drag_init($el.find('.'+ options.className +'-timeline')[0]); return false; }); $(document).on('mousemove.timeliny', function(e) { _move_elem(e); }); $(document).on('mouseup.timeliny', function() { _stop_move(); }); }
[ "function _dragableTimeline() {\n\n\t\t\tvar selected = null, x_pos = 0, x_elem = 0;\n var lastX;\n var directionRight = true;\n\n\t\t\t// Will be called when user starts dragging an element\n\t\t\tfunction _drag_init(elem, e) {\n if (e.targetTouches) {\n var touch = e.targetTouches[0];\n x_pos = touch.pageX;\n\n directionRight = undefined;\n\t\t\t\t}\n\t\t\t\tselected = elem;\n\t\t\t\tx_elem = x_pos - selected.offsetLeft;\n\t\t\t}\n\n\t\t\t// Will be called when user dragging an element\n\t\t\tfunction _move_elem(e) {\n\t\t\t\t/* if touch event / mobile */\n\t\t\t\tif (e.targetTouches) {\n var touch = e.targetTouches[0];\n x_pos = touch.pageX;\n selected.style.left = (touch.pageX - x_elem) + 'px';\n\n var currentX = e.originalEvent.touches[0].clientX;\n if(currentX > lastX){\n directionRight = false;\n }else if(currentX < lastX){\n directionRight = true;\n }\n lastX = currentX;\n\t\t\t\t} else {\n x_pos = document.all ? window.event.clientX : e.pageX;\n if (selected !== null) {\n selected.style.left = (x_pos - x_elem) + 'px';\n }\n var currentPageX = e.pageX;\n\n if(currentPageX > lastX){\n directionRight = false;\n } else if(currentPageX < lastX){\n directionRight = true;\n }\n\n lastX = currentPageX;\n\n var closestDotYearIndex = getClosestDotYearIndex(e, directionRight);\n var elements = $el.find('.' + options.className + '-dot');\n elements.removeClass('highlight');\n elements.eq(closestDotYearIndex).addClass('highlight');\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Destroy the object when we are done\n\t\t\tfunction _stop_move(e) {\n\t\t\t\tif (selected) {\n\t\t\t\t\tvar closestDotYearIndex = getClosestDotYearIndex(e, directionRight);\n var closestElement = $el.find('.' + options.className + '-dot').eq(closestDotYearIndex);\n closestElement.removeClass('highlight');\n closestElement.trigger('click');\n\t\t\t\t\tselected = null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Bind the functions...\n\t\t\tif (options.draggedElement) {\n $(options.draggedElement).on('mousedown touchstart', function(e) {\n _drag_init($el.find('.'+ options.className +'-timeline')[0], e);\n return false;\n });\n\n $(options.draggedElement).on('mousemove touchmove', function(e) {\n _move_elem(e);\n });\n\n $(document).on('mouseup touchend', function(e) {\n _stop_move(e);\n });\n\t\t\t} else {\n $el.first().on('mousedown touchstart', function(e) {\n _drag_init($el.find('.'+ options.className +'-timeline')[0], e);\n return false;\n });\n $(document).on('mousemove.timeliny touchmove.timeliny', function(e) {\n _move_elem(e);\n });\n\n $(document).on('mouseup.timeliny touchend.timeliny', function(e) {\n _stop_move(e);\n });\n\t\t\t}\n\t\t}", "function makeDraggable() {\n\n moveable.draggable({\n revert: 'invalid',\n helper:\"clone\",\n containment:\"document\",\n });\n}", "function makeDraggableAndResizable()\n {\n setEvent(\".TextView\");\n setEvent(\".Button\");\n setEvent(\".inputType\");\n setEvent(\".WebView\");\n setEvent(\".ImageView\");\n setEvent(\".ScrollView\");\n setEvent(\".LinearLayout\");\n setEvent(\".RelativeLayout\");\n setEvent(\".FrameLayout\");\n setSortable();\n }", "function makeCardDraggable( card ){\n\tcard.draggable({ \n\t\tconnectToSortable: \".line-container\",\n\t\tstart: function() {\n\t\t\t$('.line-container').css({\n\t\t\t\tbackgroundColor: 'blue',\n\t\t\t\tminHeight: card.css('height')\n\t\t\t});\n\n\t\t},\n\t\tstop: function() {\n\t\t\t$('.line-container').css({\n\t\t\t\tbackgroundColor: '#ccc'\n\t\t\t});\n\t\t}\n\t});\n\n\tcard.disableSelection();\n\t$('.line-container').disableSelection();\n}", "function lineStationDraggable() {\n $(\"#line_configurations td .station_items\").draggable({\n cancel: \"a.ui-icon\", // clicking an icon won't initiate dragging\n revert: \"invalid\", // when not dropped, the item will revert back to its initial position\n containment: \"document\",\n helper: \"clone\",\n cursor: \"move\"\n });\n }", "function tasksDraggable() {\n $(\".todo-item\").draggable({\n handle: '.draggable-action',\n connectToSortable: '.todo-list',\n revert: 'invalid',\n scroll: true,\n zIndex: 2500,\n scope: 'tasks',\n });\n}", "function makeTilesDraggable() {\n $('.tile').draggable({\n revert: true,\n revertDuration: 100,\n scroll: false,\n start: function (e, ui) {\n $(this).addClass('hovering');\n },\n stop: function (e, ui) {\n $(this).removeClass('hovering');\n }\n });\n}", "function drag(){\n $('.draggable').draggable();\n }", "function timeline_register() {\n var sortable_params = {\n axis: 'y',\n items: '.timeline-item',\n containment: 'parent',\n cursor: 'move',\n delay: 100,\n // callback when timeline is changed\n stop: changed,\n update: drag_update,\n }\n //$('.timeline-ul').sortable(sortable_params);\n //$('.timeline-ul').disableSelection();\n //$('.timeline-item').click(item_clicked);\n $('.timeline-item').hover(item_mouse_over, item_mouse_out);\n\n $('.timeline-item-navigation a.edit').live('mousedown', function(evt) {\n if (evt.button != 0) return;\n var from_url = str_concat(document.location.pathname , document.location.hash);\n var to_url = $(this).attr('href');\n // remove /# from to_url\n to_url = remove_beginning_char(to_url);\n to_url = remove_beginning_char(to_url, '#'); \n from_url = remove_beginning_char(from_url);\n\n NewmanLib.ADR_STACK = [\n { from: from_url, to: to_url }\n ];\n });\n\n /*\n $('.timeline-item-navigation .insert').live(\n 'click',\n show_insert_dialog\n );\n $('.timeline-item-navigation .append').live(\n 'click',\n show_append_dialog\n );\n\n // TODO change z-index to NULL when URL is changed before the dialog is closed.\n $('#id-modal-dialog #id-close-dialog').live(\n 'click',\n hide_dialog\n );\n */\n }", "startDrag(x, y) {}", "function addTodoListDraggableProperty() { \r\n $(\"#todo-container\").draggable({ handle: \"#todo-header\", containment: \"#background-borders\", scroll: false, delay:0,\r\n start: function(event, ui) {\r\n //console.info(\"TODO draggable\", event);\r\n },\r\n stop: function(event, ui) {\r\n updateTodoListCoordinates($(this));\r\n $(\"#todo-footer-input\").focus();\r\n }\r\n });\r\n}", "function makeDraggable() {\n\t\t$('.dps-aw-item').draggable({\n\t\t\trevert: \"invalid\",\n\t\t\tappendTo: 'body',\n\t\t\tcontainment: 'window',\n\t\t\tscroll: false,\n\t\t\thelper: 'clone',\n\t\t\tstart: function(event, ui) { jQuery(this).hide(); },\n\t\t\tstop: function(event, ui) { jQuery(this).show(); }\n \t\t});\n \t\tconsole.log(\"test\");\n\t}", "function makeDraggable() {\n\t\t$(\".selectorField\").draggable({ helper: \"clone\",stack: \"div\",cursor: \"move\", cancel: null });\n\t}", "function dvTimeline (st) {\n if (st.view === \"Dvtimeline\") {\n timeline(document.querySelectorAll('.timeline'), {\n verticalStartPosition: 'right',\n verticalTrigger: '150px'\n });\n\n }\n}", "function tFakeMove(xVal, offLeft, trueFalse, target, vid) {\n vid.player.dragging = true;\n var timelineBarFake = target.getElementsByClassName('timeline-bar-fake')[0];\n var timelineSel = target.getElementsByClassName('timeline-sel')[0];\n var width = target.clientWidth\n if (trueFalse) {\n var dist = width-(xVal.clientX-offLeft);\n // let drawX = dist / vid.player.width * 100;\n timelineBarFake.style.transform = 'translateX(-' + dist + 'px)';\n timelineBarFake.classList.add('show');\n // Move selection bar w/ drag\n timelineSel.style.transform = 'translateX(' + (width-dist) + 'px)';\n }\n}", "makeDraggable() {\n const cb = () => {};\n htmlHelpers.draggable({\n parent: $(this.dgDom.element).find('.attributeModal'),\n handle: $(this.dgDom.element).find('.jsDbMove'),\n animateDiv: '.draganime',\n cb,\n moveParent: true\n });\n }", "function makeDraggable(ds) {\n dom.forEach(ds.sources, function(src) {\n src.setAttribute('draggable', 'true');\n });\n}", "addDraggableTrack() {\n\n const controlPointGroupTandem = this.controlPointGroupTandem;\n const trackGroupTandem = this.trackGroupTandem;\n\n // Move the tracks over so they will be in the right position in the view coordinates, under the grass to the left\n // of the clock controls. Could use view transform for this, but it would require creating the view first, so just\n // eyeballing it for now.\n const offset = this.initialTracksOffsetVector;\n const controlPoints = [\n new ControlPoint( offset.x - 1, offset.y, { tandem: controlPointGroupTandem.createNextTandem() } ),\n new ControlPoint( offset.x, offset.y, { tandem: controlPointGroupTandem.createNextTandem() } ),\n new ControlPoint( offset.x + 1, offset.y, { tandem: controlPointGroupTandem.createNextTandem() } )\n ];\n this.tracks.add( new Track( this, this.tracks, controlPoints, null, this.availableModelBoundsProperty, merge( {\n tandem: trackGroupTandem.createNextTandem()\n }, Track.FULLY_INTERACTIVE_OPTIONS )\n ) );\n }", "_initTimelines() {\n const overviewContainer = document.getElementById('overview');\n\n this._timeline =\n new vis.Timeline(this._timelineContainer, this._bookmarks, this._timelineOptions);\n this._centerTime = this._timeline.getCurrentTime();\n this._timeline.moveTo(this._centerTime, {\n animation: false,\n });\n\n this._timeline.addCustomTime(this._centerTime, this._timeId);\n this._timeline.on('mouseUp', this._onMouseUp.bind(this));\n this._timeline.on('mouseDown', () => this._dragDistance = 0);\n this._timeline.on('mouseMove', (e) => {this._dragDistance += Math.abs(e.event.movementX)});\n this._timeline.on('rangechange', this._timelineDragCallback.bind(this));\n this._timeline.on('rangechanged', this._timelineDragEndCallback.bind(this));\n this._timeline.on('itemover', this._itemOverCallback.bind(this));\n this._timeline.on('itemout', this._itemOutCallback.bind(this));\n\n // create overview timeline\n this._overviewTimeline =\n new vis.Timeline(overviewContainer, this._bookmarksOverview, this._overviewTimelineOptions);\n this._overviewTimeline.addCustomTime(this._timeline.getWindow().end, this._rightTimeId);\n this._overviewTimeline.addCustomTime(this._timeline.getWindow().start, this._leftTimeId);\n this._overviewTimeline.on('rangechange', this._overviewDragCallback.bind(this));\n this._overviewTimeline.on('mouseUp', this._onMouseUp.bind(this));\n this._overviewTimeline.on('mouseDown', () => this._dragDistance = 0);\n this._overviewTimeline.on(\n 'mouseMove', (e) => this._dragDistance += Math.abs(e.event.movementX));\n this._overviewTimeline.on('itemover', this._itemOverCallback.bind(this));\n this._overviewTimeline.on('itemout', this._itemOutCallback.bind(this));\n this._initialOverviewWindow(new Date(1950, 1), new Date(2030, 12));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a Slate model to a Tag representation
function parse(model, options) { const object = isPseudoLeafRecord(model) ? 'leaf' : model.object const parser = PARSERS[object] if (!parser) { throw new Error(`Unrecognized Slate model ${object}`) } if (object === 'value') { if (model.annotations.size > 0) { model = applyAnnotationMarks(model) } if (model.selection.isFocused) { model = insertFocusedSelectionTagMarkers(model, options) } } return parser(model, options) }
[ "function parse(model: SlateModel, options: Options): Tag[] {\n const object = model.object || model.kind;\n const parser = PARSERS[object];\n if (!parser) {\n throw new Error(`Unrecognized Slate model ${object}`);\n }\n return parser(model, options);\n}", "function parse(model: SlateModel, options: Options): Tag[] {\n const object = model.object;\n const parser = PARSERS[object];\n if (!parser) {\n throw new Error(`Unrecognized Slate model ${object}`);\n }\n\n if (object === 'value') {\n const editor = new Editor({ value: model });\n const { anchor, focus } = editor.value.selection;\n if (model.decorations.size > 0) {\n applyDecorationMarks(editor);\n editor.moveAnchorTo(anchor.key, anchor.offset);\n editor.moveFocusTo(focus.key, focus.offset);\n }\n if (model.selection.isFocused) {\n insertFocusedSelectionTagMarkers(editor, options);\n editor.moveAnchorTo(anchor.key, anchor.offset);\n editor.moveFocusTo(focus.key, focus.offset);\n }\n model = editor.value;\n }\n\n return parser(model, options);\n}", "function parseTag(tagText) {\n \n}", "function makeTag(data) {\n const valueParts = data.value.split('--');\n if (!valueParts.length) return;\n\n let tag;\n let text;\n let color = 0xffffff;\n\n if (_mlyHighlightedDetection === data.id) {\n color = 0xffff00;\n text = valueParts[1];\n if (text === 'flat' || text === 'discrete' || text === 'sign') {\n text = valueParts[2];\n }\n text = text.replace(/-/g, ' ');\n text = text.charAt(0).toUpperCase() + text.slice(1);\n _mlyHighlightedDetection = null;\n }\n\n var decodedGeometry = window.atob(data.geometry);\n var uintArray = new Uint8Array(decodedGeometry.length);\n for (var i = 0; i < decodedGeometry.length; i++) {\n uintArray[i] = decodedGeometry.charCodeAt(i);\n }\n const tile = new VectorTile(new Protobuf(uintArray.buffer));\n const layer = tile.layers['mpy-or'];\n\n const geometries = layer.feature(0).loadGeometry();\n\n const polygon = geometries.map(ring =>\n ring.map(point =>\n [point.x / layer.extent, point.y / layer.extent]));\n\n tag = new mapillary.OutlineTag(\n data.id,\n new mapillary.PolygonGeometry(polygon[0]),\n {\n text: text,\n textColor: color,\n lineColor: color,\n lineWidth: 2,\n fillColor: color,\n fillOpacity: 0.3,\n }\n );\n\n return tag;\n }", "convertXmlToTagObject(response) {\n var xml = parser.parseFromString(response, \"text/xml\");\n var json = this.xmlToJsonService.xmlToJson(xml);\n return Object(class_transformer__WEBPACK_IMPORTED_MODULE_3__[\"plainToClass\"])(_models_model_interfaces__WEBPACK_IMPORTED_MODULE_4__[\"Tag\"], json);\n }", "parseTag (tagValue) {\r\n var kind = 'Tag';\r\n var name = tagValue;\r\n var className = 'fa-tag';\r\n\r\n /**\r\n * Compare first char of tag to\r\n * determine if it is a special tag\r\n */\r\n var firstChar = name.slice(0, 1);\r\n if (firstChar === TAG_KIND.FOCUS) {\r\n kind = 'Focus'; // part of\r\n className = 'fa-eye';\r\n }\r\n else if (firstChar === TAG_KIND.PLACE) {\r\n kind = 'Place'; // where\r\n className = 'fa-anchor';\r\n }\r\n else if (firstChar === TAG_KIND.GOAL) {\r\n kind = 'Goal'; // to what end\r\n className = 'fa-trophy';\r\n }\r\n else if (firstChar === TAG_KIND.NEED) {\r\n kind = 'Need'; // why\r\n className = 'fa-recycle';\r\n }\r\n else if (firstChar === TAG_KIND.BOX) {\r\n kind = 'Box'; // when\r\n className = 'fa-cube';\r\n }\r\n\r\n /**\r\n * Separate the name from the\r\n * prefix when it is a special tag\r\n */\r\n if (kind !== 'Tag') {\r\n name = name.slice(1);\r\n }\r\n\r\n /**\r\n * Return tag object\r\n */\r\n return {\r\n value: name,\r\n kind,\r\n name,\r\n className,\r\n };\r\n }", "*_parseLines(lines) {\n const reTag = /^:([0-9]{2}|NS)([A-Z])?:/;\n let tag = null;\n\n for (let i of lines) {\n\n // Detect new tag start\n const match = i.match(reTag);\n if (match || i.startsWith('-}') || i.startsWith('{')) {\n if (tag) {yield tag;} // Yield previous\n tag = match // Start new tag\n ? {\n id: match[1],\n subId: match[2] || '',\n data: [i.substr(match[0].length)]\n }\n : {\n id: 'MB',\n subId: '',\n data: [i.trim()],\n };\n } else { // Add a line to previous tag\n tag.data.push(i);\n }\n }\n\n if (tag) { yield tag; } // Yield last\n }", "static fromTrytes(tag) {\r\n if (!objectHelper_1.ObjectHelper.isType(tag, trytes_1.Trytes)) {\r\n throw new dataError_1.DataError(\"The tag should be a valid Trytes object\");\r\n }\r\n let trytesString = tag.toString();\r\n if (trytesString.length > Tag.LENGTH) {\r\n throw new dataError_1.DataError(`The tag should be at most ${Tag.LENGTH} characters in length`, { length: trytesString.length });\r\n }\r\n while (trytesString.length < Tag.LENGTH) {\r\n trytesString += \"9\";\r\n }\r\n return new Tag(trytesString);\r\n }", "function deserializeTextFormat(str) {\n const tags = new tag_map_1.TagMap();\n if (!str)\n return tags;\n const listOfTags = str.split(TAG_DELIMITER);\n listOfTags.forEach(tag => {\n const keyValuePair = tag.split(TAG_KEY_VALUE_DELIMITER);\n if (keyValuePair.length !== 2)\n throw new Error(`Malformed tag ${tag}`);\n const [name, value] = keyValuePair;\n tags.set({ name }, { value }, UNLIMITED_PROPAGATION_MD);\n });\n return tags;\n}", "function parseSTL(model, buffer) {\n if (isBinary(buffer)) {\n parseBinarySTL(model, buffer);\n } else {\n var reader = new DataView(buffer);\n\n if (!('TextDecoder' in window)) {\n console.warn(\n 'Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)'\n );\n\n return model;\n }\n\n var decoder = new TextDecoder('utf-8');\n var lines = decoder.decode(reader);\n var lineArray = lines.split('\\n');\n parseASCIISTL(model, lineArray);\n }\n return model;\n }", "function tag () {\n if (token && token.type === 'tag') {\n // create our base node with the tag's name\n const node = { type: 'tag', name: token.value, content: [] }\n\n // move past the tag token\n next()\n\n // Now we do the attributes by looping until we are through all the\n // attributes and on to another token type\n if (token.type === 'attributeKey') { node.attrs = {} }\n while (token.type === 'attributeKey' || token.type === 'attributeValue') {\n // if we have a key, add it to attrs with empty string value\n if (token.type === 'attributeKey') {\n // if this attr hasn't already been populated, initialize it\n if (!node.attrs[token.value]) { node.attrs[token.value] = [] }\n next()\n }\n\n // if we have a value, add it as the value for the previous key\n if (token.type === 'attributeValue') {\n const previousKey = tokens[current - 1].value\n // if there are multiple classes being added, add a space between them\n if (node.attrs[previousKey].length) {\n node.attrs[previousKey].push({\n type: 'text',\n content: ' ',\n location: { line: token.line, col: token.col }\n })\n }\n // push class into the node's attributes array\n node.attrs[previousKey].push({\n type: 'text',\n content: token.value,\n location: { line: token.line, col: token.col }\n })\n next()\n }\n\n // TODO need a way to handle multiples and conflicts\n }\n\n // grab the current indent level, we need to to decide how long to keep\n // searching for contents\n const currentIndent = indentLevel\n\n // now we recurse to get the contents, looping while the indent level is\n // greater than that of the current node, to pick up everything nested\n node.content.push(walk(node.content))\n while (indentLevel > currentIndent) { // eslint-disable-line\n node.content.push(walk(node.content))\n }\n\n // when finished, return the node\n return node\n }\n }", "make(tagname, candidateMicroformatKeys, labelKey=null, itemTemplate=null) {\n let content = null;\n let microformatKey = null;\n\n // Convert keys to an array if it isn't already\n if (!Array.isArray(candidateMicroformatKeys)) {\n candidateMicroformatKeys = [candidateMicroformatKeys];\n }\n for (let i = 0; i < candidateMicroformatKeys.length; i++) {\n content = getValueOr(this.microformatJson, candidateMicroformatKeys[i], null);\n if (content) {\n microformatKey = candidateMicroformatKeys[i];\n break;\n }\n }\n\n if (!content) {\n return new TagBuilder(tagname);\n }\n\n let classes = getValueOr(microformats_map, microformatKey);\n\n\n function makeItem(item) {\n const builder = new TagBuilder(tagname);\n if (itemTemplate) {\n builder.clone(itemTemplate);\n }\n builder\n .add(linkify(item))\n .addClass(classes);\n\n if (labelKey) {\n if (labelKey.indexOf('svg_icon_') >= 0) {\n builder.addPrefix(new SvgBuilder().setIcon(labelKey).addClass('h-item-icon'));\n }\n else {\n builder.addPrefix(new SpanBuilder().add(format('{}:', getMessage(labelKey))).addClass('h-item-label'));\n }\n }\n return builder;\n }\n\n let container = new TagBuilder(tagname);\n for (let i = 0; i < content.length; i++) {\n container.add(makeItem(content[i]));\n }\n\n return container;\n }", "function parseTag( tag ) {\n\t\t\tif (!tag.split) {\n\t\t\t\ttag = \"\";\n\t\t\t}\n\t\t\n\t\t\tvar parts = tag.split(\"-\"), // get the subtags\n\t\t\t\tlen = parts.length,\n\t\t\t\tcanon = [],\t\t\t\t// will hold the subtags of the canonical tag\n\t\t\t\tmatchedSubtags = {l: \"\", s:\"\", r:\"\", v:\"\"},\n\t\t\t\tstart = 0,\n\t\t\t\ti = start,\n\t\t\t\tmask = 0,\n\t\t\t\tsubtag,\n\t\t\t\tlabel;\n\t\t\n\t\t\tfor (var j = 0, jlen = subtags.length; j < jlen; j++) { // order of subtag match is important\n\t\t\t\ti = start;\n\t\t\t\tsubtag = subtags[j];\n\t\t\t\tlabel = labels[subtag];\n\t\n\t\t\t\twhile ((getSubtagPattern(parts[i]).indexOf(subtag) == -1) && (i < len)) { // indexOf allows for partial match of 'lv' regex\n\t\t\t\t\ti++; // if no match, move on\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (i < len) { // if a match is found, store it and continue with the next subtag from this point\n\t\t\t\t\tcanon[label] = parts[i];\n\t\t\t\t\tmask += masks[subtag];\n\t\t\t\t\tmatchedSubtags[subtag] = parts[i];\n\t\t\t\t\tparts[i] = \"*\";\n\t\t\t\t\tstart = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// put it all back together as a string\n\t\t\tvar canonical = canon.join(\"-\").replace(/-+/g, \"-\");\n\t\t\t\n\t\t\tif ((canonical == \"\") || (canonical.substring(0, 1) == \"-\")) { // this means there is no language subtag, so we must fail the parse\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn {canonical: canonical, mask: mask, subtags: matchedSubtags};\n\t\t\t}\n\t\t}", "_parse() {\n const match = this._nextMatch();\n if (!match) { throw Error(`Cannot parse tag ${this.id}: ${this.data}`) }\n this.fields = this._extractFields(match);\n }", "function parseMattertags(mattertags)\r\n {\r\n var tags = [];\r\n for(i =0; i < mattertags.length; i++)\r\n {\r\n var str = mattertags[i].label + ' ' + mattertags[i].description;\r\n tags.push([str, mattertags[i].sid]);\r\n\r\n }\r\n tags.sort();\r\n return tags;\r\n }", "parse() {\n while (this.matchAt()) {\n var d = this.directive()\n this.match(\"{\")\n // NOTE: although we have to parse string preamble, comment to get to the next bit of the bibtex\n // file, don't bother adding them to the structure\n if (d.toUpperCase() === \"@STRING\") {\n this.string()\n } else if (d.toUpperCase() === \"@PREAMBLE\") {\n this.preamble()\n } else if (d.toUpperCase() === \"@COMMENT\") {\n this.comment()\n } else {\n this.entry(d)\n }\n this.match(\"}\")\n }\n\n this.alernativeid()\n }", "makeTagNode (tokens) {\n\t\tlet token = tokens.pop();\n\t\tlet recursive = this.mPack[token.content].r;\n\t\tlet target = this.mPack[token.content].s;\n\t\tlet root = new pNode(\"tag\", {o:null, c:token.content});\n\t\t//if it's a unary tag, just return w/ open tag = null\n\t\tif (target === \"\")\n\t\t\treturn root;\n\t\twhile (!tokens.isEmpty()) {\n\t\t\tlet curr = tokens.pop();\n\t\t\tif (curr.type === \"open\" && curr.content === target) {\n\t\t\t\t//found the corresponding open tag\n\t\t\t\troot.content.o = curr.content;\n\t\t\t\tbreak ;\n\t\t\t}\n\t\t\tif (curr.type === \"text\") \n\t\t\t\troot.addChild(new pNode(\"text\", curr.content));\t\n\t\t\telse if (curr.type === \"close\") {\n\t\t\t\tif (recursive) {\n\t\t\t\t\ttokens.push(curr);\n\t\t\t\t\troot.addChild(this.makeTagNode(tokens));\n\t\t\t\t} else {\n\t\t\t\t\troot.addChild(new pNode(\"text\", curr.content));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//must be an open node\n\t\t\t\tif (recursive) {\n\t\t\t\t\t//shouldn't have an unclosed open tag here\n\t\t\t\t\tconsole.log(\"ERROR: unclosed tag spotted!\\nThis tag will be regarded as a text.\");\n\t\t\t\t\troot.addChild(new pNode(\"text\", curr.content));\n\t\t\t\t} else {\n\t\t\t\t\troot.addChild(new pNode(\"text\", curr.content));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!root.content.o) {\n\t\t\t//if this tag is unmatched, convert it to the text node\n\t\t\troot.type = \"text\";\n\t\t\tconsole.log(\"unmatched closing tag found!\");\n\t\t\tconsole.log(root);\n\t\t}\n\t\treturn root;\n\t}", "function preify(tagName) {\n\tvar tags = $(tagName);\n\ttags.each(function(index, tag) {\n\t\t// skip tags that don't want to be munged\n\t\tif (tag.getAttribute(\"munge\") == \"false\") return;\n\t\t\n\t\tvar html = tag.value,\n\t\t\ttype = tag.className\n\t\t;\n\t\tif (!html || (/^[\\s\\r\\n]*$/g).test(html)) {\n\t\t\thtml = \"<div class='empty'>(empty)<\\/div>\";\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\t// normalize the initial indentation to two tabs\n\t\t\tvar lines = html.split(/[\\r\\n]/);\n\t\t\twhile (/^\\s*$/.test(lines[0])) {\n\t\t\t\tlines.splice(0,1);\n\t\t\t\tif (lines.length == 0) return;\n\t\t\t}\n\t\t\t\n\t\t\t// comments\n\t\t\thtml = html.replace(/<!--([^>]*)-->/g,\"%%span class='comment'>&lt;--$1-->%%/span>\");\n\n\t\t\t// tags\n\t\t\thtml = html.replace(/<([^>]*)>/g, \"%%span class='tag'>&lt;$1&gt;%%/span>\");\n\n\t\t\t// variables\n\t\t\thtml = html.replace(/#{([^}]*)}/g,\"%%span class='variable'>#{$1}%%/span>\");\n\n\t\t\t// links within the doc set\n\t\t\thtml = html.replace(/\\/api\\/docs\\/([^\\s]*)/g, \"%%a href='$1'>/api/docs/$1%%/a>\");\n\n\t\t\t// expand tabs\n\t\t\thtml = html.replace(/\\t/g, \"&nbsp;&nbsp;&nbsp;&nbsp;\");\n\t\t\t\n\t\t\t// expand newlines\n\t\t\thtml = html.replace(/\\n/g, \"<br>\");\n\n\t\t\t// replace bullets with \"<\" \n\t\t\thtml = html.replace(/%%/g, \"<\");\n\t\t}\n\t\t$(tag).replaceWith(\"<label>\"+tagMap[type]+\"</label><div class='xml'>\"+html+\"</div>\");\n\t});\n}", "function parse(template, tags) {\n tags = tags || exports.tags;\n\n var tagRes = escapeTags(tags);\n var scanner = new Scanner(template);\n\n var tokens = [], // Buffer to hold the tokens\n spaces = [], // Indices of whitespace tokens on the current line\n hasTag = false, // Is there a {{tag}} on the current line?\n nonSpace = false; // Is there a non-space char on the current line?\n\n // Strips all whitespace tokens array for the current line\n // if there was a {{#tag}} on it and otherwise only space.\n var stripSpace = function () {\n if (hasTag && !nonSpace) {\n while (spaces.length) {\n tokens.splice(spaces.pop(), 1);\n }\n } else {\n spaces = [];\n }\n\n hasTag = false;\n nonSpace = false;\n };\n\n var type, value, chr;\n\n while (!scanner.eos()) {\n value = scanner.scanUntil(tagRes[0]);\n\n if (value) {\n for (var i = 0, len = value.length; i < len; ++i) {\n chr = value.charAt(i);\n\n if (isWhitespace(chr)) {\n spaces.push(tokens.length);\n } else {\n nonSpace = true;\n }\n\n tokens.push({type: \"text\", value: chr});\n\n if (chr === \"\\n\") {\n stripSpace(); // Check for whitespace on the current line.\n }\n }\n }\n\n // Match the opening tag.\n if (!scanner.scan(tagRes[0])) {\n break;\n }\n\n hasTag = true;\n type = scanner.scan(tagRe) || \"name\";\n\n // Skip any whitespace between tag and value.\n scanner.scan(whiteRe);\n\n // Extract the tag value.\n if (type === \"=\") {\n value = scanner.scanUntil(eqRe);\n scanner.scan(eqRe);\n scanner.scanUntil(tagRes[1]);\n } else if (type === \"{\") {\n var closeRe = new RegExp(\"\\\\s*\" + escapeRe(\"}\" + tags[1]));\n value = scanner.scanUntil(closeRe);\n scanner.scan(curlyRe);\n scanner.scanUntil(tagRes[1]);\n } else {\n value = scanner.scanUntil(tagRes[1]);\n }\n\n // Match the closing tag.\n if (!scanner.scan(tagRes[1])) {\n throw new Error(\"Unclosed tag at \" + scanner.pos);\n }\n\n tokens.push({type: type, value: value});\n\n if (type === \"name\" || type === \"{\" || type === \"&\") {\n nonSpace = true;\n }\n\n // Set the tags for the next time around.\n if (type === \"=\") {\n tags = value.split(spaceRe);\n tagRes = escapeTags(tags);\n }\n }\n\n squashTokens(tokens);\n\n return nestTokens(tokens);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the toplevel node that contains the node before this one.
function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) { node = node.parentNode; } return topLevelNodeAt(node.previousSibling, top); }
[ "function topLevelNodeBefore(node, top) {\n while (!node.previousSibling && node.parentNode != top)\n node = node.parentNode;\n return topLevelNodeAt(node.previousSibling, top);\n }", "get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }", "nodeBefore(up) {\n var newNode, node;\n node = this.node;\n while (node) {\n if (node.nodeType === node.ELEMENT_NODE && !up && node.childNodes.length) {\n newNode = node.childNodes[node.childNodes.length - 1];\n } else if (node.previousSibling) {\n newNode = node.previousSibling;\n } else {\n up = true;\n node = node.parentNode;\n continue;\n }\n return this.newPos(newNode, newNode.length);\n }\n return this.emptyPrev();\n }", "_findPrev() {\r\n var node = this.parent._head;\r\n if (node == this)\r\n return null;\r\n while (node._next !== this)\r\n node = node._next;\r\n return node;\r\n }", "before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }", "previousSibling() {\n var siblings = this._containers.top(); // If we're at the root of the tree or if the parent is an\n // object instead of an array, then there are no siblings.\n\n\n if (!siblings || !Array.isArray(siblings)) {\n return null;\n } // The top index is a number because the top container is an array\n\n\n var index = this._indexes.top();\n\n if (index > 0) {\n return siblings[index - 1];\n } else {\n return null; // There is no previous sibling\n }\n }", "function tree_getPrecedingNode(root, node) {\n if (node === root) {\n return null;\n }\n if (node._previousSibling) {\n node = node._previousSibling;\n if (node._lastChild) {\n return node._lastChild;\n }\n else {\n return node;\n }\n }\n else {\n return node._parent;\n }\n}", "prev() {\n var i;\n i = this.parent.children.indexOf(this);\n if (i < 1) {\n throw new Error(\"Already at the first node. \" + this.debugInfo());\n }\n return this.parent.children[i - 1];\n }", "function findNodeBefore(node, pos, test, base, state) {\n test = makeTest(test)\n if (!base) base = exports.base\n var max\n ;(function c(node, st, override) {\n if (node.start > pos) return\n var type = override || node.type\n if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))\n max = new Found(node, st)\n base[type](node, st, c)\n })(node, state)\n return max\n }", "function findFirstNodeAbove(node, callback) {\n let current = node;\n while (current.parent) {\n if (callback(current.parent)) {\n return current.parent;\n }\n else {\n current = current.parent;\n }\n }\n}", "function findNodeBefore(node, pos, test, baseVisitor, state) {\n test = makeTest(test);\n if (!baseVisitor) { baseVisitor = base; }\n var max\n ;(function c(node, st, override) {\n if (node.start > pos) { return }\n var type = override || node.type;\n if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))\n { max = new Found(node, st); }\n baseVisitor[type](node, st, c);\n })(node, state);\n return max\n }", "function getNodeAbove(subtree){\n var par = subtree.parent;\n for (var i = 1; i < par.children.length; ++i){\n if (par.children[i] === subtree) {\n return par.children[i-1];\n }\n }\n}", "function findPrevRowNode(node) {\n\t\tvar i,\n\t\t\tlast,\n\t\t\tprev,\n\t\t\tparent = node.parent,\n\t\t\tsiblings = parent ? parent.children : null;\n\n\t\tif (siblings && siblings.length > 1 && siblings[0] !== node) {\n\t\t\t// use the lowest descendant of the preceeding sibling\n\t\t\ti = $.inArray(node, siblings);\n\t\t\tprev = siblings[i - 1];\n\t\t\t_assert(prev.tr);\n\t\t\t// descend to lowest child (with a <tr> tag)\n\t\t\twhile (prev.children && prev.children.length) {\n\t\t\t\tlast = prev.children[prev.children.length - 1];\n\t\t\t\tif (!last.tr) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprev = last;\n\t\t\t}\n\t\t} else {\n\t\t\t// if there is no preceding sibling, use the direct parent\n\t\t\tprev = parent;\n\t\t}\n\t\treturn prev;\n\t}", "function findPrevRowNode(node){\n\tvar i, last, prev,\n\t\tparent = node.parent,\n\t\tsiblings = parent ? parent.children : null;\n\n\tif(siblings && siblings.length > 1 && siblings[0] !== node){\n\t\t// use the lowest descendant of the preceeding sibling\n\t\ti = $.inArray(node, siblings);\n\t\tprev = siblings[i - 1];\n\t\t_assert(prev.tr);\n\t\t// descend to lowest child (with a <tr> tag)\n\t\twhile(prev.children){\n\t\t\tlast = prev.children[prev.children.length - 1];\n\t\t\tif(!last.tr){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev = last;\n\t\t}\n\t}else{\n\t\t// if there is no preceding sibling, use the direct parent\n\t\tprev = parent;\n\t}\n\treturn prev;\n}", "function getInlineElementBefore(root, position) {\n return getInlineElementBeforeAfter(root, position, false /*isAfter*/);\n}", "function topLevelNodeAt(node, top) {\n while (node && node.parentNode != top)\n node = node.parentNode;\n return node;\n }", "getPreviousNode() {\r\n if (this.position.previous !== null) {\r\n this.position = this.position.previous;\r\n return this.position;\r\n } else {\r\n return this.position;\r\n }\r\n \t}", "function TreeNode_getChildBefore(aChild) {\n if (debug) alert(\"TreeNode@\"+this.identifier+\".getChildBefore(\"+aChild+\"@\"+aChild.identifier+\")\");\n\tvar index = this.getIndex(aChild);\t\t// linear search\n\t/*\n\tif (index == -1) {\n\t\tthrow new IllegalArgumentException(\"argument is not a child\");\n\t}\n\t*/\n\tif (index > 0) {\n\t\treturn this.getChildAt(index - 1);\n\t} else {\n\t\treturn null;\n\t}\n}", "childBefore(pos) { return this.enter(-1, pos); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the helper method to validate the length of gRPC match array when it is specified.
function validateGrpcMatchArrayLength(metadata) { const MIN_LENGTH = 1; const MAX_LENGTH = 10; if (metadata && (metadata.length < MIN_LENGTH || metadata.length > MAX_LENGTH)) { throw new Error(`Number of metadata provided for matching must be between ${MIN_LENGTH} and ${MAX_LENGTH}, got: ${metadata.length}`); } }
[ "function validateHttpMatchArrayLength(headers, queryParameters) {\n const MIN_LENGTH = 1;\n const MAX_LENGTH = 10;\n if (headers && (headers.length < MIN_LENGTH || headers.length > MAX_LENGTH)) {\n throw new Error(`Number of headers provided for matching must be between ${MIN_LENGTH} and ${MAX_LENGTH}, got: ${headers.length}`);\n }\n if (queryParameters && (queryParameters.length < MIN_LENGTH || queryParameters.length > MAX_LENGTH)) {\n throw new Error(`Number of query parameters provided for matching must be between ${MIN_LENGTH} and ${MAX_LENGTH}, got: ${queryParameters.length}`);\n }\n}", "validateArraySize (req, array) {\n const FREEMIUM_INPUT_SIZE = 20\n const PRO_INPUT_SIZE = 20\n\n if (req.locals && req.locals.proLimit) {\n if (array.length <= PRO_INPUT_SIZE) return true\n } else if (array.length <= FREEMIUM_INPUT_SIZE) {\n return true\n }\n\n return false\n }", "function checkArrayLength(array) {\n return array.length;\n}", "static validateArrayLengths(data, minLength, maxLength, localName) {\n let valid = true;\n let invalidFields = {};\n\n // Set defaults.\n minLength = minLength || 0;\n maxLength = maxLength || Infinity;\n\n data.forEach(element => {\n if (Validator.isNullOrUndefined(element.length)) {\n valid = false;\n\n invalidFields[element] = {\n received: \"No Length\",\n expected: [minLength, maxLength]\n };\n }\n else {\n let elementLength = element.length;\n\n if (elementLength < minLength || elementLength > maxLength) {\n valid = false;\n\n invalidFields[element] = {\n received: elementLength,\n expected: [minLength, maxLength]\n };\n }\n }\n });\n\n return {\n valid: valid,\n invalidFields: Validator.isEmptyObject(invalidFields) ? null : invalidFields,\n localName: localName,\n validationCode: VALIDATION_CODES.VALIDATE_ARRAY_LENGTHS\n };\n }", "checkArrayLength(variable, variable_name, length){\n\t\tthis.checkArrayLength(variable, variable_name, length, length);\n\t}", "function checkRequiredParams(argsLength, requiredLength) {\n if (argsLength - 1 < requiredLength) {\n return false;\n }\n\n return true;\n}", "function mustLen(arg, len, maxLen) {\n if (!Array.isArray(arg)) {\n throw `Expected array of length ${len}, got ${arg}`;\n }\n else if (maxLen === undefined && arg.length !== len) {\n throw `Expected array of length ${len}, got length ${arg.length} (${arg})`;\n }\n else if (maxLen !== undefined && (arg.length < len || arg.length > maxLen)) {\n throw `Expected array of length ${len}-${maxLen}, got length ${arg.length} (${arg})`;\n }\n else {\n return arg;\n }\n}", "function checkArrayTypeAndLength(x, expectedType, minLength, maxLength) {\n if (minLength === void 0) {\n minLength = 0;\n }\n if (maxLength === void 0) {\n maxLength = Infinity;\n }\n assert$1(minLength >= 0);\n assert$1(maxLength >= minLength);\n return Array.isArray(x) && x.length >= minLength && x.length <= maxLength && x.every(function (e) {\n return typeof e === expectedType;\n });\n}", "function checkArrayTypeAndLength(x, expectedType, minLength, maxLength) {\n if (minLength === void 0) { minLength = 0; }\n if (maxLength === void 0) { maxLength = Infinity; }\n assert(minLength >= 0);\n assert(maxLength >= minLength);\n return (Array.isArray(x) && x.length >= minLength && x.length <= maxLength &&\n x.every(function (e) { return typeof e === expectedType; }));\n}", "function validateNamedArrayAtLeastNumberOfElements(functionName,value,name,minNumberOfElements){if(!(value instanceof Array)||value.length<minNumberOfElements){throw new FirestoreError(Code.INVALID_ARGUMENT,\"Function \"+functionName+\"() requires its \"+name+\" argument to be an \"+'array with at least '+(formatPlural(minNumberOfElements,'element')+\".\"));}}", "static validateArray(array) {\n return Array.isArray(array);\n }", "checkArrayLength(variable, variable_name, min, max){\n\t\tif(min == max){\n\t\t\tif(variable.length!=min){\n\t\t\t\tvar msg = [this.ExceptionHeader()+\"'\"+variable_name+\"' must have a length of \" + min + \" but was \" + variable.length +\"!\"];\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\telse{\n\t\t\tif(variable.length<min || variable.length > max){\n\t\t\t\tvar msg = [this.ExceptionHeader()+\"'\"+variable_name+\"' must have a length between \" + min + \" and \" + max + \" but was \" + variable.length +\"!\"];\t\t\n\t\t\t\tthis.ThrowException(msg);\n\t\t\t}\n\t\t\n\t\t}\n\t\t\n\t}", "function jcv_verifyArrayElement(name, element) {\n if (element && element.length && element.length >= 2) {\n return true;\n } else {\n return false;\n }\n}", "function arrayValidator() {\n for (i = 0; i < playerArray.length; i++) {\n if (playerArray[i] != gameArray[i]) {\n return false;\n };\n };\n return true;\n }", "validatorSize (value, args) {\n this._requireParameterCount(1, args, 'size')\n\n let length = parseInt(args[0])\n\n if (typeof value === 'string' || value instanceof Array) {\n return value.length === length\n } else if (typeof value === 'number') {\n return value === length\n } else {\n return false\n }\n }", "function checkArrayTypeAndLength(x, expectedType, minLength = 0, maxLength = Infinity) {\n assert(minLength >= 0);\n assert(maxLength >= minLength);\n return (Array.isArray(x) && x.length >= minLength && x.length <= maxLength &&\n x.every(e => typeof e === expectedType));\n}", "function isValidArray(obj, minLength) {\n\t\treturn (Object.prototype.toString.call(obj) === '[object Array]' && obj.length >= minLength);\n\t}", "function validateMatch(text, match) {\n return match && match[0].length === text.length;\n }", "function isValid(arr) {\n\t\tif (arr.length == 2)\n\t\t\treturn _.uniq(arr[0].concat(arr[1])).length == 9;\n\t\treturn _.uniq(arr[0].concat(arr[1]).concat(arr[2])).length == 9;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the button grid
function initButtonGrid() { const buttons = document.querySelectorAll(".button-grid div"); buttons.forEach( button => { button.style.gridArea = button.id; // Set grid placement button.classList.add("button"); // Add button class button.classList.add(keys[keyIndexById(button.id)].type); // Add respective type class button.addEventListener("mousedown",mouseDown); // Add event listener for mouse input button.addEventListener("mouseup",mouseUp); // Add event listener for mouse input }); }
[ "function initButtons(){\n const createBtn = document.getElementById('Create');\n createBtn.addEventListener('click',updateGrid);\n const resetBtn = document.getElementById('Reset');\n resetBtn.addEventListener('click',resetGrid);\n}", "init() {\n this.prepareGrid();\n this.configureCells();\n }", "function buttonStyleSetup(){\n buttons.forEach(button => {\n button.style.gridArea = button.id;\n button.addEventListener('click', buttonClicked);\n });\n}", "function initBtns(){\n okbtn = {\n x: (width - s_buttons.Ok.width)/2,\n y : height/1.8,\n width : s_buttons.Ok.width,\n height :s_buttons.Ok.height\n };\n \n startbtn = {\n x: (width - s_buttons.Score.width)/2,\n y : height/2.5,\n width : s_buttons.Score.width,\n height :s_buttons.Score.height\n };\n \n scorebtn = {\n x: (width - s_buttons.Score.width)/2,\n y : height/2,\n width : s_buttons.Score.width,\n height :s_buttons.Score.height\n };\n \n menubtn = {\n x:(width - 2*s_buttons.Menu.width),\n y : height/1.8,\n width : s_buttons.Menu.width,\n height :s_buttons.Menu.height\n };\n \n resetbtn = {\n x: (s_buttons.Reset.width),\n y : height/1.8,\n width : s_buttons.Reset.width,\n height :s_buttons.Reset.height\n };\n}", "function initializeButtons() {\n var curDim = 3;\n for (let r = 0; r < BUTTON_ROW_COUNT; r++) {\n buttons[r] = [];\n for (let c = 0; c < BUTTON_COL_COUNT; c++) {\n buttonPadding = BUTTON_WIDTH / 2;\n buttonOffsetLeft = (ctx.canvas.width - ((BUTTON_COL_COUNT * BUTTON_WIDTH) + ((BUTTON_COL_COUNT - 1) * buttonPadding))) / 2;\n buttonOffsetTop = (ctx.canvas.height - ((BUTTON_ROW_COUNT * BUTTON_HEIGHT) + ((BUTTON_ROW_COUNT - 1) * buttonPadding))) / 2;\n var buttonX = c * (BUTTON_WIDTH + buttonPadding) + buttonOffsetLeft;\n var buttonY = r * (BUTTON_HEIGHT + buttonPadding) + buttonOffsetTop;\n var buttonText = curDim + \" x \" + curDim;\n buttons[r][c] = new interect(buttonX, buttonY, BUTTON_WIDTH, BUTTON_HEIGHT, \"center\", buttonText, buttonStyle, curDim++);\n }\n }\n}", "init() {\n this.Buttons.init()\n this.Gui.init()\n }", "function initilaizeButtons() {\n for (let i = 0; i < imageSrcArray.length; i++) {\n createButton(imageSrcArray[i]);\n }\n }", "function init_buttons(){\n // Updates all of the logging buttons.\n CROWDLOGGER.gui.buttons.update_logging_buttons();\n }", "function btngrid (buttons_info, template) {\n var content = [];\n for (var i = 0; i < buttons_info.length; i++) {\n var buttonspec = buttons_info[i];\n if (buttonspec != null) {\n var args = {};\n for (var key in template) {\n args[key] = template[key];\n }\n if (buttonspec instanceof Object) {\n for (var key in buttonspec) {\n args[key] = buttonspec[key];\n }\n var label = buttonspec.label;\n } else {\n var label = buttonspec;\n }\n var button = make_button(label, args);\n if (args.selected) {\n button.setStatus('selected');\n }\n } else {\n var button = null;\n }\n content.push(button); \n }\n return content;\n}", "function initialButtons() {\n var autoButtons = ['magical', 'robot', 'unicorn', 'javascript', 'python', 'Node Js', 'Linux', 'Oregon'];\n\n for (var i =0; i < autoButtons.length; i++){\n createButton(autoButtons[i]);\n }\n}", "createButtons() {\n this.settingsButton = this._createConnectionButton(TEXTURE_NAME_SETTINGS);\n this.deleteButton = this._createConnectionButton(TEXTURE_NAME_DELETE);\n }", "function initializeButtons() {\n // Loops through the array of topics and makes a button for each\n for (var i = 0; i < topics.length; i++) {\n makeButton( topics[i] );\n }\n}", "function initCanvasButtons ()\n{\n\t//Event to remove the color pickers if the user clicks on one canvas\n\tdocument.getElementById(\"graphAngWebGL\").onclick = function()\n\t{\n\t\tvar color_picker = document.getElementsByClassName(\"jscolor-picker-wrap\");\n\n\t\tif(color_picker.length != 0)\n\t\t{\n\t\t\ttimes_clicked++;\n\n\t\t\t//For avoid that the first time that is clicked automatically hide the color picker\n\t\t\tif(times_clicked%2 == 0)\n\t\t\t\tjscolor.hide();\n\t\t}\n\t}\n\n\tdocument.getElementById(\"backgroundColorIcon\").onclick = function()\n\t{\n\t\ttimes_clicked = 0;\n\t}\n\n\tdocument.getElementById(\"pickerGrid\").onclick = function()\n\t{\n\t\ttimes_clicked = 0;\n\t}\n\n\tdocument.getElementById(\"pickerLine\").onclick = function()\n\t{\n\t\ttimes_clicked = 0;\n\t}\n\n\tc_buttonGrid = document.getElementById(\"gridIcon\");\n\tc_buttonLine = document.getElementById(\"lineIcon\");\n\n\tc_buttonGrid.onclick = function()\n\t{\n\t\tshowGrid = !showGrid;\n\n\t\tif(showGrid)\n\t\t\tc_buttonGrid.className = \"icon icon-selected\";\n\t\telse\n\t\t\tc_buttonGrid.className = \"icon\";\n\t}\n\n\tc_buttonLine.onclick = function()\n\t{\n\t\tshowLines = !showLines;\n\n\t\tif(showLines)\n\t\t\tc_buttonLine.className = \"icon icon-selected\";\n\t\telse\n\t\t\tc_buttonLine.className = \"icon\";\n\t}\n}", "prepareButtons () {\n\t\tif (!this.buttons.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (let i = 0; i < this.buttons.length; i++) {\n\t\t\tlet button = this.buttons[i];\n\n\t\t\tvenus.get(button.id).click(button.on_click);\n\t\t}\n\t}", "function _initButtonView() {\n\t$(model).on(model.EVENTS.INSERT_TOKEN, _showButtonViewState);\n\t$(model).on(model.EVENTS.GAME_OVER, _showButtonViewGameOver);\n}", "function setupButtons() {\n d3.selectAll('.btn-group')\n .selectAll('.btn')\n .on('click', function () {\n // set all buttons on the clicked toolbar as inactive, then activate the clicked button\n var p = d3.select(this.parentNode);\n p.selectAll('.btn').classed('active', false);\n d3.select(this).classed('active', true);\n\n // toggle\n if (p.attr('id')=='split_toolbar') {\n myBubbleChart.toggleDisplay();\n } else if (p.attr('id')=='color_toolbar') {\n myBubbleChart.toggleColor();\n } else if (p.attr('id')=='year_toolbar') {\n myBubbleChart.toggleYear();\n }\n });\n}", "function initButtons() {\n\n dialog.saveBtn.enabled = false;\n dialog.openBtn.enabled = false;\n\n if (Utils.trim(dialog.pageWidth.text) == \"\") return;\n if (Utils.trim(dialog.pageHeight.text) == \"\") return;\n if (Utils.trim(dialog.cols.text) == \"\") return;\n if (Utils.trim(dialog.rows.text) == \"\") return;\n if (Utils.trim(dialog.scale.text) == \"\") return;\n if (parseInt(dialog.pageWidth.text) < 10 ) return;\n if (parseInt(dialog.pageHeight.text) < 10 ) return;\n if (parseInt(dialog.cols.text) < 1 ) return;\n if (parseInt(dialog.rows.text) < 1 ) return;\n if (parseInt(dialog.scale.text) < 1 ) return;\n\n dialog.saveBtn.enabled = true;\n\n if (Utils.trim(dialog.filename.text) == \"\") return;\n if (Utils.trim(dialog.srcFolder.text) == \"\") return;\n\n var testFolder = new Folder(dialog.srcFolder.text);\n // if (! testFolder.exists) return;\n\n dialog.openBtn.enabled = true;\n }", "function initButtons() {\n const checkboxInputs = getEl('[type=\"checkbox\"]', true, listEl)\n const removeButtons = getEl('[data-btn=\"remove\"]', true, listEl)\n\n checkboxInputs.forEach(\n (input) => (input.onclick = (e) => handleClick(e, UPDATE))\n )\n\n removeButtons.forEach((btn) => (btn.onclick = (e) => handleClick(e, REMOVE)))\n}", "function createButtonArray() {\r\n buttons = new Array(button_grid_dimensions.rows);\r\n\r\n for (var i = 0; i < buttons.length; i++) {\r\n buttons[i] = new Array(button_grid_dimensions.cols);\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getFilterCars2(); / $eq $ne $gt $gte $lt $lte $in $nin
async function getFilterPriceCars(){ //Podemos Filtrar const cars = await Car //Buscamos los que tenga el precio 2000 justos //.find({price: 2000}) //Ahora buscamos entre 2000 y 10000 y el resto no los queremos. .find({price: {$gte: 2000, $lt: 10000}}) console.log(cars) }
[ "function searchFilterPipe(cars) {\n let search_query = document.getElementById(\"car_search_input\").value;\n\n let flt_cars = []\n console.log(\"Searchig for \", search_query)\n if (search_query == undefined || search_query == null || search_query == \"\" || search_query == \"undefined\") {\n return cars;\n } else {\n //do the filtering\n flt_cars = cars.filter((car) => {\n if (car.name.toLowerCase().includes(search_query.toLowerCase()) ||\n search_query.toLowerCase().includes(car.name.toLowerCase()) ||\n car.car_Type.toLowerCase().includes(search_query.toLowerCase() ||\n search_query.toLowerCase().includes(car.car_Type.toLowerCase()))) {\n return true;\n }\n })\n }\n\n return flt_cars;\n}", "getFilterCars(req, res) {\n try {\n const data = CarModel.findFilterCars(req.query.status, req.query.minPrice, req.query.maxPrice);\n return res.status(200).send({status: 200, data});\n } catch (error) {\n res.status(404).send({ status: 404, error: 'cannot find cars' });\n }\n }", "filterCars() {\n const filteredArray = [];\n CARS.forEach((car) => {\n this.filterModel(car, filteredArray);\n });\n this.sort(filteredArray);\n this.updateList(filteredArray);\n }", "function getFilteredCars(){\n Data.get('getCarsFiltered?'+$scope.filterText).then(function (results) {\n\n if(results.status == 200){\n //if the results has more thn one car\n $scope.cars = results.value;\n $scope.no_car = false;\n }else{\n //Create a few to show no cars available for applied filters\n $scope.cars =[];\n $scope.no_car = true;\n $scope.$apply;\n\n }\n $scope.loading = false;\n $scope.$apply;\n\n });\n }", "filterVehicles() {\n let nFilteredVehicles = angular.copy(this.vehicles);\n let activeFilters = this.filters;\n\n Object.keys(activeFilters).forEach(function(filterKey, index){\n let filterValue = activeFilters[filterKey];\n\n switch(filterKey) {\n case 'quickFilter':\n if ( filterValue === \"New Conversions\" || filterValue === \"Used Conversions\" ) {\n nFilteredVehicles = nFilteredVehicles.filter(function(element, index){\n return filterValue.indexOf(element.conversion_option) > -1;\n });\n } else if ( filterValue === \"Specials\" ) {\n nFilteredVehicles = nFilteredVehicles.filter(function(element, index) {\n return parseInt(element.current_discount) > 0;\n });\n }\n break;\n case 'stockNumber':\n nFilteredVehicles = nFilteredVehicles.filter(function(element, index){\n return element.name.indexOf(filterValue) > -1;\n });\n break;\n default:\n break;\n }\n\n });\n\n // Store the filteredVehicles in the singleton in case we need to access it later.\n this.filteredVehicles = angular.copy(nFilteredVehicles);\n\n return this.filteredVehicles;\n }", "function getFilteredCars(cars, price) {\n let filteredCars = [];\n\n for (let i = 0; i < cars.length; i++) {\n let currentPrice = parseInt(cars[i].price);\n\n if (!isNaN(currentPrice) && currentPrice <= price) {\n filteredCars.push(cars[i]);\n }\n }\n\n return filteredCars;\n}", "function genreFilter(query1,query2,query3){\n\n let genres = query1.split(\":\")[1];\n let ott_platform = query2.split(\":\")[1];\n let runtime = query3.split(\":\")[1];\n let query = { \"Genres\":genres, \"Runtime\" : { $lte : parseInt(runtime) } };\n query[ott_platform] = 1;\n console.log(query)\n methods.genre(query)\n console.log(\"done\")\n return \"success\";\n\n}", "filteredTravels() {\n return this.travels.filter(\n (travel) => {\n let filterContinentResult = true\n let filterDatesResult = true\n\n // Filter continent\n if (this.filterContinent !== \"\") {\n filterContinentResult = travel.continent === this.filterContinent\n }\n\n // Filter dates \n if (this.filterStartDate !== \"\" && this.filterEndDate !== \"\") {\n filterDatesResult =\n travel.startDate >= new Date(this.filterStartDate) &&\n travel.startDate <= new Date(this.filterEndDate)\n }\n\n // return the conjunction of the two filters\n return filterContinentResult && filterDatesResult\n\n }\n )\n }", "async function getFilteredCourses2() {\n const courses = await Course\n // .find({price: {$gt: 10}})\n // .find({price: {$gt: 10, $lte: 20}})\n .find({price: {$in: [10, 15, 20]}})\n .limit(10)\n .sort({name: 1})\n .select({name: 1, tags: 1});\n\n console.log(courses);\n}", "async function getCars({ filter: { search, dateRange, order, orderBy, ...filter }, pagination }) {\n try {\n let __cars = await modelManager.getDocuments({\n model: CarModel,\n search,\n dateRange,\n filter: { ...filter, isDeleted: false },\n order,\n orderBy,\n searchFields: ['make', 'model', 'description'],\n pagination,\n populate: '',\n });\n return __cars;\n } catch (err) {\n throw err;\n }\n}", "filteredCastles() {\n return this.castles.filter(\n (castle) => {\n let filterCastleResult = true\n if (this.form.filterName !== \"\") {\n filterCastleResult = castle.name.includes(this.form.filterName)\n }\n return filterCastleResult\n }\n )\n }", "filteredTravels() {\r\n return this.travels.filter(\r\n (travel) => {\r\n let filterContinentResult = true\r\n let filterDatesResult = true\r\n let filterTypeResult = true\r\n \r\n\r\n if(this.filterType !== \"\"){\r\n filterTypeResult = (travel.type === this.filterType) || (this.filterType == \"all\")\r\n }\r\n\r\n // Filter continent\r\n if(this.filterContinent!==\"\") {\r\n filterContinentResult = (travel.continent === this.filterContinent) || (this.filterContinent == \"all\") \r\n } \r\n\r\n // Filter dates \r\n if(this.filterStartDate!==\"\" && this.filterEndDate!==\"\") {\r\n filterDatesResult = \r\n travel.startDate >= new Date(this.filterStartDate) && \r\n travel.startDate <= new Date(this.filterEndDate)\r\n }\r\n \r\n \r\n \r\n // return the conjunction of the two filters\r\n return filterContinentResult && filterDatesResult && filterTypeResult\r\n\r\n \r\n\r\n }\r\n\r\n )\r\n\r\n \r\n }", "find_cars(field, retrieve, query) {\n const found = this.cars.filter(car => car[field] === query)\n .map(car => car[retrieve]);\n\n if (found.length !== 0) {\n console.log(found.join(', '));\n } else {\n console.log('Not found');\n }\n }", "salongsFilter(salongs, filters = {\n price: {\n start: '',\n end: ''\n },\n type: {\n text: ''\n }\n }) {\n let salongsTemp = salongs;\n\n // Filter on price\n if(filters.price.start !== '') {\n salongsTemp = _.filter(salongs, (o) => { \n return (o.price >= filters.price.start && o.price <= filters.price.end);\n });\n }\n\n // Filter on type\n if(filters.type.text !== '') {\n salongsTemp = _.filter(salongsTemp, (t) => { \n return (t.types.indexOf(filters.type.text) > -1);\n });\n }\n\n return salongsTemp;\n }", "async filterArticles(data, query) {\n return data.filter(\n (item) => {\n for (let key in query) {\n switch (key) {\n case 'brand_id': // Filter by brand id\n return (item.sneaker.brand_id === Number(query.brand_id));\n default:\n return !(item[key] === undefined || item[key] != query[key])\n }\n }\n return true\n }\n )\n }", "filterBySearchTermRange(fieldName, operator, searchTerms) {\n let query = '';\n if (Array.isArray(searchTerms) && searchTerms.length === 2) {\n if (operator === OperatorType.rangeInclusive) {\n // example:: (Duration >= 5 and Duration <= 10)\n query = `(${fieldName} ge ${searchTerms[0]} and ${fieldName} le ${searchTerms[1]})`;\n }\n else if (operator === OperatorType.rangeExclusive) {\n // example:: (Duration > 5 and Duration < 10)\n query = `(${fieldName} gt ${searchTerms[0]} and ${fieldName} lt ${searchTerms[1]})`;\n }\n }\n return query;\n }", "function filter_cars_by_loc_and_day(location, day) {\n //get all the cars\n let cars = JSON.parse(JSON.stringify(sc_get_cars()));\n let unavailable_cars = [];\n\n let filtered_cars = cars.filter(function (car) {\n //compare the location\n if (car.location.toLowerCase() == location.toLowerCase()) {\n\n if (car.availability != undefined && car.availability != null) {\n let avl_days = car.availability.replace(/\\s/g, \"\").split(\",\")\n if (avl_days != null) {\n //check if the car available for that day\n let is_day_found = avl_days.find((aval_day) => {\n if (aval_day.toLowerCase() == day.toLowerCase()) {\n return true;\n }\n })\n if (is_day_found != undefined && is_day_found != null) {\n return true;\n } else {\n push_to_unavailable(car)\n false;\n }\n } else {\n push_to_unavailable(car)\n false;\n }\n } else {\n push_to_unavailable(car)\n return false;\n }\n } else {\n return false;\n }\n });\n\n /**\n * push the car to unavailable cars array\n */\n function push_to_unavailable(car) {\n car.is_available = false;\n unavailable_cars.push(car)\n }\n\n //make single array\n let all_cars = filtered_cars.concat(unavailable_cars);\n\n console.log(\"filtered cars on submit \", filtered_cars)\n console.log(\"unavailable cars \", unavailable_cars)\n console.log(\"All cars\", all_cars)\n\n return all_cars;\n}", "filter(field, condition, value) {\n if (condition === \"eq\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] === value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"neq\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] !== value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"gt\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] > value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"lt\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] < value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"eqgt\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] >= value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"eqlt\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field] <= value;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"like\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field].indexOf(value) > -1;\n });\n return new JSONQuery(filteredJson);\n }\n else if (condition === \"ilike\") {\n let filteredJson = this.json.filter(entry => {\n return entry[field].toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) > -1;\n });\n return new JSONQuery(filteredJson);\n }\n }", "function filter_cars(){\n\t\t\t\n\t\t$('#controls input[name=\"curr\"]').val('filter');\n\t\t\t\t\n\t\trefresh_cars();\t\n\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=================================================================== from vm/interpreter/qq/UnquoteSplicing.java ===================================================================
function UnquoteSplicing() { }
[ "function Unquote() {\r\n}", "get BackQuote() {}", "unscramble(s) {\n let r = '', p;\n\n while (s.length > 51){\n p = s.substring(0, 50);\n s = s.substring(50);\n r = r + this.obfusc50(p);\n }\n r = r + s;\n // now undo substitution obfuscation\n r = r.replace(/Kcl/g, '| x').replace(/LZ/g, ' |').replace(/XyQ/g, ' ');\n return r;\n }", "static unquote(s, position = 0) {\n // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string\n QUOTED_STRING.lastIndex = position;\n const [match, content, trailer] = QUOTED_STRING.exec(s) ?? [];\n assert(String(match).startsWith('\"'));\n\n return {\n value: content.replace(ESCAPED_CHAR, '$1') + (trailer ?? ''),\n next: position + match.length,\n };\n }", "function FixTokens(x) {\n\tvar r = [];\n\t// Bind quantifiers\n\t// Add application operators\n\tfor (var i = 0; i < x.length; i++) {\n\t\tif (isQuantifier(x[i-1])) {\n\t\t\t// [\"all\", \"x\"] --> [\"all_x\"]\n\t\t\t// [\"all\", \"x\", \",\"] --> [\"all_x\"]\n\t\t\tr[r.length-1] += \"_\" + x[i];\n\t\t\tif (x[i+1] === \",\") {\n\t\t\t\ti++;\n\t\t\t}\n\t\t} else {\n\t\t\t// [\"name\", \"(\"] --> [\"name\", \".\", \"(\"]\n\t\t\tif (x[i] === \"(\" && x[i-1] && isLetter(x[i-1][0]) ) {\n\t\t\t\tr.push(\".\");\n\t\t\t}\n\t\t\tr.push(x[i]);\n\t\t}\n\t}\n\t// Removes parenthesis around bound quantifiers\n\t// [\"(\", \"quant_x\", \")\"] --> [\"quant_x\"]\n\tfor (var i = 1; i+1 < r.length; i++) {\n\t\tif (r[i-1] === \"(\" && r[i+1] === \")\" && r[i].indexOf(\"_\") >= 0) {\n\t\t\tr.splice(i+1, 1);\n\t\t\tr.splice(i-1, 1);\n\t\t\t//r = r.slice(0, i - 1).concat([ r[i] ]).concat(r.slice(i + 2));\n\t\t}\n\t}\n\tfor (var i = 0; i < r.length; i++) {\n\t\tif (i === 0 || getPrecedence(r[i-1]) || r[i-1] === \"(\") {\n\t\t\tif (r[i] === \"-\") {\n\t\t\t\tr[i] = \"-u\";\n\t\t\t}\n\t\t}\n\t}\n\treturn r;\n}", "function pseudoQuote (args) { return makeFunction ('quote', args, true) }", "segment() {\n let tmp = [];\n let out = [];\n for(let i=0; i<this.exp.length; i++) {\n if(['+','-','*','/','(',')','#'].indexOf(this.exp[i])>-1) {\n if(tmp.length>0) {\n out.push(tmp.join(''));\n tmp.length = 0;\n }\n out.push(this.exp[i])\n } else {\n tmp.push(this.exp[i]);\n }\n }\n if(tmp.length>0) {\n out.push(tmp.join(''));\n }\n this.expSeg = out;\n this.exp = this.expSeg.join('');\n return this;\n }", "handleSupSubscript(name){const symbolToken=this.nextToken;const symbol=symbolToken.text;this.consume();this.consumeSpaces();// ignore spaces before sup/subscript argument\nconst group=this.parseGroup(name,false,Parser.SUPSUB_GREEDINESS);if(!group){throw new ParseError(\"Expected group after '\"+symbol+\"'\",symbolToken);}return group;}", "_parseSubscriptList() {\n const argList = [];\n let sawKeywordArg = false;\n let trailingComma = false;\n while (true) {\n const firstToken = this._peekToken();\n if (firstToken.type !== 10 && this._isNextTokenNeverExpression()) {\n break;\n }\n let argType = 0;\n if (this._consumeTokenIfOperator(\n 26\n /* Multiply */\n )) {\n argType = 1;\n } else if (this._consumeTokenIfOperator(\n 29\n /* Power */\n )) {\n argType = 2;\n }\n const startOfSubscriptIndex = this._tokenIndex;\n let valueExpr = this._parsePossibleSlice();\n let nameIdentifier;\n if (argType === 0) {\n if (this._consumeTokenIfOperator(\n 2\n /* Assign */\n )) {\n const nameExpr = valueExpr;\n valueExpr = this._parsePossibleSlice();\n if (nameExpr.nodeType === 38) {\n nameIdentifier = nameExpr.token;\n } else {\n this._addError(localize_1.Localizer.Diagnostic.expectedParamName(), nameExpr);\n }\n } else if (valueExpr.nodeType === 38 && this._peekOperatorType() === 35) {\n this._tokenIndex = startOfSubscriptIndex;\n valueExpr = this._parseTestExpression(\n /* allowAssignmentExpression */\n true\n );\n if (!this._parseOptions.isStubFile && this._getLanguageVersion() < pythonVersion_1.PythonVersion.V3_10) {\n this._addError(localize_1.Localizer.Diagnostic.assignmentExprInSubscript(), valueExpr);\n }\n }\n }\n const argNode = parseNodes_1.ArgumentNode.create(firstToken, valueExpr, argType);\n if (nameIdentifier) {\n argNode.name = parseNodes_1.NameNode.create(nameIdentifier);\n argNode.name.parent = argNode;\n }\n if (argNode.name) {\n sawKeywordArg = true;\n } else if (sawKeywordArg && argNode.argumentCategory === 0) {\n this._addError(localize_1.Localizer.Diagnostic.positionArgAfterNamedArg(), argNode);\n }\n argList.push(argNode);\n if (argNode.name) {\n this._addError(localize_1.Localizer.Diagnostic.keywordSubscriptIllegal(), argNode.name);\n }\n if (argType !== 0) {\n const unpackListAllowed = this._parseOptions.isStubFile || this._isParsingQuotedText || this._getLanguageVersion() >= pythonVersion_1.PythonVersion.V3_11;\n if (argType === 1 && !unpackListAllowed) {\n this._addError(localize_1.Localizer.Diagnostic.unpackedSubscriptIllegal(), argNode);\n }\n if (argType === 2) {\n this._addError(localize_1.Localizer.Diagnostic.unpackedDictSubscriptIllegal(), argNode);\n }\n }\n if (!this._consumeTokenIfType(\n 12\n /* Comma */\n )) {\n trailingComma = false;\n break;\n }\n trailingComma = true;\n }\n if (argList.length === 0) {\n const errorNode = this._handleExpressionParseError(\n 3,\n localize_1.Localizer.Diagnostic.expectedSliceIndex(),\n /* targetToken */\n void 0,\n /* childNode */\n void 0,\n [\n 16\n /* CloseBracket */\n ]\n );\n argList.push(parseNodes_1.ArgumentNode.create(\n this._peekToken(),\n errorNode,\n 0\n /* Simple */\n ));\n }\n return {\n list: argList,\n trailingComma\n };\n }", "function parseQuasiQuotedItem(sexp, depth) {\n\t if (isCons(sexp) && sexp[0].val === 'unquote') {\n\t return parseUnquoteExpr(sexp, depth);\n\t } else if (isCons(sexp) && sexp[0].val === 'unquote-splicing') {\n\t return parseUnquoteSplicingExpr(sexp, depth);\n\t } else if (isCons(sexp) && sexp[0].val === 'quasiquote') {\n\t return parseQuasiQuotedExpr(sexp, depth);\n\t } else if (isCons(sexp)) {\n\t var res = sexp.map(function (x) {\n\t return parseQuasiQuotedItem(x, depth);\n\t });\n\t res.location = sexp.location;\n\t return res;\n\t } else if (depth === 0) {\n\t return parseExpr(sexp);\n\t } else {\n\t return function () {\n\t var res = new structures.quotedExpr(sexp);\n\t res.location = sexp.location;\n\t return res;\n\t }();\n\t }\n\t }", "function parenthesesSplicer(innerParenthesesStart, innerParenthesesEnd, numResult) {\n var difference = (innerParenthesesEnd - innerParenthesesStart) + 1\n calcArray.splice(innerParenthesesStart, difference, numResult);\n if (calcArray.includes(\"(\" || \")\")) {\n parentheses(calcArray)\n }\n}", "function unpack() { // ( x a -- n )\n var string = s[sp--] ; // string\n w = string.length ; // string len\n tos += w ; // last dest address + 1\n for (var i=w; i; m[--tos]=string.charCodeAt(--i) ) {} ;\n tos = w ;\n}", "function test_joinToString(){\nvar $j=m$1.tpl$([1,2,3]);\nm$1.print(joinToString($j,undefined,undefined,undefined,{Item$joinToString:{t:m$1.Integer}}));\nm$1.print(($k=$j,$l=\"(\",$m=\")\",joinToString($k,undefined,$l,$m,{Item$joinToString:{t:m$1.Integer}})));\nvar $k,$l,$m;\nm$1.print(($n=$j,$o=\"; \",$p=\"(\",$q=\")\",joinToString($n,$o,$p,$q,{Item$joinToString:{t:m$1.Integer}})));\nvar $n,$o,$p,$q;\n}", "function unpack() { // ( x a -- n )\n const string = s[sp--]; // string\n w = string.length; // string len\n tos += w; // last dest address + 1\n for (let i = w; i; m[--tos] = string.charCodeAt(--i)) {}\n tos = w;\n}", "function unquote(token) {\n return token[1].replace(new RegExp('^' + token[1][0]), '').replace(new RegExp(token[1][0] + '$'), '');\n}", "function parseQuasiQuotedItem(sexp, depth) {\n\t if (isCons(sexp) && sexp[0].val === 'unquote') {\n\t return parseUnquoteExpr(sexp, depth);\n\t } else if (isCons(sexp) && sexp[0].val === 'unquote-splicing') {\n\t return parseUnquoteSplicingExpr(sexp, depth);\n\t } else if (isCons(sexp) && sexp[0].val === 'quasiquote') {\n\t return parseQuasiQuotedExpr(sexp, depth);\n\t } else if (isCons(sexp)) {\n\t var res = sexp.map(function (x) {\n\t return parseQuasiQuotedItem(x, depth);\n\t });\n\t res.location = sexp.location;\n\t return res;\n\t } else if (depth === 0) {\n\t return parseExpr(sexp);\n\t } else {\n\t return function () {\n\t var res = new _structures.quotedExpr(sexp);\n\t res.location = sexp.location;\n\t return res;\n\t }();\n\t }\n\t}", "function extractFromParanthesis (eq2) {\n var res = [];\n var seperators = [];\n var tempSep = [];\n var pCnt = 0;\n var pStart = 0;\n var inside = false;\n var tmpPos = true;\n var i, j;\n var eq = String(eq2).replace(/\\s/g, \"\"); //removes whitespace - could do this at the very beginning\n // eq = eq.replace(/\\s/g, \"\"); \n if (!eq.includes('(')) return [[eq], \"\"];\n for (i=0; i<eq.length; i++) {\n if (eq[i] == '(') {\n if (pCnt == 0) pStart = i;\n pCnt = pCnt+1;\n inside = true;\n for (j=0; j<tempSep.length; j++) if (tempSep[j]=='-') tmpPos = !tmpPos; //go through all the signs between parenthesis, determine final sign\n if (tmpPos) seperators.push(\"+\");\n else seperators.push(\"-\");\n tempSep = [];\n tmpPos = true;\n } \n else if ((eq[i] == ')')) {\n if (pCnt == 1) {\n res.push(eq.substring(pStart+1,i));\n inside = false;\n // if (i!=(eq.length-1)) seperators.push(eq.substring(i+1,i+2))\n }\n pCnt = pCnt - 1;\n } else if (!inside) tempSep.push(eq.substring(i,i+1))\n }\n return [res, seperators];\n}", "visitSubstrFunctionCall(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function prefix_v(id_, bp) {\n prefix(id_, bp); // init as prefix op;\n\n function toJS() {\n r = '';\n r += this.get(\"value\");\n r += this.space();\n r += this.children[0].toJS();\n return r;\n }\n symbol(id_).toJS = toJS;\n\nfunction preinfix(id_, bp) { // pre-/infix operators (+, -);\n infix(id_, bp); // init as infix op;\n\n ////;\n // give them a pfix() for prefix pos;\n function pfix() {\n this.set(\"left\", \"true\"); // mark prefix position;\n this.childappend(expression(130)); // need to use prefix rbp!;\n return this;\n }\n symbol(id_).pfix = pfix;\n\n function toJS() { // need to handle pre/infix cases;\n r = [];\n first = this.children[0].toJS();\n op = this.get(\"value\");\n prefix = this.get(\"left\", 0);\n if (prefix && prefix == \"true\") {\n r = [op, first];\n } else {\n second = this.children[1].toJS();\n r = [first, op, second];\n }\n return r.join('');\n }\n symbol(id_).toJS = toJS;\n\n/*\n function toListG() {\n prefix = this.get(\"left\",0);\n if (prefix && prefix == 'true') {\n r = [[this], this.children[0].toListG()];\n } else {\n r = [this.children[0].toListG(), [this], this.children[1].toListG()];\n }\n _.concat(*r.forEach(function (e) {\n return e;\n });\n }\n*/\n// symbol(id_).toListG = toListG;\n\n\nfunction prepostfix(id_, bp) { // pre-/post-fix operators (++, --);\n function pfix() { // prefix;\n this.set(\"left\", \"true\");\n this.childappend(expression(symbol(\"delete\").bind_left - 1)) // so that only >= unary ops (\"lvals\") get through;\n return this;\n }\n symbol(id_, bp).pfix = pfix;\n\n function ifix(left) { // postfix;\n // assert(left, lval);\n this.childappend(left);\n return this;\n }\n symbol(id_).ifix = ifix;\n\n function toJS() {\n operator = this.get(\"value\");\n operand = this.children[0].toJS();\n if (this.get(\"left\", 0) == \"true\") {\n r = [' ', operator, operand];\n } else {\n r = [operand, operator, ' '];\n }\n return r.join('');\n }\n symbol(id_).toJS = toJS;\n\n/*\n function toListG() {\n if (this.get(\"left\",0) == 'true') {\n r = [[this], this.children[0].toListG()];\n } else {\n r = [this.children[0].toListG(), [this]];\n }\n for (var (var e in _.chain(r)\n return e;\n }\n*/\n// symbol(id_).toListG = toListG;\n}\n\n\nfunction advance(id_) {\n id_ = id_ || null;\n var t = token;\n if (id_ && token.id != id_)\n throw new Error(\"Syntax error: Expected %r (pos %r)\" + id_ + token.get(\"line\") + token.get(\"column\"));\n if (token.id != \"eof\")\n token = next();\n return t;\n}\n\n\n// =============================================================================;\n\n// Grammar;\n\nsymbol(\".\", 160); symbol(\"[\", 160);\nprefix_v(\"new\", 160);\n\nsymbol(\"(\", 150);\n\nprepostfix(\"++\", 140); prepostfix(\"--\", 140) // pre/post increment (unary);\n\nprefix(\"~\", 130); prefix(\"!\", 130);\n//prefix(\"+\", 130); prefix(\"-\", 130) // higher than infix position! handled in preinfix.pfix();\nprefix_v(\"delete\", 130); prefix_v(\"typeof\", 130); prefix_v(\"void\", 130);\n\ninfix(\"*\", 120); infix(\"/\", 120); infix(\"%\", 120);\n\npreinfix(\"+\", 110); preinfix(\"-\", 110) // pre/infix '+', '-';\n\ninfix(\"<<\", 100); infix(\">>\", 100); infix(\">>>\", 100);\n\ninfix(\"<\", 90); infix(\"<=\", 90);\ninfix(\">\", 90); infix(\">=\", 90);\ninfix_v(\"in\", 90); infix_v(\"instanceof\", 90);\n\ninfix(\"!=\", 80); infix(\"==\", 80) // (in)equality;\ninfix(\"!==\", 80); infix(\"===\", 80) // (non-)identity;\n\ninfix(\"&\", 70);\ninfix(\"^\", 60);\ninfix(\"|\", 50);\ninfix(\"&&\", 40);\ninfix(\"||\", 30);\n\nsymbol(\"?\", 20) // ternary operator (.ifix takes care of ':');\n\ninfix_r(\"=\", 10) // assignment;\ninfix_r(\"<<=\",10); infix_r(\"-=\", 10); infix_r(\"+=\", 10); infix_r(\"*=\", 10);\ninfix_r(\"/=\", 10); infix_r(\"%=\", 10); infix_r(\"|=\", 10); infix_r(\"^=\", 10);\ninfix_r(\"&=\", 10); infix_r(\">>=\",10); infix_r(\">>>=\",10);\n\n//symbol(\",\", 0) ;\ninfix(\",\", 5) // good for expression lists, but problematic for parsing arrays, maps;\n\nsymbol(\":\", 5) //infix(\":\", 15) // ?: && {1:2,...} && label:;\n\nsymbol(\";\", 0);\nsymbol(\"*/\", 0) // have to register this in case a regexp ends in this string;\nsymbol(\"\\\\\", 0) // escape char in strings (\"\\\");\n\n// constant;\nsymbol(\"constant\").pfix = identity;\n\nsymbol(\"(unknown)\").pfix = identity;\nsymbol(\"eol\");\nsymbol(\"eof\");\n\n\nsymbol(\"constant\").toJS = function () {\n r = '';\n if (this.get(\"constantType\") == \"string\") {\n quote = this.get(\"detail\")==\"singlequotes\" ? \"'\" : '\"';\n r += quote + this.write(this.get(\"value\")) + quote;\n } else {\n r += this.write(this.get(\"value\"));\n };\n return r;\n};\n\n/*\n//symbol(\"constant\").toListG = function () {\n return this;\n}\n*/\n\nsymbol(\"identifier\");\n\nsymbol(\"identifier\").pfix = function () {\n return this;\n}\n\nsymbol(\"identifier\").toJS = function () {\n r = '';\n v = this.get(\"value\", \"\");\n if (v) {\n r = this.write(v);\n }\n return r;\n}\n\n/*\n//symbol(\"identifier\").toListG = function () {\n return this;\n}\n*/\n\n\n//symbol(\"/\")) // regexp literals - already detected by the Tokenizer;\n//.pfix = function () {\n// ;\n\n\n// ternary op ?:;\nsymbol(\"?\").ifix = function (left) {\n // first;\n this.childappend(left);\n // second;\n this.childappend(expression(symbol(\":\").bind_left +1));\n advance(\":\");\n // third;\n this.childappend(expression(symbol(\",\").bind_left +1));\n return this;\n}\n\n\nsymbol(\"?\").toJS = function () {\n r = [];\n r.push(this.children[0].toJS());\n r.push('?');\n r.push(this.children[1].toJS());\n r.push(':');\n r.push(this.children[2].toJS());\n return r.join('');\n}\n\n/*\n//symbol(\"?\").toListG = function () {\n for (var (var e in _.concat(this.children[0].toListG(), [this], this.children[1].toListG(), this.children[2].toListG)\n return e;\n}\n*/\n\n\n////;\n// The case of <variable>:;\n// <variable> is an important node in the old ast, I think because as it mainly;\n// guides dependency analysis, which has to look for variable names. So it might;\n// be a good trap to have a <variable> node wrapper on all interesting places.;\n// I'm keeping it here for the \".\" (dotaccessor) && for the <identifier>'s,;\n// because these are the interesting nodes that contain variable names. I'm not;\n// keeping it for the \"[\" (accessor) construct, as \"foo[bar]\" seems more naturally;\n// divided into the variable part \"foo\", && something else in the selector.;\n// Dep.analysis has then just to parse <dotaccessor> && <identifier> nodes.;\n// Nope.;\n// I revert. I remove the <variable> nodes. Later when parsing the ast, I will;\n// either check for (\"dotaccessor\", \"identifier\"), ||, maybe better, provide a;\n// Node.isVar() method that returns true for those two node types.;\n\nsymbol(\".\").ifix = function (left) {\n if (token.id != \"identifier\") {\n throw new Error(\"Expected an attribute name (pos %r).\");\n }\n accessor = new symbol(\"dotaccessor\")(token.get(\"line\"), token.get(\"column\"));\n accessor.childappend(left);\n accessor.childappend(expression(symbol(\".\").bind_left)) ;\n // i'm providing the rbp to expression() here explicitly, so \"foo.bar(baz)\" gets parsed;\n // as (call (dotaccessor ...) (param baz)), && !(dotaccessor foo;\n // (call bar (param baz))).;\n return accessor;\n}\n\n\nsymbol(\"dotaccessor\");\n\nsymbol(\"dotaccessor\").toJS = function () {\n r = this.children[0].toJS();\n r += '.';\n r += this.children[1].toJS();\n return r;\n}\n\n/*\n//symbol(\"dotaccessor\").toListG = function () {\n _.concat(this.children[0].toListG(.forEach(function (e) {, [this], this.children[1].toListG()))\n return e;\n}\n*/\n\n////;\n// walk down to find the \"left-most\" identifier ('a' in 'a.b().c');\nsymbol(\"dotaccessor\").getLeftmostOperand = function () {\n var ident = this.children[0];\n while (!(ident.type in [\"identifier\", \"constant\"])) { // e.g. 'dotaccessor', 'first', 'call', 'accessor', ...;\n ident =ident.children[0];\n }\n return ident;\n}\n\n////;\n// walk down to find the \"right-most\" identifier ('c' in a.b.c);\nsymbol(\"dotaccessor\").getRightmostOperand = function () {\n var ident = this.children[1];\n return ident // \"left-leaning\" syntax tree (. (. a b) c);\n}\n\n// constants;\n\nfunction constant(id_) {\n symbol(id_);\n symbol(\"constant\").pfix = function () {\n this.id = \"constant\";\n this.value = id_;\n return this;\n }\n// symbol(id_).toListG = toListG_self_first;\n}\n\nconstant(\"null\");\nconstant(\"true\");\nconstant(\"false\");\n\n// bracket expressions;\n\nsymbol(\"(\"), symbol(\")\"), symbol(\"arguments\");\n\nsymbol(\"(\").ifix = function (left) { // <call\n call = new symbol(\"call\")(token.get(\"line\"), token.get(\"column\"));\n // operand;\n operand = new symbol(\"operand\")(token.get(\"line\"), token.get(\"column\"));\n call.childappend(operand);\n operand.childappend(left);\n // params - parse as group;\n params = new symbol(\"arguments\")(token.get(\"line\"), token.get(\"column\"));\n call.childappend(params);\n group = this.pfix();\n group.children.forEach(function (c) {\n params.childappend(c);\n })\n return call;\n}\n\nsymbol(\"operand\");\n\nsymbol(\"operand\").toJS = function () {\n return this.children[0].toJS();\n}\n\n/*\n//symbol(\"operand\").toListG = function () {\n this.children[0].toListG().forEach(function (e) {\n return e;\n });\n}\n*/\n\n\nsymbol(\"(\").pfix = function () { // <group\n // There is sometimes a one-to-one replacement of the symbol instance from;\n // <token> && a different symbol created in the parsing method (here;\n // \"symbol-(\" vs. \"symbol-group\"). But there are a lot of attributes you want to;\n // retain from the token, like \"line\", \"column\", .comments, && maybe others.;\n // The reason for !retaining the token itself is that the replacement is;\n // more specific (as here \"(\" which could be \"group\", \"call\" etc.). Just;\n // re-writing .type would be enough for most tree traversing routines. But;\n // the parsing methods themselves are class-based.;\n group = new symbol(\"group\")();\n ////this.patch(group) // for \"line\", \"column\", .comments, etc.;\n if (token.id != \")\") {\n while (true) {\n if (token.id == \")\") {\n break;\n }\n //group.childappend(expression()) // future:;\n group.childappend(expression(symbol(\",\").bind_left +1));\n if (token.id != \",\") {\n break;\n }\n advance(\",\");\n }\n }\n //if (!group.children) { // bug//7079;\n // raisenew Error(\"Empty expressions in groups are !allowed\", token);\n advance(\")\");\n return group;\n}\n\nsymbol(\"group\").toJS = function () {\n r = [];\n r.push('(');\n a = [];\n this.children.forEach(function (c) {\n a.push(c.toJS());\n });\n r.push(a.join(','));\n r.push(')');\n return r.join('');\n}\n\n/*\n//symbol(\"group\").toListG = function () {\n for (var e in _.concat([this], [c.toListG() for c in this.children))\n return e;\n}\n*/\n\n\nsymbol(\"]\");\n\nsymbol(\"[\").ifix = function (left) { // \"foo[0]\", \"foo[bar]\", \"foo['baz'];\n accessor = new symbol(\"accessor\")();\n //this.patch(accessor);\n // identifier;\n accessor.childappend(left);\n // selector;\n key = new symbol(\"key\")(token.get(\"line\"), token.get(\"column\"));\n accessor.childappend(key);\n key.childappend(expression());\n // assert token.id == ']';\n affix_comments(key.commentsAfter, token);\n advance(\"]\");\n return accessor;\n}\n\nsymbol(\"[\").pfix = function () { // arrays, \"[1, 2, 3]\n arr = new symbol(\"array\")();\n ////this.patch(arr);\n is_after_comma = 0;\n while (true) {\n if (token.id == \"]\") {\n if (is_after_comma) { // preserve dangling comma (bug//6210);\n arr.childappend(new symbol(\"(empty)\")());\n }\n if (arr.children) {\n affix_comments(arr.children[-1].commentsAfter, token);\n } else {\n affix_comments(arr.commentsIn, token);\n }\n break;\n } else if (token.id == \",\") { // elision;\n arr.childappend(new symbol(\"(empty)\")());\n } else {\n //arr.childappend(expression()) // future: ;\n arr.childappend(expression(symbol(\",\").bind_left +1));\n }\n if (token.id != \",\") {\n break;\n } else {\n is_after_comma = 1;\n advance(\",\");\n }\n }\n advance(\"]\");\n return arr;\n}\n\nsymbol(\"accessor\");\n\nsymbol(\"accessor\").toJS = function () {\n r = '';\n r += this.children[0].toJS();\n r += '[';\n r += this.children[1].toJS();\n r += ']';\n return r;\n}\n\n/*\n//symbol(\"accessor\").toListG = function () {\n _.chain(this.children[0].toListG(.forEach(function (e) {, [this], this.children[1].toListG)\n return e;\n })\n}\n*/\n\n\nsymbol(\"array\");\n\nsymbol(\"array\").toJS = function () {\n r = [];\n this.children.forEach(function (c) {\n r.push(c.toJS());\n });\n return '[' + r.join(',') + ']';\n}\n\n//symbol(\"array\").toListG = toListG_self_first;\n\n\nsymbol(\"key\");\n\nsymbol(\"key\").toJS = function () {\n return this.children[0].toJS();\n}\n\n/*\n//symbol(\"key\").toListG = function () {\n this.children[0].toListG.forEach(function (e) {\n return e;\n });\n*/\n\n\nsymbol(\"}\");\n\nsymbol(\"{\").pfix = function () { // object literal\n mmap = new symbol(\"map\")();\n //this.patch(mmap);\n if (token.id != \"}\") {\n is_after_comma = 0;\n while (true) {\n if (token.id == \"}\") {\n if (is_after_comma) { // prevent dangling comma '...,}' (bug//6210);\n throw new Error(\"Illegal dangling comma in map (pos %r)\");\n }\n break;\n }\n is_after_comma = 0;\n map_item = new symbol(\"keyvalue\")(token.get(\"line\"), token.get(\"column\"));\n mmap.childappend(map_item);\n // key;\n keyname = token;\n /*\n assert (keyname.type=='identifier' ||\n (keyname.type=='constant' && keyname.get('constantType','') in ('number','string'));\n ), \"Illegal map key: %s\" % keyname.get('value');\n */\n advance();\n // the <keyname> node is !entered into the ast, but resolved into <keyvalue>;\n map_item.set(\"key\", keyname.get(\"value\"));\n quote_type = keyname.get(\"detail\", false);\n map_item.set(\"quote\", quote_type ? quote_type : '');\n map_item.comments = keyname.comments;\n advance(\":\");\n // value;\n //keyval = expression() // future: ;\n keyval = expression(symbol(\",\").bind_left +1);\n val = new symbol(\"value\")(token.get(\"line\"), token.get(\"column\"));\n val.childappend(keyval);\n map_item.childappend(val) // <value> is a child of <keyvalue>;\n if (token.id != \",\") {\n break;\n } else {\n is_after_comma = 1;\n advance(\",\");\n }\n }\n }\n advance(\"}\");\n return mmap;\n}\n\nsymbol(\"{\").std = function () { // blocks;\n a = statements();\n advance(\"}\");\n return a;\n}\n\nsymbol(\"map\");\n\nsymbol(\"map\").toJS = function () {\n r = '';\n r += this.write(\"{\");\n a = [];\n this.children.forEach(function (c) {\n a.push(c.toJS());\n });\n r += a.join(',');\n r += this.write(\"}\");\n return r;\n}\n\n/*\n//symbol(\"map\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\nsymbol(\"value\").toJS = function () {\n return this.children[0].toJS();\n}\n\n/*\n//symbol(\"value\").toListG = function () {\n this.children[0].toListG.forEach(function (e) {\n return e;\n });\n*/\n\nsymbol(\"keyvalue\");\n\nsymbol(\"keyvalue\").toJS = function () {\n key = this.get(\"key\");\n key_quote = this.get(\"quote\", '');\n if (key_quote) {\n quote = key_quote == 'doublequotes' ? '\"' : \"'\";\n } else if ( key in lang.RESERVED \n || !identifier_regex.match(key)\n // TODO: || !lang.NUMBER_REGEXP.match(key);\n ) \n {\n console.log( \"Warning: Auto protect key: \" + key);\n quote = '\"';\n } else {\n quote = '';\n }\n value = this.getChild(\"value\").toJS();\n return quote + key + quote + ':' + value;\n}\n\n/*\n//symbol(\"keyvalue\").toListG = function () {\n for (var e in _.concat([this], this.children[0].toListG)\n return e;\n*/\n\n\n////;\n// The next is a shallow wrapper around \"{\".std, to have a more explicit rule to;\n// call for constructs that have blocks, like \"for\", \"while\", etc.;\n\nfunction block() {\n t = token;\n advance(\"{\");\n s = new symbol(\"block\")();\n t.patch(s);\n s.childappend(t.std()) // the \"{\".std takes care of closing \"}\";\n return s;\n}\n\nsymbol(\"block\");\n\nsymbol(\"block\").toJS = function () {\n r = [];\n r.push('{');\n r.push(this.children[0].toJS());\n r.push('}');\n return r.join('');\n}\n\n/*\n//symbol(\"block\").toListG = function () {\n for (var e in _.concat([this], this.children[0].toListG)\n return e;\n*/\n\nsymbol(\"function\");\n\nsymbol(\"function\").pfix = function () {\n // optional name;\n opt_name = undefined;\n if (token.id == \"identifier\") {\n //this.childappend(token.get(\"value\"));\n //this.childappend(token);\n //this.set(\"name\", token.get(\"value\"));\n opt_name = token;\n advance();\n }\n // params;\n //assert token.id == \"(\", \"Function definition requires parameter list\";\n params = new symbol(\"params\")();\n token.patch(params);\n this.childappend(params);\n group = expression() // group parsing as helper;\n group.children.forEach(function (c) {\n params.childappend(c);\n });\n //params.children = group.children retains group as parent!;\n // body;\n body = new symbol(\"body\")();\n token.patch(body);\n this.childappend(body);\n if (token.id == \"{\") {\n body.childappend(block());\n } else {\n body.childappend(statement());\n }\n // add optional name as last child;\n if (opt_name) {\n this.childappend(opt_name);\n }\n return this;\n}\n\nsymbol(\"function\").toJS = function () {\n r = this.write(\"function\");\n if (this.getChild(\"identifier\",0)) {\n functionName = this.getChild(\"identifier\",0).get(\"value\");\n r += this.space(result=r);\n r += this.write(functionName);\n }\n // params;\n r += this.getChild(\"params\").toJS();\n // body;\n r += this.getChild(\"body\").toJS();\n return r;\n}\n\n/*\n//symbol(\"function\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n.toJS = function () {\n r = [];\n r.push('(');\n a = [];\n this.children.forEach(function (c) {\n a.push(c.toJS());\n });\n a.join(r.push(','));\n r.push(')');\n return r.join('');\n*/\n\nsymbol(\"params\").toJS = toJS;\nsymbol(\"arguments\").toJS = toJS // same here;\n\n//symbol(\"params\").toListG = toListG_self_first;\n//symbol(\"arguments\").toListG = toListG_self_first;\n\nsymbol(\"body\").toJS = function () {\n r = [];\n r.push(this.children[0].toJS());\n // 'if', 'while', etc. can have single-statement bodies;\n if (this.children[0].id != 'block' && !r[-1].endswith(';')) {\n r.push(';');\n }\n return r.join('');\n}\n\n/*\n//symbol(\"body\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\n\n// -- statements ------------------------------------------------------------;\n\nsymbol(\"var\");\n\nsymbol(\"var\").pfix = function () {\n while (true) {\n defn = new symbol(\"definition\")(token.get(\"line\"), token.get(\"column\"));\n this.childappend(defn);\n n = token;\n if (n.id != \"identifier\") {\n throw new Error(\"Expected a new variable name (pos %r)\" );\n }\n advance();\n // initialization;\n if (token.id == \"=\") {\n t = token;\n advance();\n elem = t.ifix(n);\n // plain identifier;\n } else {\n elem = n;\n }\n defn.childappend(elem);\n if (token.id != \",\") {\n break;\n } else {\n advance(\",\");\n }\n }\n return this;\n}\n\nsymbol(\"var\").toJS = function () {\n r = [];\n r.push(\"var\");\n r.push(this.space());\n a = [];\n this.children.forEach(function (c) {\n a.push(c.toJS());\n });\n a.join(r.push(','));\n return r.join('');\n}\n\n/*\n//symbol(\"var\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\nsymbol(\"definition\").toJS = function () {\n return this.children[0].toJS();\n}\n\n/*\n//symbol(\"definition\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\n////;\n// returns the identifier node of the util.defined symbol;\n//;\nsymbol(\"definition\").getDefinee = function () {\n dfn = this.children[0] // (definition (identifier a)) or (definition (assignment (identifier a)(const 3)));\n if (dfn.type == \"identifier\") {\n return dfn;\n } else if (dfn.type == \"assignment\") {\n return dfn.children[0];\n } else {\n throw SyntaxTreeError(\"Child of a 'definition' symbol must be in ('identifier', 'assignment')\");\n }\n}\n\n////;\n// returns the initialization of the util.defined symbol, if any;\n//;\nsymbol(\"definition\").getInitialization = function () {\n dfn = this.children[0];\n if (dfn.type == \"assignment\") {\n return dfn.children[1];\n } else {\n return undefined;\n }\n}\n\nsymbol(\"for\"); symbol(\"in\");\n\nsymbol(\"for\").std = function () {\n this.type = \"loop\" // compat with Node.type;\n this.set(\"loopType\", \"FOR\");\n\n // condition;\n advance(\"(\");\n // try to consume the first part of a (pot. longer) condition;\n if (token.id != \";\") {\n chunk = expression();\n } else {\n chunk = undefined;\n }\n\n // for (in);\n if (chunk && chunk.id == 'in') {\n this.set(\"forVariant\", \"in\");\n this.childappend(chunk);\n\n // for (;;) [mind: all three subexpressions are optional];\n } else {\n this.set(\"forVariant\", \"iter\");\n condition = new symbol(\"expressionList\")(token.get(\"line\"), token.get(\"column\")) // TODO: expressionList is bogus here;\n this.childappend(condition);\n // init part;\n first = new symbol(\"first\")(token.get(\"line\"), token.get(\"column\"));\n condition.childappend(first);\n if (undef(chunk)) { // empty init expr;\n ;\n } else { // at least one init expr;\n exprList = new symbol(\"expressionList\")(token.get(\"line\"), token.get(\"column\"));\n first.childappend(exprList);\n exprList.childappend(chunk);\n if (token.id == ',') {\n advance(',');\n lst = init_list();\n lst.forEach(function (assgn) {\n exprList.childappend(assgn);\n });\n }\n }\n //else if (token.id == ';') { // single init expr;\n // first.childappend(chunk);\n //else if (token.id == ',') { // multiple init expr;\n // advance();\n // exprList = symbol(\"expressionList\")(token.get(\"line\"), token.get(\"column\"));\n // first.childappend(exprList);\n // exprList.childappend(chunk);\n // lst = init_list();\n // for assgn in lst:;\n // exprList.childappend(assgn);\n advance(\";\");\n // condition part ;\n second = new symbol(\"second\")(token.get(\"line\"), token.get(\"column\"));\n condition.childappend(second);\n if (token.id != \";\") {\n exprList = new symbol(\"expressionList\")(token.get(\"line\"), token.get(\"column\"));\n second.childappend(exprList);\n while (token.id != ';') {\n expr = expression(0);\n exprList.childappend(expr);\n if (token.id == ',') {\n advance(',');\n }\n }\n }\n advance(\";\");\n // update part;\n third = new symbol(\"third\")(token.get(\"line\"), token.get(\"column\"));\n condition.childappend(third);\n if (token.id != \")\") {\n exprList = new symbol(\"expressionList\")(token.get(\"line\"), token.get(\"column\"));\n third.childappend(exprList);\n while (token.id != ')') {\n expr = expression(0);\n exprList.childappend(expr);\n if (token.id == ',') {\n advance(',');\n }\n }\n }\n }\n\n // body;\n advance(\")\");\n body = new symbol(\"body\")(token.get(\"line\"), token.get(\"column\"));\n body.childappend(statementOrBlock());\n this.childappend(body);\n return this;\n}\n\nsymbol(\"for\").toJS = function () {\n r = [];\n r.push('for');\n r.push(this.space(false,result=r));\n // cond;\n r.push('(');\n // for (in);\n if (this.get(\"forVariant\") == \"in\") {\n r.push(this.children[0].toJS());\n // for (;;);\n } else {\n r.push(this.children[0].getChild(\"first\").toJS());\n r.push(';');\n r.push(this.children[0].getChild(\"second\").toJS());\n r.push(';');\n r.push(this.children[0].getChild(\"third\").toJS());\n }\n r.push(')');\n // body;\n r.push(this.getChild(\"body\").toJS());\n return r.join('');\n}\n\n/*\n//symbol(\"for\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\nsymbol(\"in\").toJS = function () { // of 'for (in);\n r = '';\n r += this.children[0].toJS();\n r += this.space();\n r += 'in';\n r += this.space();\n r += this.children[1].toJS();\n return r;\n}\n\n/*\n//symbol(\"in\").toListG = function () {\n _.concat(this.children[0].toListG(.forEach(function (e) {, [this], this.children[1].toListG)\n return e;\n*/\n\n\nsymbol(\"expressionList\").toJS = function () { // WARN: this conflicts (and is overwritten) in for(;;).toJS;\n r = [];\n this.children.forEach(function (c) {\n r.push(c.toJS());\n });\n return r.join(',');\n}\n\n/*\n//symbol(\"expressionList\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\n\nsymbol(\"while\");\n\nsymbol(\"while\").std = function () {\n this.type = \"loop\" // compat with Node.type;\n this.set(\"loopType\", \"WHILE\");\n t = advance(\"(\");\n group = t.pfix() // group parsing eats \")\";\n exprList = new symbol(\"expressionList\")(t.get(\"line\"),t.get(\"column\"));\n this.childappend(exprList);\n group.children.forEach(function (c) {\n exprList.childappend(c);\n });\n body = new symbol(\"body\")(token.get(\"line\"), token.get(\"column\"));\n body.childappend(statementOrBlock());\n this.childappend(body);\n return this;\n}\n\nsymbol(\"while\").toJS = function () {\n r = '';\n r += this.write(\"while\");\n r += this.space(false,result=r);\n // cond;\n r += '(';\n r += this.children[0].toJS();\n r += ')';\n // body;\n r += this.children[1].toJS();\n return r;\n}\n\n/*\n//symbol(\"while\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\nsymbol(\"do\");\n\nsymbol(\"do\").std = function () {\n this.type = \"loop\" // compat with Node.type;\n this.set(\"loopType\", \"DO\");\n body = new symbol(\"body\")(token.get(\"line\"), token.get(\"column\"));\n body.childappend(statementOrBlock());\n this.childappend(body);\n advance(\"while\");\n advance(\"(\");\n this.childappend(expression(0));\n advance(\")\");\n return this;\n}\n\nsymbol(\"do\").toJS = function () {\n r = [];\n r.push(\"do\");\n r.push(this.space());\n r.push(this.children[0].toJS());\n r.push('while');\n r.push('(');\n r.push(this.children[1].toJS());\n r.push(')');\n return r.join('');\n}\n\n/*\n//symbol(\"do\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\n\nsymbol(\"with\");\n\nsymbol(\"with\").std = function () {\n this.type = \"loop\" // compat. with Node.type;\n this.set(\"loopType\", \"WITH\");\n advance(\"(\");\n this.childappend(expression(0));\n advance(\")\");\n body = new symbol(\"body\")(token.get(\"line\"), token.get(\"column\"));\n body.childappend(statementOrBlock());\n this.childappend(body);\n return this;\n}\n\n// the next one - like with other loop types - is *used*, as dispatch is by class, ;\n// !obj.type (cf. \"loop\".toJS());\nsymbol(\"with\").toJS = function () {\n r = [];\n r.extend([\"with\"]);\n r.extend([\"(\"]);\n r.extend([this.children[0].toJS()]);\n r.extend([\")\"]);\n r.extend([this.children[1].toJS()]);\n return r.join('');\n}\n\n/*\n//symbol(\"with\").toListG = function () {\n for (var e in _.concat([this], *[c.toListG() for c in this.children)\n return e;\n*/\n\n// while;\nsymbol(\"while\").pfix = function () {\n token = next();\n //assert(token.source=='while');\n advance('(');\n condition = token.pfix();\n body = token.pfix();\n this.addChild(condition, body);\n return this;\n}\n};\n\nsymbol(\"while\").toJS = function () {\n var r = [\n 'while'\n ,'('\n ,this.children[0].toJS()\n ,')'\n ,this.children[1].toJS()\n ].join('');\n return r;\n}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw and check to see if pellets were eaten.
function handlePellets(){ for (var i = 0; i < pellets.length; i++){ fill(120, 255, 120); ellipse(pellets[i].x, pellets[i].y, pellets[i].r * 2, pellets[i].r * 2); if (blob.eats(pellets[i].x, pellets[i].y, pellets[i].r)){ pellets.splice(i, 1); } } }
[ "function drawPellets() {\n\t//draw the pellets\n\tcontext.fillStyle=\"#BBFF00\";\n\tfor (var i = 0; i < pellets.length; ++i) {\n\t\tcontext.fillRect(pellets[i].x - pellets[i].width/2, pellets[i].y - pellets[i].height/2,pellets[i].width,pellets[i].height);\n\t}\n}", "function check(){\r\n\tvar pellet = document.getElementsByClassName('pellet');\r\n\r\n\tfor(var i= 0; i < pellet.length; i++){\r\n\tvar cell = pellet[i];\r\n\tvar x = parseInt(cell.style.left);\r\n\tvar y = parseInt(cell.style.top);\r\n\tvar piex = parseInt(pieman.style.left);\r\n\tvar piey = parseInt(pieman.style.top);\r\n\t \r\n\tif( x - piex <= 25 && y - piey <= 25 && x - piex >= -25 && y - piey >= -25 ){\r\n\t\t++score;\r\n\t\tremovePellet(cell);\r\n\t\tgeneratePellet(2);\r\n\t\ttimeout = timeout * ratio;\r\n\t\tupdateScore();\r\n\t\treturn;\r\n\t}else continue;\r\n}\r\n if(pelletCount> 0) updateScore();\r\n}", "function addPellet() {\n // loop until finds random point not in snake or a current pellet\n while (true) {\n const x = Math.floor(Math.random() * NCOLS);\n const y = Math.floor(Math.random() * NROWS);\n pt = y + \"-\" + x;\n\n if (!pellets.has(pt) && !snake.includes(pt)) {\n pellets.add(pt);\n setCellStyle(\"pellet\", pt);\n return;\n }\n }\n}", "function checkPegs() {\n for (let i = 0; i < activePegs.length; i++) {\n if (activePegs[i].style.backgroundColor === \"black\") {\n win = true;\n } else {\n win = false;\n }\n }\n}", "function checkPellets() {\n if (pelletsIndex >= 15 && deadPellets >= 15) {\n resetPellets();\n }\n}", "show(){\r\n if(this.dot){\r\n if(!this.eaten){//draw dot if not eaten\r\n fill(255, 255, 0);\r\n noStroke();\r\n ellipse(this.pos.x, this.pos.y, 3, 3);\r\n }\r\n }else if(this.bigDot){\r\n if(!this.eaten){\r\n fill(255, 255, 0);\r\n noStroke();\r\n ellipse(this.pos.x, this.pos.y, 6, 6);\r\n }\r\n }\r\n }", "function paddleHit(){\n if (ball.isTouching(paddle)) {\n ball.bounceOff(paddle);\n if (blockCount == 0) createBlocks(); // if no blocks exist, create a new grid of blocks\n }\n}", "function peelCheck() {\n paused = true;\n if (isValidShape(grid.tiles))\n $('#peel-btn button').attr('disabled', false);\n else\n $('#peel-btn button').attr('disabled', true);\n paused = false;\n}", "function draw(){\r\n\r\n // draw poopies over the pet\r\n function drawPoop(){\r\n var poo_dimension = 20;\r\n var column = 0;\r\n var row = 0;\r\n \r\n for( var p = 0; p < Math.trunc(poo); p++ ){\r\n var x = poo_dimension + (column * (poo_dimension+5) );\r\n var y = row*poo_dimension;\r\n\r\n column++;\r\n if( x+(2*poo_dimension) > CANVAS_WIDTH ){\r\n column = 0;\r\n row++;\r\n }\r\n canvasCtx.drawImage(img_poop, \r\n x, \r\n y );\r\n }\r\n }\r\n \r\n drawBackground();\r\n var _baseImage = baseImage;\r\n \r\n if( sleepState == SLEEP_SLEEP ){\r\n _baseImage += \"_sleep\"; // use a sleepy image instead\r\n }\r\n \r\n // show dumping\r\n // should not be pooping when sleeping\r\n if( !self.isDead() && Math.trunc(poo) > previousPoo ){\r\n drawBaseImage('img_dump');\r\n setTimeout(function(){\r\n drawBaseImage(_baseImage);\r\n },TICK_MILLISECONDS - 500\r\n );\r\n previousPoo = Math.trunc(poo);\r\n }else{\r\n drawBaseImage(_baseImage);\r\n }\r\n \r\n if( !self.isDead() ){\r\n drawPoop();\r\n }\r\n \r\n // put any flash message onto the pet\r\n if( message ){\r\n canvasCtx.font = \"bold 18px serif\";\r\n canvasCtx.fillStyle = \"yellow\";\r\n canvasCtx.fillText(message, 10, CANVAS_HEIGHT/1.8, CANVAS_WIDTH);\r\n }\r\n }", "function googly() {\n for (i=0; i<poses.length; i++){\n for (j=0; j < poses[i].pose.keypoints.length; j++){\n let keypoint = poses[i].pose.keypoints[j];\n if (keypoint.part == \"leftEye\"){\n let lx = keypoint.position.x\n let ly = keypoint.position.y\n fill(255, 255, 255)\n ellipse(lx, ly, 45, 45)\n fill(0,0,0)\n ellipse(lx + int(random(-7,7)), ly + int(random(-7,7)), 15, 15)\n }\n if (keypoint.part == \"rightEye\"){\n let rx = keypoint.position.x\n let ry = keypoint.position.y\n fill(255, 255, 255)\n ellipse(rx, ry, 45, 45)\n fill(0,0,0)\n ellipse(rx + int(random(-7,7)), ry + int(random(-7,7)), 15, 15)\n }\n }\n }\n}", "drawFinishIfLessThan3Points(){\n this.hull=this.points;\n this.drawCurrentState(true);\n this.stop(); \n }", "function playerPearlDetection () {\r\n if (player.x + player.w >= pearl.x && player.x <= pearl.x + pearl.w && player.y + player.h >= pearl.y && player.y <= pearl.y + pearl.h) {\r\n // Left Side // Right Side // Top Side // Bottom Side\r\n pearlCollected();\r\n }\r\n}", "draw() {\n // The paper shows an ingredient\n if (paperStateCounter === 2) {\n image(paperImageGood, 0, 0, width, height);\n }\n // Else a message says nothing happened\n else if (paperStateCounter === 1) {\n image(paperImageBad, 0, 0, width, height);\n }\n // Else the the normal state of the paper is displayed\n else {\n image(paperImageNormal, 0, 0, width, height);\n }\n }", "checkParticles(particles){\n particles.forEach(particle =>{\n const d = dist(this.pos.x,this.pos.y,particle.pos.x,particle.pos.y);\n if(this.color[0] == particle.color[0] && d < D && this !== particle){\n if(!points){\n stroke(this.color[1]);\n line(this.pos.x,this.pos.y,particle.pos.x,particle.pos.y);\n }\n this.attract(particle);\n }\n \n });\n }", "function meet(){\n\tfor (var i=0;i<ghostArray.length;i++){\n\t\tif ((ghostArray[i].alive)&&((ghostArray[i].loc[0]==curPos[0])&&(ghostArray[i].loc[1]==curPos[1]))){\n\t\t\tif (this.strong){\n\t\t\t\tghostArray[i].alive=false;\n\t\t\t\tpageTimer[noOfTimer++]=setTimeout(\"ghostStart(\"+i+\")\",5000);\n\t\t\t\tghostInside++;\n\t\t\t\taudioNoLoop.src=\"eatGhost.wav\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcheckGameOver();\n\t\t\t\t\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function powerPelletEaten() {\n if (squares[pacmanCurrentIndex].classList.contains('power-pellet')) {\n score +=10\n ghosts.forEach(ghost => ghost.isScared = true)\n setTimeout(unScareGhosts, 10000)\n squares[pacmanCurrentIndex].classList.remove('power-pellet')\n }\n }", "function is_eating(w) {\n return (w.food).equals(w.snake.segs.x);\n }", "checkGameVictory() {\n if (this.iterable === (this.alienships.spaceships.length - 1) && this.nova.hull > 0) {\n console.log('%c Congratulations! You\\'ve destroyed Thanos\\' invading alien army and saved Earth!', 'font-size: 20px; font-style: italic; border: 1px solid grey; color: gold;');\n alert(\"Congratulations! You've destroyed Thanos' invading alien army and saved Earth!\");\n this.state = false;\n window.stop();\n }\n }", "function paintPlanets(){\n\n\tfor (var i = 0; i < Game.planets.length; i++) {\n\t\tGame.planets[i].draw();\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
kind may be `const` or `let` Both are experimental and not in the specification yet. see and
function parseConstLetDeclaration(kind) { var declarations; delegate.markStart(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind)); }
[ "function parseConstLetDeclaration(kind) {\n\t var declarations, marker = markerCreate();\n\t\n\t expectKeyword(kind);\n\t\n\t declarations = parseVariableDeclarationList(kind);\n\t\n\t consumeSemicolon();\n\t\n\t return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));\n\t }", "function parseConstLetDeclaration(kind) {\n\t var declarations;\n\n\t delegate.markStart();\n\n\t expectKeyword(kind);\n\n\t declarations = parseVariableDeclarationList(kind);\n\n\t consumeSemicolon();\n\n\t return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind));\n\t }", "function parseConstLetDeclaration(kind) {\n\t\t\t\t\tvar declarations;\n\n\t\t\t\t\tskipComment();\n\t\t\t\t\tdelegate.markStart();\n\n\t\t\t\t\texpectKeyword(kind);\n\n\t\t\t\t\tdeclarations = parseVariableDeclarationList(kind);\n\n\t\t\t\t\tconsumeSemicolon();\n\n\t\t\t\t\treturn delegate.markEnd(delegate.createVariableDeclaration(declarations, kind));\n\t\t\t\t}", "function parseConstLetDeclaration(kind) {\n var declarations, marker = markerCreate();\n \n expectKeyword(kind);\n \n declarations = parseVariableDeclarationList(kind);\n \n consumeSemicolon();\n \n return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));\n }", "function parseConstLetDeclaration(kind) {\n var declarations, node = new Node();\n \n expectKeyword(kind);\n \n declarations = parseVariableDeclarationList(kind);\n \n consumeSemicolon();\n \n return node.finishVariableDeclaration(declarations, kind);\n }", "function parseConstLetDeclaration(kind) {\n\t var declarations;\n\t\n\t expectKeyword(kind);\n\t\n\t declarations = parseVariableDeclarationList(kind);\n\t\n\t consumeSemicolon();\n\t\n\t return delegate.createVariableDeclaration(declarations, kind);\n\t }", "function parseConstLetDeclaration(kind) {\n var declarations, marker = markerCreate();\n\n expectKeyword(kind);\n\n declarations = parseVariableDeclarationList(kind);\n\n consumeSemicolon();\n\n return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));\n }", "_$kind() {\n super._$kind();\n this._value.kind = this._node.kind;\n }", "function stringtoSymbolKind(kind) {\n switch (kind) {\n case 'module': return vscode_languageserver_types_1.SymbolKind.Module;\n case 'class': return vscode_languageserver_types_1.SymbolKind.Class;\n case 'local class': return vscode_languageserver_types_1.SymbolKind.Class;\n case 'interface': return vscode_languageserver_types_1.SymbolKind.Interface;\n case 'enum': return vscode_languageserver_types_1.SymbolKind.Enum;\n case 'enum member': return vscode_languageserver_types_1.SymbolKind.Constant;\n case 'var': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'local var': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'function': return vscode_languageserver_types_1.SymbolKind.Function;\n case 'local function': return vscode_languageserver_types_1.SymbolKind.Function;\n case 'method': return vscode_languageserver_types_1.SymbolKind.Method;\n case 'getter': return vscode_languageserver_types_1.SymbolKind.Method;\n case 'setter': return vscode_languageserver_types_1.SymbolKind.Method;\n case 'property': return vscode_languageserver_types_1.SymbolKind.Property;\n case 'constructor': return vscode_languageserver_types_1.SymbolKind.Constructor;\n case 'parameter': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'type parameter': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'alias': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'let': return vscode_languageserver_types_1.SymbolKind.Variable;\n case 'const': return vscode_languageserver_types_1.SymbolKind.Constant;\n case 'JSX attribute': return vscode_languageserver_types_1.SymbolKind.Property;\n // case 'script'\n // case 'keyword'\n // case 'type'\n // case 'call'\n // case 'index'\n // case 'construct'\n // case 'primitive type'\n // case 'label'\n // case 'directory'\n // case 'external module name'\n // case 'external module name'\n default: return vscode_languageserver_types_1.SymbolKind.Variable;\n }\n}", "['@_kind']() {\n super['@_kind']();\n if (this._value.kind) return;\n this._value.kind = 'external';\n }", "function kindToString(kind) {\n return ts.SyntaxKind[kind];\n}", "function sourceKittenKindToAtomType(kind) {\n switch (kind) {\n case 'source.lang.swift.keyword':\n return 'keyword';\n case 'source.lang.swift.decl.associatedtype':\n return 'type';\n case 'source.lang.swift.decl.class':\n return 'class';\n case 'source.lang.swift.decl.enum':\n return 'class';\n case 'source.lang.swift.decl.enumelement':\n return 'property';\n case 'source.lang.swift.decl.extension.class':\n return 'class';\n case 'source.lang.swift.decl.function.accessor.getter':\n return 'method';\n case 'source.lang.swift.decl.function.accessor.setter':\n return 'method';\n case 'source.lang.swift.decl.function.constructor':\n return 'method';\n case 'source.lang.swift.decl.function.free':\n return 'function';\n case 'source.lang.swift.decl.function.method.class':\n return 'method';\n case 'source.lang.swift.decl.function.method.instance':\n return 'method';\n case 'source.lang.swift.decl.function.method.static':\n return 'method';\n case 'source.lang.swift.decl.function.operator.infix':\n return 'function';\n case 'source.lang.swift.decl.function.subscript':\n return 'method';\n case 'source.lang.swift.decl.generic_type_param':\n return 'variable';\n case 'source.lang.swift.decl.protocol':\n return 'type';\n case 'source.lang.swift.decl.struct':\n return 'class';\n case 'source.lang.swift.decl.typealias':\n return 'type';\n case 'source.lang.swift.decl.var.global':\n return 'variable';\n case 'source.lang.swift.decl.var.instance':\n return 'variable';\n case 'source.lang.swift.decl.var.local':\n return 'variable';\n }\n\n return 'variable';\n}", "_$kind() {\n super._$kind();\n this._value.kind = 'external';\n }", "['@_kind']() {\n super['@_kind']();\n if (this._value.kind) return;\n\n this._value.kind = 'variable';\n }", "_$kind() {\n super._$kind();\n this._value.kind = 'variable';\n }", "isValidKindName(kind) {\n return this.availableProtocols()\n .get(this.name, immutable.List())\n .includes(kind)\n }", "function isKind(val, kind){\n return kindOf(val) === kind;\n }", "function isKind(val, kind){\n return kindOf_1(val) === kind;\n }", "function isKind(val, kind){\n return kindOf(val) === kind;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback called when the 'quantity' subproperty is created/changed
@onValuesChanged("quantity", ["insert", "modify"]) changeQuantity(value) { eventLog.push("Quantity changed: " + value); }
[ "setQuantity(newQuantity) {\n this.quantity = newQuantity;\n }", "setQuantity(quantity) {\n this.quantity = quantity;\n }", "function updateQuantity(event) {\n setQuantity(event.target.value);\n }", "handleQuantityChange(event) {\n const productId = event.detail.productId;\n const qty = event.detail.quantity;\n if (qty > 0) {\n for (let i = 0; i < this.allProducts.length; i++) {\n if (this.allProducts[i].id === productId) {\n this.allProducts[i].quantity = qty;\n }\n }\n }\n }", "function quantityChanged (event) {\n let inputs = event.target\n if (isNaN(inputs.value) || inputs.value <= 0) {\n inputs.value = 1\n } \n outcome = getProduct(event)\n console.log(this.value)\n outcome[0].qty= this.value\n console.log(outcome[0].qty)\n\n}", "function setItemQuantity(iQuantity) {\n\t\n}", "function incrementQuantity(item){\n item.quantity++;\n }", "function fieldQuantityHandler(evt) {\r\n var variantId = parseInt($(this).closest('.cart-item').attr('data-variant-id'), 10);\r\n var props = $(this).closest('.cart-item').attr('data-properties');\r\n var cartLineItem = findCartItemByVariantId(variantId,props);\r\n var quantity = evt.target.value;\r\n if (cartLineItem) {\r\n updateVariantInCart(cartLineItem, quantity);\r\n }\r\n }", "_initProductChangeQty(event) {\n const product = {\n productId: $(event.currentTarget).data('product-id'),\n attributeId: $(event.currentTarget).data('attribute-id'),\n customizationId: $(event.currentTarget).data('customization-id'),\n newQty: $(event.currentTarget).val(),\n };\n\n this.productManager.changeProductQty(this.cartId, product);\n }", "increaseQuantity () {\n this.quantity += 1\n }", "get quantity () {\n\t\treturn this._quantity;\n\t}", "onQuantityChange(event) {\n const symbol = this.props.symbol;\n const quantity = event.target.value;\n const newEntry = {symbol: symbol, quantity: quantity};\n this.props.onUpdate(newEntry);\n }", "updateQuantity () {\n this.$emit('updateQuantity', this.book, this.$refs[`book-in-cart-${this.book.id}`].value)\n }", "function updateProduct(quantity) {\n}", "function setItemQuantity(item, quantity) {\n item.quantity = parseInt(item.quantity) + parseInt(quantity);\n }", "notifyAddToCart() {\n let quantity = this._quantityFieldValue;\n this.dispatchEvent(\n new CustomEvent('addtocart', {\n detail: {\n quantity\n }\n })\n );\n }", "function fieldQuantityHandler(evt) {\r\n\t var variantId = parseInt($(this).closest('.cart-item').attr('data-variant-id'), 10);\r\n\t var variant = product.variants.filter(function (variant) {\r\n\t return (variant.id === variantId);\r\n\t })[0];\r\n\t var cartLineItem = findCartItemByVariantId(variant.id);\r\n\t var quantity = evt.target.value;\r\n\t if (cartLineItem) {\r\n\t updateVariantInCart(cartLineItem, quantity);\r\n\t }\r\n\t }", "function fieldQuantityHandler(event) {\n let productId = parseInt($(this).closest('.cart-item').data('product-id'), 10);\n let variantId = parseInt($(this).closest('.cart-item').data('variant-id'), 10);\n let product = collectionProductsHash[productId];\n\n let variant = product.variants.filter((variant) => {\n return (variant.id === variantId);\n })[0];\n\n var cartLineItem = findCartItemByVariantId(variant.id);\n var quantity = event.target.value;\n\n if (cartLineItem) {\n updateVariantInCart(cartLineItem, quantity);\n }\n }", "IncrementQuantity() {\n this.quantity++;\n this.UpdateQuantityLabel();\n this.UpdatePriceLabel();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating the support reactions at the 2 support nodes using moments
function calculateSupportReactions(){ //calculate support reactions, and otherwise 0 if the car is completely out of the bridge and not touching the supports E.supportA.setForce(-1*Math.abs(E.crane_length/E.crane_height*E.loadedPin.external_force[1]),Math.abs(E.loadedPin.external_force[1]),Grid.canvas); E.supportB.setForce(-1*E.supportA.external_force[0],0,Grid.canvas); }
[ "chooseActions(edge, n1, n2) {\n let inst = this;\n let actions = this.model.selectedActions;\n let stroke = \"gray\";\n let lineWidth = 1;\n edge.act = null;\n var h = n1.happiness;\n //console.log(\"edge\", n1, h, n2);\n if (n1.arousal > Math.random()) {\n for (var action of actions) {\n if (action == \"smile\" && h > Math.random()) {\n //console.log(\"smile\", n1, n2);\n edge.act = action;\n stroke = \"green\";\n lineWidth = 3;\n n2.receivedActions.push(action);\n }\n if (action == \"scowl\" && h < Math.random()) {\n //console.log(\"smile\", n1, n2);\n edge.act = action;\n stroke = \"red\";\n lineWidth = 3;\n n2.receivedActions.push(action);\n }\n }\n }\n //edge.style = { stroke, lineWidth };\n }", "neuronAxonInteraction() {\n for (let neuron1 of this.neurons) //loop über jedes neuron im Neuronensystem\n {\n\n for (let axon of neuron1.axons) //loop über jedes axon von den neuronen\n {\n\n for (let neuron2 of this.neurons) //loop über alle neurone\n {\n if (neuron1 !== neuron2 && p5.Vector.sub(axon.positionEnd,neuron2.position).mag()<30)\n {\n axon.positionEnd = neuron2.position;\n axon.velocity = createVector(0,0);\n axon.foundNeuron=true;\n }\n else if(neuron1 !== neuron2 && p5.Vector.sub(axon.positionEnd,neuron2.position).mag()<50)//ausschließen dass das neuron eigene axone anzieht\n {\n let force = neuron2.attract(axon);\n axon.applyAttraction(force);\n }\n\n\n }\n\n }\n }\n }", "findTransform(matches, count, homo3x3, matchMask) {\n // motion kernel\n var homoKernel = new jsfeat.motion_model.homography2d()\n // ransac params\n var num_model_points = 4 // minimum points to estimate motion\n var reproj_threshold = 3 // max error to classify as inlier\n var eps = 0.5 // max outliers ratio\n var prob = 0.99 // probability of success\n var maxIters = 1000\n var ransacParam = new jsfeat.ransac_params_t(num_model_points,\n reproj_threshold, eps, prob)\n\n var patternXy = []\n var searchXy = []\n // construct correspondences\n for (var ii = 0; ii < count; ++ii) {\n var m = matches[ii]\n var skp = this.sCorners[m.searchIdx]\n var pkp = this.pCorners[m.patternIdx]\n patternXy[ii] = {\n x: pkp.x,\n y: pkp.y,\n }\n searchXy[ii] = {\n x: skp.x,\n y: skp.y,\n }\n }\n\n // estimate motion\n let ok = false\n ok = jsfeat.motion_estimator.ransac(ransacParam, homoKernel,\n patternXy, searchXy, count, homo3x3, matchMask, maxIters)\n\n // extract good matches and re-estimate\n var goodCnt = 0\n if (ok) {\n for (let i = 0; i < count; ++i) {\n // only keep good matches\n if (matchMask.data[i]) {\n patternXy[goodCnt].x = patternXy[i].x\n patternXy[goodCnt].y = patternXy[i].y\n searchXy[goodCnt].x = searchXy[i].x\n searchXy[goodCnt].y = searchXy[i].y\n goodCnt++\n }\n }\n // run kernel directly with inliers only\n homoKernel.run(patternXy, searchXy, homo3x3, goodCnt)\n } else {\n jsfeat.matmath.identity_3x3(homo3x3, 1.0)\n debug('ransac not ok,homo3x3 going to be an identity matrix', homo3x3)\n }\n debug('is ransac ok:', ok, 'goodCnt', goodCnt)\n return { goodCnt, patternXy, searchXy }\n }", "function showSystemImpacts(thisButtonElement, nodeClassname){\n\t\t\t\t\t\t// a. Call function to update node event\n\t\t\t\t\t\tconst nodeID = 'node'+thisButtonElement.id.slice(thisButtonElement.id.indexOf('_'))\t\t\t// Get the node id from thisElement (i.e. the control button)\n\t\t\t\t\t\td3.event.stopPropagation()\t\t\t\t\t\t\t\t\t// a. Stop propagation back to associated node or vis element\n // Remove selected node from selections...\n const selectedNodeID = '#'+nodeID,\n selectedNodeLabelID = selectedNodeID.replace('node', 'label'),\n selectedNodeImagelID = selectedNodeID.replace('node', 'nodeImage'),\n animationTime = 1000,\n radiusChange = 1.1\n\n let nodePositiveSelectionArray = influenceData.nodePositiveSelection.split(\",\").filter( d => d !== selectedNodeID),\n nodeNegativeSelectionArray = influenceData.nodeNegativeSelection.split(\",\").filter( d => d !== selectedNodeID),\n nodeMixedSelectionArray = influenceData.nodeMixedSelection.split(\",\").filter( d => d !== selectedNodeID),\n nodePositiveSelection = nodePositiveSelectionArray.join(' , '),\n nodeNegativeSelection = nodeNegativeSelectionArray.join(' , '),\n nodeMixedSelection = nodeMixedSelectionArray.join(' , '),\n labelPositiveSelection = nodePositiveSelection.replace(/node/g, 'label'),\n labelNegativeSelection = nodeNegativeSelection.replace(/node/g, 'label'),\n labelMixedSelection = nodeMixedSelection.replace(/node/g, 'label'),\n nodeImagePositiveSelection = nodePositiveSelection.replace(/node/g, 'nodeImage'),\n nodeImageNegativeSelection = nodeNegativeSelection.replace(/node/g, 'nodeImage'),\n nodeImageMixedSelection = nodeMixedSelection.replace(/node/g, 'nodeImage')\n\n\t\t\t\t\t\t// NOTE: The influence data is calculated by default for an \"increase\" and simply switched here for the negative\n if(d3.select(thisButtonElement).classed('nodeControl-up')){ \n if(nodePositiveSelection !== '')\n d3.selectAll(nodePositiveSelection+' , '+nodePositiveSelection.replace(/node/g, 'nodeBackground')) \n .transition().duration(animationTime)\n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(167.6,41.2%,91.4%)' : null })\n .attr('r', function(){return d3.select(this).attr('r') * radiusChange })\n if(labelPositiveSelection !== '') \n d3.selectAll(labelPositiveSelection+' , '+nodeImagePositiveSelection) \n .transition().duration(animationTime)\n .attr('transform', function(){\n const currentTransfrom = d3.select(this).attr('transform'),\n stemToScale = currentTransfrom.slice(0,currentTransfrom.indexOf('c')+5),\n scaleStem = currentTransfrom.slice(currentTransfrom.indexOf('c')+5, currentTransfrom.length),\n newScale = (scaleStem.indexOf(',') === -1) ? +scaleStem.slice(0, -1) * radiusChange : +scaleStem.slice(0, scaleStem.indexOf(',')) * radiusChange \n return stemToScale+newScale+', '+newScale+')'\n })\n .style('fill', function(){ return d3.select(this).attr('id') === 'label_'+visData.centerNodeID ? 'hsl(167.6,41.2%,91.4%)' : null })\n\n if(nodeNegativeSelection !== '')\n d3.selectAll(nodeNegativeSelection+' , '+nodeNegativeSelection.replace(/node/g, 'nodeBackground'))\n .transition().duration(animationTime) \n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(338.9,80%,91.2%)' : null }) \n .attr('r', function(){\n return d3.select(this).attr('r') / radiusChange\n })\n if(labelNegativeSelection !== '') \n d3.selectAll(labelNegativeSelection+' , '+nodeImageNegativeSelection)\n .transition().duration(animationTime)\n .attr('transform', function(){\n const currentTransfrom = d3.select(this).attr('transform'),\n stemToScale = currentTransfrom.slice(0,currentTransfrom.indexOf('c')+5),\n scaleStem = currentTransfrom.slice(currentTransfrom.indexOf('c')+5, currentTransfrom.length),\n newScale = (scaleStem.indexOf(',') === -1) ? +scaleStem.slice(0, -1) / radiusChange : +scaleStem.slice(0, scaleStem.indexOf(',')) / radiusChange \n return stemToScale+newScale+', '+newScale+')'\n }) \n .style('fill', function(){ return d3.select(this).attr('id') === 'label_'+visData.centerNodeID ? 'hsl(338.9,80%,91.2%)' : null }) \n if(nodeMixedSelection !== '')\n d3.selectAll(nodeMixedSelection)\n .transition().duration(animationTime) \n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(44.9,100%,90%)' : null }) \n\n d3.select(thisButtonElement)\n .transition().duration(animationTime) \n .style('fill', '#3E9583') \n d3.select('.nodeControl-down.nodeControl-'+nodeClassname)\n .transition().duration(animationTime) \n .style('fill', 'rgb(168, 166, 167)') \n\t\t\t\t\t\t} else if (d3.select(thisButtonElement).classed('nodeControl-down')){\t\t\n if(nodePositiveSelection !== '') \t\t \t\t\n d3.selectAll(nodePositiveSelection+' , '+nodePositiveSelection.replace(/node/g, 'nodeBackground'))\n .transition().duration(animationTime)\n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(338.9,80%,91.2%)' : null})\n .attr('r', function(){ return d3.select(this).attr('r') / radiusChange }) \n if(labelPositiveSelection !== '') \n d3.selectAll(labelPositiveSelection+' , '+nodeImagePositiveSelection) \n .transition().duration(animationTime)\n .attr('transform', function(){\n const currentTransfrom = d3.select(this).attr('transform'),\n stemToScale = currentTransfrom.slice(0,currentTransfrom.indexOf('c')+5),\n scaleStem = currentTransfrom.slice(currentTransfrom.indexOf('c')+5, currentTransfrom.length),\n newScale = (scaleStem.indexOf(',') === -1) ? +scaleStem.slice(0, -1) / radiusChange : +scaleStem.slice(0, scaleStem.indexOf(',')) / radiusChange \n return stemToScale+newScale+', '+newScale+')'\n }) \n .style('fill', function(){ return d3.select(this).attr('id') === 'label_'+visData.centerNodeID ? 'hsl(338.9,80%,91.2%)' : null })\n\n if(nodeNegativeSelection !== '')\n d3.selectAll(nodeNegativeSelection+' , '+nodeNegativeSelection.replace(/node/g, 'nodeBackground'))\n .transition().duration(animationTime)\n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(167.6,41.2%,91.4%)' : null})\n .attr('r', function(){return d3.select(this).attr('r') * radiusChange })\n if(labelNegativeSelection !== '') \n d3.selectAll(labelNegativeSelection+' , '+nodeImageNegativeSelection)\n .transition().duration(animationTime)\n .attr('transform', function(){\n const currentTransfrom = d3.select(this).attr('transform'),\n stemToScale = currentTransfrom.slice(0,currentTransfrom.indexOf('c')+5),\n scaleStem = currentTransfrom.slice(currentTransfrom.indexOf('c')+5, currentTransfrom.length),\n newScale = (scaleStem.indexOf(',') === -1) ? +scaleStem.slice(0, -1) * radiusChange : +scaleStem.slice(0, scaleStem.indexOf(',')) * radiusChange \n return stemToScale+newScale+', '+newScale+')'\n }) \n .style('fill', function(){ return d3.select(this).attr('id') === 'label_'+visData.centerNodeID ? 'hsl(167.6,41.2%,91.4%)' : null }) \n if(nodeMixedSelection !== '')\n d3.selectAll(nodeMixedSelection)\n .transition().duration(animationTime)\n .style('fill', function(){ return d3.select(this).attr('id') !== 'node_'+visData.centerNodeID ? 'hsl(44.9,100%,90%)' : null}) \n\n d3.select(thisButtonElement)\n .transition().duration(animationTime) \n .style('fill', '#BD1550') \n d3.select('.nodeControl-up.nodeControl-'+nodeClassname)\n .transition().duration(animationTime) \n .style('fill', 'rgb(168, 166, 167)')\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "function weightedManhattanDistance(nodeOne, nodeTwo, nodes) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n\n if (noc[0] < ntc[0] && noc[1] < ntc[1]) {\n\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] < ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx <= ntc[0]; cx++) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] < ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy <= ntc[1]; cy++) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n } else if (noc[0] >= ntc[0] && noc[1] >= ntc[1]) {\n let axc = 0,\n ayc = 0;\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${nodeOne.id.split(\"-\")[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${ntc[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n\n let oaxc = 0,\n oayc = 0;\n for (let cy = noc[1]; cy >= ntc[1]; cy--) {\n let cId = `${nodeOne.id.split(\"-\")[0]}-${cy}`;\n let cnn = nodes[cId];\n ayc += cnn.weight;\n }\n for (let cx = noc[0]; cx >= ntc[0]; cx--) {\n let cId = `${cx}-${ntc[1]}`;\n let cnn = nodes[cId];\n axc += cnn.weight;\n }\n\n if (axc + ayc < oaxc + oayc) {\n xChange += axc;\n yChange += ayc;\n } else {\n xChange += oaxc;\n yChange += oayc;\n }\n }\n\n\n return xChange + yChange;\n\n\n}", "computeTrend(expHomRef, expHet, expHomAlt, conHomRef, conHet, conHomAlt) {\n let self = this;\n // Define variables\n let controlTotal = conHomRef + conHet + conHomAlt; // Aka S\n let expTotal = expHomRef + expHet + expHomAlt; // Aka R\n let sampleTotal = controlTotal + expTotal; // Aka N\n let hetTotal = expHet + conHet; // Aka n_1\n let homAltTotal = expHomAlt + conHomAlt; // Aka n_2\n\n // Calculate numerator and denominator of Sasieni notation for CA using weighted vector of (0,1,2)\n let trendTestStat = (sampleTotal * (expHet + (2 * expHomAlt))) - (expTotal * (hetTotal + (2 * homAltTotal))); // Aka U_mod\n let trendVarA = controlTotal * expTotal; // Aka S * R\n let trendVarB = sampleTotal * (hetTotal + (4 * homAltTotal)); // Aka N * (n_1 + 4*n_2)\n let trendVarC = (hetTotal + (2 * homAltTotal)) ** 2; // Aka (n_1 + 2*n_2)^2\n let numerator = sampleTotal * (trendTestStat ** 2); // Aka N * U_mod\n let denominator = trendVarA * (trendVarB - trendVarC); // Aka A*(B-C)\n let z = Math.sqrt((numerator / denominator));\n\n // Find where our chi-squared value falls & return appropriate p-value\n let lowestBound = self.singleDegreeChiSqValues[0];\n let highestBound = self.singleDegreeChiSqValues[self.singleDegreeChiSqValues.length - 1];\n let pVal = 1;\n if (z <= lowestBound) {\n pVal = self.correspondingPValues[0];\n } else if (z >= highestBound) {\n pVal = self.correspondingPValues[self.correspondingPValues.length - 1];\n } else {\n // Iterate through array, comparing adjacent values to see if curr number falls in that range\n for (let i = 0; i < self.correspondingPValues.length; i++) {\n let lowBound = self.singleDegreeChiSqValues[i];\n let highBound = self.singleDegreeChiSqValues[i + 1];\n if (z >= lowBound && z < highBound) {\n pVal = self.correspondingPValues[i];\n break;\n }\n }\n }\n return pVal;\n }", "function CalcFromCurrentToEndWeight_hh2(){ // FromCurrentToEndWeight_hh[] // Calc h for all nodes\n\t\tvar Target = GetXandYvalues(targetLeaf); var Target2 = GetXandYvalues(targetLeaf2);\n\t\tvar TargetX = Target[0];\t\t\t\t var TargetX2 = Target2[0];\n\t\tvar TargetY = Target[1];\t\t\t\t var TargetY2 = Target2[1];\n\n\tfor(var a : int = 0; a < LeavesActiveInSceneInt.Length; a++){\n\t\tvar curr = LeavesActiveInSceneInt[a];\n\t\tvar cur = GetXandYvalues(curr);\n\t\tvar curX = cur[0];\n\t\tvar curY = cur[1];\n\t\tFromCurrentToEndWeight_hh[a] = (Mathf.Sqrt(((TargetX-curX)*(TargetX-curX))+((TargetY-curY)*(TargetY-curY))))+(Mathf.Sqrt(((TargetX2-curX)*(TargetX2-curX))+((TargetY2-curY)*(TargetY2-curY))));\n\t\t}\n}", "function calcAttractiveForce(node1) {\n var totalForce = createVector(0.0, 0.0);\n var distance;\n var force;\n\n var P = createVector(node1[\"pos_x\"], node1[\"pos_y\"]);\n var Q = createVector(0.0, 0.0);\n\n var link = null;\n var node2 = null;\n\n // Iterate over all links to check if this node is a part of it.\n // Iterate over all nodes to calculate repulsion\n var arrayLength = allLinks.length;\n for (var i = 0; i < arrayLength; i++) {\n link = allLinks[i];\n if((node1[\"id\"] === link[\"source\"]) || (node1[\"id\"] === link[\"target\"])){\n // This link is connected to the node\n if(node1[\"id\"] === link[\"source\"]) {\n node2 = nodes[link[\"target\"]];\n } else {\n node2 = nodes[link[\"source\"]];\n }\n\n Q.set(node2[\"pos_x\"], node2[\"pos_y\"]);\n distance = p5.Vector.dist(P, Q);\n if((distance - springRestLength) <= 0.0) continue;\n force = attractionConstant * (distance - springRestLength);\n totalForce.add(p5.Vector.sub(Q, P).normalize().mult(force));\n }\n }\n\n return totalForce; \n}", "calculateTweens(TICK_RATE) {\n this.players.forEach((player) => {\n if (player.mage.fromX && player.mage.fromY && player.mage.toX && player.mage.toY) {\n if (player.mage.fromX < player.mage.toX) player.mage.setFlipX(true);\n if (player.mage.fromX > player.mage.toX) player.mage.setFlipX(false);\n var ex = player.mage.toX;\n var ey = player.mage.toY;\n\n this.tweens.add({\n targets: player.mage,\n x: {\n value: ex,\n duration: TICK_RATE\n },\n y: {\n value: ey,\n duration: TICK_RATE\n }\n });\n }\n\n });\n if (this.projectiles) {\n this.projectiles.forEach((projectile) => {\n if (projectile.fromX && projectile.fromY && projectile.toX && projectile.toY) {\n var ex = projectile.toX;\n var ey = projectile.toY;\n\n this.tweens.add({\n targets: projectile,\n x: {\n value: ex,\n duration: TICK_RATE\n },\n y: {\n value: ey,\n duration: TICK_RATE\n }\n });\n }\n\n });\n }\n\n\n\n }", "function moon_node_conjunction(date0, node) {\n //\n // compute how many degrees the moon is away from the planet\n // this function is positive from 180 degrees behind down\n // to conjunction, and negative from conjunction up to\n // -180 degrees behind (ie, ahead).\n //\n function degrees_from_conjunction(t) {\n var eph = ephemerides_at_time(t);\n var moonlon = eph.Moon.lonecl;\n var nodelon = eph.Moon.N + (node === 'ascending' ? 0 : 180);\n var d = moonlon - nodelon;\n return (d > 180) ? (d - 360) : (d < -180) ? (d + 360) : d;\n } \n function moon_node_conjunction_time(time0) {\n var times = ephemerides_cached_times();\n var t0;\n var d0;\n for (var i in times) {\n var t1 = new Number(times[i]);\n var d1 = degrees_from_conjunction(times[i]);\n if (t1 < time0) {\n ;\n } else if (d1 == 0) {\n return t1;\n } else if (t0 == null) {\n t0 = t1;\n d0 = d1;\n } else if (d1 * d0 < 0 && d0 < 0) {\n return find_zero_by_brents_method(degrees_from_conjunction, t0, d0, t1, d1);\n } else {\n t0 = t1;\n d0 = d1;\n }\n }\n return null;\n }\n\n var t = moon_node_conjunction_time(date0.getTime());\n return t == null ? null : new Date(t);\n}", "function manhattanDist(nodeOne, nodeTwo) {\n let noc = nodeOne.id.split(\"-\").map(ele => parseInt(ele));\n let ntc = nodeTwo.id.split(\"-\").map(ele => parseInt(ele));\n let xChange = Math.abs(noc[0] - ntc[0]);\n let yChange = Math.abs(noc[1] - ntc[1]);\n return (xChange + yChange);\n}", "Mutate() {\n /*weight_mut_rate = 0.8;\n uniform_perturbance = 0.9; // if weights mutated, 90% chance they are uniformly perturbed. 10% they are assigned new random value\n disable_inherited_disabled_gene = 0.75;\n crossover_no_mut = 0.25;\n interspecies_mate_rate = 0.001;\n node_add_rate = 0.03;\n connec_add_rate = 0.05;\n large_pop_connec_rate = 0.3;*/\n\n //add new node\n if (Math.random() < node_add_rate) this.mu_add_node();\n\n //add new connection\n if (Math.random() < connec_add_rate) this.mu_add_connection();\n\n for (let i = 0; i < this.connections.length; i++) {\n if (Math.random() < weight_mut_rate) {\n if (Math.random() < uniform_perturbance) {\n //add or subtract 10% from weight\n this.connections[i].weight += ((Math.random() < 0.5) ? (-weight_mut_power) : (weight_mut_power));\n }\n else {\n //new random weight between -2 and 2\n this.connections[i].weight = (Math.random() * 4) - 2;\n }\n }\n if (Math.random() < mut_toggle_enable_prob) {\n this.connections[i].toggle();\n }\n }\n }", "function saturn_model(test_date, sun_view_radius, saturn_view_radius) {\n\n // Long of asc. node\n saturn_N = rev(113.6634 + 2.38980E-5 * test_date);\n\n // Inclination\n saturn_i = rev( 2.4886 - 1.081E-7 * test_date);\n\n // Argument of perihelion\n saturn_w = rev(339.3939 + 2.97661E-5 * test_date);\n\n // semi-major axis \n saturn_a = 9.55475;\n\n // Eccentricity \n saturn_e = rev(0.055546 - 9.499E-9 * test_date);\n\n // Mean anomaly\n saturn_M = rev(316.9670 + 0.0334442282 * test_date); \n\n // Dump the 6 parameters\n // =====================\n // console.log(\"Saturn\");\n // console.log(\"N deg: \" + saturn_N);\n // console.log(\"i deg: \" + saturn_i);\n // console.log(\"w deg: \" + saturn_w);\n // console.log(\"a a.e: \" + saturn_a);\n // console.log(\"e : \" + saturn_e);\n // console.log(\"M deg: \" + saturn_M);\n\n // compute E, the eccentric anomaly\n // use the iteration formula to obtain an accurate value of E\n E = compute_E(saturn_M, saturn_e);\n // console.log (\"E = \" + E);\n\n // compute x,y coordinates in the plane of the orbit...\n x = saturn_a * (Math.cos(E * Math.PI / 180.0) - saturn_e);\n y = saturn_a * (Math.sqrt(1 - (saturn_e * saturn_e))) * \n Math.sin(E * Math.PI / 180.0);\n\n\n // compute r\n r = Math.sqrt((x * x) + (y * y));\n r += sun_view_radius;\n r += saturn_view_radius;\n\n // compute v\n v = Math.atan2(y, x) * 180 / Math.PI;\n v = rev(Math.atan2(y, x) * 180 / Math.PI);\n\n\n // compute the position in ecliptic coordinates\n\n xeclip = compute_xeclip(r, saturn_N, v, saturn_w, saturn_i);\n yeclip = compute_yeclip(r, saturn_N, v, saturn_w, saturn_i);\n zeclip = compute_zeclip(r, v, saturn_w, saturn_i);\n\n \n // compute Heliocentric longitude, latitude and distance\n longitude = rev (Math.atan2(yeclip, xeclip) * 180 / Math.PI);\n\n latitude = (Math.atan2(zeclip, Math.sqrt((xeclip * xeclip) +\n (yeclip * yeclip))) * 180 / Math.PI);\n\n distance = Math.sqrt( (xeclip * xeclip) + (yeclip * yeclip) +\n (zeclip * zeclip));\n\n\n // console.log (\"x = \" + x);\n // console.log (\"y = \" + y);\n // console.log (\"r = \" + r);\n // console.log (\"v = \" + v);\n // console.log (\"xeclip = \" + xeclip);\n // console.log (\"yeclip = \" + yeclip);\n // console.log (\"zeclip = \" + zeclip);\n // console.log (\"longitude = \" + longitude);\n // console.log (\"latitude = \" + latitude);\n // console.log (\"distance = \" + distance);\n\n // check\n // console.log(\"Saturn: (\" + xeclip + \", \" + yeclip + \", \" + zeclip + \")\");\n return [xeclip, yeclip, zeclip];\n\n}", "measureDistances( featureRanges ) {\n var ranges = {};\n // For each feature, compute the distance between min and max for \n // normalization\n for ( var i in featureRanges ) {\n ranges[i] = featureRanges[i].max - featureRanges[i].min;\n if ( ranges[i] === 0 ) {\n ranges[i] = 1;\n }\n }\n\n // For each neighbor\n for ( var i in this.neighbors ) {\n var neighbor = this.neighbors[i];\n var delta = [];\n var mul = 0;\n // console.log( neighbor.name );\n // For each feature\n for ( var j in this.meaningfulFeatures ) {\n if ( !neighbor.features[this.meaningfulFeatures[j]]) {\n neighbor.features[this.meaningfulFeatures[j]] = [featureRanges[this.meaningfulFeatures[j]].min];\n }\n if ( !this.features[this.meaningfulFeatures[j]]) {\n this.features[this.meaningfulFeatures[j]] = [featureRanges[this.meaningfulFeatures[j]].min];\n }\n var diff = 0;\n if ( neighbor.features[this.meaningfulFeatures[j]].length > 1 ) {\n diff = ( neighbor.features[this.meaningfulFeatures[j]][0] +\n neighbor.features[this.meaningfulFeatures[j]][1]) / 2 -\n ( this.features[this.meaningfulFeatures[j]][0] + this.features[this.meaningfulFeatures[j]][1]) / 2;\n } else {\n diff = neighbor.features[this.meaningfulFeatures[j]][0] - \n this.features[this.meaningfulFeatures[j]][0];\n }\n // var diff = neighbor.features[meaningfulFeatures[j]] - \n // this.features[meaningfulFeatures[j]];\n // console.log( diff );\n var delta = diff / ranges[this.meaningfulFeatures[j]];\n // console.log( diff + \" / \" + ranges[meaningfulFeatures[j]] );\n mul += ( delta * delta );\n // console.log( mul );\n // } else {\n // mul += 0.01;\n // }\n }\n\n neighbor.distance = Math.sqrt( mul );\n // console.log( neighbor.distance );\n }\n }", "ecmp(e1, e2, u) {\n\t\tea && assert(this.validVertex(u) &&\n\t\t\t\t\t this.validEdge(e1) && this.validEdge(e2));\n\t\tlet v1 = this.mate(u, e1); let v2 = this.mate(u, e2);\n\t\treturn (v1 != v2 ? v1 - v2 : this.weight(e1) - this.weight(e2));\n\t}", "function calcActRev(actArray){\n if(actArray.length > 0){\n actArray.forEach(function (x) {\n //Count activity only if conservee\n if(x.conservee && x.conservee == \"true\"){\n d.activitiestot ++;\n }\n //Revenue sum for conservee activities\n if(x.conservee == \"true\"){\n if(x.remuneration && x.remuneration.montant.montant){\n //If the revenue only has 1 entry the data structure is a bit different\n if(x.remuneration.montant.montant.annee && x.remuneration.montant.montant.annee == currentYear){\n d.revenuetot += Number(x.remuneration.montant.montant.montant);\n } else if(x.remuneration.montant.montant.length > 0){\n //If there are more entries, loop through revenue entries, 1 entry per year; pick the current year entry\n x.remuneration.montant.montant.forEach(function (y) {\n if(y.annee == currentYear){\n d.revenuetot += Number(y.montant);\n }\n });\n }\n }\n //Revenue sum average\n var thisacttot = 0;\n var thisactyears = 0;\n if(x.remuneration && x.remuneration.montant.montant){\n //If the revenue only has 1 entry the data structure is a bit different\n if(x.remuneration.montant.montant.annee){\n d.revenuetotAvg += Number(x.remuneration.montant.montant.montant);\n } else if(x.remuneration.montant.montant.length > 0){\n //If there are more entries, loop through revenue entries, 1 entry per year; sum the revenues and divide by years amount\n x.remuneration.montant.montant.forEach(function (y) {\n thisacttot += Number(y.montant);\n thisactyears ++;\n });\n }\n }\n if(thisactyears > 0){\n d.revenuetotAvg += Number(thisacttot)/Number(thisactyears);\n //.toFixed(2)\n }\n }\n //If any is kept, set activcons to OUI\n if(x.conservee && x.conservee == \"true\"){\n d.activcons = \"OUI\";\n }\n });\n }\n }", "calcManhattanDist(img1, img2) {\n debugger;\n let manhattan = 0;\n\n for (let i = 0; i < img1.color_moments.length; i++) {\n for(let x = 0; x < img1.color_moments[i].length; x++){\n manhattan += Math.abs(img1.color_moments[i][x] - img2.color_moments[i][x]);\n }\n }\n manhattan /= img1.color_moments.length;\n return manhattan;\n }", "function visitTheAffectation(n, fromWhichSide) {n.temporarilyMarkedDuringCompositionTraversal = true;var conditionForCurrentAffectation = graph.matchUndirectedEdges({ type: 'InteractionInstanceOperand', from: { node: n, index: 0 }, to: { node: { type: 'InteractionInstance' } } }).map(function (e) {return e.to;}).value();var compos = graph.matchUndirectedEdges({ type: 'InteractionInstanceOperand', from: { node: n }, to: { index: 0, node: { type: 'InteractionInstance', unSuitableForCompositionReduction: false, content: { type: 'InteractionSimple', operatorType: 'Composition' } } } }).filter(function (e) {return e.from.index === 3 - fromWhichSide && e.to.node.temporarilyMarkedDuringCompositionTraversal !== true;}).map(function (e) {return { compositionNode: e.to.node, condition: conditionForCurrentAffectation };}).value();var otheraffects = graph.matchUndirectedEdges({ typae: 'InteractionInstanceOperand', from: { node: n }, to: { node: { type: 'InteractionInstance', content: { type: 'InteractionSimple', operatorType: 'Affectation' } } } }).filter(function (e) {return e.from.index === 3 - fromWhichSide && (e.to.index === 1 || e.to.index === 2) && e.to.node.temporarilyMarkedDuringCompositionTraversal !== true;}).map(function (e) {return visitTheAffectation(e.to.node);}).flatten().map(function (x) {return { compositionNode: x.compositionNode, condition: x.condition.concat(conditionForCurrentAffectation) };}).value();n.temporarilyMarkedDuringCompositionTraversal = false;return compos.concat(otheraffects);}", "function updateMode() {\n\n // update mass\n documents.forEach(function (d) {\n d.mass = d.entities.reduce(function (acc, e) {\n return acc + entities[e.name].weight * e.value;\n }, 0);\n });\n // console.log(documents);\n\n // weighted sum model, to calculate the similarity\n // update edges\n edges.forEach(function (e) {\n console.log(e.strength);\n e.strength = cosineDistance(e.source, e.target, entities);\n console.log(e.strength);\n // edges.strength = cosineDistance(e.source, e.target, entities);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a package of game data.
function getGameDataPackage() { Android.test("creating package..."); return gameString(startingJSON); }
[ "function newGameData() {\n var data = {\n 'area': 'shore',\n 'inventory': {\n 'items' : {},\n 'weapons' : {},\n 'armors' : {},\n 'helmets' : {},\n 'boots' : {}\n },\n 'visibleSkills': [],\n 'defeatedMonsters': {},\n 'unlockedClasses' : {'youth' : true},\n 'gold': 10,\n 'experience': 0,\n 'level': 0,\n 'learnedSkills': [],\n 'skillPoints': 0,\n 'skillCost': 1,\n 'time': 0,\n 'gameSpeed': 1,\n 'bonusPoints': 0,\n 'programs': [],\n 'weapon': baseEquipment.weapon.key,\n 'helmet': baseEquipment.helmet.key,\n 'boots': baseEquipment.boots.key,\n 'armor': baseEquipment.armor.key,\n 'enchantments': {\n 'weapon': emptyEnchantments(),\n 'armor': emptyEnchantments(),\n 'helmet': emptyEnchantments(),\n 'boots': emptyEnchantments()\n },\n 'flags': {}\n };\n for (var i = 0; i < 13; i++) {\n data.visibleSkills[i] = [];\n for (var j = 0; j < 13; j++) {\n data.visibleSkills[i][j] = false;\n }\n }\n return data;\n}", "function createGame() {\n playersData.remove();\n var grid = generateRandomWeightedGrid(20,12);\n saveMap(grid);\n var newGame = {\n grid: JSON.stringify(grid), \n creatorName: getNomJoueur()\n }\n gameList.push(newGame);\n}", "function createGame() {\r\n createBoard();\r\n createCoins();\r\n createRules();\r\n}", "function setupGameData() {\n game_data = {\n started: false,\n questions: setupQuestions(QUESTIONS_COUNT),\n incorrect_questions: [],\n current_question: null,\n score: 0,\n };\n }", "_createPack() {\n let pack = []\n\n // Create a card for each suit, for each face.\n suits.forEach(function(suit) {\n let facesAndValuesKeys = Object.keys(facesAndValues)\n facesAndValuesKeys.forEach(function(face) {\n pack.push(api._createCard(suit, face))\n })\n })\n\n // Return the pack of cards.\n return pack\n }", "function createNewPlayerData(name, image) {\n return {\n // Basics\n name: name,\n image: image,\n qp: 4000,\n lastSave: curDateTime(),\n lastLoad: curDateSlashes(),\n\n // Options\n options: { },\n\n // Servants (array of loading functions)\n servants: [],\n\n // Servant data / improvements\n servantData: [],\n\n // Completed Battle Simulation maps\n battleSim: [],\n };\n}", "static buildFromProto (myData) {\n const newGameData = new GameData(\n myData.title, myData.byLine, myData.bannerWide || myData.bannerWideURI,\n myData.webPlayLink, myData.windowsDownloadLink, myData.macOSDownloadLink\n )\n\n if (myData.media) {\n myData.media.forEach((mediaData) => {\n if (mediaData.type === 'video' || mediaData.vimeoID) {\n newGameData.addMediaVideo(mediaData.title, mediaData.vimeoID, mediaData.thumb, mediaData.alt)\n } else {\n newGameData.addMediaImage(mediaData.title, mediaData.link, mediaData.thumb, mediaData.alt)\n }\n })\n }\n\n return newGameData\n }", "function createGame() {\n // Generate a random ID for the game\n var gId = rand.genereteRandomId(config.GAME_ID_LENGTH);\n while (games[gId] != undefined) {\n gId = rand.genereteRandomId(config.GAME_ID_LENGTH);\n }\n\n // Setup the game\n games[gId] = {\n users: {},\n objects: [],\n userCount: 0\n };\n\n // Return the ID\n return gId;\n }", "function createData(\n name,\n loadScore,\n ticketCount,\n location,\n type,\n fts,\n ooo,\n visible\n) {\n counter += 1;\n return {\n id: counter,\n name,\n loadScore,\n ticketCount,\n location,\n type,\n fts,\n ooo,\n visible\n };\n}", "function create_data()\r\n{\r\n\tif((edit_mode == 9) &&(stats_chk9() == 1)) return;\r\n\tif((edit_mode == 0) &&(stats_chk0() == 1)) return;\r\n\r\n\tif(edit_mode == 0){\r\n\t\thex_head = \"55AA55AA60000000\";\t//\r\n\t}else{\r\n\t\thex_head = \"55AA55AA5C000000\";\t//\r\n\t}\r\n\r\n\thex_ans0 = \"00000000\";\t\t\t// 16\talways zero\r\n\thex_ans0+= cre_charname();\t\t// 20\r\n\thex_ans0+= \"20\";\t\t\t\t// 36\r\n\thex_ans0+= cre_progression();\t// 37\r\n\thex_ans0+= \"0000\";\t\t\t\t// \r\n\thex_ans0+= cre_class();\t\t\t// 40\r\n\thex_ans0+= \"101E\";\t\t\t\t// 41\r\n\thex_ans0+= cre_level1();\t\t// 43\r\n\thex_ans0+= \"00000000\";\t\t\t// 44\r\n\thex_ans0+= cre_UTCtime();\t\t// 48\tUTC time stamp\r\n\thex_ans0+= \"FFFFFFFF\";\t\t\t// 52\r\n\thex_ans0+= cre_skillkey();\t\t// 56\t4 x 20skills\r\n\thex_ans0+= wearing0;\t// 136 wearing in select screen\r\n\thex_ans0+= \"800000\";\t\t\t// 168\twhere you playing\r\n\thex_ans0+= \"0DA1931C\";\t\t\t// 171\t?\r\n\thex_ans0+= \"0000\";\t\t\t\t// 175\r\n\thex_ans0+= cre_mercID();\t\t// 177\tE5 0F 44 62 \r\n\thex_ans0+= cre_mercdata();\t\t// 183\r\n\thex_ans0+= cre_repeat(\"00\",144);\t// 191\r\n\r\n\thex_ans1 = \"576F6F21\";\t\t\t// 335\tWoo! ?\r\n\thex_ans1+= \"060000002A01\";\t\t// 339\r\n\thex_ans1+= \"01000110011001100110011001100100\";\t// quest data (apply all)\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"01000110011201100100000000000000\";\r\n\thex_ans1+= \"00000000000001100110011001100110\";\r\n\thex_ans1+= \"51170000000000000000000000000100\";\r\n\thex_ans1+= \"01000110011001100110011001100100\";\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"01000110011201100120000000000000\";\r\n\thex_ans1+= \"00000000000001100110011001100110\";\r\n\thex_ans1+= \"51170000000000000000000000000100\";\r\n\thex_ans1+= \"01000110011001100110011001100100\";\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"00000110011001100110011001100100\";\r\n\thex_ans1+= \"01000110011201100100000000000000\";\r\n\thex_ans1+= \"00000000000001100110011001100110\";\r\n\thex_ans1+= \"51170000000000000000000000000000\";\r\n\r\n\thex_ans1+= \"5753010000005000\";\t// 633\tWS....P.\r\n\thex_ans1+= \"0201FFFFFFFFFFFFFFFFFFFFFFFFFFFF\";\t// 633\tway point\r\n\thex_ans1+= \"00000000000000000201FFFFFFFFFFFF\";\r\n\thex_ans1+= \"FFFFFFFFFFFFFFFF0000000000000000\";\r\n\thex_ans1+= \"0201FFFFFFFFFFFFFFFFFFFFFFFFFFFF\";\r\n\thex_ans1+= \"000000000000000001\";\r\n\r\n\thex_ans1+= \"773400AEBEA5B907000000AEBEA5F907\";\t// 714\ttalk to NPC\r\n\thex_ans1+= \"000000AEBEA5B9070000000000000000\";\r\n\thex_ans1+= \"00000000000000000000000000000000\";\r\n\thex_ans1+= \"000000\";\r\n\r\n\thex_ans2 = \"6766\";\t\t\t\t// 765 gf\tstarting character stats data\r\n\thex_ans2+= cre_statdata();\r\n\r\n\thex_ans2+= \"6966\";\t\t\t\t// if\t character skill data\r\n\thex_ans2+= cre_skilldata();\r\n\r\n\thex_ans2+= cre_itemdata();\t\t// character item data\r\n\r\n//file size\r\n\thex_dum = hex_head + hex_ans0 + hex_ans1 + hex_ans2;\r\n\r\n\thex_size = hex_dum.length / 2 + 8;\r\n\r\n//check sum\r\n\thex_dum = hex_head + dec_hex(hex_size,4) + \"00000000\" + hex_ans0 + hex_ans1 + hex_ans2;\r\n\r\n\thex_chksum = checksum(hex_dum);\r\n\r\n\thex_dum = hex_head + dec_hex(hex_size,4) + dec_hex(hex_chksum,4) + hex_ans0 + hex_ans1 + hex_ans2;\r\n\r\n\thex_dum = hex_dum.toUpperCase();\r\n\r\n\thex_ans = \"\";\r\n\r\n\tvar filesize = hex_dum.length / 2;\r\n\r\n\tfor(i = 0; i < hex_dum.length; i+=2) hex_ans += String.fromCharCode(32) + hex_dum.substr(i,2);\r\n\r\n\tfor(hex_dum = \"\",i = 0; i*48 < hex_ans.length; i++) hex_dum += \"e\" + tohex(i+16,16) + \"0\" + hex_ans.substr(i*48,48) + String.fromCharCode(13);\r\n\r\nhex_dum += \"rcx\" + String.fromCharCode(13) + tohex(filesize,16) + String.fromCharCode(13) + \"n\" + document.stats_sheet.chr_name.value + \".d2s\" + String.fromCharCode(13) + \"w\" + String.fromCharCode(13) + \"q\" + String.fromCharCode(13) + \":begin\" + String.fromCharCode(13) + \"debug<%0>nul\" + String.fromCharCode(13);\r\nhex_dum = \";@echo off\" + String.fromCharCode(13) + \";goto begin\" + String.fromCharCode(13) + hex_dum;\r\n\r\n\tdocument.last_sheet.hex_answer.value = hex_dum;\r\n\t\r\n\t//WriteBatchFile(hex_ans);\r\n\talert(\"=== 存档建立成功! ===\" + tohex(256,16));\r\n\tdocument.last_sheet.hex_answer.focus();\r\n\tdocument.last_sheet.hex_answer.select();\r\n}", "async function onCreateGame (e) {\n\n // create a new Dat archive\n const game = await DatArchive.create()\n\n // Create architecture for application.\n await game.mkdir('/img')\n await game.mkdir('/css')\n await game.mkdir('/js')\n\n // Read originals essential build files.\n const html = await archive.readFile('index.html')\n const bundle = await archive.readFile('bundle.js')\n const animation = await archive.readFile('/js/animate.js')\n const dragdrop = await archive.readFile('/js/dragdrop.js')\n const beakerAPI = await archive.readFile('js/beakerapi.js')\n const cssmain = await archive.readFile('/css/main.css')\n const img = await archive.readFile('/img/sir-tim-berners-lee.jpg', 'base64')\n\n // Writing corresponding file for newly created app.\n await game.writeFile('index.html', html)\n await game.writeFile('bundle.js', bundle)\n await game.writeFile('/js/animate.js', animation)\n await game.writeFile('/js/beakerapi.js', beakerAPI)\n await game.writeFile('/js/dragdrop.js', dragdrop)\n await game.writeFile('/css/main.css', cssmain)\n await game.writeFile('/img/sir-tim-berners-lee.jpg', img, 'base64')\n\n // Save our dat url to local library\n .then(archive => {\n localStorage.targetDatURL = game.url\n console.log('Created and saved!')\n })\n\n // open newly created dat in browser window...\n window.location = game.url\n }", "function initGameData() {\n //Load shapes\n if (!shapeMatrix) {\n Utility.loadJson(\"../src/data/shapeMatrix\").then(json => shapeMatrix = json);\n }\n //Load images\n if (!colors) {\n Utility.loadJson(\"../src/data/colors\").then(json => colors = json);\n }\n //Load init game data\n if (!dropIntervall) {\n Utility.loadJson(\"../src/data/initData\").then((json) => {\n //Initialize data\n dropIntervall = json.dropInterval;\n currentTime = json.currentTime;\n scoreBorder = json.scoreBorder;\n player = json.player;\n direction = json.direction;\n gameIsOver = json.gameIsOver;\n gameIsRunning = json.gameIsRunning;\n });\n }\n}", "function GameDataObject() {\n\t// object type\n\tthis.type = 'GameDataObject';\n\n\t// game data id for referencing\n\tthis.id = '';\n\n\t// contains the assemblage for the data item\n\tthis.assemblage = '';\n\n\t// contains the components for the data item\n\tthis.components = new Array();\n\n\t// contains the actual data\n\tthis.data = {};\n}", "function get_new_gamedata() {\r\n\treturn {\r\n\t\t'turn' : 0,\r\n\t\t'board' : [-1, -1, -1, -1, -1, -1, -1, -1, -1],\r\n\t\t'ended' : false\r\n\t};\r\n}", "static async getGamesData() {\r\n\t\t// Doi du lieu tra ve tu game.json moi tiep tuc\r\n\t\tconst result = await fetch('game.json');\r\n\t\t// Doi loc du lieu tra ve xong roi moi tiep tuc\r\n\t\tconst data = await result.json();\r\n\t\t// Lay thong tin can thiet trong du lieu da loc\r\n\t\t// Du lieu tra ve la mot mang object\r\n\t\tlet games = data.items;\r\n\r\n\t\t// Tao mot mang object moi voi du lieu da duoc toi gian hoa\r\n\t\tgames = games.map(x => {\r\n\t\t\tconst { title, price } = x.fields;\r\n\t\t\tconst { id } = x.sys;\r\n\t\t\tconst img = x.fields.image.fields.file.url;\r\n\t\t\treturn { title, price, id, img };\r\n\t\t});\r\n\r\n\t\t// Tra ve du lieu cho nguoi dung\r\n\t\treturn games;\r\n\t}", "function createGame () {}", "function genCirclePackData(data) {\n\n var vData = { name: \"genre\", children: data };\n \n return vData;\n }", "function setupGameData() {\n // only run it the first time we play\n if (dataTotal === 0) {\n\n // music setup\n STARZ.SoundManager.init('audio');\n STARZ.SoundManager.addMusic('title');\n STARZ.SoundManager.addMusic('gameplay');\n STARZ.SoundManager.addFX('bonus');\n STARZ.SoundManager.addFX('hurry');\n STARZ.SoundManager.addFX('locked');\n STARZ.SoundManager.addFX('broken');\n STARZ.SoundManager.addFX('correct');\n STARZ.SoundManager.addFX('incorrect');\n\n // button setup\n UI.ButtonFX.init('.button1');\n\n STARZ.ScreenManager.showScreen('#loading');\n STARZ.JSONLoader.load('data/images.json', tvDataLoaded, gameError);\n STARZ.JSONLoader.load('data/quiz.json', quizDataLoaded, gameError);\n } else {\n STARZ.ScreenManager.showScreen('#titleScreen');\n }\n }", "function createNewGameFile(data){\r\n let filename = 'game' + data.game.gameId + \".json\";\r\n data = JSON.stringify(data, null, 4);\r\n status = writer.writeNew(data, filename)\r\n return status;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
spicchio di sfera di "gradi" radianti, ruotato di alpha, traslato di trasla (opzionale)
function sfera (r,gradi,alpha,trasla) { if (trasla === undefined) { trasla = []; }; var tx = trasla[0] || 0; var ty = trasla[1] || 0; var tz = trasla[2] || 0; var funzione = function (p) { var a = p[0] * PI/2; var b = alpha + p[1] * gradi; return [tx + r * COS(a) * SIN(b),ty + r * COS(a) * COS(b),tz + r * SIN(a)]; } return funzione; }
[ "function conversion_grados_radianes(nombre_unidad, valor_unidad){\n var varRadianes, varGrados;\n valor_unidad = valor_unidad.replace(\",\", \".\");\n if(isNaN(valor_unidad)){\n alert(\"Por favor ingresa un valor numérico, gracias!\");\n document.getElementsByTagName(\"input\")[0].value = \"\";\n document.getElementsByTagName(\"input\")[1].value = \"\";\n }\n else {\n if (nombre_unidad == 'grados') {\n varGrados = valor_unidad;\n varRadianes = Math.PI / 180 * valor_unidad;\n }\n if (nombre_unidad == 'radianes') {\n varRadianes = valor_unidad;\n varGrados = 180 / Math.PI * valor_unidad;\n }\n document.getElementsByTagName(\"input\")[0].value = varGrados;\n document.getElementsByTagName(\"input\")[1].value = varRadianes;\n }\n}", "function cilindro (r,h,gradi,alpha,trasla) {\n if (trasla === undefined) {\n trasla = [];\n };\n var x = trasla[0] || 0;\n var y = trasla[1] || 0;\n var z = trasla[2] || 0;\n\n var funzione = function (p) {\n var u = alpha + p[0] * gradi;\n var w = p[1] * h;\n\n return [x + r * COS(u), y + r * SIN(u), z + w];\n }\n\n return funzione;\n}", "function conversorgradosradianes(unidad, valor) {\n var valor_radianes, valor_grados;\n\n valor = valor.replace(',', '.');\n valor = valor.replace('°', '');\n\n if (isNaN(valor)) {\n alert(\"El valor ingresado en \" + unidad + \" es invalido.\")\n valor_radianes = \"\";\n valor_grados = \"\";\n }\n\n if (unidad == \"grados\") {\n valor_radianes = valor * Math.PI / 180;\n valor_grados = valor;\n }\n else if (unidad == \"radianes\") {\n valor_grados = valor * 180 / Math.PI;\n valor_radianes = valor;\n }\n\n document.conver_radgr.unid_grados.value = valor_grados;\n document.conver_radgr.unid_radianes.value = valor_radianes;\n}", "function arcocerchio (r,ty,tz,gradi,alpha) { \n var funzione = function (p) { \n var u = alpha + p[0] * gradi;\n\n return [r * SIN(u) , ty , tz + r * COS(u)];\n };\n\n return funzione;\n}", "function ocen_statycznie()\n{\n return szachownica.ocena.material + (szachownica.ocena.faza_gry * szachownica.ocena.tablice + (70 - szachownica.ocena.faza_gry) * szachownica.ocena.tablice_koncowka) * 0.03;\n}", "function g(RD) {\n return 1/Math.sqrt(1 + (3 * Q * Q * RD * RD / (Math.PI * Math.PI)))\n}", "getSemitono(gris) { \n let lugar = Math.floor(gris / (255 / this.ntonos));\n return this.ctx.getImageData(lugar*this.swidth, 0, this.swidth, this.sheight);\n }", "function beratBadanWanita(tinggi){\r\n let ideal = (tinggi - 100) - (tinggi -100) * 0.15\r\n return `Wanita = ${ideal} Kg`; \r\n}", "function diamentroCirculo (radio) {\n return radio * 2;\n \n}", "function hitungLuasSegitiga(alas,tinggi){\n var luas = 0.5 * alas * tinggi;\n return luas;\n}", "function Circolare2Quadrantale(rotta){\n let rottaQuad;\n if (rotta<=90){\n rottaQuad=rotta;\n }else if ((rotta>90) && (rotta<=180)){\n rottaQuad=180-rotta;\n }else if ((rotta>180) && (rotta<=270)){\n rottaQuad=rotta-180;\n }else if ((rotta>270) && (rotta<=360)){\n rottaQuad=360-rotta;\n }else{\n alert(\"Errore trasformazione rotta da circolare in quadrantale.\");\n }\n\n return rottaQuad;\n}//end funcction Circolare2Quadrantale(...)", "function MascaraRG(rg){\r\n if((rg)==false){\r\n event.returnValue = false;\r\n }\r\n return formataCampo(rg, '00.000.000-0', event);\r\n }", "function perimetroCirculo(radio){\n const diametro = radio * 2;\n return diametro * Math.PI;\n}", "raizQuadrada(){\n\n let ultimaOperacao = this.getUltimaOperacao();\n\n this.displayNumeros = Math.sqrt(ultimaOperacao);\n\n\n\n\n }", "function pazymiuVidurkis() {\n\nvar x = 5;\nvar y = 10;\nvar t = 8;\nvar w = 6;\nvar r = 8;\nvar vidurkis = (( x + y + t + w + r)/5);\nconsole.log(\"vidurkis (5,10,8,6,8) yra:\",vidurkis);\nconsole.log(\"skaiciuoti vidurki\");\n}", "function estiloVictoriano() {\n //definir ancho en px del borde de la figura\n //strokeWeight(px);\n strokeWeight(5);\n\n //definir el color del trazo\n //stroke(color) \n //noStroke()\n stroke(200, 50, 66, 156)\n\n //Definir el color del relleno\n //fill(color);\n //noFill();\n fill(100, 2, 1)\n}", "function luasLingkaran(r){\nlet pi=3.14;\n hasil=pi*r*r;\n console.log(\"luas lingkaran=\"+hasil)\n}", "function stDoRad(stopnie) {\n // 1 rad = 180st/pi = 57.296st\n let radiany = stopnie / (180 / Math.PI);\n return radiany;\n}", "function inv_gam_sRGB(ic) {\n\n let c = ic / 255.0;\n\n if (c <= 0.04045) {\n return c / 12.92;\n } else {\n return Math.pow(((c + 0.055) / (1.055)), 2.4);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log('participants at useEffect in Call.js line 25:', callObject.participants())
function handleNewParticipantsState(event) { //debugger // event.participant.owner = true if event.participant.local AND user.is_admin? if (event) { event.participant.owner = true } console.log('callObject.partis @ handlenewparticipants:', callObject.participants()) // event && logDailyEvent(event) // console.log('event @ handleNewPartcipantsState (Call.js ln 34):', event, Date.now()) // console.log('callObject @ handleNewPartcipantsState:', callObject) dispatch({ type: PARTICIPANTS_CHANGE, participants: callObject.participants(), }) }
[ "get activeParticipants () {\n return this.participants.filter(p => p.status === CallParticipantStatus.ACTIVE)\n }", "function resolvePendingCalls(participantDict) {\n console.log(\"Participant list arrived from the server.\");\n\n // Store the names of participants you received from the server.\n for (let userId in participantDict) {\n participants[userId] = participantDict[userId];\n }\n\n // Accept or reject each pending calls to presenterPeer.\n while (presenterPeer.pendingCalls.length > 0) {\n let call = presenterPeer.pendingCalls.shift();\n acceptOrDeclineCall(call, presenterPeer, stream);\n }\n\n // Accept or reject each pending calls to screenPeer.\n while (screenPeer.pendingCalls.length > 0) {\n let call = screenPeer.pendingCalls.shift();\n\n // Answer only if you are sharing screen.\n if (screenStream) {\n acceptOrDeclineCall(call, screenPeer, screenStream);\n }\n }\n\n // Now you do not have to keep calls pending. You're ready.\n isReady = true;\n }", "function getParticipants() {\r\n chatService.getParticipants(conId).then(function(participants) {\r\n scope.authors = participants;\r\n loadHistory();\r\n }, function(err) {\r\n console.log(err);\r\n });\r\n }", "_userListReceived(userList) {\n const { updatable } = this.props;\n const memberProfiles = userList.filter(user => updatable.members.indexOf(user._id) > -1);\n\n GroupActions.userListReceived(userList);\n GroupActions.membersReceived(memberProfiles);\n }", "function WaitingParticipantView(props) {\n\n let {\n _waitingList = [],\n _isWaitingEnabled = false,\n _conferenceId\n } = props;\n\n // Holds the jid of the waiting participant on whom the action is to be taken.\n // setJids should be set only when trying to update waiting participant. \n // So because, _updateWaitingParticipant call is made from useEffect.\n const [ jids, setJids ] = useState([])\n useEffect(() => {\n async function call() {\n let res = await _updateWaitingParticipant(true)\n\n // update the waiting list in the store if update call succeeds\n res && APP.store.dispatch(removeWaitingParticipants(jids)) && setJids([])\n \n }\n jids.length > 0 && call();\n }, [jids]);\n\n // Holds the host's decision to admit/reject the waiting participant.\n const [ status, setStatus ] = useState(false);\n\n //Holds the collapse state of the waiting list participants container\n const [ collapsed, setCollapsed ] = useState(false);\n\n\n const formWaitingParticipantRequestBody = () => {\n let participants = []\n typeof jids === \"object\" && jids.forEach((jid) => {\n participants.push({\n jid,\n status\n })\n })\n\n return {\n 'conferenceId': _conferenceId,\n participants\n }\n };\n\n const [ _updateWaitingParticipant ] = useRequest({\n url: `${config.conferenceManager + config.authParticipantsEP}`,\n method: 'put',\n body: formWaitingParticipantRequestBody\n });\n\n\n const updateWaitingParticipant = async (_jid, admit) => {\n if(typeof _jid === \"string\" && _jid === \"all\") {\n _jid = _waitingList.map((p) => p.jid)\n }\n setStatus(admit ? 'APPROVED' : 'REJECTED');\n setJids(_jid);\n }\n\n // Toggle waiting participants collapse view\n const toggleContainer = () => {\n setCollapsed(!collapsed)\n }\n\n /**\n * Implements React's {@link Component#render()}.\n *\n * @inheritdoc\n * @returns {ReactElement}\n */\n\n return (\n <>\n {\n //_waitingList.length > 0 &&\n _isWaitingEnabled &&\n <div className = 'waiting-list'>\n <div className = {`waiting-list__header ${_waitingList.length == 0 ? 'no-action' : ''}`}\n onClick = { toggleContainer }>\n <div>\n { `Waiting to join (${_waitingList.length}) ...` } \n </div>\n {\n _waitingList.length > 0 &&\n <div>\n <Icon\n size = { 24 }\n color = { '#3a3a3a' }\n src = { collapsed ? IconMenuDown : IconMenuUp } \n />\n </div>\n }\n </div>\n {\n _waitingList.length > 0 &&\n <div className = {`waiting-list__content ${collapsed ? 'collapsed' : ''}`}>\n {\n _waitingList.length > 1 &&\n <div className=\"waiting-actions__all\">\n <div className={`participants-list__mask${jids.length == 0 ? '__hidden': ''}`}></div>\n\n <button \n className='waiting-actions__all__btn waiting-actions reject'\n onClick = {() => {\n updateWaitingParticipant('all', false)\n }}\n >\n \n <Icon\n size = { 16 }\n src = { IconRejectAll } \n />\n {'Reject All'}\n </button>\n\n <button \n className='waiting-actions__all__btn waiting-actions admit'\n onClick = {() => {\n updateWaitingParticipant('all', true)\n }}\n >\n <Icon\n size = { 16 }\n src = { IconAdmitAll } \n />\n {'Admit All'}\n </button>\n </div>\n }\n <ul className = {`participants-list__list`}>\n {\n _waitingList\n .map(participant => {\n return (<li key = { participant.jid }>\n <div className={`participants-list__mask${!jids.includes(participant.jid) ? '__hidden': ''}`}></div>\n <div className = 'participants-list__label'>\n <Avatar size={ 32 } \n displayName={ participant.username } \n url={ participant.avatarUrl }/>\n <div \n title = {participant.username}\n className = 'participants-list__participant-name'>\n {participant.username}\n </div>\n </div>\n <div className = 'participants-list__controls'>\n <button \n className='waiting-actions reject'\n onClick = {() => {\n updateWaitingParticipant([participant.jid], false)\n }}\n >\n {'Reject'}\n </button>\n\n <button \n className='waiting-actions admit'\n onClick = {() => {\n updateWaitingParticipant([participant.jid], true)\n }}\n >\n {'Admit'}\n </button>\n </div>\n </li>);\n }\n )\n }\n </ul>\n </div>\n }\n \n </div>\n }\n </>\n );\n}", "getParticipants() {\n return this.participants;\n }", "generateEndpoints () {\n return this.participants.reduce((body, user) => {\n const interlocutorsEndpoints = {\n ...this.participants // eslint-disable-line\n .filter(p => p.id !== user.id)\n .reduce((res, p) => ({\n ...res,\n ['play-' + p.id]: {\n kind: 'WebRtcPlayEndpoint',\n force_relay: false,\n src: `local://${this.id}/${p.id}/publish`\n }\n }), {})\n }\n\n return {\n ...body,\n [user.id]: {\n credentials: 'test',\n kind: 'Member',\n // on_join: 'grpc://127.0.0.1:9099',\n // on_leave: 'grpc://127.0.0.1:9099',\n pipeline: {\n ...publicPipelineEndpoint,\n ...interlocutorsEndpoints\n }\n }\n }\n }, {})\n }", "if (isCallResult(staticTrace)) {\n // call results: reference their call by `resultCallId` and vice versa by `resultId`\n // NOTE: upon seeing a result, we need to pop *before* handling its potential role as argument\n const beforeCall = beforeCalls.pop();\n // debug('[callIds]', ' '.repeat(beforeCalls.length), '<', beforeCall.traceId, `(${staticTrace.displayName} [${TraceType.nameFrom(this.dp.util.getTraceType(traceId))}])`);\n if (staticTrace.resultCallId !== beforeCall.staticTraceId) {\n logError('[resultCallId]', beforeCall.staticTraceId, staticTrace.staticTraceId, 'staticTrace.resultCallId !== beforeCall.staticTraceId - is trace result of a CallExpression-tree? [', staticTrace.displayName, '][', trace, '][', beforeCall);\n beforeCalls.push(beforeCall); // something is wrong -> push it back\n }\n else {\n beforeCall.resultId = traceId;\n trace.resultCallId = beforeCall.traceId;\n }\n }", "function logParticipants(){\n console.log('Current PAarticipants'); \n for(i=0; i<participants.length; i++){\n console.log(' ' + participants[i].username);\n }\n }", "gatherIceCandidates () {\n return this.client.gatherIceCandidates(this)\n }", "startCall () {\n this.removeState(RoomState.Inactive)\n this.addState(RoomState.Active)\n this.startTime = new Date().getTime()\n this.declines = 0\n\n this.notify({\n data: {\n participants: this.participants.map(p => p.serialize()),\n startTime: this.startTime,\n roomId: this.id\n },\n method: SocketMessage.CallStarted\n })\n }", "join (id) {\n const user = this.participants.find(p => p.id === id)\n if (user) {\n user.status = CallParticipantStatus.ACTIVE\n } else {\n const user = new Participant({ id, status: CallParticipantStatus.ACTIVE })\n this.participants.push(user)\n }\n\n user.activeRoomId = this.id\n\n user.notify({\n data: {\n participants: this.participants.map(user => user.serialize()),\n startTime: this.startTime,\n roomId: this.id\n },\n method: SocketMessage.CallStarted\n })\n }", "componentDidUpdate(prevProps, prevState, snapshot) {\n\n //avoid infinite looping\n if(this.props.conversation.participants !== prevProps.conversation.participants)\n {\n this.setState({\n sender:this.props.participants[this.state.currentUser],\n recipient:this.props.participants[this.state.sender]\n })\n this.connect();\n this.loadMessages()\n }\n }", "init(participants, pricing) {\r\n this.isBusy = true;\r\n if(Array.isArray(participants)){\r\n if(participants.length == 0 || participants.every((item) => 'seniorityLevel' in item)) {\r\n this.participants = participants;\r\n }\r\n }\r\n if (typeof pricing === \"object\" && pricing != null) {\r\n this.pricing = pricing;\r\n }\r\n this.isBusy = false;\r\n }", "function grabChatsAfterStateChange() {\n firebase.auth().onAuthStateChanged(function (somebody) {\n let chatList = []\n if (somebody) {\n grabAllChatsWithUserId().then(result => {\n result.forEach(docSnapshot => {\n chatList.push(docSnapshot.data().chat);\n\n })\n let uniqueChatlist = [...new Set(chatList)]\n\n if (uniqueChatlist.length === 0) {\n noChatsYet();\n } else {\n getChatData(uniqueChatlist)\n }\n\n\n });\n }\n })\n}", "function addOnParticipantsChange() {\n\n window.WAPI.onParticipantsChanged = async function (groupId, callback) {\n return await window.WAPI.waitForStore(['Chat', 'Msg'], () => {\n const subtypeEvents = [\n 'invite',\n 'add',\n 'remove',\n 'leave',\n 'promote',\n 'demote'\n ];\n const chat = window.Store.Chat.get(groupId);\n //attach all group Participants to the events object as 'add'\n const metadata = window.Store.GroupMetadata.default.get(groupId);\n if (!groupParticpiantsEvents[groupId]) {\n groupParticpiantsEvents[groupId] = {};\n metadata.participants.forEach((participant) => {\n groupParticpiantsEvents[groupId][participant.id.toString()] = {\n subtype: 'add',\n from: metadata.owner\n };\n });\n }\n let i = 0;\n chat.on('change:groupMetadata.participants', (_) =>\n chat.on('all', (x, y) => {\n const { isGroup, previewMessage } = y;\n if (\n isGroup &&\n x === 'change' &&\n previewMessage &&\n previewMessage.type === 'gp2' &&\n subtypeEvents.includes(previewMessage.subtype)\n ) {\n const { subtype, from, recipients } = previewMessage;\n const rec = recipients[0].toString();\n if (\n groupParticpiantsEvents[groupId][rec] &&\n groupParticpiantsEvents[groupId][recipients[0]].subtype == subtype\n ) {\n\n } else {\n //ignore the first message\n if (i == 0) {\n //ignore it, plus 1,\n i++;\n } else {\n groupParticpiantsEvents[groupId][rec] = {\n subtype,\n from\n };\n\n callback({\n by: from.toString(),\n action: subtype,\n who: recipients\n });\n chat.off('all', this);\n i = 0;\n }\n }\n }\n })\n );\n return true;\n });\n };\n}", "async function getInteractions(query, res) {\n\n //Create an array that will hold all interactions and the data we care about for displaying to the end user in the UI.\n //NOTE: May want to update to a class in the future to optimize??\n let interactionContext = [{\n CallSid: \"\",\n CallStatus: \"\",\n StatusDate: new Date(),\n CallerSid: \"\",\n CallerName: \"\",\n RecipientSid: \"\",\n RecipientName: \"\",\n Voice: false,\n Content: \"\",\n RecSid: \"\"\n }];\n interactionContext.pop(); //Remove the initial values (probably a better way to enforce types during initialization without needed to do this?)\n\n //Retrive a list of all interactions associated with the contextual proxy service \n let interactionList = await client.proxy.services(query.serviceSid)\n .sessions(query.sessionSid)\n .interactions\n .list();\n \n for(const [index, interaction] of interactionList.entries())\n {\n //For each interaction, initialize each variable in the interactionContext array. We will populate and push to the array\n let callSid = \"\";\n let callStatus = \"\";\n let statusDate = new Date();\n let callerSid = \"\";\n let callerName = \"\";\n let recipientSid = \"\";\n let recipientName= \"\";\n let voice = false;\n let content = \"\";\n let recSid = []; \n \n if(interaction.outboundParticipantSid == query.participantSid)\n {\n //This participant acted as the reciever of this interaction (ie. call or sms)\n recipientSid = interaction.outboundParticipantSid;\n recipientName = query.participantName;\n callerSid = interaction.inboundParticipantSid;\n\n //Determine who the initalizing participant was for this interaction \n let participant = await client.proxy.services(query.serviceSid)\n .sessions(query.sessionSid)\n .participants(interaction.inboundParticipantSid)\n .fetch();\n callerName = participant.friendlyName;\n }\n else if(interaction.inboundParticipantSid == query.participantSid)\n {\n //This participant acted as the initializer of this interaction (ie. call or sms)\n callerSid = interaction.inboundParticipantSid;\n callerName = query.participantName;\n recipientSid = interaction.outboundParticipantSid;\n\n //Determine who the receiving participant was for this interaction \n let participant = await client.proxy.services(query.serviceSid)\n .sessions(query.sessionSid)\n .participants(interaction.outboundParticipantSid)\n .fetch();\n recipientName = participant.friendlyName;\n }\n else{\n //This interaction was not associated to this participant, so we don't care to process it and will skip ahead to the next interaction\n break;\n }\n\n if(interaction.type == \"Voice\")\n {\n voice = true;\n //NOTE: Right now we only care about capturing the callSid for purposes of retrieving recordings. In the future, we may want to capture the messaging sid for SMS and do something specific with it\n callSid = interaction.inboundResourceSid; \n\n //Get the list of recordings for this call\n let listRecordings = await client.recordings.list({callSid: interaction.inboundResourceSid});\n\n for(const [index, recording] of listRecordings.entries())\n {\n //Push each recording associated with this call into the recSid array (part of our interactionContext). We later handle this in interactions.handlebars, but only link to the first element in the array. In the future, we may want additional functionality to handle all recordings tied to a specific call\n recSid.push(recording.sid);\n }\n }\n\n let data = JSON.parse(interaction.data);\n if(data.duration != null)\n {\n //For voice calls, the duration will be in seconds\n content = data.duration + \" seconds\";\n }\n else if(data.body != null)\n {\n //For SMS, the body will hold the message contents. We may have to be careful here and update our UI to only display partial message body so that the display doesn't get distorted when trying to display lengthy messages\n content = data.body;\n }\n\n //The status we care about is the outbound status because it tells us what the result of the interaction was\n //NOTE: In the future, should update the variable name to represent a more generic status (since SMS status is used here too) \n callStatus = interaction.outboundResourceStatus;\n let options = { year: '2-digit', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric'};\n statusDate = interaction.dateUpdated.toLocaleTimeString(\"en-US\", options); //In the future, may want to add sorting of interaction records by date\n\n //With all values accounted for, we can push the context of this interaction to the array\n interactionContext.push({\n CallSid: callSid,\n CallStatus: callStatus,\n StatusDate: statusDate,\n CallerSid: callerSid,\n CallerName: callerName,\n RecipientSid: recipientSid,\n RecipientName: recipientName,\n Voice: voice,\n Content: content,\n RecSid: recSid\n });\n }\n\n res.render('interactions', {\n interactions: interactionContext,\n selectedParticipant: query.participantName,\n sessionSid: query.sessionSid,\n serviceSid: query.serviceSid\n }); \n}", "getClientCalls() {\n\n }", "getPeopleFollowers(state) {\n return state.peopleFollowers;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the color (of the disk in the) cell and its state when filled
setFilled(color) { this.filled = true; this.color = color; }
[ "fillUncolored()\n {\n console.log(\"Original Color: \", this.state.bgColor);\n if (this.state.bgColor === \"white\" || this.state.bgColor === \"\")\n {\n this.fillCell();\n console.log(\"New Color: \", this.state.bgColor);\n }\n }", "function setFill(){\n if (black === 0) {\n fill(255);\n black = 1;\n }\n else {\n fill(0);\n black = 0;\n }\n}", "setColour(c){\n this.dragFill = c;\n }", "function setFillColorCell(cellId){\n for (var c = 0; c < cellColors.length; c++) {\n if(cellColors[c][0] == voronoiDiagram.cells[cellId].site.x && cellColors[c][1] == voronoiDiagram.cells[cellId].site.y){\n fill(cellColors[c][2]);\n }\n }\n }", "function setFilled(flag) {\n fillFlag = flag;\n repaint();\n }", "setSolid(x,y){ this.getCell(x,y)._solid = true;}", "function onFillEmptyClick() {\n \n let activeColor = $('.palette .active').css('background-color');\n let allCells = $('.cell');\n \n for (let index = 0; index < allCells.length; index = index + 1) {\n \n let cell = allCells[index];\n\n if ($(cell).css('background-color') == 'rgba(0, 0, 0, 0)') {\n \n $(cell).css('background-color', activeColor);\n \n }\n }\n }", "function paintFill(screenArr, row, column, newColor) {}", "function updateCellColors(){\n setCellColors();\n d3.selectAll('.dp_sphere appearance material')\n .attr('diffuseColor', function(d){return d.meta.color;});\n d3.selectAll('.node-circle')\n .attr('fill', function(d){return d.color;});\n d3.selectAll('.small_multiples_datapoint')\n .attr('fill', function(d){return d.meta.color;});\n d3.selectAll('.pca_datapoint')\n .attr('fill', function(d){return d.meta.color;});\n}", "function color_cell(color){\r\n let sz = g_canvas.cell_size;\r\n let sz2 = sz / 2;\r\n let x = 1 + g_bot.x*sz;\r\n let y = 1 + (g_bot.y- 1)*sz;\r\n let big = sz - 2; \r\n fill(color);\r\n noStroke();\r\n //strokeWeight(1);\r\n //stroke( 'white' ); \r\n rect(x, y, big, big ); \r\n}", "function progressCellColorToDefault(event) {\n var items = event.events;\n for (var i = 0; i < items.length; ++i) {\n var time = items[i].time.getTime();\n var cell = getCellByTime(time);\n if (cell) {\n cell.attr(\"fill\", _scaleConfig.bgColor);\n }\n }\n }", "_colorFillPaths() {\n if (this.fillColor) {\n this.element\n .querySelectorAll('.ck-icon__fill')\n .forEach((path) => {\n path.style.fill = this.fillColor;\n });\n }\n }", "function set_changecolor_39_1(){\nset_39_1.attr('fill','red');\n}", "setOpen(x,y){ this.getCell(x,y)._solid = false;}", "function click_on_filled_cell(d){\n if(d.selected == true){ states.active_cell = null; }\n else{ states.active_cell = d; }\n update();\n}", "function reset(){\n filledPixel = {};\n}", "function setFill(currentID) {\n if (lastID && occupyFill(lastID)) {\n $(\"#\" + lastID).css(\"fill\", \"red\");\n }\n else {\n $(\"#\" + lastID).css(\"fill\", \"inherit\");\n }\n lastID = currentID;\n $(\"#\" + currentID).css(\"fill\", \"yellow\");\n}", "function fillCell(context, cell, color) {\n var corners = cell.corners;\n context.fillStyle = color;\n context.strokeStyle = \"lightgray\";\n context.beginPath();\n context.moveTo(corners[corners.length - 1].x, corners[corners.length - 1].y);\n for (var i = 0; i < corners.length; i++) {\n context.lineTo(corners[i].x, corners[i].y);\t\n }\n \n context.closePath();\n context.fill();\n context.stroke();\n }", "function setFillColor(color) {\n fillColor = color;\n repaint();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reverses the order of the players array
function swapPlayers(playersArray) { playersArray.unshift(playersArray.pop()); }
[ "reverseInvaders() {\n let index = 0;\n for (let invader of this.invaders) {\n this.invaders[index].reverse();\n this.invaders[index].position.y += 50;\n index++;\n }\n }", "function down(index) {\r\n if (user_player_arr.length > 1 && index < ((user_player_arr.length) - 1)) {\r\n let up_player = user_player_arr.splice(index + 1, 1);\r\n let down_player = user_player_arr.splice(index, 1);\r\n let temp;\r\n temp = up_player[0];\r\n up_player[0] = down_player[0];\r\n down_player[0] = temp;\r\n user_player_arr.splice(index, 0, down_player[0], up_player[0]);\r\n show();\r\n }\r\n}", "function _rotatePlayers() {\n _players.push( _players.shift() );\n }", "getPlayerOrder() {\n var array = this.players;\n var curr_index = array.length;\n var temp_value;\n var rand_index;\n\n // While there remain elements to shuffle...\n while (0 !== curr_index) {\n\n // Pick a remaining element...\n rand_index = Math.floor(Math.random() * curr_index);\n curr_index -= 1;\n\n // And swap it with the current element.\n temp_value = array[curr_index];\n array[curr_index] = array[rand_index];\n array[rand_index] = temp_value;\n }\n\n return array;\n }", "function up(index) {\r\n if (user_player_arr.length > 1 && index > 0) {\r\n let up_player = user_player_arr.splice(index, 1);\r\n let down_player = user_player_arr.splice(index - 1, 1);\r\n let temp;\r\n temp = up_player[0];\r\n up_player[0] = down_player[0];\r\n down_player[0] = temp;\r\n user_player_arr.splice(index - 1, 0, down_player[0], up_player[0]);\r\n show();\r\n }\r\n}", "function jatekosSorrend(){\n\tgetPlayOrder(winner);\n\tplayerOrder.length = 4;\n\tconsole.log(\"Player order is : \" + playerOrder + \" round is: \" + round);\n\t\n\tfor(i=0; i<playerOrder.length; i++){\n\t\toriginalPlayerOrder.push(playerOrder[i]);\n\t}\n\toriginalPlayerOrder.length = 4;\n}", "function sortDescending(arr){\r\n const array = arr;\r\n arr = [];\r\n array.length = 0;\r\n console.log(\"Descending\");\r\n array.splice(0, array.length);\r\n let decks = [\"♧A\",\"♤A\",\"♥A\",\"♦A\",\r\n\t\t\t \"♧2\",\"♤2\",\"♥2\",\"♦2\",\r\n \"♧3\",\"♤3\",\"♥3\",\"♦3\",\r\n \"♧4\",\"♤4\",\"♥4\",\"♦4\",\r\n \"♧5\",\"♤5\",\"♥5\",\"♦5\",\r\n \"♧6\",\"♤6\",\"♥6\",\"♦6\",\r\n \"♧7\",\"♤7\",\"♥7\",\"♦7\",\r\n \"♧8\",\"♤8\",\"♥8\",\"♦8\",\r\n \"♧9\",\"♤9\",\"♥9\",\"♦9\",\r\n \"♧10\",\"♤10\",\"♥10\",\"♦10\",\r\n \"♧J\",\"♤J\",\"♥J\",\"♦J\",\r\n \"♧Q\",\"♤Q\",\"♥Q\",\"♦Q\",\r\n \"♧K\",\"♤K\",\"♥K\",\"♦K\"\r\n];\r\n console.log(decks.reverse());\r\n}", "function mirrorMe() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tnewArray.push(oldArray[(oldArray.length - 1) - i]);\n\t}\n}", "function shuffleArray(players) {\r\n for (var i = players.length - 1; i > 0; i--) {\r\n var j = Math.floor(Math.random() * (i + 1));\r\n var temp = players[i];\r\n players[i] = players[j];\r\n players[j] = temp;\r\n }\r\n return players;\r\n }", "unmute(players) {\n const indexes = []\n _.forEach(players, p => {\n _.forEach(this.gameState.mutedPlayers, (muted, index) => {\n if (muted.id == p.id) {\n indexes.push(index)\n }\n })\n })\n _.pullAt(this.gameState.mutedPlayers, indexes)\n }", "reverse() {\r\n for (let i = 0; i < row; i++) {\r\n this.grid[i] = this.grid[i].reverse();\r\n }\r\n }", "ShiftPlayers ()\n\t{\n\t\tif (! this.aPlayerOrder) {\n\t\t\tthrow \"not good\";\t// TODO exceptions.\n\t\t}\n\n\t\t// The first player in the previous game becomes the last player in the next game, everybody else shifts accordingly.\n\t\tconst newOrder = _.clone(this.aPlayerOrder);\n\t\tnewOrder.push(newOrder.shift());\n\n\t\tthis.SetOrder(...newOrder);\n\t}", "reverse() {\n this.order.reverse();\n }", "reverseInPlace() {\n if (this._points.length >= 2) {\n let i0 = 0;\n let i1 = this._points.length - 1;\n while (i0 < i1) {\n const a = this._points[i0];\n this._points[i1] = this._points[i0];\n this._points[i0] = a;\n i0++;\n i1--;\n }\n }\n }", "function reverseNewArr(arr) {\n}", "function reorderPyramidPlayers() {\n var i = 1;\n _.forEach(vm.addedPlayers, function (player) {\n player.position = i;\n ++i;\n });\n }", "function RemovePlayerFromOrder (strPlayerOrder, leftIndex)\n{\n let strOrder = \"\";\n for (let i = 0; i < strPlayerOrder.length; i++)\n {\n let r = Number(strPlayerOrder[i]);\n if (r < leftIndex)\n {\n strOrder += r.toString();\n }\n else if (r > leftIndex)\n {\n strOrder += (r-1).toString();\n }\n //If it is equal then that player left and does not need to be in the order anymore... The people higher than him will be shifted to the left in the players array and their server index will decrease by 1.\n }\n\n return strOrder;\n}", "reverse() {\n // ignore on empty arrays\n if (this.length == 0) {\n return;\n }\n\n var oldArray = this.__array.concat();\n this.__array.reverse();\n\n this.__updateEventPropagation(0, this.length);\n\n this.fireDataEvent(\n \"change\",\n {\n start: 0,\n end: this.length - 1,\n type: \"order\",\n added: [],\n removed: []\n },\n\n null\n );\n\n // fire change bubbles event\n this.fireDataEvent(\"changeBubble\", {\n value: this.__array,\n name: \"0-\" + (this.__array.length - 1),\n old: oldArray,\n item: this\n });\n }", "function reverse_teams(matches){\n\tvar first_team = \"\";\n\tvar second_team = \"\";\n\tfor (var i = 0; i < matches.length; i++) {\n\t\tfirst_team = matches[i].team_one;\n\t\tsecond_team = matches[i].team_two;\n\t\tmatches[i].team_one = second_team;\n\t\tmatches[i].team_two = first_team;\n\t}\n\treturn matches;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Firebase cache ref for the given ip address
function ipCacheRef(ip) { var fbkey = ip.replace(/\./g, '-'); var url = process.env.FBIO_GEOCACHE_URL + "/" + fbkey; return new Firebase(url); }
[ "function refFromURL(db, url) {\n db = _firebaseUtil.getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() && repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' + ': Host name does not match the current database: ' + '(found ' + repoInfo.host + ' but expected ' + db._repo.repoInfo_.host + ')');\n }\n return ref(db, parsedURL.path.toString());\n}", "function refFromURL(db, url) {\n db = Object(_firebase_util__WEBPACK_IMPORTED_MODULE_2__[\"getModularInstance\"])(db);\n db._checkNotDeleted('refFromURL');\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')');\n }\n return ref(db, parsedURL.path.toString());\n}", "function refFromURL(db, url) {\n db = Object(_firebase_util__WEBPACK_IMPORTED_MODULE_2__[\"getModularInstance\"])(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n const repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')');\n }\n return ref(db, parsedURL.path.toString());\n}", "static getRef(path) {\n return firebase.database().ref(path);\n }", "getReferenceForValue(value) {\n let cachedRef = this._containerCache.get(value);\n\n if (cachedRef !== undefined) {\n return cachedRef;\n }\n\n let varRef = this._referenceMap.add(value);\n\n this._containerCache.set(value, varRef);\n\n return varRef;\n }", "function refFromURL(db, url) {\r\n db = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_2__.getModularInstance)(db);\r\n db._checkNotDeleted('refFromURL');\r\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n var repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}", "function refFromURL(db, url) {\n db = (0,_firebase_util__WEBPACK_IMPORTED_MODULE_2__.getModularInstance)(db);\n db._checkNotDeleted('refFromURL');\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (!db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')');\n }\n return ref(db, parsedURL.path.toString());\n}", "function refFromURL(db, url) {\n db = Object(_firebase_util__WEBPACK_IMPORTED_MODULE_2__[\"getModularInstance\"])(db);\n\n db._checkNotDeleted('refFromURL');\n\n var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n var repoInfo = parsedURL.repoInfo;\n\n if (!db._repo.repoInfo_.isCustomHost() && repoInfo.host !== db._repo.repoInfo_.host) {\n fatal('refFromURL' + ': Host name does not match the current database: ' + '(found ' + repoInfo.host + ' but expected ' + db._repo.repoInfo_.host + ')');\n }\n\n return ref(db, parsedURL.path.toString());\n}", "function getReferenceString(path) {\n\treturn `redisRef:///${path}`;\n}", "function getCurrentCacheLocation(key) {\n const now = Date.now()\n const secs = Math.floor(now / 1000)\n const mins = Math.floor(secs / 60)\n const hours = Math.floor(mins / 60)\n const days = Math.floor(hours / 24)\n const hash = crypto.createHash('sha1')\n .update(`${days}:${key}`)\n .digest('hex')\n\n return `cache/${hash}`\n}", "function cacheDns() {\n self.getServerTime(function (err) {\n if (!err) {\n calculateTimeDiff();\n } else {\n syncTime();\n }\n });\n }", "static get_grafana_url_by_ip(ip) {\n\t\treturn new Promise(async(resolve, reject) => {\n\t\t\ttry {\n\t\t\t\tconst res = await axios.get(`${url}graf_url/${ip}`);\n\t\t\t\tconst data2 = res.data;\n\t\t\t\tresolve(data2);\n\t\t\t} catch (err) {\n\t\t\t\treject(err);\n\n\t\t\t}\n\t\t});\n\n\t}", "queryDnsbl(ip) {\n\t\tif (exports.IPTools.dnsblCache.has(ip)) {\n\t\t\treturn Promise.resolve(exports.IPTools.dnsblCache.get(ip) || null);\n\t\t}\n\t\tconst reversedIpDot = ip.split('.').reverse().join('.') + '.';\n\t\treturn new Promise((resolve, reject) => {\n\t\t\texports.IPTools.queryDnsblLoop(ip, resolve, reversedIpDot, 0);\n\t\t});\n\t}", "cacheGet(id) {\n return this.cache[id]\n }", "function getDocFromCache(reference) {\n reference = cast(reference, DocumentReference$1);\n var firestore = cast(reference.firestore, Firestore$1);\n var client = ensureFirestoreConfigured(firestore);\n var userDataWriter = new ExpUserDataWriter(firestore);\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(function (doc) { return new DocumentSnapshot$1(firestore, userDataWriter, reference._key, doc, new SnapshotMetadata(doc !== null && doc.hasLocalMutations, \n /* fromCache= */ true), reference.converter); });\n}", "function cachedGet(url, cache) {\n var deferred = Q.defer();\n\n const options = {\n url: url,\n headers: {\n 'User-Agent': 'adoptopenjdk-admin openjdk-api'\n }\n };\n\n if (cache.hasOwnProperty(options.url) && Date.now() - cache[options.url].cacheTime < 120000) {\n console.log(\"cache property present\")\n // For a given file check at most once every 2 min\n console.log(\"cache hit cooldown\");\n deferred.resolve(cache[options.url].body);\n } else {\n console.log(\"Checking \" + options.url);\n request(options, function (error, response, body) {\n if (error !== null) {\n deferred.reject(formErrorResponse(error, response, body));\n return;\n }\n\n if (response.statusCode === 200) {\n cache[options.url] = {\n cacheTime: Date.now(),\n body: JSON.parse(body)\n };\n deferred.resolve(cache[options.url].body)\n } else {\n deferred.reject(formErrorResponse(error, response, body));\n }\n });\n }\n return deferred.promise;\n}", "function getterFactory(cache) {\n return getter\n\n /* Get a node from the bound definition-cache. */\n function getter(identifier) {\n var id = identifier && normalise(identifier)\n return id && own.call(cache, id) ? cache[id] : null\n }\n}", "function getCachedField(cacheRes, field) {\n if (cacheRes.length === 0) {\n return undefined;\n }\n return JSON.parse(cacheRes[0].body)[field];\n}", "function getCurrentCacheLocation(key) {\n const now = Date.now()\n const secs = Math.floor(now / 1000)\n const mins = Math.floor(secs / 60)\n const hours = Math.floor(mins / 60)\n const days = Math.floor(hours / 24)\n const hash = crypto.createHash('sha1')\n .update(`${days}:${key}`)\n .digest('hex')\n\n return `cache/${hash}.json`\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set whether collection is enabled for this ID.
function setAnalyticsCollectionEnabled(analyticsId, enabled) { window["ga-disable-" + analyticsId] = !enabled; }
[ "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\n window[\"ga-disable-\" + analyticsId] = !enabled;\n }", "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\n window[\"ga-disable-\" + analyticsId] = !enabled;\n}", "function setAnalyticsCollectionEnabled(initializationPromise, enabled) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var measurementId;\n return tslib.__generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, initializationPromise];\n case 1:\n measurementId = _a.sent();\n window[\"ga-disable-\" + measurementId] = !enabled;\n return [2 /*return*/];\n }\n });\n });\n}", "function _setAnalyticsCollectionEnabled(initializationPromise, enabled) {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(this, void 0, void 0, function () {\n var measurementId;\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , initializationPromise];\n\n case 1:\n measurementId = _a.sent();\n window[\"ga-disable-\" + measurementId] = !enabled;\n return [2\n /*return*/\n ];\n }\n });\n });\n }", "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\n window[\"ga-disable-\" + analyticsId] = !enabled;\n}", "function setAnalyticsCollectionEnabled(enabled) {\n firebase.analytics().setAnalyticsCollectionEnabled(enabled);\n}", "async enableCollection() {\n self.db = await self.apos.db.collection('aposMigrations');\n }", "enable() {\n this.enabled = true;\n }", "get isCollection() {\n return this.isSetView;\n }", "async setDeveloperFlag(collection, mode) {\n\n await this.getApiLock();\n\n let result = null;\n\n if (!this.isAuthenticated()) {\n console.error(\"reference_to_mongo_db.setDeveloper\", \"user is not authenticated.\");\n } else {\n console.info(\"Setting developer flag to: \" + mode);\n\n try {\n result = await this.promiseTimeout(this.reference_to_mongo_db.collection(collection).updateOne({\n user_id: this.stitch_actual_client.auth.user.id\n }, {\n $set: {\n is_developer: mode\n }\n }, {\n upsert: true\n }));\n localStorage.setItem(\"__stitch_dev_flag\", mode);\n } catch (e) {\n result = e;\n console.error(\"reference_to_mongo_db.setDeveloper\", e);\n }\n }\n\n this.apiUnlock();\n\n return result;\n }", "function toggleCollection(selectedCollection) {\n // If we are dealing with a single post the user can add and remove from collection\n // For mass updates of many post the user is only permitted to add to collection\n if ($scope.posts.length === 1) {\n if (_.contains($scope.posts[0].sets, String(selectedCollection.id))) {\n $scope.removeFromCollection(selectedCollection);\n } else {\n $scope.addToCollection(selectedCollection);\n }\n } else {\n $scope.addToCollection(selectedCollection);\n }\n }", "async enableCollection() {\n self.cacheCollection = await self.apos.db.collection('aposCache');\n await self.cacheCollection.createIndex({\n namespace: 1,\n key: 1\n }, { unique: true });\n await self.cacheCollection.createIndex({ expires: 1 }, { expireAfterSeconds: 0 });\n }", "function onSetCollection() {\n this.ensureRendered();\n}", "enable(key) {\n this.set(key, true)\n }", "set selectable(value) {\n this._selectable = value;\n }", "function onSetCollection(view, collection) {\n // Undefined to force conditional render\n var options = view.getObjectOptions(collection) || undefined;\n if (view.shouldRender(options && options.render)) {\n // Ensure that something is there if we are going to render the collection.\n view.ensureRendered();\n }\n}", "function onSelectCollection(collection) {\n return async (event) => {\n const isCheck = event.target.checked\n if (isCheck) {\n collections.forEach(c => {\n if(c.collectionInfo.lectureId === collection.collectionInfo.lectureId){\n c.isChecked = true\n } \n })\n setCollections([...collections])\n setNoSelectedCollections(false);\n } else {\n collections.forEach(c => {\n if(c.collectionInfo.lectureId === collection.collectionInfo.lectureId)\n c.isChecked = false\n })\n setCollections([...collections])\n }\n }\n }", "function isCollectionEditing(){\r\n\t\t\treturn loadingData.EDITING_COLLECTION;\r\n\t\t}", "toggleEnabled() {\n const self = this;\n if (!self.enabled) self.enable();\n else self.disable();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removeWidget called by the handleDrop func removes widget with id from origin which is either RightPanel or canvas.
removeWidget(id, origin){ let addOrPanelRemove; if (origin === 'Canvas'){ addOrPanelRemove = this.state.canvasWidgets; } else { addOrPanelRemove = this.state.rightPanelWidgets; } const newState = addOrPanelRemove.filter( el => el.widgetId !== id ); return newState; }
[ "handleDropRender(id, origin, target){\n if ( origin === target){\n return false;\n }\n let newCanvasWidget;\n let newRightPanelWidget;\n if ( origin === 'Canvas'){\n newCanvasWidget = this.removeWidget(id, origin);\n newRightPanelWidget = this.addWidget(id, target);\n }\n else {\n newCanvasWidget = this.addWidget(id, target);\n newRightPanelWidget = this.removeWidget(id, origin);\n }\n console.log(`Widget ${id} moved from ${origin} to ${target}`);\n this.setState({canvasWidgets: newCanvasWidget, rightPanelWidgets: newRightPanelWidget});\n }", "_onWidgetRemoved(sender, widget) {\n if (widget === this._lastCurrent) {\n this._lastCurrent = null;\n }\n algorithm_1.ArrayExt.removeAt(this._items, this._findWidgetIndex(widget));\n this._sideBar.removeTab(widget.title);\n this._refreshVisibility();\n }", "removeWidgetFromArea(aWidgetId) {\n CustomizableUIInternal.removeWidgetFromArea(aWidgetId);\n }", "removeWidget(widget) {\n this.native.removeWidget(widget.native);\n this.widgets.delete(widget.native);\n this.permanentWidgets.delete(widget.native);\n }", "_onWidgetRemoved(sender, widget) {\n if (widget === this._lastCurrent) {\n this._lastCurrent = null;\n }\n ArrayExt.removeAt(this._items, this._findWidgetIndex(widget));\n this._sideBar.removeTab(widget.title);\n this._refreshVisibility();\n }", "removeWidget(id) {\n this.focus(() => {\n var {\n editorState,\n contentState\n } = this._getDraftData();\n\n var selection = DraftUtils.findPattern(contentState, widgetRegexForId(id)); //eslint-disable-line max-len\n\n var newDraftData = DraftUtils.deleteSelection({\n editorState,\n selection\n });\n\n this._handleChange({\n editorState: newDraftData.editorState\n });\n });\n }", "function deleteWidget(){\n\ttry{\n\t\tvar l_id = $(\"#selected\").attr(\"l_id\");\n\t\tvar layer = widget_array[l_id][6];\n\n\t\t// remove from widget array\n\t\twidget_array[l_id] = emptyWidg();\n\n\t\t// remove from screen\n\t\t$(\"#selected\").remove();\n\n\t\t// set layers to adjust for one fewer widgets\n\t\tfor (i = 0; i < widget_array.length; ++i){\n\t\t\tif (widget_array[i][6] > layer){\n\t\t\t\twidget_array[i][6] = parseInt(widget_array[i][6]) - 1;\n\t\t\t}\n\t\t}\n\t\t// set num layers to 1 fewer\n\t\tslide_array[current_slide - 1].widget_count -= 1;\n\n\t\t// set selected to null\n\t\tsetSelected(null);\n\t}\n\tcatch(e){\n\t\tlog(\"widget_attr.js\", e.lineNumber, e);\n\t}\n}", "function onWidgetRemoved(sender, widget) {\n\t if (sender.childCount() === 0) {\n\t removeTabPanel(sender.parent);\n\t }\n\t }", "function widgetDrop(ui, widget, region) {\n var widgetType = ui.draggable.data('widget').id;\n performDrop(widgetType, region, widget);\n regionQueue = [];\n widgetStacks = {};\n updateDropFeedback();\n }", "_removeDropPointer() {\n if (!this.__dropPointer) {\n return;\n }\n this.shadowRoot.removeChild(this.__dropPointer);\n this.__dropPointer = undefined;\n }", "moveWidget (widgetId, location) {\n for (var r = 0; r < this.data.length; r++) {\n for (var w = 0; w < this.data[r].length; w++) {\n if (String(this.data[r][w].id) === String(widgetId)) {\n let widget = Object.assign({}, this.data[r][w])\n // Remove from data\n this.data[r].splice(w, 1)\n\n // Add to data\n this.addWidget(widget, location)\n\n this.clean()\n return\n }\n }\n }\n }", "_onRemove() {\n RB.DnDUploader.instance.unregisterDropTarget(this.$el);\n }", "function widgetDrag(e) {\n e.dataTransfer.setData(\"widgetID\", e.target.id);\n }", "function onWidgetDrop(event) {\n // Move the widget to the target widget.\n viewmodel.moveWidget(draggedWidget, viewmodel.getWidgetFromElementId(this.id));\n event.preventDefault();\n }", "function removeWidget(widget) {\n if (widget) {\n widgetObj = widget;\n return Widget.remove({ _id: widgetId });\n } else {\n errorMessage.message = \"Could not find widget with id\" + widgetId;\n throw new Error(errorMessage);\n }\n }", "function removeWidget(el, parent) {\r\n parent.removeChild(el);\r\n}", "function removeWidget(){\n\tfrmAnimation.hboxContainer.setVisibility(false, animationConfigDisable);\n}", "function removeWidget(arg_sceneName) {\n var widgetID = \"statusWidget_\" + arg_sceneName;\n var widgetToRemove = p.getnamed(widgetID);\n p.remove(widgetToRemove);\n}", "removeWidgetHandler() {\n const event = new CustomEvent(\"remove-widget\", {\n detail: {\n fname: this.getAttribute(\"fname\"),\n },\n });\n this.dispatchEvent(event);\n this.toggleMenu();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You need to cook pancakes, but you are very hungry. As known, one needs to fry a pancake one minute on each side. What is the minimum time you need to cook n pancakes, if you can put on the frying pan only m pancakes at a time? n and m are positive integers between 1 and 1000.
function cookPancakes(n, m) { return (m > n * 2 || n === 1) ? 2 : Math.ceil(n * 2 / m ); }
[ "function chocolateFeast(n, c, m) {\n var numberOfWrappers, numberOfChoclates;\n\n numberOfWrappers = numberOfChoclates = Math.floor(n / c);\n\n while (numberOfWrappers >= m) {\n var freeBars = Math.floor(numberOfWrappers / m);\n if (freeBars > 0) {\n numberOfChoclates += freeBars;\n numberOfWrappers -= freeBars * m;\n numberOfWrappers += freeBars;\n }\n }\n\n return numberOfChoclates;\n}", "function minimumPasses(m, w, p, n) {\n let currentPassTimes = 1;\n let currentCandies = m * w;\n let minPassTimes = Math.ceil(n / currentCandies);\n while (true) {\n if (currentCandies >= n) {\n minPassTimes = Math.min(minPassTimes, currentPassTimes);\n break;\n }\n if (currentPassTimes >= minPassTimes) {\n break;\n }\n const maxPurchaseAndHireNum = Math.floor(currentCandies / p);\n if (maxPurchaseAndHireNum > 0) {\n const mwGap = Math.abs(m - w);\n let addToLow = maxPurchaseAndHireNum;\n let addToHigh = 0;\n if (mwGap < maxPurchaseAndHireNum) {\n addToLow = mwGap + Math.ceil((maxPurchaseAndHireNum - mwGap) / 2);\n addToHigh = Math.floor((maxPurchaseAndHireNum - mwGap) / 2);\n }\n if (m <= w) {\n m += addToLow;\n w += addToHigh;\n } else {\n w += addToLow;\n m += addToHigh;\n }\n currentCandies -= maxPurchaseAndHireNum * p;\n const candiesToProduce = n - currentCandies;;\n const candiesMake = m * w;\n let extraPassTimes = currentPassTimes + Math.ceil(candiesToProduce / candiesMake);\n minPassTimes = Math.min(minPassTimes, extraPassTimes);\n currentCandies += m * w;\n currentPassTimes += 1;\n } else {\n let extraTimes = Math.ceil((p - currentCandies) / (m * w));\n currentPassTimes += extraTimes;\n currentCandies += m * w * extraTimes;\n }\n }\n return minPassTimes;\n}", "function cookingTime(eggs){\n return Math.ceil(eggs / 8) * 5;\n}", "function candies(n, m) {\n const candy = Math.floor(m / 3);\n\n return candy * n;\n}", "function cookingTime(eggs) {\n return Math.ceil(eggs / 8) * 5;\n}", "function manydonuts() {\r\n while(prizeCount.donut<500) {\r\n simulateonce()\r\n }\r\n}", "function hoopCount (n) {\n if(n >= 10) { return \"Great, now move on to tricks\";} \n return \"Keep at it until you get it\";\n}", "function chocolateFeast(n, c, m) {\n let wrappers = Math.floor(n/c);\n let totalChoc = Math.floor(n/c);\n while(wrappers >= m){\n totalChoc += Math.floor(wrappers/m);\n wrappers = Math.floor(wrappers/m) + wrappers %m;\n }\n return totalChoc;\n}", "function hoopCount (n) {\n return n < 10 ? 'Keep at it until you get it' : 'Great, now move on to tricks'\n }", "calcTime() {\n this.cookingTime = Math.ceil(this.ingredients.length / 3) * 15;\n }", "function hoopCount (n) {\n return (n < 10) ? 'Keep at it until you get it' : 'Great, now move on to tricks';\n}", "function sharePizza(people) {\n var numSlices = 8;\n var slicesPerPerson = numSlices / people;\n return ' Each person gets ' + slicesPerPerson + \" slices of pizza. \";\n\n}", "function hoopCount(n) {\r\n\r\n if (n > 9) {\r\n return \"Great, now move on to tricks\";\r\n }\r\n else {\r\n return \"Keep at it until you get it\";\r\n }\r\n}", "function chocolateFeast(n, c, m) {\n //total number of chocolate bar bought & num of wrapper\n var numOfBar = Math.floor(n / c);\n var numOfWrapper = Math.floor(n / c);\n\n while (numOfWrapper >= m) {\n var leftOverWraps = numOfWrapper % m;\n var barExchanged = Math.floor(numOfWrapper / m);\n numOfBar += barExchanged;\n //remaining number of wrapper\n numOfWrapper = leftOverWraps + barExchanged;\n }\n return numOfBar;\n\n}", "function startCooking() {\n count++\n var step_s__p_ = \"\";\n if (count == 1) {\n step_s__p_ = lemon();\n } else if (count == 2) {\n step_s__p_ = water();\n }else if (count == 3) {\n step_s__p_ = sugar();\n }else if (count == 4) {\n step_s__p_ = mix();\n }else if (count == 5) {\n step_s__p_ = lemonslice();\n }else if (count == 6) {\n step_s__p_ = umbrella();\n }else if (count == 7) {\n step_s__p_ = boil();\n }else if (count == 8) {\n step_s__p_ = pork();\n }\n cook(step_s__p_);\n}", "function fivehsk() {\r\n while (numdonutsk < 500) {\r\n oncesk();\r\n }\r\n}", "function growTomatoes() {\n console.log(\"1. Thoroughly moisten the seed-starting mix\");\n console.log(\"2. fill the containers to within 1/2 of the top\");\n console.log(\"3. Water to ensure good seed-to-mix contact\");\n console.log(\"4. Place the pots in a warm spot or on top of a heat mat\");\n console.log(\"5.Keep the mix moist but not soaking wet\");\n}", "function elevateLakes(){if(\"Atoll\"===templateInput.value)return;console.time(\"elevateLakes\");const e=pack.cells,t=pack.features,n=e.i.length/100;e.i.forEach(a=>{e.h[a]>=20||\"freshwater\"!==t[e.f[a]].group||t[e.f[a]].cells>n||(e.h[a]=20)}),console.timeEnd(\"elevateLakes\")}", "calculateCookingTime() {\n const numOfIngredients = this.ingredients.length;\n const timePeriod = Math.ceil(numOfIngredients / 3);\n this.cookingTime = timePeriod * 15;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions scrape CL, call the other functions to make and post the markov chain this is the function we call to make magic happen
function gen_markov() { // Scrape CL missed connections headlines request('http://austin.craigslist.org/mis/', function(error, response, body) { var final_text = []; if (!error && response.statusCode == 200) { var $ = cheerio.load(body); // Scrape the response HTML according to craigslist's (incredibly fucking messy) DOM layout var links = $(body).find('a.hdrlnk').each(function(i, elem){ var split_link = $(this).text().split(' -'); final_text.push((split_link[0])); }); } // make the markov *after* the request. Thanks, async post_to_twitter(markov(final_text)); }); }
[ "function callCreate() {\n\n multiMarkov.createMarkov(myval);\n\n\n}", "function processUrl(inputUrl){ \n axios\n .get(inputUrl)\n .then(function(resp){ \n let mm = new MarkovMachine(resp.data);\n console.log(mm.makeText(numWords=50));\n })\n .catch(function(err){\n console.log(`Error reading ${inputUrl}:`);\n console.log(`${err}`);\n process.exit(1);\n })\n}", "function callGenerateandOutput() {\n\n multiMarkov.generate();\n outputResult(multiMarkov);\n\n}", "function generateMarkov(text){\n let mm = new markov.MarkovMachine(text);\n console.log(mm.makeText());\n}", "function generateMarkov(){\n //the bot hasn't been trained yet\n if(trainingData.length==0) return 'Please teach me words first :)';\n\n console.log(\"generating...\");\n\n //constructs an array of strings by chaining them together. \n var sentenceFinished = false;\n var constructedSentence = [];\n //\"Start1\" prepended before training, so all markov chains begin with Start1.\n //\"Start1\" is never pushed to constructedSentence. it's just a tag.\n var currentWord = 'Start1';\n\n while(!sentenceFinished){\n //findIndex attempts to locate current word in trainingData\n //given the linked nature of training markov chains, we expect findIndex to be successful.\n var wordLocation = trainingData.findIndex((element) =>{\n return element[0] == currentWord;\n })\n \n //selects the next word randomly from the current word's array. \n var nextWord = trainingData[wordLocation][1][\n Math.floor(Math.random()*trainingData[wordLocation][1].length)\n ];\n\n //add this newly found word to constructedSentence.\n constructedSentence.push(nextWord);\n //update currentWord with our new word.\n currentWord = nextWord;\n\n //\"End1\" is the sentence end tag. if it was chosen, the sentence has reached a natural end.\n if(currentWord == 'End1'){\n sentenceFinished = true;\n }\n }\n // remove \"End1\" from the end of the array\n constructedSentence.pop();\n\n //concatenates all the strings in the sentence array. \n var connectedSentence = '';\n for(i in constructedSentence){\n connectedSentence += constructedSentence[i] + ' ';\n }\n //one final test for empty sentence\n if(connectedSentence.replace(/\\s/g, \"\") == \"\"){\n if(attempts++ == maxAttempts){\n return \"beep boop :)\";\n }\n return generateMarkov();\n }\n\n return connectedSentence;\n}", "function train(){\n clarifai.train('beard', cb).then(\n promiseResolved,\n promiseRejected \n );\n}", "generate() {\n this.len *= 0.5; //So the tree becomes denser instead of larger.\n this.branchValue += 1; //To ensure increased thickness of trunk.\n let nextSentence = \"\";\n for (let i = 0; i < this.sentence.length; i++) {\n let current = this.sentence.charAt(i);\n if (current === current.toLowerCase()) {\n current = current.toUpperCase();\n }\n let found = false;\n\n if (current === this.rules1.letter) {\n found = true;\n nextSentence += this.rules1.becomes;\n } else if (current === this.rules2.letter) {\n found = true;\n nextSentence += this.rules2.becomes;\n } else if (current === this.rules3.letter) {\n found = true;\n nextSentence += this.rules3.becomes;\n }\n\n if (!found) {\n nextSentence += current;\n }\n }\n this.sentence = nextSentence;\n }", "function train() {\n\n //(1)DT algorithm===============================================================================\n console.log(\"start the decision tree algorithm***************************\");\n var xtree = trainingSetX;\n /*console.log(\"xtree+++++++++++++++++\");\n console.log(xtree);*/\n //console.log(trainingSetYNum);\n var result2 = [];\n var resYCal = [];\n var classifier = new ml.DecisionTree({\n data: xtree,\n result: trainingSetYCal\n });\n classifier.build();\n\n for (var i = 0; i < testSetX.length; i++) {\n result2.push(classifier.classify(testSetX[i]));\n }\n //console.log(\"Object.keys(result2[0]\");\n\n\n //console.log(\"decision tree prediction testSetY: \");\n for (var i = 0; i < result2.length; i++) {\n resYCal.push(Object.keys(result2[i])[0]);\n }\n\n var predictionError = error(resYCal, testSetYCal);\n var treepredict = classifier.classify(todayActi);\n classifier.prune(1.0);\n //dt.print();\n /* console.log(\"resYCal++++++++++++++++++++++++\");\n console.log(resYCal);\n console.log(\"testSetYCal+++++++++++++++++++\");\n console.log(testSetYCal);\n console.log('Decision Tree algorithm result = ${predict}------------------');\n console.log(predict);*/\n // console.log(\"sleep quality will be:=======\");\n //console.log(Object.keys(treepredict)[0]);\n var tree_accuracy = Math.round((testSetLength - predictionError) / testSetLength * 100);\n /* console.log(\"decision tree prediction accuracy will be: test length-${testSetLength} and number of wrong predictions - ${predictionError}\");\n console.log(testSetLength);\n console.log(predictionError);\n console.log(tree_accuracy);*/\n\n // (2) svm suppourt vector machine===================================================================================\n\n console.log(\"start the SVM algorithm, this one is pretty slow***********************************\");\n var svmResult = [];\n var xsvm = xtree.map(function (subarray) {\n return subarray.slice(0, 8);\n });\n\n /* console.log(\"trainingsetx:++++++++++++++++ in svm\");\n console.log(xsvm);\n console.log(\"trainingSetYBin:+++++++++++in svm\");\n console.log(trainingSetYBin);*/\n var svm = new ml.SVM({\n x: xsvm,\n y: trainingSetYBin\n\n });\n svm.train({\n C: 1.1, // default : 1.0. C in SVM.\n tol: 1e-5, // default : 1e-4. Higher tolerance --> Higher precision\n max_passes: 20, // default : 20. Higher max_passes --> Higher precision\n alpha_tol: 1e-5, // default : 1e-5. Higher alpha_tolerance --> Higher precision\n\n kernel: {type: \"polynomial\", c: 1, d: 5}\n });\n\n for (var i = 0; i < testSetX.length; i++) {\n svmResult.push(svm.predict(testSetX[i]));\n }\n /* console.log(\"svmResult-----------------array\");\n console.log(svmResult);*/\n\n var predictionError = error(svmResult, testSetYBin);\n var svm_accuracy = Math.round((testSetLength - predictionError) / testSetLength * 100);\n var svmpredict = svm.predict(todayActi);\n let svmpredictRel;\n if (svmpredict == 1) {\n svmpredictRel = 'good';\n }\n if (svmpredict == -1) {\n svmpredictRel = 'fair or poor';\n }\n\n // (3) KNN (K-nearest neighbors)===================================================================================\n\n console.log(\"start KNN algorithm ****************************************\");\n\n var knnResult = [];\n var knnResult2 = [];\n let Rel;\n var xknn = xtree.map(function (subarray) {\n return subarray.slice(0, 8);\n });\n var knn = new ml.KNN({\n data: xknn,\n result: trainingSetYNum\n });\n for (var i = 0; i < testSetX.length; i++) {\n var y = knn.predict({\n x: testSetX[i],\n k: 1,\n weightf: {type: 'gaussian', sigma: 10.0},\n distance: {type: 'euclidean'}\n });\n if (y > 97) {\n Rel = 'good';\n }\n else if (y > 93 && y <= 97) {\n Rel = 'fair';\n }\n else {\n Rel = 'poor';\n }\n knnResult2.push(Rel);\n\n knnResult.push(y);\n }\n /* console.log(\"knn predict test y: \");\n console.log(knnResult2);\n console.log(knnResult);*/\n\n\n var predictionError = error(knnResult2, testSetYCal);\n var knn_accuracy = Math.round((testSetLength - predictionError) / testSetLength * 100);\n\n var knnpredict = knn.predict({\n\n x: todayActi,\n k: 1,\n weightf: {type: 'gaussian', sigma: 10.0},\n distance: {type: 'euclidean'}\n\n });\n\n let knnpredictRel;\n if (knnpredict > 97) {\n knnpredictRel = 'good';\n }\n else if (knnpredict > 93 && knnpredict <= 97) {\n knnpredictRel = 'fair';\n }\n else {\n knnpredictRel = 'poor';\n }\n\n\n // (4) MLP algorithm===================================================================================\n\n /* console.log(\"start MLP (Multi-Layer Perceptron)================================================\");\n\n var mlpResult = [];\n // let Rel;\n var xmlp = xtree.map(function (subarray) {\n return subarray.slice(0, 8);\n });\n console.log(xmlp);\n var mlp = new ml.MLP({\n 'input': xmlp,\n 'label': trainingSetYBin,\n 'n_ins': 8,\n 'n_outs': 1,\n 'hidden_layer_sizes': [4, 4, 5]\n });\n\n mlp.set('log level', 1); // 0 : nothing, 1 : info, 2 : warning.\n\n mlp.train({\n 'lr': 0.6,\n 'epochs': 800\n });\n for (var i = 0; i < testSetX.length; i++) {\n mlpResult.push(mlp.predict(testSetX[i]));\n\n }\n console.log(mlpResult);*/\n\n\n //return results\n return [Object.keys(treepredict)[0], tree_accuracy, svmpredictRel, svm_accuracy, knnpredictRel, knn_accuracy];\n\n\n }", "function webCat(url) {\n axios.get(url)\n .then(resp => {\n let mm = new MarkovMachine(resp.data);\n console.log(mm.makeText());\n })\n .catch(err => {\n console.log(`Error fetching ${url}: ${err}`)\n })\n}", "buildCorpus(data) {\r\n const options = this.options;\r\n // Loop through all sentences\r\n data.forEach(item => {\r\n const line = item.string;\r\n const words = line.split(' ');\r\n const stateSize = options.stateSize; // Default value of 2 is set in the constructor\r\n //#region Start words\r\n // \"Start words\" is the list of words that can start a generated chain.\r\n const start = lodash_1.slice(words, 0, stateSize).join(' ');\r\n const oldStartObj = this.startWords.find(o => o.words === start);\r\n // If we already have identical startWords\r\n if (oldStartObj) {\r\n // If the current item is not present in the references, add it\r\n if (!lodash_1.includes(oldStartObj.refs, item)) {\r\n oldStartObj.refs.push(item);\r\n }\r\n }\r\n else {\r\n // Add the startWords (and reference) to the list\r\n this.startWords.push({ words: start, refs: [item] });\r\n }\r\n //#endregion Start words\r\n //#region End words\r\n // \"End words\" is the list of words that can end a generated chain.\r\n const end = lodash_1.slice(words, words.length - stateSize, words.length).join(' ');\r\n const oldEndObj = this.endWords.find(o => o.words === end);\r\n if (oldEndObj) {\r\n if (!lodash_1.includes(oldEndObj.refs, item)) {\r\n oldEndObj.refs.push(item);\r\n }\r\n }\r\n else {\r\n this.endWords.push({ words: end, refs: [item] });\r\n }\r\n //#endregion End words\r\n //#region Corpus generation\r\n // We loop through all words in the sentence to build \"blocks\" of `stateSize`\r\n // e.g. for a stateSize of 2, \"lorem ipsum dolor sit amet\" will have the following blocks:\r\n // \"lorem ipsum\", \"ipsum dolor\", \"dolor sit\", and \"sit amet\"\r\n for (let i = 0; i < words.length - 1; i++) {\r\n const curr = lodash_1.slice(words, i, i + stateSize).join(' ');\r\n const next = lodash_1.slice(words, i + stateSize, i + stateSize * 2).join(' ');\r\n if (!next || next.split(' ').length !== options.stateSize) {\r\n continue;\r\n }\r\n // Check if the corpus already has a corresponding \"curr\" block\r\n if (this.corpus.hasOwnProperty(curr)) {\r\n const oldObj = this.corpus[curr].find(o => o.words === next);\r\n if (oldObj) {\r\n // If the corpus already has the chain \"curr -> next\",\r\n // just add the current reference for this block\r\n oldObj.refs.push(item);\r\n }\r\n else {\r\n // Add the new \"next\" block in the list of possible paths for \"curr\"\r\n this.corpus[curr].push({ words: next, refs: [item] });\r\n }\r\n }\r\n else {\r\n // Add the \"curr\" block and link it with the \"next\" one\r\n this.corpus[curr] = [{ words: next, refs: [item] }];\r\n }\r\n }\r\n //#endregion Corpus generation\r\n });\r\n }", "async function createMarkovFromSite(url){\n let content;\n try {\n content = await axios.get(url);\n } catch (err) {\n console.log(err);\n console.log(\"The url is incorrect or could not be read.\");\n process.exit(1);\n }\n let mm = new MarkovMachine(content.data)\n return mm;\n}", "function markovText(text) {\n let mm = new markov.MarkovMachine(text);\n console.log(mm.makeText())\n}", "function circusParade(){\n \n}", "function process1(results_pre){\r\n //find risk\r\n var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\r\n console.log(\"here1\");\r\n console.table(results_pre);\r\n var coef_pre = [-7.4979, 0.2046, 0.6388, 0.8574, 0, 0.3873, -0.1431, 0, 0.4306, 0.7455, -0.1134, 0, 0.6918, 1.2067, 1.3694, 1.1966];\r\n var x =new Array();\r\n for(i=1; i<=coef_pre.length; i++){\r\n x.push(0);\r\n }\r\n var numchoices = [4, 3, 4];\r\n var pos = 0;\r\n for(i=0; i<4; i++){\r\n if(i == 0){\r\n x[alphabet.indexOf(results_pre[i])] = 1;\r\n }\r\n else{\r\n pos += numchoices[i-1];\r\n x[alphabet.indexOf(results_pre[i])+pos] = 1; }\r\n }\r\n for(j=1; j<coef_pre.length; j++){\r\n coef_pre[j] = coef_pre[j] * x[j]; }\r\n console.table(coef_pre);\r\n var sum = 0;\r\n for(k=0; k<coef_pre.length; k++){\r\n sum += coef_pre[k]; }\r\n var result = expit(sum);\r\n\r\n //find ci\r\n var initial=[\"\",\"(Intercept)\",\"agegrp2\",\"agegrp3\",\"agegrp4\",\"brstproc1\",\"brstproc9\",\"nrelbc1\",\"nrelbc2\",\"nrelbc9\",\"density2\",\"density3\",\"density4\",\"density9\",\r\n\"(Intercept)\",0.0664320407720038,-0.0136477809143394,-0.0138226584176114,-0.0140337639655768,-0.000368668948297425,-0.000669985624335268,-0.00134556054544901,-0.00115023052970805,-0.000996895369675293,-0.0526980169293713,-0.0527055607302102,-0.0528459396706879,-0.0528076582849449,\r\n\"agegrp2\",-0.0136477809143394,0.0153609318379136,0.0134813974213118,0.0134852020646986,7.35839158267006e-05,-5.48092501402831e-05,0.000696526829566442,0.000594810227314313,2.28157777018567e-05,1.57177605201402e-05,5.2746690572284e-06,7.4098726099541e-05,-2.57677108882098e-05,\r\n\"agegrp3\",-0.0138226584176114,0.0134813974213118,0.0150035745922805,0.0135672940477572,-8.88829792689026e-05,0.000544084284501666,0.000705624437962924,0.000486575821328683,0.000493507049237037,3.47887451661009e-05,5.47778015924148e-05,0.00019568775853053,0.000203018249761248,\r\n\"agegrp4\",-0.0140337639655768,0.0134852020646986,0.0135672940477572,0.0159963764640307,-0.000225753455981637,0.000532686823271202,0.000728289797921222,0.000501203600049731,0.000413646103351074,0.000133470659030696,0.000265982101707256,0.000572719455982893,0.000479977596847101,\r\n\"brstproc1\",-0.000368668948297425,7.35839158267006e-05,-8.88829792689026e-05,-0.000225753455981637,0.003507542277175,0.000739075758926512,-0.000182217891718771,-0.000305887318920678,-6.27765252749106e-05,-0.000149339552045004,-0.000342820766317262,-0.000575948326118015,-0.000276083005492901,\r\n\"brstproc9\",-0.000669985624335268,-5.48092501402831e-05,0.000544084284501666,0.000532686823271202,0.000739075758926512,0.0142996340469006,-0.000125486743605135,-3.82068205668379e-05,-0.00198676697838275,-0.000127374361096728,-0.000124653230605475,-0.000192948879171283,-0.000726552686825026,\r\n\"nrelbc1\",-0.00134556054544901,0.000696526829566442,0.000705624437962924,0.000728289797921222,-0.000182217891718771,-0.000125486743605135,0.00388938043170478,0.000856189008884572,0.000852371373605705,-5.38087537350653e-05,-0.000119773020539559,-0.000139069081483798,-0.00013120865176463,\r\n\"nrelbc2\",-0.00115023052970805,0.000594810227314313,0.000486575821328683,0.000501203600049731,-0.000305887318920678,-3.82068205668379e-05,0.000856189008884572,0.0568633403727103,0.000785357728791108,-8.34372346923235e-05,-0.00014491240596884,-0.000258637703112285,2.97934980385034e-05,\r\n\"nrelbc9\",-0.000996895369675293,2.28157777018567e-05,0.000493507049237037,0.000413646103351074,-6.27765252749106e-05,-0.00198676697838275,0.000852371373605705,0.000785357728791108,0.00829444114303608,1.44247033717548e-05,-3.72189073630302e-05,4.13146878454954e-05,-0.000201963466954932,\r\n\"density2\",-0.0526980169293713,1.57177605201402e-05,3.47887451661009e-05,0.000133470659030696,-0.000149339552045004,-0.000127374361096728,-5.38087537350653e-05,-8.34372346923235e-05,1.44247033717548e-05,0.0559561037141258,0.0526933590206496,0.0527108542928949,0.0527009769404816,\r\n\"density3\",-0.0527055607302102,5.2746690572284e-06,5.47778015924148e-05,0.000265982101707256,-0.000342820766317262,-0.000124653230605475,-0.000119773020539559,-0.00014491240596884,-3.72189073630302e-05,0.0526933590206496,0.0541494819161978,0.0527613146490688,0.0527341115729378,\r\n\"density4\",-0.0528459396706879,7.4098726099541e-05,0.00019568775853053,0.000572719455982893,-0.000575948326118015,-0.000192948879171283,-0.000139069081483798,-0.000258637703112285,4.13146878454954e-05,0.0527108542928949,0.0527613146490688,0.0568323912554103,0.0527803600641544,\r\n\"density9\",-0.0528076582849449,-2.57677108882098e-05,0.000203018249761248,0.000479977596847101,-0.000276083005492901,-0.000726552686825026,-0.00013120865176463,2.97934980385034e-05,-0.000201963466954932,0.0527009769404816,0.0527341115729378,0.0527803600641544,0.0550574313194564,\r\n];\r\n var sub = new Array();\r\n var v = new Array();\r\n for(i=14; i<= 14*14;i++){\r\n if(i%14 != 0){\r\n sub.push(initial[i]);\r\n }\r\n if(i != 14 && i%14 ==0){\r\n v.push(sub);\r\n sub = new Array();\r\n }\r\n }\r\n var realv = new Array();\r\n var temp = new Array();\r\n for(i = 0; i<=12; i++){\r\n for(j=0; j<=12; j++){\r\n temp.push(v[j][i])\r\n }\r\n realv.push(temp);\r\n temp = new Array();\r\n }\r\n var xT = new Array();\r\n for(i=1;i<x.length; i++){\r\n if(i!= 0 && i!=4 && i!=7 && i!=11){\r\n xT.push(x[i]);\r\n }\r\n }\r\n xT.unshift(1);\r\n\r\n var prod1 = new Array();\r\n var sum1 = 0;\r\n for(k=0; k<13; k++){\r\n for(l=0; l<13; l++){\r\n sum1 += realv[k][l]*xT[l]; }\r\n prod1.push(sum1);\r\n sum1=0;\r\n }\r\n var variance = 0;\r\n for(i=0;i<13;i++){\r\n variance+=prod1[i]*xT[i];\r\n }\r\n variance = 1.96*Math.pow(variance, 1/2);\r\n var ci_low = Math.round(100000*expit(sum-variance))/1000;\r\n var ci_high = Math.round(100000*expit(sum+variance))/1000;\r\n result = Math.round(100000*result)/1000;\r\n\r\n $('#grp').html(\"premenopausal\");\r\n $('#grp_prob').html(\"0.304%\");\r\n $('#value').html(result+\"%\");\r\n $('#ci').html(ci_low +\"% - \"+ci_high+\"%\")\r\n\r\n\r\n //graph\r\n // sets dimensions and margins\r\n var margin = {top: 50, right: 30, bottom: 50, left: 70},\r\n width = 460 - margin.left - margin.right,\r\n height = 400 - margin.top - margin.bottom;\r\n\r\n // append the svg object to the body of the page\r\n var svg = d3.select(\"#hist\")\r\n .append(\"svg\")\r\n .attr(\"width\", width + margin.left + margin.right)\r\n .attr(\"height\", height + margin.top + margin.bottom)\r\n .append(\"g\")\r\n .attr(\"transform\",\r\n \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\r\n // get data\r\n d3.csv(\"https://raw.githubusercontent.com/czhang2718/generic-repo/master/pre_prob.txt\", function(data) {\r\n // console.log(\"type of data array is \" +typeof data);\r\n\r\n // X axis: scale and draw:\r\n var x = d3.scaleLinear()\r\n .domain([0, d3.max(data, function(d) { return +d.price })])\r\n .range([0, width]);\r\n svg.append(\"g\")\r\n .attr(\"transform\", \"translate(0,\" + height + \")\")\r\n .call(d3.axisBottom(x));\r\n\r\n //title\r\n svg.append(\"text\")\r\n .attr(\"x\", (width / 2))\r\n .attr(\"y\", 0 - (margin.top / 2))\r\n .attr(\"text-anchor\", \"middle\")\r\n .style(\"font-size\", \"18px\")\r\n .style(\"text-decoration\", \"underline\")\r\n .text(\"Breast Cancer Risk*\");\r\n\r\n //x axis label\r\n svg.append(\"text\")\r\n .attr(\"transform\", \"translate(\" + (width/2) + \" ,\" +\r\n (height + margin.top-15) + \")\") //+20???\r\n .style(\"text-anchor\", \"middle\")\r\n .style(\"font-size\", \"14px\")\r\n .text(\"Probability of Breast Cancer within 1 year (%)\");\r\n\r\n // set the parameters for the histogram\r\n var histogram = d3.histogram()\r\n .value(function(d) { return d.price; })\r\n .domain(x.domain())\r\n .thresholds(x.ticks(40)); //# bins\r\n\r\n // And apply this function to data to get the bins\r\n var bins = histogram(data);\r\n\r\n // Y axis: scale and draw:\r\n var y = d3.scaleLinear()\r\n .range([height, 0]);\r\n y.domain([0, d3.max(bins, function(d) { return d.length; })]); // d3.hist has to be called before the Y axis obviously\r\n svg.append(\"g\")\r\n .call(d3.axisLeft(y));\r\n // text label for the y axis\r\n svg.append(\"text\")\r\n .attr(\"transform\", \"rotate(-90)\")\r\n .attr(\"y\", 0 - (margin.left)+10) //-2\r\n .attr(\"x\",0 - (height / 2))\r\n .attr(\"dy\", \"1em\")\r\n .style(\"text-anchor\", \"middle\")\r\n .style(\"font-size\", \"14px\")\r\n .text(\"Number of Women\");\r\n\r\n // append the bar rectangles to the svg element\r\n svg.selectAll(\"rect\")\r\n .data(bins)\r\n .enter()\r\n .append(\"rect\")\r\n .attr(\"x\", 1)\r\n .attr(\"transform\", function(d) { return \"translate(\" + x(d.x0) + \",\" + y(d.length) + \")\"; })\r\n .attr(\"width\", function(d) { return x(d.x1) - x(d.x0); })\r\n .attr(\"height\", function(d) { return height - y(d.length); })\r\n .style(\"fill\", \"#8FBC8F\");\r\n\r\n //draw vertical line for datapoint\r\n svg.append(\"line\")\r\n .attr(\"x1\", 360*(result/d3.max(data, function(d) { return +d.price }))) //<<== change your code here\r\n .attr(\"y1\", 0)\r\n .attr(\"x2\", 360*(result/d3.max(data, function(d) { return +d.price }))) //<<== and here\r\n .attr(\"y2\", height)\r\n .attr(\"class\", \"specification-line\");\r\n //grp average\r\n svg.append(\"line\")\r\n .attr(\"x1\", 360*(0.444/d3.max(data, function(d) { return +d.price }))) //<<== change your code here\r\n .attr(\"y1\", 0)\r\n .attr(\"x2\", 360*(0.444/d3.max(data, function(d) { return +d.price }))) //<<== and here\r\n .attr(\"y2\", height)\r\n .attr(\"class\", \"spec-line2\");\r\n });\r\n\r\n $.get('https://raw.githubusercontent.com/czhang2718/generic-repo/master/pre_prob.txt', function(data){\r\n var dat = data.split(\"\\n\");\r\n // dat = dat.split(\",\");\r\n console.log(\"length is \"+ dat.length);\r\n var ind = sortedIndex(dat, result);\r\n var p = ind/280205*100;\r\n $('#percentile').html(Math.round(1000*ind/280205*100)/1000+\"%\");\r\n });\r\n\r\n\r\n}", "showCddSiteAll() {\n let ic = this.icn3d,\n me = ic.icn3dui\n let thisClass = this\n\n ic.chainid2pssmid = {}\n\n let chnidBaseArray = $.map(ic.protein_chainid, function (v) {\n return v\n })\n let chnidArray = Object.keys(ic.protein_chainid)\n // show conserved domains and binding sites\n // live search\n // let url = me.htmlCls.baseUrl + \"cdannots/cdannots.fcgi?fmt&live=lcl&queries=\" + chnidBaseArray;\n // precalculated\n let url = me.htmlCls.baseUrl + 'cdannots/cdannots.fcgi?fmt&queries=' + chnidBaseArray\n // live search for AlphaFold structures\n if (me.cfg.afid) {\n url = me.htmlCls.baseUrl + 'cdannots/cdannots.fcgi?fmt&live=lcl&queries=' + ic.giSeq[chnidArray[0]].join('')\n }\n\n $.ajax({\n url: url,\n dataType: 'jsonp',\n cache: true,\n tryCount: 0,\n retryLimit: 1,\n success: function (data) {\n let chainWithData = {}\n for (let chainI = 0, chainLen = data.data.length; chainI < chainLen; ++chainI) {\n let cddData = data.data[chainI]\n let chnidBase = cddData._id\n //var pos = chnidBaseArray.indexOf(chnidBase);\n //var chnid = chnidArray[pos];\n let chnid = chnidArray[chainI]\n chainWithData[chnid] = 1\n let html = '<div id=\"' + ic.pre + chnid + '_cddseq_sequence\" class=\"icn3d-cdd icn3d-dl_sequence\">'\n let html2 = html\n let html3 = html\n let domainArray = cddData.doms\n let result = thisClass.setDomainFeature(domainArray, chnid, true, html, html2, html3)\n\n ic.chainid2pssmid[chnid] = {\n pssmid2name: result.pssmid2name,\n pssmid2fromArray: result.pssmid2fromArray,\n pssmid2toArray: result.pssmid2toArray,\n }\n\n let acc2domain = result.acc2domain\n html = result.html + '</div>'\n html2 = result.html2 + '</div>'\n html3 = result.html3 + '</div>'\n $('#' + ic.pre + 'dt_cdd_' + chnid).html(html)\n $('#' + ic.pre + 'ov_cdd_' + chnid).html(html2)\n $('#' + ic.pre + 'tt_cdd_' + chnid).html(html3)\n\n html = '<div id=\"' + ic.pre + chnid + '_siteseq_sequence\" class=\"icn3d-dl_sequence\">'\n html2 = html\n html3 = html\n\n // features\n let featuteArray = cddData.motifs\n result = thisClass.setDomainFeature(featuteArray, chnid, false, html, html2, html3, acc2domain)\n\n html = result.html // + '</div>';\n html2 = result.html2 // + '</div>';\n html3 = result.html3 // + '</div>';\n\n let siteArray = data.data[chainI].sites\n let indexl = siteArray !== undefined ? siteArray.length : 0\n for (let index = 0; index < indexl; ++index) {\n let domain = siteArray[index].srcdom\n let type = siteArray[index].type\n let resCnt = siteArray[index].sz\n let title = 'site: ' + siteArray[index].title\n if (title.length > 17) title = title.substr(0, 17) + '...'\n //var fulltitle = \"site: \" + siteArray[index].title + \"(domain: \" + domain + \")\";\n let fulltitle = siteArray[index].title\n let resPosArray,\n adjustedResPosArray = []\n for (let i = 0, il = siteArray[index].locs.length; i < il; ++i) {\n resPosArray = siteArray[index].locs[i].coords\n for (let j = 0, jl = resPosArray.length; j < jl; ++j) {\n //adjustedResPosArray.push(Math.round(resPosArray[j]) + ic.baseResi[chnid]);\n adjustedResPosArray.push(\n thisClass.getAdjustedResi(\n Math.round(resPosArray[j]),\n chnid,\n ic.matchedPos,\n ic.chainsSeq,\n ic.baseResi,\n ) - 1,\n )\n }\n }\n let htmlTmp2 =\n '<div class=\"icn3d-seqTitle icn3d-link icn3d-blue\" site=\"site\" posarray=\"' +\n adjustedResPosArray.toString() +\n '\" shorttitle=\"' +\n title +\n '\" setname=\"' +\n chnid +\n '_site_' +\n index +\n '\" anno=\"sequence\" chain=\"' +\n chnid +\n '\" title=\"' +\n fulltitle +\n '\">' +\n title +\n ' </div>'\n let htmlTmp3 =\n '<span class=\"icn3d-residueNum\" title=\"residue count\">' + resCnt.toString() + ' Res</span>'\n let htmlTmp = '<span class=\"icn3d-seqLine\">'\n html3 += htmlTmp2 + htmlTmp3 + '<br>'\n html += htmlTmp2 + htmlTmp3 + htmlTmp\n html2 += htmlTmp2 + htmlTmp3 + htmlTmp\n let pre = 'site' + index.toString()\n //var widthPerRes = ic.seqAnnWidth / ic.maxAnnoLength;\n let prevEmptyWidth = 0\n let prevLineWidth = 0\n let widthPerRes = 1\n for (let i = 0, il = ic.giSeq[chnid].length; i < il; ++i) {\n html += ic.showSeqCls.insertGap(chnid, i, '-')\n if (resPosArray.indexOf(i) != -1) {\n let cFull = ic.giSeq[chnid][i]\n let c = cFull\n if (cFull.length > 1) {\n c = cFull[0] + '..'\n }\n //var pos =(i >= ic.matchedPos[chnid] && i - ic.matchedPos[chnid] < ic.chainsSeq[chnid].length) ? ic.chainsSeq[chnid][i - ic.matchedPos[chnid]].resi : ic.baseResi[chnid] + 1 + i;\n let pos = thisClass.getAdjustedResi(i, chnid, ic.matchedPos, ic.chainsSeq, ic.baseResi)\n\n html +=\n '<span id=\"' +\n pre +\n '_' +\n ic.pre +\n chnid +\n '_' +\n pos +\n '\" title=\"' +\n c +\n pos +\n '\" class=\"icn3d-residue\">' +\n cFull +\n '</span>'\n html2 += ic.showSeqCls.insertGapOverview(chnid, i)\n let emptyWidth =\n me.cfg.blast_rep_id == chnid\n ? Math.round(\n (ic.seqAnnWidth * i) / (ic.maxAnnoLength + ic.nTotalGap) -\n prevEmptyWidth -\n prevLineWidth,\n )\n : Math.round(\n (ic.seqAnnWidth * i) / ic.maxAnnoLength - prevEmptyWidth - prevLineWidth,\n )\n //if(emptyWidth < 0) emptyWidth = 0;\n if (emptyWidth >= 0) {\n html2 +=\n '<div style=\"display:inline-block; width:' + emptyWidth + 'px;\">&nbsp;</div>'\n html2 +=\n '<div style=\"display:inline-block; background-color:#000; width:' +\n widthPerRes +\n 'px;\" title=\"' +\n c +\n pos +\n '\">&nbsp;</div>'\n prevEmptyWidth += emptyWidth\n prevLineWidth += widthPerRes\n }\n } else {\n html += '<span>-</span>' //'<span>-</span>';\n }\n }\n htmlTmp =\n '<span class=\"icn3d-residueNum\" title=\"residue count\">&nbsp;' +\n resCnt.toString() +\n ' Residues</span>'\n htmlTmp += '</span>'\n htmlTmp += '<br>'\n html += htmlTmp\n html2 += htmlTmp\n }\n html += '</div>'\n html2 += '</div>'\n html3 += '</div>'\n $('#' + ic.pre + 'dt_site_' + chnid).html(html)\n $('#' + ic.pre + 'ov_site_' + chnid).html(html2)\n $('#' + ic.pre + 'tt_site_' + chnid).html(html3)\n } // outer for loop\n // missing CDD data\n for (let chnid in ic.protein_chainid) {\n if (!chainWithData.hasOwnProperty(chnid)) {\n $('#' + ic.pre + 'dt_cdd_' + chnid).html('')\n $('#' + ic.pre + 'ov_cdd_' + chnid).html('')\n $('#' + ic.pre + 'tt_cdd_' + chnid).html('')\n $('#' + ic.pre + 'dt_site_' + chnid).html('')\n $('#' + ic.pre + 'ov_site_' + chnid).html('')\n $('#' + ic.pre + 'tt_site_' + chnid).html('')\n }\n }\n // add here after the ajax call\n ic.showAnnoCls.enableHlSeq()\n ic.bAjaxCddSite = true\n if (ic.deferredAnnoCddSite !== undefined) ic.deferredAnnoCddSite.resolve()\n },\n error: function (xhr, textStatus, errorThrown) {\n this.tryCount++\n if (this.tryCount <= this.retryLimit) {\n //try again\n $.ajax(this)\n return\n }\n console.log('No CDD data were found for the protein ' + chnidBaseArray + '...')\n for (let chnid in ic.protein_chainid) {\n $('#' + ic.pre + 'dt_cdd_' + chnid).html('')\n $('#' + ic.pre + 'ov_cdd_' + chnid).html('')\n $('#' + ic.pre + 'tt_cdd_' + chnid).html('')\n $('#' + ic.pre + 'dt_site_' + chnid).html('')\n $('#' + ic.pre + 'ov_site_' + chnid).html('')\n $('#' + ic.pre + 'tt_site_' + chnid).html('')\n }\n // add here after the ajax call\n ic.showAnnoCls.enableHlSeq()\n ic.bAjaxCddSite = true\n if (ic.deferredAnnoCddSite !== undefined) ic.deferredAnnoCddSite.resolve()\n return\n },\n })\n }", "prepToStart() {\n\n // each algorithm will be required to provide a function\n // to create its LDV\n this.ldv = this.createLDV();\n\n // set the comparator if there is one (for priority queue LDVs)\n if (this.hasOwnProperty(\"comparator\")) {\n this.ldv.setComparator(this.comparator);\n }\n\n // add LDV to display element and set its callback to\n // display an individual entry\n // note that this means each algorithm must provide a function\n // named displayLDVItem that takes an LDV entry as its\n // parameter\n this.ldv.setDisplay(hdxAVCP.getDocumentElement(\"discovered\"),\n displayLDVItem);\n\n // update stopping condition\n const selector = document.getElementById(\"stoppingCondition\");\n this.stoppingCondition =\n selector.options[selector.selectedIndex].value;\n \n // pseudocode will depend on specific options chosen, so set up\n // the code field based on the options in use\n this.setupCode();\n }", "function determineWord(wordsArray, inputArray)\n{\n //get all synsets of first word\n wordsArray[0].getSynsets(function (err, data)\n {\n var synsets1 = data;\n //console.log(\"this are synsets 1 \" + synsets);\n //get all synsets of sec word\n wordsArray[1].getSynsets(function (err, data)\n {\n var synsets2 = data;\n //console.log(\"this are synsets 2 \" + synsets);\n //get all synsets of third word\n wordsArray[2].getSynsets(function (err, data)\n {\n var synsets3 = data;\n //LCS with first synset of three labels\n var WUObject = {}//{ 000:'a', 011:'b', 010:'c', 001:'d',\n // 100:'a',111:'b',110:'c',101:'d',200:'a',211:'b',210:'c',201:'d'};\n LCS(synsets1[0], emptyArray1, synsets2[0], emptyArray2, synsets3[0], emptyArray3,compare)\n //compare all retreived wu addings\n .then(function(data000)\n {\n LCS(synsets1[0], emptyArray1, synsets2[1], emptyArray2, synsets3[1], emptyArray3,compare)\n .then(function(data011)\n {\n LCS(synsets1[1], emptyArray1, synsets2[0], emptyArray2, synsets3[0], emptyArray3,compare)\n .then(function(data100)\n {\n LCS(synsets1[1], emptyArray1, synsets2[1], emptyArray2, synsets3[1], emptyArray3,compare)\n .then(function(data111)\n {\n LCS(synsets1[2], emptyArray1, synsets2[0], emptyArray2, synsets3[0], emptyArray3,compare)\n .then(function(data200)\n {\n\n LCS(synsets1[2], emptyArray1, synsets2[1], emptyArray2, synsets3[1], emptyArray3,compare)\n .then(function(data211)\n {\n getAddedWU(data000, data011, WUObject, 0);\n getAddedWU(data100, data111, WUObject, 1);\n getAddedWU(data200, data211, WUObject, 2);\n calculatedWUArray = [];\n for (var item in WUObject) {\n calculatedWUArray.push(WUObject[item]);\n }\n var lowestWU = Math.min.apply(Math, calculatedWUArray);\n for (var key in WUObject) {\n if (WUObject[key] === lowestWU)\n {\n /*console.log(\"true key\" + key);\n console.log(\"true keyfirst\" + key.charAt(0));\n console.log(\"The output\" +\n \" is\" +\n util.inspect(synsets1[key.charAt(0)]),\n null, 3);*/\n\n return synsets1[key.charAt(0)];\n //returns the first number of the key of the\n // keyValuePair in objectWU with the lowest\n // value (= lowest semantic difference\n // between labels)\n //-> first number can be used as index for\n // the synset1 - Array to retreive the\n // chosen synset (which has, according to\n // all calculations, the lowest sem.distance\n // to the other labels)\n //-> synset1[key.charAt(0)]\n }\n }\n })\n })\n })\n })\n })\n })\n\n });\n });\n });\n}", "async function makeText(){\n \n let args=[];\n let argv = process.argv;\n for(let i=2; i < argv.length; i++){\n args.push(argv[i]);\n }\n \n if(args[0]===\"file\"){\n let mm = await createMarkovFromFile(args[1]);\n console.log(mm.getText());\n }else{\n let mm = await createMarkovFromSite(args[1]);\n console.log(mm.getText());\n }\n \n}", "function makeTrain() {\n\tconsole.log(\"Make me a Train\");\n\n\t// ---- put function here ----\n\tfunction makeTrain(a, b, c) {\n\t\treturn `${a}.${b}.${c}`\n\t}\n\n\n\tconst myTrain = makeTrain('one', 'two', 'three');\n\tconst shouldTrain = 'one.two.three';\n\n\tif (myTrain != shouldTrain) {\n\t\tconsole.log(\"***** We have an error here *****\",\n\t\t\tmyTrain,\n\t\t\t\" is not = \",\n\t\t\tshouldTrain,\n\t\t\t\" and it should be.\"\n\t\t)\n\t}\n\n\tconsole.log(\"SB \" ,shouldTrain, myTrain);\n\n\tconsole.log(\"SB a.b.c:\", makeTrain(\"a\", \"b\", \"c\"));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ECMA262 13.4 Empty Statement
function parseEmptyStatement(node) { expect(';'); return node.finishEmptyStatement(); }
[ "function parseEmptyStatement(node) {\n expect(';');\n return node.finishEmptyStatement();\n }", "static isEmptyStatement(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.EmptyStatement;\r\n }", "visitEmptyStatement_(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "jsx_parseEmptyExpression() {\n \t\t let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n \t\t return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);\n \t\t }", "visitEmptyStatement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parseJSXEmptyExpression() {\n if (tokType !== _braceR) {\n unexpected();\n }\n\n var tmp;\n\n tmp = tokStart;\n tokStart = lastEnd;\n lastEnd = tmp;\n\n tmp = tokStartLoc;\n tokStartLoc = lastEndLoc;\n lastEndLoc = tmp;\n\n return finishNode(startNode(), \"JSXEmptyExpression\");\n }", "duiParseEmptyExpression(): N.JSXEmptyExpression {\n const node = this.startNodeAt(\n this.state.lastTokEnd,\n this.state.lastTokEndLoc,\n );\n return this.finishNodeAt(\n node,\n \"JSXEmptyExpression\",\n this.state.start,\n this.state.startLoc,\n );\n }", "function parseXJSEmptyExpression() {\r\n if (tokType !== _braceR) {\r\n unexpected();\r\n }\r\n\r\n var tmp;\r\n\r\n tmp = tokStart;\r\n tokStart = lastEnd;\r\n lastEnd = tmp;\r\n\r\n tmp = tokStartLoc;\r\n tokStartLoc = lastEndLoc;\r\n lastEndLoc = tmp;\r\n\r\n return finishNode(startNode(), \"XJSEmptyExpression\");\r\n }", "jsx_parseEmptyExpression() {\n let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);\n }", "jsx_parseEmptyExpression() {\n var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);\n }", "function parseXJSEmptyExpression() {\n if (tokType !== _braceR) {\n unexpected();\n }\n\n var tmp;\n\n tmp = tokStart;\n tokStart = lastEnd;\n lastEnd = tmp;\n\n tmp = tokStartLoc;\n tokStartLoc = lastEndLoc;\n lastEndLoc = tmp;\n\n return finishNode(startNode(), \"XJSEmptyExpression\");\n }", "visitEmptyDeclaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "isEmpty() { return !this.ast; }", "function is_empty_list_expression(stmt) {\n return is_tagged_object(stmt, \"empty_list\");\n}", "function legacy_control_comments() {\n\t/*@ignore@*/\n\t; /*warning:empty_statement*/\n\t/*@end@*/\n}", "function test_nondet_empty() {\n parse_and_eval(\"amb();\");\n\n assert_equal(null, final_result);\n}", "function noop() { } // tslint:disable-line:no-empty", "function Triple$LocalVariable$AssignmentExpression$function$$$$Expression$$$$void$E() {\n}", "get isEmpty() {\n return this.statements.length === 0;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
WEEKDAY_BEFORE Return Julian date of given weekday (0 = Sunday) in the seven days ending on jd.
function weekday_before(weekday, jd) { return jd - jwday(jd - weekday); }
[ "function weekday_before(weekday, jd)\n{\n return jd - jwday(jd - weekday);\n}", "function weekday_before(weekday, jd){\n return jd - jwday(jd - weekday);\n}", "function dayOfWeek( julian ){\n\n\treturn (julian+1)%7;\n\n}", "function findWeekStart(d, firstWeekday) {\n firstWeekday = parseIntDec(firstWeekday);\n if (!isWeekdayNum(firstWeekday)) {\n firstWeekday = 0;\n }\n\n for (var step = 0; step < 7; step++) {\n if (d.getDay() === firstWeekday) {\n return d;\n } else {\n d = prevDay(d);\n }\n }\n throw \"unable to find week start\";\n }", "function findWeekStart(d, firstWeekday) {\n firstWeekday = parseIntDec(firstWeekday);\n if(!isWeekdayNum(firstWeekday)){\n firstWeekday = 0;\n }\n\n for(var step=0; step < 7; step++){\n if(getDay(d) === firstWeekday){\n return d;\n }\n else{\n d = prevDay(d);\n }\n }\n throw \"unable to find week start\";\n }", "function _adjustWeekday(weekday) {\n return weekday > 0 ? weekday - 1 : 6\n }", "function weekday(yearArr, prevFirst) {\r\n\tvar num = days(yearArr);\r\n\r\n\tlet m = 0;\r\n\twhile (m + 7 <= num) {\r\n\t\tm += 7;\r\n\t}\r\n\r\n\tlet res = (num - m + prevFirst) % 7 ? (num - m + prevFirst) % 7 : 7;\r\n\r\n\treturn res;\r\n}", "function search_weekday(weekday, jd, direction, offset)\n{\n return weekday_before(weekday, jd + (direction * offset));\n}", "function firstWeekOffset(year, dow, doy) { // 1105\n var // first-week day -- which january is always in the first week (4 for iso, 1 for other) // 1106\n fwd = 7 + dow - doy, // 1107\n // first-week day local weekday -- which local weekday is fwd // 1108\n fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; // 1109\n // 1110\n return -fwdlw + fwd - 1; // 1111\n } // 1112", "function search_weekday(weekday, jd, direction, offset)\n {\n return weekday_before(weekday, jd + (direction * offset));\n }", "function FindFirstMondayOfTheWeek()\r\n{\r\n\t//set the day of the calendar to monday\r\n\t/*var d = new Date();\r\n\tvar DayNumber = d.getDay();\r\n\tvar DateNumber = d.getDate();\r\n\tvar MonthNumber = d.getMonth()+1;\r\n\tvar YearNumber = d.getFullYear();\r\n\tvar FirtMondayOfThisWeek;\r\n\t\r\n\t//DateNumber=19;\r\n\t//DayNumber=6;\r\n\t//alert(YearNumber+\"-\"+MonthNumber+\"-\"+DateNumber);\r\n\t\r\n\tif(DayNumber > 1)\r\n\t{\r\n\t\tFirtMondayOfThisWeek = DateNumber - DayNumber + 1;\r\n\t}\r\n\telse if(DayNumber < 1)\r\n\t{\r\n\t\tFirtMondayOfThisWeek = DateNumber + DayNumber + 1;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tFirtMondayOfThisWeek = DateNumber ;\t\r\n\t}\r\n\t\r\n\t\r\n\treturn FirtMondayOfThisWeek;\r\n\t*/\r\n\t\r\n\t//Get the current date\r\n\tvar Calendar \t=\t$.calendars.instance(); \r\n\tvar CurrentDate =\tCalendar.today();\r\n\tvar JulianDate \t= \tCurrentDate.toJD();\r\n\tvar DayOfWeek\t=\tCalendar.dayOfWeek(CurrentDate); \r\n\tvar JulianDateModay = JulianDate - ( DayOfWeek - 1 );\r\n\tvar MondayDate = Calendar.fromJD(JulianDateModay);\r\n\t\r\n\treturn MondayDate;\r\n\t//alert(YearNumber+\"-\"+MonthNumber+\"-\"+FirtMondayOfThisWeek+\" 12:15:00\");\r\n\t//alert(YearNumber+\"-\"+MonthNumber+\"-\"+FirtMondayOfThisWeek+\" 13:00:00\");\r\n}", "function search_weekday(weekday, jd, direction, offset) {\n return weekday_before(weekday, jd + (direction * offset));\n}", "function startOfWeek(date)\r\n {\r\n var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);\r\n\r\n return new Date(date.setDate(diff));\r\n\r\n }", "function calcDayOfWeek(juld)\n\n\t{\n\n\t\tvar A = (juld + 1.5) % 7;\n\n\t\tvar DOW = (A==0)?\"Sunday\":(A==1)?\"Monday\":(A==2)?\"Tuesday\":(A==3)?\"Wednesday\":(A==4)?\"Thursday\":(A==5)?\"Friday\":\"Saturday\";\n\n\t\treturn DOW;\n\n\t}", "function getFirstDayOfWeek(d) {\n d = new Date(d);\n var day = d.getDay(),\n diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday\n return new Date(d.setDate(diff));\n }", "function getSevenDayBefore() {\n var dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD');\n return dateFrom;\n}", "findEarlierMonday () {\n\t\tconst now = Date.now();\n\t\tconst dayOfWeek = (new Date(now)).getDay();\n\t\tlet lastMonday;\n\t\tif (dayOfWeek === 0) {\n\t\t\t// it's sunday? we really should be getting this on monday, \n\t\t\t// but i guess we need to assume it's 6 days too late...\n\t\t\tlastMonday = now - ONE_WEEK - 6 * ONE_DAY;\n\t\t}\n\t\telse if (dayOfWeek === 1) {\n\t\t\t// this is more like it\n\t\t\tlastMonday = now - ONE_WEEK;\n\t\t} else {\n\t\t\t// this might mean our queue overflowed?\n\t\t\tlastMonday = now - (dayOfWeek - 1) * ONE_DAY;\n\t\t}\n\t\treturn new Date(lastMonday).toLocaleDateString('en-US', { \n\t\t\tweekday: 'long',\n\t\t\tyear: 'numeric',\n\t\t\tmonth: 'long',\n\t\t\tday: 'numeric'\n\t\t});\n\t}", "function week21c(gregorianDate) {\n //const gDate = new Date( gregorianDate );\n //console.log(`argum = ${gregorianDate}`);\n //console.log(`gDate = ${gDate}`);\n const diff = (0, julian_day_1.default)(gregorianDate) - exports.JDN_of_20010101;\n //console.log(`diff = ${diff}`);\n return Math.floor(diff / 7) + 1;\n}", "weekDaysBeforeFirstDayOfTheMonth() {\n const firstDayOfTheMonth = new Date(`${this.displayedYear}-${Object(_util__WEBPACK_IMPORTED_MODULE_1__[\"pad\"])(this.displayedMonth + 1)}-01T00:00:00+00:00`);\n const weekDay = firstDayOfTheMonth.getUTCDay();\n return (weekDay - parseInt(this.firstDayOfWeek) + 7) % 7;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main public function that is called to parse the XML string and return a root element object
function Xparse(src) { var frag = new _frag(); // remove bad \r characters and the prolog frag.str = _prolog(src); // create a root element to contain the document var root = new _element(); root.name="ROOT"; // main recursive function to process the xml frag = _compile(frag); // all done, lets return the root element + index + document root.contents = frag.ary; root.index = _Xparse_index; _Xparse_index = new Array(); return root; }
[ "function parseXML(xmlStr){\n var xmlDocumentNode = $.parseXML(xmlStr).documentElement;\n rootNode = copyTree(xmlDocumentNode, null, 0);\n firstWalk(rootNode);\n secondWalk(rootNode, rootNode.mod);\n calculateCoordinates2D(rootNode);\n calculateCoordinates3D(rootNode);\n renderTree(rootNode);\n printTree(rootNode);\n}", "function parseXML (XML_string) {\r\n\treturn (new DOMParser()). parseFromString (XML_string, 'text/xml');\r\n}", "function parseXML(string) {\n return parse('xml', string);\n}", "function _XMLNode_parse()\n{\n\n // if it's a comment, strip off the packaging, mark it a comment node \n // and quit\n\n \n if(this.src.indexOf('!--')==0)\n {\n this.nodeType = 'COMMENT';\n this.content = this.src.substring(3,this.src.length-2);\n this.src = \"\";\n return true; \n }\n\n // if it's CDATA, do similar\n\n else if(this.src.indexOf('![CDATA[')==0)\n {\n this.nodeType = 'CDATA';\n this.content = this.src.substring(8,this.src.length-2);\n this.src = \"\";\n return true; \n }\n\n // it's a closing tag - mark it as a CLOSE node for use in pass 3, and snip\n // off the first character\n\n else if(this.src.charAt(0)=='/')\n {\n this.nodeType = 'CLOSE';\n this.src = this.src.substring(1);\n }\n\n // otherwise it's an open tag (possibly an empty element)\n \n else if(this.src.indexOf('?')==0)\n {\n this.nodeType = 'PROC';\n this.src = this.src.substring(1,this.src.length-1);\n }\n\n else this.nodeType = 'OPEN';\n\n // if the last character is a /, check it's not a CLOSE tag\n \n if(this.src.charAt(this.src.length-1)=='/')\n {\n if(this.nodeType=='CLOSE') \n return this.doc.error(\"singleton close tag\");\n else this.nodeType = 'SINGLE';\n \n // strip off the last character\n \n this.src = this.src.substring(0,this.src.length-1);\n }\n\n // set up the properties as appropriate\n \n if(this.nodeType!='CLOSE') this.attributes = new Array();\n if(this.nodeType=='OPEN') this.children = new Array();\n \n // trim the whitespace off the remaining content \n \n this.src = trim(this.src,true,true);\n \n // chuck out an error if there's nothing left\n \n if(this.src.length==0) return this.doc.error(\"empty tag\");\n \n // scan forward until a space...\n \n var endOfName = firstWhiteChar(this.src,0);\n \n // if there is no space, this is just a name (e.g. (<tag>, <tag/> or </tag>\n \n if(endOfName==-1) { this.tagName = this.src; return true;} \n\n // otherwise, we should expect attributes - but store the tag name first\n\n this.tagName = this.src.substring(0,endOfName);\n //this.path= this.tagName;\n // start from after the tag name\n \n var pos = endOfName; \n \n // now we loop:\n\n while(pos<this.src.length) \n {\n \n // chew up the whitespace, if any\n \n while((pos < this.src.length) && (whitespace.indexOf(this.src.charAt(pos))!=-1)) pos++; \n \n // if there's nothing else, we have no (more) attributes - just break out\n\n if(pos >= this.src.length) break; \n \n var p1 = pos;\n \n while((pos < this.src.length) && (this.src.charAt(pos)!='=')) pos++; \n \n var msg = \"attributes must have values\";\n \n // parameters without values aren't allowed.\n \n if(pos >= this.src.length) return this.doc.error(msg);\n \n // extract the parameter name\n \n var paramname = trim(this.src.substring(p1,pos++),false,true);\n \n // chew up whitespace\n \n while((pos < this.src.length) && (whitespace.indexOf(this.src.charAt(pos))!=-1)) pos++; \n \n // throw an error if we've run out of string\n\n if(pos >= this.src.length) return this.doc.error(msg); \n \n msg = \"attribute values must be in quotes\";\n \n // check for a quote mark to identify the beginning of the attribute value \n \n var quote = this.src.charAt(pos++);\n \n // throw an error if we didn't find one\n \n if(quotes.indexOf(quote)==-1) return this.doc.error(msg);\n p1 = pos;\n \n while((pos < this.src.length) && (this.src.charAt(pos)!=quote)) pos++; \n \n // throw an error if we found no closing quote\n \n if(pos >= this.src.length) return this.doc.error(msg);\n \n // extract the parameter value\n \n var paramval = trim(this.src.substring(p1,pos++),false,true);\n \n // if there's already a parameter by that name, it's an error\n \n if(this.attributes[paramname]!=null)\n return this.doc.error(\"cannot repeat attribute names in elements\");\n \n // otherwise, store the parameter\n \n this.attributes[paramname] = xmlUnescape( paramval );\n \n // and loop\n \n }\n return true;\n}", "function parseXmlString(xmlstring) {\r\n return new xmldom_1.DOMParser().parseFromString(xmlstring);\r\n }", "function zenXMLParser_parseString(xml)\r\n{\r\n\t// copy xml into workspace\r\n\tvar ws = self.document.getElementById('zenWorkspace');\r\n\tif (ws) {\r\n\t\tws.innerHTML = xml\r\n\t\tthis.parse(ws);\r\n\t}\r\n}", "convertStringToXML() {\n\t\t// validate DOMParser\n\t\tif (typeof window.DOMParser === 'undefined') {\n\t\t\tthrow new Error('No XML parser found');\n\t\t}\n\n\t\t// create a new DOMParser object\n\t\tconst domParser = new DOMParser();\n\n\t\t// parse the XML string into an XMLDocument object\n\t\treturn domParser.parseFromString(this.xmlString, 'text/xml');\n\t}", "function xmlGetRootElement() {\n\t\n\tif (sXmlRoot === null) {\n\t\t//var theXmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t\tvar theXmlHttp = new XMLHttpRequest();\n\t\ttheXmlHttp.open(\"GET\", cals_res_info.xml_report, false);\n\t\ttheXmlHttp.send();\n\t\tsXmlRoot = theXmlHttp.responseXML;\n\t}\n\treturn sXmlRoot;\n}", "function zenXMLParser_parseString(xml)\n{\n\t// copy xml into workspace\n\tvar ws = self.document.getElementById('zenWorkspace');\n\tif (ws) {\n\t\tws.innerHTML = xml\n\t\tthis.parse(ws);\n\t}\n}", "function parseXML(text) {\n var xmlDoc;\n\n if (typeof DOMParser != \"undefined\") {\n var parser = new DOMParser();\n xmlDoc = parser.parseFromString(text, \"text/xml\");\n } else {\n xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async = \"false\";\n xmlDoc.loadXML(text);\n }\n\n return xmlDoc;\n }", "function parseXml(str)\n{\n if (typeof parseXml.parser === 'undefined') {\n\n if (typeof window.DOMParser != \"undefined\") {\n parseXml.parser = function(xmlStr) {\n return ( new window.DOMParser() ).parseFromString(xmlStr, \"text/xml\");\n };\n } else if (typeof window.ActiveXObject != \"undefined\" &&\n new window.ActiveXObject(\"Microsoft.XMLDOM\")) {\n parseXml.parser = function(xmlStr) {\n var xmlDoc = new window.ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async = \"false\";\n xmlDoc.loadXML(xmlStr);\n return xmlDoc;\n };\n } else {\n throw new Error(\"No XML parser found\");\n }\n }\n return parseXml.parser(str);\n}", "function parseMainXml(){\n\tvar main_result = new Object();\n\t\n\tvar main_meta = getMetaConfig(\"data/config/config_\" + main_id +\".xml\");\n\tmain_result.meta = main_meta;\n\t\n\tif(main_meta.type == \"person\")\n\t{\n\t\tmain_result.list = parsePersonXml(main_meta.id, null, \"yes\");\n\t}\n\telse if(main_meta.type == \"group\")\n\t{\n\t\tmain_result.list = parseGroupXml(main_meta.id);\n\t}\n\n\treturn main_result;\n}", "function XmlElement(tag){// Capture the parser object off of the XmlDocument delegate\nvar parser=delegates[delegates.length-1].parser;this.name=tag.name;this.attr=tag.attributes;this.val=\"\";this.children=[];this.firstChild=null;this.lastChild=null;// Assign parse information\nthis.line=parser.line;this.column=parser.column;this.position=parser.position;this.startTagPosition=parser.startTagPosition;}// Private methods", "function makeParser() {\n\n\t//The parser's on method handles events. Here, we'll define what happens when it finishes parsing an object \n\tparser.on('object', function(name, obj) {\n\n\t \t//Because of the parseRecord function below, fetching the title is a lot easier\n\t \tvar marcDict = {};\n\t \tmarcDict[\"245\"] = {\"*\" :\"Title\"};\n\n\t \tvar record = parseRecord(obj, marcDict);\n\t \tconsole.log(record.Title);\n\t});\n\n\t//And what happens when it finishes parsing all of the records. \n\tparser.on('end', function() {\n\t console.log('Finished parsing xml!');\n\t}); \n\n}", "function parseString2XMLDOM(xmlStr){\n var parser = new DOMParser() ;\n if(!parser) return \"\" ;\n return parser.parseFromString(xmlStr , \"text/xml\")\n}", "function zenXMLParser_parse(el)\n{\n\tif (!el) return;\n\n\t// loop over nodes until we find an element\n\tfor (var n = 0; n < el.childNodes.length; n++) {\n\t\tvar node = el.childNodes[n];\n\t\tif (1 == node.nodeType) {\n\t\t\tthis.handler.startDocument();\n\t\t\tthis.parseNode(node);\n\t\t\tthis.handler.endDocument();\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function parseXML(xmlStr) {\n if (!xmlStr) {\n return $();\n }\n // HACK convince jQuery Sizzle that this is XML, not HTML\n xmlStr = xmlStr\n .replace(/<(h:)?html\\b/, \"<h:xdoc\")\n .replace(/<\\/(h:)?html\\b>/, \"</h:xdoc>\");\n return $($.parseXML(xmlStr));\n }", "function xmlParser(xml) {\n\t\t\tvar parse;\n\t\t\t\n\t\t\tif (typeof window.DOMParser !== 'undefined') {\n\t\t\t\tparse = function (xml) {\n\t\t\t\t\treturn (new window.DOMParser()).parseFromString(xml, 'text/xml');\n\t\t\t\t};\n\t\t\t}\n\t\t\telse if (typeof window.ActiveXObject !== 'undefined' && new window.ActiveXObject('Microsoft.XMLDOM')) {\n\t\t\t\tparseXml = function (xml) {\n\t\t\t\t\tvar xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM');\n\t\t\t\t\txmlDoc.async = 'false';\n\t\t\t\t\txmlDoc.loadXML(xml);\n\t\t\t\t\treturn xmlDoc;\n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('inject - no xml parser found.');\n\t\t\t\tparse = function (xml) {\n\t\t\t\t\treturn null;\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\treturn parse(xml);\n\t\t}", "function ParseXML(xmlObject_in)\n {\n \t//declare variables\n \tvar xmlObject = xmlObject_in;\n \tvar titleElements;\n \tvar pubDateElements;\n \tvar categoryElements;\n\n \tthis.titleElements = xmlObject.getElementsByTagName(\"title\");\n \tthis.pubDateElements = xmlObject.getElementsByTagName(\"pubDate\");\n\tthis.categoryElements = xmlObject.getElementsByTagName(\"category\");\n\n \t//declare arrays to store titles and pubdates\n \tvar titleArray = new Array();\n \tvar datesArray = new Array();\n \tvar catArray = new Array();\n\n \t//add elements to the arrays\n \tfor(i = 0; i < this.titleElements.length; i++)\n \t{\n \t\ttitleArray.push(this.titleElements[i].childNodes[0].nodeValue);\n \t\tdatesArray.push(this.pubDateElements[i].childNodes[0].nodeValue);\n \t\tcatArray.push(this.categoryElements[i].childNodes[0].nodeValue);\n\n \t}\n\n \t/**\n \t * getTitles\n \t * Returns: titleArray, the array of parsed xml titles\n \t */\n \tthis.getTitles = function()\n \t{\n \t\treturn titleArray;\n \t}\n\n\t/**\n \t * getDates\n \t * Returns: datesArray, the array of parsed xml dates\n \t */\n \tthis.getDates = function()\n \t{\n \t\treturn datesArray;\n \t}\n\n \t/**\n \t * getCategories\n \t * Returns: catArray, the array of parsed xml categories\n \t */\n \tthis.getCategories = function()\n \t{\n \t\treturn catArray;\n \t}\n\n \t/**\n \t * Code to test the contents of the title and publication date variables, and the arrays.\n \t * Used for debugging.\n \t */\n \tif(debug)\n \t{\n\t\tfor (i = 0; i < this.titleElements.length; i++)\n\t\t{ \n\t\t\t//document.write(this.titleElements[i].childNodes[0].nodeValue, \" :: \");\n\t\t\t//document.write(this.pubDateElements[i].childNodes[0].nodeValue, \" :: \");\n\t\t\t//document.write(this.categoryElements[i].childNodes[0].nodeValue);\n\n\t\t\t//document.write(\"<br />\");\n\n\t\t\tdocument.write(titleArray[i], \" :: \");\n\t\t\tdocument.write(datesArray[i], \" :: \");\n\t\t\tdocument.write(catArray[i]);\n\n \t\t\tdocument.write(\"<br />\");\t\n\t\t}\n\t}\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make the game history into a list, draw on the constant set at the start gameHistory Applies to playerMove and cpuMove
function drawHistory() { let historyElement = document.getElementById("history"); let displayString = ""; for (let i = 0; i < gameHistory.length; i++) { displayString += "<li>" + gameHistory[i].playerMove + " vs " + gameHistory[i].cpuMove + "</li>"; } historyElement.innerHTML = displayString; }
[ "function getHistory() {\n let result = ''\n for (let m = 0; m < game.moves.length; ++m) {\n result += outerCell(game.moves[m])\n }\n return { firstPlayer: outerPlayer(game.startPlayer), moves: result }\n}", "renderHistory() {\n const boards = this.state.boards;\n const moves = boards.map((step, iBoard) => {\n const desc = (iBoard !== 0) ? ('Move #' + iBoard) : 'Game start'; \n return (\n <li key={iBoard.toString()}>\n <a href=\"#\" onClick={() => this.jumpToBoard(iBoard)}>{desc}</a>\n </li>\n );\n });\n\n return moves;\n }", "updateHistory(board) {\r\n /* add current board to history and increment history index\r\n *** if historyIndex is less than historyLength-1, it \r\n means that a move has been played after the user has \r\n used the jump backwards button. Therefore, all elements in history after\r\n where historyIndex currently is should be erased *** \r\n */\r\n const historyIndex = this.state.historyIndex;\r\n const historyLength = this.state.history.length;\r\n let history = this.state.history;\r\n if (historyIndex < historyLength - 1) {\r\n history = this.state.history.splice(0, historyIndex + 1);\r\n }\r\n\r\n return history.concat([{ board: board }]);\r\n }", "updateHistory(currentBoard) {\n /* add current board to history and increment history index\n *** if historyIndex is less than historyLength-1, it \n means that a move has been played after the user has \n used the jump backwards button. Therefore, all elements in history after\n where historyIndex currently is should be erased *** \n */\n const historyIndex = this.state.historyIndex;\n const historyLength = this.state.history.length;\n var history = this.state.history;\n if (historyIndex < historyLength - 1) {\n history = this.state.history.splice(0, historyIndex + 1);\n }\n\n return history.concat([{ currentBoard: currentBoard }]);\n }", "function getBoardHistory() {\r\n return boardHistory;\r\n}", "onTurn(x, y, playerMarker) {\n // In normal gameplay (where the user hasn't click move history buttons), we might be on \n // move 4 of a game, and the 'selectedMove' counter will be as such. However, the user \n // can click to view a previous move (say, move 2), and the board will update, but the moves\n // visible will remain the same, until a move is played, and then all of the history down to\n // the last two moves will be erased, and the *new* move 3 will be added to the move list.\n let movesTemp;\n if (this.state.selectedMove === this.state.moves.length) {\n movesTemp = this.state.moves.slice(0);\n } else {\n movesTemp = this.state.moves.slice(0, this.state.selectedMove);\n }\n\n movesTemp.push(this.createMoveHistoryItem(x, y, playerMarker));\n\n this.setState({\n playerWhosTurnItIs: this.nextPlayer(this.state.playerWhosTurnItIs),\n moves: movesTemp,\n selectedMove: this.state.selectedMove + 1\n }, this.checkAndApplyWinConditions);\n }", "historyToStart() {\n const fenCode = this.state.chessBoardHistory.toStart();\n console.log('to start');\n console.log(this.state.chessBoardHistory);\n this.updateBoard(fenCode);\n }", "function replayHistory(){\n var i = 0;\n hafStartMove(i);\n}", "function processHistory() {\r\n $(\"span#trackerstatus\").html(\"ONLINE, PROCESSING HISTORY...\");\r\n\r\n // At startup we did one initial retrieve of live data so we had a nice display\r\n // from the start. Now we have history data to load in which is older. So,\r\n // delete the existing live data first.\r\n entities.forEach(function(e) {\r\n if (e.fixed == false) {\r\n entities.delete(e.hex);\r\n }\r\n });\r\n\r\n // History data could have come in any order, so first sort it.\r\n historyStore.sort((a, b) => (a.now > b.now) ? 1 : -1);\r\n\r\n // Now use it\r\n for (item of historyStore) {\r\n handleData(item, false);\r\n }\r\n\r\n // Drop anything timed out\r\n dropTimedOutAircraft();\r\n\r\n // Now trigger retrieval of a new set of live data, to top off the history\r\n requestLiveData();\r\n}", "insertToMatchHistory(from, to) {\n\t\tconst move = {\n\t\t\tpiece: to.piece.getAlias(),\n\t\t\tfrom: from.info.position,\n\t\t\tto: to.info.position,\n\t\t};\n\n\t\tthis.data.matchHistory.push(move);\n\t\tto.piece.player.data.movesHistory.push(move);\n\t\tconsole.log(JSON.stringify(this.data.matchHistory));\n\t}", "logBoard (board) {\n // console.log('logging board ... ')\n let newBoardHistory = JSON.parse(JSON.stringify(this.state.boardHistory));\n newBoardHistory.push(board);\n \n this.setState({\n boardHistory: newBoardHistory,\n moveDisplayed: newBoardHistory.length-1 \n });\n // console.log('board logged', this.state.moveDisplayed);\n }", "function renderHistory() {\n dom_history.innerHTML = \"\";\n var history_log = chrome.extension.getBackgroundPage().history_log;\n for (var i = 0; i < history_log.length; i++) {\n var data = history_log[i];\n renderItem(data['state'], data['time'], dom_history);\n }\n}", "function loadHistory() {\n if (Cookie.prototype.checkCookie(\"history\")) {\n var history = Cookie.prototype.getCookie(\"history\"), i, row, col, curPlayer;\n if (history.length % 3 === 0) {\n for (i = 0; i < history.length; i += 3) {\n row = parseInt(history.charAt(i + 1), 10);\n col = parseInt(history.charAt(i + 2), 10);\n curPlayer = parseInt(history.charAt(i), 10);\n ticTacToeBoard.update(row, col, curPlayer);\n if (i === history.length - 3) {\n currentPlayer = curPlayer === player1.getValue() ? player2.getValue() : player1.getValue();\n }\n }\n }\n }\n}", "function getMoves(){\n var moves = \"\";\n var history = board.getMoveHistory();\n for(var i =0;i<history.length;i++){\n var move = history[i];\n moves+= \" \" + move.from + move.to + (move.promotion?move.promotion:\"\");\n }\n console.log(\"******************\");\n console.log(\"MOVES : \" + moves);\n return moves;\n }", "function updateHistory() {\n var historyEl;\n\n // Insert currentOperation into historlist for later retrieval\n historyList.push(currentOperation);\n\n // Create history element with operation display contents\n historyEl = document.createElement('div');\n historyEl.innerHTML = currentOperation.join(\" \");\n\n // Update operation display with id to pull operation from historylist\n historyEl.setAttribute('data-history-id', historyList.length - 1);\n\n // add click event handler\n historyEl.addEventListener('click', historyClickHandler);\n\n // insert operation display into calc history el\n calc.getElementsByClassName('js_calc_history')[0]\n .appendChild(historyEl);\n }", "function populateHistory() {\n savedHistory.forEach(element => {\n historyEl.append(\"<div id='hist-item'>\" + element + \"</div>\");\n });\n}", "historyList() {\n let list = this.historyData.slice();\n let total = list.length;\n let start = ( this.historyPage - 1 ) * this.historyShow;\n let end = ( start + this.historyShow );\n\n this.historyPages = ( total > this.historyShow ) ? Math.ceil( total / this.historyShow ) : 1;\n list = list.slice( start, end );\n return list;\n }", "function addEntryToGameHistoryDisplay(game) {\n const gameHistoryCollection = document.querySelector('.collection');\n\n let entry = document.createElement('li');\n entry.setAttribute('class', 'collection-item');\n if (game.winner === 'Dealer') {\n entry.innerText = `Winner: ${game.winner} || Winning Cards: ${game.dealercards} || Losing Cards: ${game.playercards}`;\n } else if (game.winner === 'Player') {\n entry.innerText = `Winner: ${game.winner} || Winning Cards: ${game.playercards} || Losing Cards: ${game.dealercards}`;\n } else {\n entry.innerText = `Draw || Dealer Cards: ${game.dealercards} || Player Cards: ${game.playercards} `;\n }\n // gameHistoryCollection.appendChild(entry);\n gameHistoryCollection.insertBefore(entry,gameHistoryCollection.firstChild)\n}", "function renderHistoryList() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
redo Canvas Changes This function will redo all of the changes made to the canvas and increase the variable canvasHistoryPointer by one so that it will point at the current canvas state Source for the idea of this method:
function redo_Canvas_Change(){ // Checks to see whether the we can go forward one step if(canvasHistoryPointer+1 < canvasHistory.length){ canvasHistoryPointer++; postCardCanvasContext.putImageData(canvasHistory[canvasHistoryPointer].image, 0, 0); } // If we can't go forward any further then change the color of the redo button if(canvasHistoryPointer+1 >= canvasHistory.length){ // Button 1 - the Redo Button buttons[0].material.color.setHex(0xffffff); buttons[1].material.color.setHex(0x575757); } // Otherwise this means that we can can assume that now we have a space to go // backwards. For this reason, new we'll set the button 0 (The Undo Button) // color back to normal else{ buttons[0].material.color.setHex(0xffffff); buttons[1].material.color.setHex(0xffffff); } }
[ "function undo_Canvas_Change(){\n\t\t // Checks to see whether the we can go back one step\n\t\t if(canvasHistoryPointer >= 1){\n\t\t\t canvasHistoryPointer--;\n\t\t\t postCardCanvasContext.putImageData(canvasHistory[canvasHistoryPointer].image, 0, 0);\n\t\t }\n\t\t \n\t\t // If we can't go back any further then change the color of the undo button\n\t\t if(canvasHistoryPointer <= 0){\n\t\t\t // Button 0 - the Undo Button\n\t\t\t buttons[0].material.color.setHex(0x575757);\n\t\t\t buttons[1].material.color.setHex(0xffffff);\n\t\t }\n\t\t // Otherwise this means that we can can assume that now we have a space to go\n\t\t // forward. For this reason, new we'll set the button 1 (The redo button)\n\t\t // color back to normal\n\t\t else{\n\t\t\t buttons[0].material.color.setHex(0xffffff);\n\t\t\t buttons[1].material.color.setHex(0xffffff);\n\t\t }\n\t }", "function redo() {\n\tcanvas.getCommandStack().redo();\n\treturn true;\n}", "function save_Canvas_Changes(){\n\t\t canvasHistory.push(postCardCanvasContext.getImageData(0, 0, postCardCanvas.width, postCardCanvas.height));\n\t\t canvasHistoryPointer++;\n\t }", "function updateCanvasState(){\n\tif((_config.undoStatus == false && _config.redoStatus == false)){\n\t\tvar jsonData = canvas.toJSON();\n\t\tvar canvasAsJson = JSON.stringify(jsonData);\n\t\tif(_config.currentStateIndex < _config.canvasState.length-1){\n\t\t\tvar indexToBeInserted = _config.currentStateIndex+1;\n\t\t\t_config.canvasState[indexToBeInserted] = canvasAsJson;\n\t\t\tvar numberOfElementsToRetain = indexToBeInserted+1;\n\t\t\t_config.canvasState = _config.canvasState.splice(0,numberOfElementsToRetain);\n\t\t} else {\n\t\t\t_config.canvasState.push(canvasAsJson);\n\t\t\t_config.canvasState = _config.canvasState.filter(function(item, pos){\n\t\t\t\treturn _config.canvasState.indexOf(item)== pos; \n\t\t\t});\n\t\t}\n\t\t_config.currentStateIndex = _config.canvasState.length-1;\n\t\tif((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){\n\t\t\tundoBtn.prop('disabled', false);\n\t\t\tundo_caption.parent('.g-menu-item').removeClass('g-disabled');\n\t\t\t\n\t\t\tredoBtn.prop('disabled', true);\n\t\t\tredo_caption.parent('.g-menu-item').addClass('g-disabled');\n\t\t}\n\t}\n}", "function redo(){\n if (redolistyforpoints.length > 0){\n historyforpts.redo();\n }\n}", "saveCurrentCanvasState(canvas, list, keepRedo) {\n keepRedo = keepRedo || false;\n\n if (!keepRedo) {\n this.redoList = [];\n }\n\n (list || this.undoList).push(canvas.toDataURL('image/png'));\n }", "redo() {\n for(var i = 0; i < this.movedObjects.length; i++) {\n this.movedObjects[i].move(this.moveVector);\n }\n this.canvas.update();\n }", "function redo() {\n charaster.raster = rasterHistory.redo();\n charaster.gridHeight = charaster.raster.length;\n charaster.gridWidth = charaster.raster[0].length;\n charaster.drawAll();\n}", "function redo () {\n\t\tremoveModeClasses();\n\t\tvar data = serialize(g);\n\t\tundoStack.push(data);\n\t\tdata = redoStack.pop();\n\t\tinitialize(data);\n\t\tdocument.getElementById(\"undoButton\").disabled = false;\n\t\tif(redoStack.length == 0) {\n\t\t\tdocument.getElementById(\"redoButton\").disabled = true;\n\t\t}\n\t}", "function undoCommit() {\r\n\tsavedCanvas.pop();\r\n}", "function onRedoClick() {\n let stroke = redoStack.pop();\n if (stroke.command === \"delstroke\") {\n stroke.strokes.forEach((stroke) => {\n undoStack.splice(undoStack.indexOf(stroke), 1);\n });\n } else if (stroke.command === \"fill\") {\n // we're filling the canvas with a new color, so reset backgroundColor so that\n // erase has the correct color\n backgroundColor = stroke.color;\n }\n undoStack.push(stroke);\n if (redoStack.length === 0) {\n setButtonDisableStatus(\"btn-redo\", true);\n }\n setButtonDisableStatus(\"btn-undo\", false);\n }", "function undo() {\n clear_canvas(true);\n complete = false;\n}", "function redo() {\r\n graphEditor.getInteractionHandler().redo();\r\n}", "function redo(project){\n\tclips_stack.unshift(clips_redo_stack.shift());\n\tproject[\"clips\"] = clone(clips_stack[0]);\n\tif(clips_stack.length > maxClipsStackSize){\n\t\tclips_stack.pop();\n\t}\n\tpopulateTimelineWithCurrentClips();\n\tupdateUndoRedoButtons();\n\tsaveClips(false, \"redo\");\n}", "function cRedo() {\r\n if (cStep < cPushArray.length-1) {\r\n console.log('cRedo');\r\n cStep++;\r\n var canvasPic = new Image();\r\n canvasPic.src = cPushArray[cStep];\r\n canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }\r\n }\r\n}", "redo() {\n if (this.__redoStack.length > 0) {\n const change = this.__redoStack.pop()\n // console.log(\"redo:\", change.name)\n change.redo()\n this.__undoStack.push(change)\n this.emit('changeRedone')\n }\n }", "redo () {\n if (this.redoStack.length === 0) return;\n\n let edit = reverseInput(this.redoStack.pop());\n this.edit(edit);\n this.editHistory.push(edit);\n }", "recordChange() {\n //DEBUG\n console.log(\"Undo manager: Change recorded!\");\n\n //To avoid double callback errors causing weird behaviour, we should first check that the state we are about to record is not the same as the\n //previous state!\n let newState = {\n structure : serialiseNodeState(),\n arrangement : serialiseNodeArrangement(),\n globalContextArrangement : canvasState.globalContextArrangement\n };\n\n if (newState.structure === this.currentState.structure &&\n newState.arrangement === this.currentState.arrangement &&\n newState.globalContextArrangement === this.currentState.globalContextArrangement) {\n //OOPS! We probably shouldn't record this\n console.log(\"Undo manager was asked to record the same change twice!!\");\n\n return;\n }\n\n //The first thing to do, is push the current state into the undo stack. This is so we can return to it later!\n //We should make sure we do not push null states though (should never happen anyway, but let's be safe aye?)\n if (this.currentState) {\n this.undoStates.push(this.currentState);\n }\n\n //Now, we need to make sure we record the new current state, by serialising it!\n this.currentState = newState;\n\n //Any previously stored redo states are now invalid, since the user made a new state change and thus have branched away from the redo state chain.\n //Clear it!\n this.redoStates = [];\n\n //Finally, trim the undo states to make sure we are not storing to many, as defined by our limit.\n while (this.undoStates.length > this.maxUndoStates) {\n //Trim the FRONT item (the oldest state..)\n this.undoStates.shift(); //Don't need to keep the old one..\n }\n\n //Update buttons accordingly\n this.makeRedoButtonUnavailable();\n this.makeUndoButtonAvailable();\n }", "function redo() {\n\tur.redo();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fix clearType problems in ie6 by setting an explicit bg color (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s, 10).toString(16); return s.length < 2 ? '0' + s : s; } function getBg(e) { for (; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e, 'background-color'); if (v && v.indexOf('rgb') >= 0) { var rgb = v.match(/\d+/g); return '#' + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function () { $(this).css('background-color', getBg(this)); }); }
[ "function clearTypeFix($slides) {\r\n\tdebug('applying clearType background-color hack');\r\n\tfunction hex(s) {\r\n\t\ts = parseInt(s,10).toString(16);\r\n\t\treturn s.length < 2 ? '0'+s : s;\r\n\t};\r\n\tfunction getBg(e) {\r\n\t\tfor ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {\r\n\t\t\tvar v = $.css(e,'background-color');\r\n\t\t\tif (v && v.indexOf('rgb') >= 0 ) {\r\n\t\t\t\tvar rgb = v.match(/\\d+/g);\r\n\t\t\t\treturn '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);\r\n\t\t\t}\r\n\t\t\tif (v && v != 'transparent')\r\n\t\t\t\treturn v;\r\n\t\t}\r\n\t\treturn '#ffffff';\r\n\t};\r\n\t$slides.each(function() { $(this).css('background-color', getBg(this)); });\r\n}", "function clearTypeFix($slides) {\r\n debug('applying clearType background-color hack');\r\n function hex(s) {\r\n s = parseInt(s,10).toString(16);\r\n return s.length < 2 ? '0'+s : s;\r\n }\r\n function getBg(e) {\r\n for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {\r\n var v = $.css(e,'background-color');\r\n if (v && v.indexOf('rgb') >= 0 ) {\r\n var rgb = v.match(/\\d+/g);\r\n return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);\r\n }\r\n if (v && v != 'transparent')\r\n return v;\r\n }\r\n return '#ffffff';\r\n }\r\n $slides.each(function() { $(this).css('background-color', getBg(this)); });\r\n}", "function clearTypeFix($slides) {\r\n\tdebug('applying clearType background-color hack');\r\n\tfunction hex(s) {\r\n\t\ts = parseInt(s,10).toString(16);\r\n\t\treturn s.length < 2 ? '0'+s : s;\r\n\t}\r\n\tfunction getBg(e) {\r\n\t\tfor ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {\r\n\t\t\tvar v = $.css(e,'background-color');\r\n\t\t\tif (v && v.indexOf('rgb') >= 0 ) {\r\n\t\t\t\tvar rgb = v.match(/\\d+/g);\r\n\t\t\t\treturn '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);\r\n\t\t\t}\r\n\t\t\tif (v && v != 'transparent')\r\n\t\t\t\treturn v;\r\n\t\t}\r\n\t\treturn '#ffffff';\r\n\t}\r\n\t$slides.each(function() { $(this).css('background-color', getBg(this)); });\r\n}", "function clearTypeFix($slides) {\n debug('applying clearType background-color hack');\n function hex(s) {\n s = parseInt(s,10).toString(16);\n return s.length < 2 ? '0'+s : s;\n }\n function getBg(e) {\n for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {\n var v = $.css(e,'background-color');\n if (v && v.indexOf('rgb') >= 0 ) {\n var rgb = v.match(/\\d+/g);\n return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);\n }\n if (v && v != 'transparent')\n return v;\n }\n return '#ffffff';\n }\n $slides.each(function() { $(this).css('background-color', getBg(this)); });\n}", "function clearTypeFix($slides) {\n debug(\"applying clearType background-color hack\");\n function hex(s) {\n s = parseInt(s, 10).toString(16);\n return s.length < 2 ? \"0\" + s : s;\n }\n function getBg(e) {\n for (;e && e.nodeName.toLowerCase() != \"html\"; e = e.parentNode) {\n var v = $.css(e, \"background-color\");\n if (v && v.indexOf(\"rgb\") >= 0) {\n var rgb = v.match(/\\d+/g);\n return \"#\" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);\n }\n if (v && v != \"transparent\") return v;\n }\n return \"#ffffff\";\n }\n $slides.each(function() {\n $(this).css(\"background-color\", getBg(this));\n });\n }", "function clearTextContentConvas()\n{\nclear();\n\tbackground(235);\n}", "function setColor(fadeObj)\n{\n var theColor=getColor(fadeObj);\n var str=\"<FONT COLOR=\"+ theColor + \">\" + fadeObj.text + \"</FONT>\";\n var theDiv=fadeObj.name;\n \n//if IE 4+\n if(document.all)\n {\n document.all[theDiv].innerHTML=str;\n } \n//else if NS 4\n else if(document.layers)\n {\n document.nscontainer.document.layers[theDiv].document.write(str);\n document.nscontainer.document.layers[theDiv].document.close();\n }\n//else if NS 6 (supports new DOM, may work in IE5) - see Website Abstraction for more info.\n//http://www.wsabstract.com/javatutors/dynamiccontent4.shtml\n else if (document.getElementById)\n {\n theElement = document.getElementById(theDiv);\n theElement.style.color=theColor;\n }\n \n}", "function applyBackgroundColor(newColor)\t{\n\tif(editor) {\n\t/*\tif(DOMC(\"icon icon-check bgcolor\") !== null) {\n\t\t\tDOMC(\"icon icon-check bgcolor\").className = \"\"; \n\t\t}\n\t\tfor(var index = 0; index <= 6; index++) {\n\t\t\tvar element = DOM(\"dot_BGCOLOR_\" + index)\n\t\t\tif(element.style.backgroundColor == newColor) {\n\t\t\t\telement.children[0].className = \"icon icon-check bgcolor\";\n\t\t\t\telement.children[0].style.color = get_visible_color(newColor);\n\t\t\t}\n\t\t}*/\n\t}\n\tcurrentSlide.style.backgroundImage = \"none\";\n\tcurrentSlide.style.backgroundColor = newColor;\n\t\n\tvar c = colorToArray(currentSlide.style.backgroundColor);\n\tdocument.body.style.backgroundColor = \"rgb(\" + ~~(parseInt(c.r) * .8) + \",\" + ~~(parseInt(c.g) * .8) + \",\" + ~~(parseInt(c.b) * .8) + \")\";\n\tif(DOMexists(\"ROOT\")) {\n\t\tDOM(\"ROOT\").style.backgroundColor = document.body.style.backgroundColor;\n\t}\n}", "function resetBGColor () {\r\n\teditValue('bgColor', '#0000FF');\r\n\tchangeBGColor('bgColor');\r\n}", "function Themes_PreProcessWebBrowser(theObject)\n{\n\tvar bgColor = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_DEFAULT], null);\n\tif (bgColor == null || __NEMESIS_REGEX_TRANSPARENT_COLOR.test(bgColor))\n\t\ttheObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_DEFAULT] = \"#ffffff\";\n}", "function clearBackground() {\r\n mainContainer.style.background = \"#FFFFFF\";\r\n}", "function resetColour() {\r\n //check for text Immunity\r\n globalColour = util.makeColour(redSlider.value, greenSlider.value, blueSlider.value);\r\n\r\n canvas.changeColour(redSlider.value, greenSlider.value, blueSlider.value);\r\n immmune.style.color = \"#fff\";\r\n\r\n let actualColour = textImmunityBool ? \"#fff\" : globalColour;\r\n\r\n textChangers.forEach(e => {e.style.color = actualColour});\r\n borderChangers.forEach(e => {e.style.borderColor = actualColour});\r\n bgChangers.forEach(e => {e.style.backgroundColor = actualColour});\r\n\r\n\r\n\r\n //Thank You Stack Overflow for allowing us to have a dynamically color changing slider\r\n\r\n let sliderStyle = document.querySelector('#sliderThumbChange');\r\n sliderStyle.innerHTML = \".slider::-webkit-slider-thumb {background:\"+globalColour+\"} \" +\r\n \".slider::-moz-range-thumb {background:\"+actualColour+\"} \";\r\n\r\n\r\n actualColour = util.changeColour(actualColour, 'a', 0.5);\r\n butttons.forEach(e => e.style.borderBottomColor = e.style.borderRightColor = actualColour);\r\n }", "function setColor(fadeObj)\n{\n\tvar theColor=getColor(fadeObj);\n\tvar str=\"<FONT COLOR=\"+ theColor + \">\" + fadeObj.text + \"</FONT>\";\n\tvar theDiv=fadeObj.name;\n\t\n//if IE 4+\n//\tif(document.all)\n//\t{\n//\t\tdocument.all[theDiv].innerHTML=str;\n//\t}\t\n//else if NS 4\n\tif(document.layers)\n\t{\n\t\tif(!fadeObj.layer)\n\t\t\tfadeObj.layer = getLayer(theDiv, document);\n\t\tfadeObj.layer.document.write(str);\n\t\tfadeObj.layer.document.close();\n\t}\n//else if NS 6 (supports new DOM, may work in IE5) - see Website Abstraction for more info.\n//http://www.wsabstract.com/javatutors/dynamiccontent4.shtml\n\telse if (document.getElementById)\n\t{\n\t\ttheElement = document.getElementById(theDiv);\n\t\ttheElement.style.color=theColor;\n\t}\n\t\n}", "function ie03Clr(){ \r\n\tz_ie03_nav_details_flag = false;\r\n}", "function resetBackground (){\n viewer.setBackgroundColor(169,169,169, 255,255, 255);\n}", "static processBackgroundColor(element,valueNew){return TcHmi.System.Services.styleManager.processBackground(element,{color:valueNew})}", "function changeBGcolor(){\n//pend to refactor\nif (v_mode_debug>1) console.log(\"before BG/FG \"+v_color_erase+\" /\"+v_color);\nv_color_erase=0xFFFF-v_color_erase;\nv_color=0xFFFF-v_color;\nif (v_mode_debug>1) console.log(\"after result BG/FG \"+v_color_erase+\" /\"+v_color);\n//g.setColor(color_result);\ng.setBgColor(v_color_erase);// 0 white, 1 black\ng.setColor(v_color);\n//move to event?\nClearScreen();\nClearBox();//?\ngetTemperature();\ndrawGraph();\n//setDrawLayout(); //uncomment if layout can work with setUI\n//g.clear();//impact on widgets\n}", "function handleBgError() {\n qs(\"body\").style.backgroundColor = \"rgb(71, 50, 127)\";\n }", "function setTextBackground(color, opacity) {\r\n text.style.background = color;\r\n text.style.opacity = opacity;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watch set user offline
function watchSetUserOffline(action) { var roomId, authedUser, uid; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function watchSetUserOffline$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: roomId = action.payload.roomId; _context17.next = 3; return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_8__["select"])(_store_reducers_authorize_authorizeSelector__WEBPACK_IMPORTED_MODULE_12__["authorizeSelector"].getAuthedUser); case 3: authedUser = _context17.sent; uid = authedUser.get('uid'); if (!uid) { _context17.next = 8; break; } _context17.next = 8; return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_8__["put"])(_store_actions_globalActions__WEBPACK_IMPORTED_MODULE_11__["showMessage"]('User is offline!')); case 8: case "end": return _context17.stop(); } } }, _marked17); }
[ "function toDoUserOffline() {\n for (var i = 0; i < fakeUsers.length; i++) {\n if (fakeUsers[i].id === getCurrentUser().id) {\n fakeUsers[i].online = false;\n updateStorage();\n return;\n }\n }\n }", "function setOffline(){\n\tsocket.emit('setOffline', userID);\n\taskForUsers();\n}", "function updateLastSeen(user) {\n\tif (user.presence.status != \"offline\") {\n\t\tseen[user.id] = Date.now();\n\t}\n}", "function notifyFriendsOffline(user){\n var friends = user.friends;\n for(var i = 0; i < friends.length; i++){\n if (friends[i] in user_name_data){\n io.sockets.connected[user_name_data[friends[i]]].emit(\"friend_offline\", user.username);\n }\n }\n}", "userIsOnline(){\n this.server.get('/api/user-is-online', (req, res) => {\n try {\n const bind = {\n username: req.query.username\n };\n\n var isOnline = false;\n\n this.App.onlineUsers.forEach(user => {\n if (user.username == bind.username) {\n isOnline = true;\n return\n }\n });\n\n res.send(isOnline ? \"online\" : \"offline\")\n }\n catch (err){\n this.App.throwErr(err, this.prefix, res)\n }\n })\n }", "function fireOnlineStatus(user) {\n for(let i = 0;i<user.friends.length;i++) {\n online_friend = connected_users.get(user.friends[i]);\n // Emit message only to online friends that I am now online\n if(online_friend) {\n online_friend.socket.emit('message',{type:'friend_online',\n friend: user.user_name});\n }\n }\n}", "function updateUsersOnlineStatus(name){\n var findUser = allChatUsers.filter(e => e.name == name);\n \n //Look if name is found in socketIDAndUserName list, if found\n if(Object.values(socketIDAndUserName).includes(name)){\n //then user is online\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = true;\n findUser[0].isOnline = true;\n }\n else{//offline\n // allChatUsers[allChatUsers.indexOf(findUser[0])].isOnline = false;\n findUser[0].isOnline = false;\n }\n\n //DONE Broadcast users online status and broadcast global changed\n broadcastUserStatusChanged(name);\n\n updateGlobalUsers();//UNFIN?\n }", "function checkForOfflineUsers() {\n\t\t$.ajax({\n\t\t\turl: \"https://wind-bow.gomix.me/twitch-api/channels/\" + user,\n\t\t\tdataType: \"jsonp\",\n\t\t\tsuccess: function (data) {\n if (data.status === 422 || data.status === 404) {\n if (data.message.length > 0) {\n status = data.message;\n logo = \"../images/error-icon-25266.png\";\n } else {\n status = \"Information about '\" + user + \"' was not found\";\n logo = \"../images/error-icon-25266.png\";\n }\n updateHTML();\n } else {\n\t\t\t\t status = \"Channel <a href='\" + data.url + \"' target=_blank>\" + data.display_name + \"</a> is currently offline\";\n\t\t\t\t if (data.logo !== null) {\n\t\t\t\t logo = data.logo;\n\t\t\t\t } else {\n\t\t\t\t logo = \"../images/error-icon-25242.png\";\n\t\t\t\t }\n\t\t\t\t updateHTML();\n }\n }\n });\n\t}", "function check_user_online(user_id)\n{\n\n}", "function setOnline() {\n\tsocket.emit('setOnline', userID);\n\taskForUsers();\n}", "offlineWatching() {\n if (window.navigator) {\n if (_.isBoolean(window.navigator.onLine)) {\n this.set({ offline: !window.navigator.onLine });\n $('body').toggleClass('offline', !window.navigator.onLine);\n }\n\n window.addEventListener('load', () => {\n window.addEventListener('online', () => {\n this.set({ offline: false });\n $('body').toggleClass('offline', false);\n });\n window.addEventListener('offline', () => {\n this.set({ offline: true });\n $('body').toggleClass('offline', true);\n });\n });\n }\n }", "function _userStatusNotify() {\n $rootScope.$broadcast('user:updated', user);\n }", "function watchUser() {\n $scope.$watch(function(){\n return authenticationService.user;\n }, function(newVal, oldVal){\n if (newVal === oldVal) {\n return;\n }\n getMovie();\n });\n }", "function onOnlineUserList(){\n console.log(\"send online user list to all ussers\")\n console.log(\"all logged users:\",Object.keys(usersConnected));\n wss.broadcast(JSON.stringify({\n type: \"availableUsers\",\n availableUsers: usersConnected\n }));\n}", "function addOfflineUser (val) {\n if (userOffline.includes(val)) {\n return;\n }\n else {\n userOffline.push(val);\n return;\n }\n }", "function updateUsers(){\n io.sockets.emit('user online', Object.keys(users));\n }", "listenToOnlineUsers({commit}){\n commit(\"setNoOfUsersOnline\", null);\n let database = firebase.database().ref().child('usersessions');\n database.on('value', function (snapshot) {\n let noOfUsers = 0;\n snapshot.forEach(function (users) {\n if(users.child(\"userActiveState\").val() === \"online\") {\n noOfUsers++;\n }\n });\n commit(\"setNoOfUsersOnline\", noOfUsers);\n\n });\n commit(\"setUsersOnlineListener\", database);\n }", "async function setWatch(client){\n const watch = randomElement(viewing);\n await client.user.setPresence({game: {name: watch, type: 3}});\n console.log(`${utils.currentTime()} - Currently watching ${watch}.`);\n}", "function updateliveuser (){\r\n io.emit('liveuser', liveusers);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find class name for method
function find_method(method, node){ var result = ""; var class_name = ""; if (node.type === "class"){ class_name = node.start_statement; class_name = class_name.match(/class\s+([a-zA-Z_-]+)/)[1]; } for (var i in node.children){ var child = node.children[i]; if (child.type === 'class'){ result = find_method(method, child); if (result != ""){ return result; } } else if(child.type === 'method'){ var method_from_code = child.name.replace(/\(.*\)/,""); if (method_from_code === method){ if (class_name != ""){ result = class_name + " " + method; } return result; } } } return result; }
[ "function findClass() {}", "getClassName() {\n return this.constructor\n .className;\n }", "function getClassName(obj) {\n\tvar c = obj.constructor.toString();\n\treturn c.substring(c.indexOf('function ')+9, c.indexOf('('));\n}", "getClassName(ast) {\n logging.taskInfo(this.constructor.name, `getClassName ${ast}`);\n\n logging.taskInfo(this.constructor.name, `getClassName keys ${_.keys(ast)}`);\n }", "static getClassName(object) {\r\n if (object === null || object === undefined) {\r\n return undefined;\r\n }\r\n const constructor = typeof object === \"function\" ? object.toString() : object.constructor.toString();\r\n const results = constructor.match(/\\w+/g);\r\n return (results && results.length > 1) ? results[1] : undefined;\r\n }", "function getClassName(obj) {\n var funcNameRegex = /function\\s+(.+?)\\s*\\(/;\n var results = funcNameRegex.exec(obj['constructor'].toString());\n return (results && results.length > 1) ? results[1] : '';\n }", "static staticMethod() {\n\t\treturn 'classy';\n\t}", "static staticMethod() {\n return 'I must be called using the class name, not object name.'\n }", "function generateNameForClassExpression(){return makeUniqueName(\"class\");}", "function getClass(name){\n\tfor(var i = 0; i < this.classes.length; i++){\n\t\tif(this.classes[i][0] === className){\n\t\t\treturn this.classes[i][1];\n\t\t}\n\t}\n\n\tthrow new Error(\"Undeclared Class.\");\n}", "function getQualifiedMethod(service, method) {\n return service + '.' + method;\n }", "function get$className()/* : String*/\n {\n return flash.utils.getQualifiedClassName(this).replace(/::/, \".\");\n }", "function getJavaClass(sourceCode){\n var tokens = sourcecode.split(\" \");\n var fname = \"\";\n for (let i = 0; i < tokens.length; i++)\n if (tokens[i] == \"public\")\n if (tokens[i + 1] == \"class\")\n return fname = tokens[i + 2];\n}", "function getClassByName(classname) {\n return _nameToClass[classname];\n }", "function generateNameForClassExpression() {\n return makeUniqueName(\"class\");\n }", "processNamedClass() {\n if (!this.tokens.matches2(TokenType._class, TokenType.name)) {\n throw new Error(\"Expected identifier for exported class name.\");\n }\n const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);\n this.processClass();\n return name;\n }", "function getName(method) {\n return _.upperFirst(_.camelCase(method.tags[0].replace(/(-rest)?-controller/, \"\")));\n}", "function fullyQualifiedFunctionName(event) {\n\t const { defined_class, method_id } = event;\n\t if ( defined_class && method_id ) {\n\t return [defined_class, method_id].join(event.static ? '.' : '#');\n\t }\n\n\t return getLabel(event);\n\t}", "function generateNameForClassExpression() {\n return makeUniqueName(\"class\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates dataset of summed integers of a given size
function create_dataset(size) { let data = []; for (let i = 0; i < size; i++) { let input = utils.create_random_array(2, 0, 100); let label = f(input[0], input[1]); data.push([input, label]); } return data; }
[ "function setsize(dataset, size)\n{\n // random variante\n\tif (dataset.length == 0)\n\treturn []\n\n var final_set = []\n _(size).times(function(n){ \n final_set.push(_.sample(dataset, 1)[0])\n });\n\n return final_set\n \n /*var cur_size = dataset.length\n \n if (size > cur_size)\n {\n _(Math.ceil(size/cur_size)).times(function(n){ \n final_set = final_set.concat(dataset)\n });\n }\n else\n final_set = JSON.parse(JSON.stringify(dataset))\n\n return final_set.splice(0,size)*/\n}", "function weightedSum(amplitudes, noises, size) {\n var output = Array.apply(null, new Array(size)).map(Number.prototype.valueOf,0)\n for(var k=0; k < noises.length; k++) {\n for(var x=0; x < size; x++) {\n output[x] += amplitudes[k] * noises[k][x]\n //console.log(amplitudes[k], noises[k][x], amplitudes[k] * noises[k][x])\n }\n }\n return output\n}", "function createValues(size) {\n\tvar values = [], value;\n\n\tfor(value = 1; value < size + 1; value++) {\n\t\tvalues.push(value);\n\t}\n\n\treturn values;\n}", "function createDataSet() {\n var dataSet = [\n {ssn: 123456789, name: \"rahul\", medicalCondition: \"fit\"}\n ];\n for (var i = 1; i < 100; i++) {\n dataSet.push({ssn: (dataSet[i - 1].ssn + 1), name: \"rahul\" + i, medicalCondition: (i % 2 === 0 ? \"fit\" : \"not fit\")});\n }\n return dataSet;\n }", "function createBinomialDataset(n, p, endPoint, inc) {\n var dataset = []\n\n for (var i = 0; i < endPoint + inc; i = i + inc) {\n var y = jStat.binomial.pdf(i, n, p)\n dataset.push({ x: i, y: y })\n }\n\n return dataset\n}", "sampleToSize(start, length) {\n const table = this.getSampleSizeTable();\n let size = 0;\n for (let i = start; i < start + length; i++) {\n size += table[i];\n }\n return size;\n }", "function randomIntSet(density, size, intSetSource) {\n var data = [];\n for (var i=0; i<size; i++) {\n if (Math.random() < density) {\n data.push(i);\n }\n }\n return ozone.intSet.build(ozone.intSet.ArrayIndexIntSet.fromArray(data), intSetSource);\n}", "function sliceSum(arr, n) {\n return [...arr.slice(0, n)].reduce((acc, el) => acc + el, 0);\n}", "function sumAttributeData(id_attributes,new_data){\n\n let original_length = new_data.length\n \n //new_data e id_attributes poseen el mismo largo\n console.log('esto es lo que me entro de datos: ',new_data )\n console.log('Estos son los atributos: ',id_attributes )\n\n const distinct_ids = [...new Set(id_attributes)] // [1,1,1,2,3,3] => [1,2,3], distinct values (only primitive types)\n console.log('Este es el arreglo distinto de datos: ',distinct_ids )\n\n console.log('el largo de los resultados:', id_attributes.length)\n\n var id_aux = id_attributes[0]\n var index = 0\n\n var almost_results = new Array(id_attributes.length).fill(0);\n console.log('Este es el arreglo de almost_results: ', almost_results)\n\n for (let i = 0; i < id_attributes.length; i++) {\n if(id_aux !== id_attributes[i]){\n index++\n id_aux = id_attributes[i]\n }\n almost_results[index] += new_data[i];\n \n }\n\n console.log('este es el almost results: ',almost_results)\n let result = almost_results.filter(data => data !== 0)\n\n if(result.length === 0){\n //No hubo ningun cambio... (puede pasar con datos externos obtenidos desde dispositivos en ciertos casos)\n result = new Array(original_length).fill(0);\n }\n console.log('Este es el resultado final ',result )\n\n let result_object = {\n \"id_attributes\": distinct_ids,\n \"new_data\":result\n }\n return result_object\n \n}", "function buildRandomDataset(N) {\n var dataset = Array(N);\n for (\n it = 0;\n it < N;\n dataset[it++] = [0, 0, 0].map(Math.random)\n );\n return dataset;\n}", "function CalcBins( datalist, binnum, binsize )\n{\n var bin_list = Array.apply( null, Array( binnum + 1 ) ).map( Number.prototype.valueOf, 0 )\n var bin_num\n for ( var i = 0; i < datalist.length; i++ )\n {\n bin_num = Math.floor( datalist[ i ] / binsize )\n if( bin_num < 1 )\n {\n bin_num = 0;\n }\n bin_list[ bin_num ] += 1\n }\n// console.log( bin_list )\n return bin_list\n}", "function toData(nums,sequenceLength) {\n const data=full(sequenceLength+1).map(e=>[]);\n const iMax=nums.length-sequenceLength;\n for (let i=0; i<iMax; i+=sequenceLength) {\n for (let j=0; j<sequenceLength+1; j++) {\n data[j].push(nums[i+j]);\n }\n }\n return data;\n}", "function createSalesDataArray(){\n //Get all table cells\n var tableCells = document.querySelectorAll('td');\n var tableCellData = [];\n for(var j=0; j < tableCells.length; j++){\n tableCellData.push(tableCells[j].innerHTML);\n }\n\n //Multi-dimensional array to store table data\n var salesDataMatrix = [];\n\n //Grab items from tableCells in chunks of 16\n // for each of the 5 stores\n var k = 1;\n for(var i=0; i < storeCt; i++){\n //For each chunk of 16, add to a list\n //Add that list to salesDataMatrix\n var dataRow = tableCellData.slice((k-1) * 16, k * 16);\n salesDataMatrix.push(dataRow);\n k++;\n }\n return salesDataMatrix;\n}", "function sumSize(burls) {\n var iSum = 0;\n // Implement the sum function using the burls 'size':\n for(var i=0; i<burls.length; i++)\n {\n iSum += burls[i].size;\n }\n return iSum;\n}", "function array_gen(size) {\n var ints = [];\n for (j = 1; j < size + 1; j++) {\n ints.push(j);\n }\n return ints;\n}", "chunk(array, size){\n let arrayChunks = [];\n for(let i= 0; i < array.length; i += size){\n arrayChunks.push(array.slice(i, i+size));\n }\n return arrayChunks;\n }", "function sum(array) {}", "get sumElements(){\n let sum = 0;\n this.dataset.forEach(element => {\n sum += element;\n });\n return sum;\n }", "function generateXData() {\n xdata = [];\n for (let i=0; i<=100; i++) {\n xdata.push(i);\n }\n return xdata;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
routine to set the selected value in an option list.
function set_selected_option (what, set_val) { var last =what.length -1; var index; for (index=0; index<what.length; index++) { if (what[index].value == set_val) { what.selectedIndex = index; } } }
[ "function set_selected(p_obj, p_value) {\n for (i = 0; i < p_obj.options.length; i++) {\n if (p_obj.options[i].value == p_value) {\n p_obj.options[i].selected = true;\n break;\n }\n }\n}", "function setSelectValue() {\n var values = (hasMultiple) ? $select.val() : [$select.val()];\n clearTemplateOptions();\n $(values).each(function (index, value) {\n $template.find('[data-option-value=\"' + value + '\"]')\n .attr('aria-checked', 'true');\n });\n setTemplateTabIndex();\n }", "function setOptionValue(selectId, value){\n\t\t// get dropdown list by itemSelectId\n\t\tvar itemSelect = $(selectId);\n\t\t// select given value as selected in dropdown list \n\t\tvar index = 0;\n\t\tfor (var i = 0; i < itemSelect.options.length; i++) {\n\t\t\tvar option = itemSelect.options[i];\n\t\t\tif(option.value==value){\n\t\t\t\tindex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t//set value to dropdown list\n\t\titemSelect.options[index].selected = true;\n\t}", "function set_select_value(v, e) {\n\t$(e).select('option').find(function(opt, i) {\n\t\tif(opt.readAttribute('value') == v) {\n\t\t\te.selectedIndex = i\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t});\n}", "function selectItemByValue(elmnt, value){\n\n\t\t\tfor(var i=0; i < elmnt.options.length; i++)\n\t\t\t{\n\t\t\t\tif(elmnt.options[i].value == value)\n\t\t\t\telmnt.selectedIndex = i;\n\t\t\t}\n\t\t}", "function setOption(selectElement, value) {\n var options = selectElement.options;\n for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {\n if (options[i].value === value) {\n selectElement.selectedIndex = i;\n }\n }\n}", "function update_hidden_select_selection( value ) {\n\t\t\t\t$(hidden_select).val(value).change();\n\t\t\t}", "setDefaultSelectedOption() {\n if (this.$fastController.isConnected && this.options) {\n const selectedIndex = this.options.findIndex(el => el.getAttribute(\"selected\") !== null || el.selected);\n this.selectedIndex = selectedIndex;\n\n if (!this.dirtyValue && this.firstSelectedOption) {\n this.value = this.firstSelectedOption.text;\n }\n\n this.setSelectedOptions();\n }\n }", "SetSelectedCategoryValue (value) {\n SelectCategoryValue = value;\n }", "function selectOptionByValue(element,value)\n{\n\t// set the option in the select box\n\tfor( var optionIdx = 0; optionIdx < element.options.length; optionIdx++ )\n\t{\n\t\tif(\telement.options[optionIdx].value == value )\n\t\t{\n\t\t\telement.selectedIndex = optionIdx;\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function selectItemByValue(element, value) {\n\tif(element.options.length) {\n\t\tfor(var i=0;i<element.options.length;i++) {\n\t\t\tif(element.options[i].value == value) {\n\t\t\t\telement.options[i].selected = true;\n\t\t\t}\n\t\t}\n\t}\n}", "function setSelection(list, item) {\n var lastItem = getSelection(list),\n value = null;\n \n if (item !== lastItem) {\n if (lastItem) {\n lastItem.classList.remove('state--selected');\n }\n if (item) {\n item.classList.add('state--selected');\n value = item.dataset.value;\n }\n list.dispatchEvent(new CustomEvent('change', {\n detail: value,\n bubbles: true\n }));\n }\n }", "function selectOptionWithValue(select, value) {\n select\n .children(\"option\")\n .prop(\"selected\", false)\n ;\n\n select\n .children(\"option[value='\" + value + \"']\")\n .prop(\"selected\", true)\n ;\n}", "function selectUpdateValue(e) {\n var target = e.target;\n var value = target.textContent;\n var thisSelectElement = target.parentNode.parentNode.parentNode.querySelector('select');\n var thisEntryPoint = target.parentNode.parentNode.previousElementSibling;\n thisSelectElement.value = value;\n thisEntryPoint.textContent = value;\n // close the list when you've selected an option\n selectOpenList(thisEntryPoint);\n softDismiss.style.zIndex = '';\n }", "function set_select(ctrl, val) {\r\n opts = $(ctrl).options\r\n for (var i = 0; i < opts.length; i++) {\r\n if (val == opts[i].value) {\r\n opts[i].selected = true;\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "function changeSelectOption(tagSelect,strSelectValue)\r\n{\r\n\tvar strSelectOption = \"\";//holds the select option the user has choosen\r\n\t\r\n\t//goes around finding the current seleted value from tagSelection\r\n\tfor (var intIndex = 0;intIndex < tagSelect.options.length; intIndex++)\r\n\t{\r\n\t\tif (tagSelect.options[intIndex].value == strSelectValue)\r\n\t\t\ttagSelect.options[intIndex].selected = true;\r\n\t}//end of for loop\r\n}//end of changeSelectOption()", "function setSelect(elem, val) {\n \tvar opts = elem.options;\n \tfor (var i=0; i<opts.length; i++)\n \t\tif (opts[i].value == val) {\n\t\t\telem.selectedIndex = i;\n\t\t\treturn false;\n\t\t}\n\t// if not found, reset to Index 0\n\telem.selectedIndex =0;\n}", "function updateSelectedOption( optionPosition, value ) {\n if ( !optionPosition ) {\n console.log( `ERROR : [ productUtils - updateSelectedOption() ] -- Option position was not passed, unable to update selection state.` );\n return;\n }\n state.selectedOptions[ `option${optionPosition}` ] = value;\n }", "handleSelect(value) {\n\t\tthis.setValue(value, true)\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function that takes a string and an integer of i and creates a new array of length i where each value is equal to the string passed in myFunction('sunshine', 3) => ['sunshine', 'sunshine', 'sunshine']; Put your answer below
function myFunction(str, i) { var arr = []; for (j = 0; j < i; j++) { arr[j] = str; } }
[ "function myFunction(word, integer){\n const myArray = []\n for(let i = 0; i < integer; i++){\n myArray.push(word);\n }\n return myArray;\n\n}", "function myFunction(string, num1){\n var array = [];\n for(i = 0; i < num1; i++)\n array.push(string);\n return array;\n}", "function myFunction(string, integer) {\n let arr = [];\n for (let i = 0; i < integer; i++) {\n arr.push(string);\n }\n console.log(arr);\n}", "function myFunction(str, x){\n let strArray = [];\n for (let i = 0; i <= x; i++){\n strArray = strArray.concat(str);\n }\n return strArray;\n}", "function newArray(str, i) {\n var myArray = [];\n\n for (let j = 1; j <= i ; j++){\n // for (let j = 0; j < i ; j++){\n myArray.push(str);\n }\n return myArray;\n}", "function onlySunshine(str, i) {\n let output = []\n for (j = 0; j < i; j++) {\n output[j] = str\n }\n return output;\n}", "function finalFunction(num){\n var array =[];\n for (i=0;i<num;i++){\n array.push('string')\n }\n return array\n}", "function finalFunction(num) {\n var newArray = [];\n for (i = 0; i < num; i++) {\n newArray.push('string');\n }\n return newArray\n}", "function finalFunction(number){\n let myArray = [];\n while (myArray.length < number){\n myArray.push(\"string\");\n }\n return myArray;\n}", "function finalFunction(num) {\n var finalArray = [];\n for (var i=0; i<num; i++) {\n finalArray.push('string');\n }\n return finalArray;\n}", "function newArr(num){\r\n var arr = [];\r\n for (var i = 0; i < num; i++){\r\n arr.push(newWord());\r\n }\r\n return arr;\r\n}", "function makeFruitArray() {\n let Array = [\"Mango\", \"Kiwi\", \"Papaya\", \"Plum\"];\n return Array;\n}", "function finalFunction(number){\n\n arr= [];\n \n for (x = 1; x<=number; x++)\n {\n arr.push('help')\n }\n return arr\n }", "function myFunc3(a, b, c) {\n const array = [a.toUpperCase(), b.toUpperCase(), c.toUpperCase()];\n return array;\n}", "function array_maker(int) {\n\tvar array = []\n var possible = \"abcdefghijklmnopqrstuvwxyz\";\n \n\t\n\tfor (i = 0; i < int; i++) { \n\tvar text = \"\";\n\t\tfor( var x=0; x < Math.random() * (0 + 11); x++ ){\n\t\t\ttext += possible.charAt(Math.floor(Math.random() * possible.length))}\n \t\t\t \n array[i] = text;\n\t}\n\n\tconsole.log(array)\n\treturn(array)\n}", "function finalFunction(num){\n var arr = []\n for (var i =0;i<num;i++){\n arr.push(\"A\")\n }\n return arr;\n}", "function modifyStrings(strings, modify) {\n // YOUR CODE BELOW HERE //\n \n // inputs an array, containing string. a function that modifies strings, BUT NOT ARRAYS\n //outputs return an array, where all of its contents have been modified individually by the function\n \n //should increment over array strings, taking each value in it and applying the modify function to it, placing the results in a new array\n //should return the new array\n let newArray = [];\n for (let i = 0; i< strings.length; i++){\n newArray.push(modify(strings[i]));\n \n }\n return newArray;\n \n \n // YOUR CODE ABOVE HERE //\n}", "function arrayFromIndex( myArray, startingIndex){\n console.log('in arrayFromIndex:', myArray, startingIndex );\n\n ///-full array test\n let stringToReturn = '';\n for(let i=startingIndex; i < myArray.length; i++ ){\n //return a string that combines all of the values\n stringToReturn += myArray[ i ] + ' ';\n } //end for\n return stringToReturn;\n}//end funtion", "function shortWords (arr){\nlet newArray = [];\nlet originalArray = [\"basin\", \"pit\", \"cheese\", \"bun\", \"river\"];\nfor originalArray.length(if i <=3) \n return newArray; \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the amount of a price in a given currency. If the amount for the currency is not defined in the price object it will be computer from the euro amount.
function getAmountInCurrency(price, currency, convertFromEuro) { return currency in price ? price[currency] : convertFromEuro(price["eur"], currency); }
[ "function getAmountInCurrency(price, currency, convertFromEuro) {\n return currency in price ?\n price[currency] :\n convertFromEuro(price[\"eur\"], currency);\n }", "toDecimal(currency) { return priceToDecimal(this.value(currency)); }", "function toCents(priceEuro) {\n return Math.round(priceEuro * 100);\n}", "function getValue(crypto, amount, currency, type) {\n return parseFloat((getPrice(crypto, type, currency) * amount));\n}", "function currencyConverter(currency, amount){\n if(currency == 'USD')\n {\n amount = amount * 3.75;\n return amount;\n }\n else if (currency == 'GBP')\n {\n amount = amount * 4.85;\n return amount;\n \n }\n else if (currency == 'EGP')\n {\n amount = amount / 4.68;\n return amount;\n \n }\n else if (currency == 'BD')\n {\n amount = amount / 0.10;\n return amount;\n }\n \n }", "function getPrice(crypto, type, currency) {\n args = [\"crypto\",\"type\",\"currency\"];\n args.forEach(function(i) { if (isObject(eval(i))) { eval(i + \" = null;\"); }});\n crypto = crypto || \"Bitcoin\";\n var symbol = getSymbol(crypto);\n type = type || \"sell\";\n currency = (currency || \"USD\").toUpperCase();\n if (symbol == \"xrp\") {\n // Ripple prices pulled from Bitsane's API\n var url = (\"https://bitsane.com/api/public/ticker?pairs=\" + symbol.toUpperCase() + \"_\" + currency);\n// return url;\n } else {\n // It's traded on Coinbase, \n var url = \"https://api.coinbase.com/v2/prices/\" + symbol + \"-\" + currency + \"/\" + type;\n }\n// return symbol;\n var price = getFromApi(url, type);\n return parseFloat(price);\n}", "function convertToUSD(amount, currency) {\n const exchangerate = currency === \"USD\" ? 1 : fiatData.rates[currency];\n const usdamount = amount / exchangerate;\n \n //Convert amount to Ether\n return fetch(api.ethereumCoinmarketCap)\n .then(resp => resp.json())\n .then(data => {\n return (usdamount / data[0].price_usd)\n })\n }", "function calculatePriceFromAmount(cost, amount) {\n var price = cost;\n if(cost && amount){\n price = cost + amount;\n price = (Math.round(price * 100)) / 100;\n }\n return price;\n }", "function parseAmount(amount,currency){\r\n var out_currency=currencyCode.find(o => (o.Num === currency || o.Code === currency));\r\n if(out_currency) {\r\n if(out_currency.Dec!==0 && out_currency.Dec!==null){\r\n return parseFloat(amount/Math.pow(10,out_currency.Dec)).toFixed(out_currency.Dec);\r\n }\r\n else {\r\n return amount;\r\n }\r\n }\r\n else {\r\n return amount;\r\n }\r\n }", "function convertToETHPrice(priceUSD){\n let ETHPrice = cmcArrayDict['eth'.toUpperCase()]['quote']['USD']['price'];\n return priceUSD / ETHPrice;\n}", "function currencyConverter( amount, currency ){\n if(\"USD\"==currency){ \n return amount*3.75;\n }\n\n else if(\"GBP\"==currency){ \n return amount*4.84;\n }\n else if(\"EGP\"==currency){ \n return amount/4.86 ;\n }\n else if(\"BD\"==currency){ \n return amount/0.10;\n } \n \n\n\n}", "function dollarToEuro(dollar) {\r\n return dollar * changeRate;\r\n}", "function convertToUSD(value, currency) {\n // Index into currency conversion table for specified currency\n if (window.rates[currency]) {\n return parseFloat(value / window.rates[currency]).toFixed(2);\n }\n\n // By default, just return the provided value\n return value;\n}", "function toStripeAmount( amount, currency ) {\n // TODO: needs currency and amount validation more precisely\n // https://stripe.com/docs/currencies#zero-decimal\n let ret = amount; // original amount\n let cur = currency.toUpperCase( );\n if ( !zeroDecimalCurrencies.find( e => e == cur ) ) {\n ret = ret * 100; // multiply by the smallest unit... which we don't have!\n // TODO: get a list of smallest units by currency. it's usually 100\n }\n return Math.round( ret ); // make it integer... although value is supposed to be integer already\n}", "function totalPricePerAmount(amount, price) {\n return amount * price;\n }", "async function getPriceUnit(currency) {\n let decimals = await getDecimals(currency)\n if (!currency) {\n currency = '0x0000000000000000000000000000000000000000'\n }\n return unatomic(await MyNFT.methods.getPriceUnit(currency).call(), decimals)\n}", "getPrice(balance, baseSymbol, quoteSymbol) { \n balance = BigNumber(balance)\n baseSymbol = normalizeTokenSymbol(baseSymbol)\n quoteSymbol = normalizeTokenSymbol(quoteSymbol)\n \n if(baseSymbol == quoteSymbol)\n return balance\n\n return this.exchangeRates[quoteSymbol][baseSymbol].multipliedBy(balance)\n }", "function getProductValueInCOP(currency, value){\n\n for(var i = 0; i < $scope.rates.length; i++)\n if (currency == $scope.rates[i].currency) {\n return value * $scope.rates[i].rate;\n };\n return currency == 'COP' ? value : 0;\n }", "get priceInDollars () {\n return self.priceInSatoshis && self.bitcoinPrice\n ? numeral(self.priceInSatoshis)\n .multiply(self.bitcoinPrice)\n .divide(100000000)\n .format('$0.00000')\n : null\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Horizontal direction to the right
*directionHorizontalRight() { yield this.sendEvent({ type: 0x03, code: 0x00, value: 255 }); }
[ "function directionLeftToRight() {\n currentOffset.x = -50;\n offsetX = -1;\n\n if (fromLeftBottom) {\n currentOffset.y = -(backgroundSize.y - contentSize.y) + 60;\n offsetY = 1;\n fromLeftBottom = false;\n }\n else {\n currentOffset.y = -60;\n offsetY = -1;\n fromLeftBottom = true;\n }\n }", "turnRight() {\n this.direction += 90;\n if (this.direction > directions.W) {\n this.direction = directions.N;\n }\n }", "static get horizontal() { return this.rtl; }", "static right() {\n\n // Return a Direction pointing towards the right\n return new Direction([1, 0, 0]);\n }", "function shiftToRight(){\n updateCurrentRight();\n updateDisplayRight();\n $slider.addClass('moving');\n $slideContainer.animate({'margin-left': '-='+totalWidth}, animationSpeed, function(){\n $slider.removeClass('moving');\n });\n }", "get right() {\n return this.x + this.width;\n }", "get right() {\r\n return this.x + this.width;\r\n }", "turnRight() {\n\n if (this.orientation == 0) {\n this.orientation = 3;\n } else {\n this.orientation -= 1;\n }\n\n }", "function right(x) { \n currentAlignment = alignRight \n}", "function right(x) { currentAlignment = alignRight }", "get right() {\n return -this.x / this.scale.x + this.worldScreenWidth;\n }", "function directionRightToLeft() {\n var returnFunction = new function () {\n currentOffset.x = -(backgroundSize.x - contentSize.x) + 20;\n offsetX = 1;\n\n if (fromRightBottom) {\n currentOffset.y = -(backgroundSize.y - contentSize.y) + 60;\n offsetY = 1;\n fromRightBottom = false;\n }\n else {\n currentOffset.y = -60;\n offsetY = -1;\n fromRightBottom = true;\n }\n }\n }", "get right () {\n // x is left position + the width to get end point\n return this.x + this.width\n }", "get right()\n {\n return (-this.x / this.scale.x) + this.worldScreenWidth;\n }", "turnRight() {\n if(this.isCrashed()) {\n this.recoverFromCrash(DIRECTION_RIGHT);\n }\n\n if(this.direction === DIRECTION_RIGHT) {\n this.moveSkierRight();\n }\n else {\n this.setDirection(this.direction + 1);\n }\n }", "moveRight(){\t\t\n\t\tif(this.checkMoveRight()){\n\t\t\tthis.col++;\n\t\t}\n\t}", "get right()\n {\n return (-this.x / this.scale.x) + this.worldScreenWidth;\n }", "get right() {\n // x is left position + the width to get end point\n return this.x + this.width\n }", "static get DIRECTION_RIGHT() {\n return \"right\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Force selectionChange when editable was focused. Similar to hack in selection.js~620.
function onEditableFocus() { // Gecko does not support 'DOMFocusIn' event on which we unlock selection // in selection.js to prevent selection locking when entering nested editables. if ( CKEDITOR.env.gecko ) this.editor.unlockSelection(); // We don't need to force selectionCheck on Webkit, because on Webkit // we do that on DOMFocusIn in selection.js. if ( !CKEDITOR.env.webkit ) { this.editor.forceNextSelectionCheck(); this.editor.selectionChange( 1 ); } }
[ "_updateFocus() {\n\t\tif ( this.isFocused ) {\n\t\t\tconst editable = this.selection.editableElement;\n\n\t\t\tif ( editable ) {\n\t\t\t\tthis.domConverter.focus( editable );\n\t\t\t}\n\t\t}\n\t}", "selectFocused(){this._focusedField.selectItem()}", "updateSelection(mustRead = false, fromPointer = false) {\n if (mustRead || !this.view.observer.selectionRange.focusNode)\n this.view.observer.readSelectionRange();\n if (!(fromPointer || this.mayControlSelection()))\n return;\n let force = this.forceSelection;\n this.forceSelection = false;\n let main = this.view.state.selection.main;\n // FIXME need to handle the case where the selection falls inside a block range\n let anchor = this.domAtPos(main.anchor);\n let head = main.empty ? anchor : this.domAtPos(main.head);\n // Always reset on Firefox when next to an uneditable node to\n // avoid invisible cursor bugs (#111)\n if (browser$4.gecko && main.empty && betweenUneditable(anchor)) {\n let dummy = document.createTextNode(\"\");\n this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));\n anchor = head = new DOMPos(dummy, 0);\n force = true;\n }\n let domSel = this.view.observer.selectionRange;\n // If the selection is already here, or in an equivalent position, don't touch it\n if (force || !domSel.focusNode ||\n !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||\n !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {\n this.view.observer.ignore(() => {\n // Chrome Android will hide the virtual keyboard when tapping\n // inside an uneditable node, and not bring it back when we\n // move the cursor to its proper position. This tries to\n // restore the keyboard by cycling focus.\n if (browser$4.android && browser$4.chrome && this.dom.contains(domSel.focusNode) &&\n inUneditable(domSel.focusNode, this.dom)) {\n this.dom.blur();\n this.dom.focus({ preventScroll: true });\n }\n let rawSel = getSelection(this.view.root);\n if (!rawSel) ;\n else if (main.empty) {\n // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076\n if (browser$4.gecko) {\n let nextTo = nextToUneditable(anchor.node, anchor.offset);\n if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {\n let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1);\n if (text)\n anchor = new DOMPos(text, nextTo == 1 /* NextTo.Before */ ? 0 : text.nodeValue.length);\n }\n }\n rawSel.collapse(anchor.node, anchor.offset);\n if (main.bidiLevel != null && domSel.cursorBidiLevel != null)\n domSel.cursorBidiLevel = main.bidiLevel;\n }\n else if (rawSel.extend) {\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n rawSel.collapse(anchor.node, anchor.offset);\n // Safari will ignore the call above when the editor is\n // hidden, and then raise an error on the call to extend\n // (#940).\n try {\n rawSel.extend(head.node, head.offset);\n }\n catch (_) { }\n }\n else {\n // Primitive (IE) way\n let range = document.createRange();\n if (main.anchor > main.head)\n [anchor, head] = [head, anchor];\n range.setEnd(head.node, head.offset);\n range.setStart(anchor.node, anchor.offset);\n rawSel.removeAllRanges();\n rawSel.addRange(range);\n }\n });\n this.view.observer.setSelectionRange(anchor, head);\n }\n this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);\n this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);\n }", "function addFocusToSelection(selection,node,offset,selectionState){if(selection.extend&&containsNode(getActiveElement(),node))// If `extend` is called while another element has focus, an error is\n// thrown. We therefore disable `extend` if the active element is somewhere\n// other than the node we are selecting. This should only occur in Firefox,\n// since it is the only browser to support multiple selections.\n// See https://bugzilla.mozilla.org/show_bug.cgi?id=921444.\n// logging to catch bug that is being reported in t16250795\noffset>getNodeLength(node)&&// the call to 'selection.extend' is about to throw\nDraftJsDebugLogging.logSelectionStateFailure({anonymizedDom:getAnonymizedEditorDOM(node),extraParams:JSON.stringify({offset:offset}),selectionState:JSON.stringify(selectionState.toJS())}),selection.extend(node,offset);else{// IE doesn't support extend. This will mean no backward selection.\n// Extract the existing selection range and add focus to it.\n// Additionally, clone the selection range. IE11 throws an\n// InvalidStateError when attempting to access selection properties\n// after the range is detached.\nvar range=selection.getRangeAt(0);range.setEnd(node,offset),selection.addRange(range.cloneRange());}}", "onEditStart() {\n\t\tthis.setMod('focused', true);\n\t}", "focus() {\n if (!this.disabled) {\n this.contenteditable = \"true\";\n this.__focused = true;\n }\n this.dispatchEvent(\n new CustomEvent(\"focus\", {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: this.querySelector(\"*\"),\n })\n );\n }", "function on_selection_changed() { }", "function onFocus() {\n if (this._mouseDownFlag !== true && this._options.autoSelect === true && this.index === -1) {\n this._activeDescendant.index = 0;\n this.items[0].setAttribute('aria-selected', 'true');\n\n if (this._options.useAriaChecked === true) {\n this.items[0].setAttribute('aria-checked', 'true');\n }\n }\n this._mouseDownFlag = false;\n}", "function _set_focus() {\n new_node.hasFocus=true;\n new_node.focus();\n new_node.select(); // Safari\n\n try {\n if (false) {\n // set cursor position based on old range\n if (old_sel_start != null && old_sel_end != null) {\n set_selection_range(new_node, old_sel_start, old_sel_end);\n }\n } else {\n // select whole text and set cursor at end; this is the preferred behavior for semi hidden passwords now\n set_selection_range(new_node, 0, new_node.value.length);\n }\n } catch(e) {\n ;\n }\n\n // no longer active, stop blocking events\n __semihidden_replacement_active[id] = \"\";\n }", "selectFocused() {\n this._tabs[this._focusIndex].selectItem();\n }", "function addFocusToSelection(selection,node,offset){if(selection.extend&&containsNode(getActiveElement(),node)){// If `extend` is called while another element has focus, an error is\r\n\t// thrown. We therefore disable `extend` if the active element is somewhere\r\n\t// other than the node we are selecting. This should only occur in Firefox,\r\n\t// since it is the only browser to support multiple selections.\r\n\t// See https://bugzilla.mozilla.org/show_bug.cgi?id=921444.\r\n\tselection.extend(node,offset);}else{// IE doesn't support extend. This will mean no backward selection.\r\n\t// Extract the existing selection range and add focus to it.\r\n\t// Additionally, clone the selection range. IE11 throws an\r\n\t// InvalidStateError when attempting to access selection properties\r\n\t// after the range is detached.\r\n\tvar range=selection.getRangeAt(0);range.setEnd(node,offset);selection.addRange(range.cloneRange());}}", "function onChangeSelection(e, editor) {\n var lead = editor.getSelection().lead;\n if (editor.session.$bidiHandler.isRtlLine(lead.row)) {\n if (lead.column === 0) {\n if (editor.session.$bidiHandler.isMoveLeftOperation && lead.row > 0) {\n editor.getSelection().moveCursorTo(lead.row - 1, editor.session.getLine(lead.row - 1).length);\n } else {\n if (editor.getSelection().isEmpty())\n lead.column += 1;\n else\n lead.setPosition(lead.row, lead.column + 1);\n }\n }\n }\n}", "focus() {\n this.select.focus();\n }", "function onSelectionChangeCursor() {\n var cursorPos = fileEditor.aceEditor.getCursorPosition();\n\n _publishPosition(CURSOR_POSITION_CHANGE, cursorPos);\n }", "selectionChanged() {}", "focus() {\n if (this.select.current) {\n this.select.current.focus();\n }\n }", "_selectFocus(startRow, table, focus) {\n const range = table.selectionRangeOfFocus(focus, startRow);\n if (range !== undefined) {\n this._textEditor.setSelectionRange(range);\n }\n else {\n this._moveToFocus(startRow, table, focus);\n }\n }", "selectFocused(){this._tabs[this._focusIndex].selectItem()}", "function focusIntoSelectedCell(element) {\n var jsnRange;\n var bolReWriteSelection;\n\n // we use the latest range a lot, let's save a shortcut\n jsnRange = element.internalSelection.ranges[\n element.internalSelection.ranges.length - 1\n ];\n //console.log(jsnRange);\n\n // if more than one selection: warn and move selection to endpoint of\n // latest selection\n if (element.internalSelection.ranges.length > 1) {\n console.warn('GS-TABLE Warning: \"focusIntoSelectedCell\" called' +\n ' when multiple selections were present. Now clearing all' +\n ' selections and creating new selection at last' +\n ' selection\\'s endpoint.');\n // because this if block uses the same issue resolution as the\n // \"else if\" block below, we'll just set a boolean variable and\n // below this waterfall we'll add another if statement that\n // handles this type of resolution\n bolReWriteSelection = true;\n\n // else if one selection that is more than one cell:\n // warn and move selection to endpoint of latest selection\n } else if (\n jsnRange &&\n (\n jsnRange.start.column !== jsnRange.end.column ||\n jsnRange.start.row !== jsnRange.end.row\n )\n ) {\n console.warn('GS-TABLE Warning: \"focusIntoSelectedCell\" called' +\n ' when the selection contained multiple cells. Now' +\n ' clearing all selections and creating new selection at' +\n ' last selection\\'s endpoint.');\n // because this if block uses the same issue resolution as the\n // \"if\" block above, we'll just set a boolean variable and\n // below this waterfall we'll add another if statement that\n // handles this type of resolution\n bolReWriteSelection = true;\n\n // else if no selections:\n // warn, focus hiddenFocusControl so we can still listen to\n // keypresses and stop execution\n } else if (!jsnRange) {\n console.warn('GS-TABLE Warning: \"focusIntoSelectedCell\" called' +\n ' when there was no selection to focus into. Stopping' +\n ' execution of \"focusIntoSelectedCell\".');\n\n focusHiddenControl(element);\n return;\n }\n\n // if there's more than one selection or the only selection contains\n // multiple, the response is the same: change selection to only\n // last cell of last selection range, so, instead of copying the\n // code to resolve it into both cases in the waterfall, they set\n // a boolean variable if this is what they need done.\n if (bolReWriteSelection) {\n // set the new list of selection ranges to the endpoint of the\n // latest selection\n element.internalSelection.ranges = [\n {\n \"start\": {\n \"row\": jsnRange.end.row,\n \"column\": jsnRange.end.column\n },\n \"end\": {\n \"row\": jsnRange.end.row,\n \"column\": jsnRange.end.column\n },\n \"negator\": false\n }\n ];\n\n // get the new selection range, this is a shortcut\n jsnRange = element.internalSelection.ranges[0];\n\n // re-render the selection because we've just changed it and\n // the user needs to see the update\n renderSelection(element);\n }\n\n // pass the last selection's enpoint cell to focusIntoCell\n focusIntoCell(\n element,\n jsnRange.end.row,\n jsnRange.end.column\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
"returns the longest side of each set of triangle data
function getLongestSides(triangles) { if (!triangles) throw new Error("triangles is required"); //take each item in array and put in decreasing number order using .sort, return first index using slice function sortNumber(a, b) { return b - a; } let sortNums = triangles.map(n => n.sort(sortNumber)[0]); return sortNums; }
[ "function calcLongestSide(a,b)\n{\n\treturn Math.sqrt((a*a) + (b*b));\n}", "function maximumPerimeterTriangle(sticks) {\n let max = -1;\n return sticks\n .sort((a, b) => a - b)\n .reduce(\n (acc, curr, idx) => {\n if (idx + 2 < sticks.length) {\n if (curr + sticks[idx + 1] > sticks[idx + 2]) {\n if (curr + sticks[idx + 1] + sticks[idx + 2] > max) {\n acc = [curr, sticks[idx + 1], sticks[idx + 2]];\n max = curr + sticks[idx + 1] + sticks[idx + 2];\n }\n }\n }\n return acc;\n },\n [-1]\n );\n}", "function rightTriangle(rows){\n var triangleRows = \"\";\n var secondLoop = rows;\n // first loop: height of triangle\n for (var x = rows; x > 0; x--) {\n secondLoop--;\n // second loop: decreasing number of *s in row\n for (var y = secondLoop + 1; y >= 0; y--) {\n if (y === 0){\n triangleRows += \"\\n\";\n }\n else {\n triangleRows += \"*\";\n }\n }\n } \n return triangleRows;\n}", "function triangle(...sides) {\n if (sides.some(side => side <= 0) || sides.length > 3) return 'invalid';\n if (sides.every(side => side === sides[0])) return 'equilateral';\n let [longest, ...otherSides] = sides.sort((a, b) => b - a);\n if (otherSides.reduce((total, len) => total + len) <= longest) return 'invalid';\n return otherSides.some(side => side === longest) ? 'isosceles' : 'scalene';\n}", "function triangle(s1, s2, s3) {\n let perimeter = s1 + s2 + s3;\n let sides = [s1, s2, s3];\n let longest = Math.max(...sides);\n let shortest = Math.min(...sides);\n let mid = perimeter - longest - shortest; // ahh this is easy and smart!\n \n if (sides.includes(0) || longest >= mid + shortest) return \"invalid\";\n if (longest === shortest && shortest === mid) {\n return \"equilateral\";\n } else if (longest !== mid && mid !== shortest && longest !== shortest) {\n return \"scalene\";\n } else {\n return \"isosceles\";\n }\n}", "function maximumPathSumI(triangle) {\n // Good luck!\n // This first part just flips the triangle around for easy indexing\n // Start at the bottom and work our way up\n const triAdjusted = [];\n for (let i = triangle.length - 1; i >= 0; i--) {\n let triRow = new Array(i + 1);\n for (let n = 0; n <= i; n++) {\n triRow[n] = triangle[i][n];\n }\n triAdjusted.push(triRow);\n }\n\n // Start one row up from the bottom\n for (let i = 1; i < triAdjusted.length; i++) {\n for (let n = 0; n < triAdjusted[i].length; n++) {\n triAdjusted[i][n] += triAdjusted[i - 1][n] >= triAdjusted[i - 1][n + 1] ? triAdjusted[i - 1][n] : triAdjusted[i - 1][n + 1];\n }\n }\n // Resulting array triAdjusted has side effect of leaving breadcrumb trail\n // Should one want the path travled\n return triAdjusted.pop()[0];\n}", "function longestPath() {\n // The algorithm assigns vertices layer by layer. This is the layer currently being processed.\n // Initially set to 0 - the lowest layer\n var currentLayer = 0;\n\n // All vertices already assigned to the current layer\n var currentLayerAssignedVertices = new Set();\n\n // All vertices not assigned to any layer\n var nonAssignedVertices = new Set([...vertices]);\n\n // All vertices already assigned to a layer that is smaller (below) than the current layer\n var belowCurrentLayerAssignedVertices = new Set();\n\n while (nonAssignedVertices.size) {\n // Select a non-assigned vertex that its immedidate successors already assigned to the layer below the current one\n var v = undefined;\n nonAssignedVertices.forEach(n => {\n if (v) return;\n if (!n.outEdges.length || n.outEdges.every(e => belowCurrentLayerAssignedVertices.has(e.target))) v = n;\n });\n\n if (v) {\n v.layer = currentLayer;\n currentLayerAssignedVertices.add(v);\n nonAssignedVertices.delete(v);\n } else {\n currentLayer++;\n belowCurrentLayerAssignedVertices = new Set([...belowCurrentLayerAssignedVertices, ...currentLayerAssignedVertices]);\n currentLayerAssignedVertices.clear();\n }\n }\n }", "function downHollowTriangle(rows) {\n let string = \"\";\n for (let i = rows; i >= 1; i--) {\n for (let j = i; j < rows; j++) {\n string += \" \";\n }\n for (let k = 1; k <= (2 * i - 1); k++) {\n if (k == 1 || i == rows || k == (2 * i - 1)) {\n string += \"*\";\n }\n else {\n string += \" \";\n }\n }\n string += \"\\n\";\n }\n return string;\n}", "longestPath() {\n let longest = [];\n let currPath = [];\n function dfs(currNode) {\n if (!currNode) {\n if (currPath.length > longest.length) longest = [...currPath];\n return;\n }\n currPath.push(currNode.value);\n dfs(currNode.left);\n dfs(currNode.right);\n currPath.pop();\n }\n dfs(this);\n console.log(longest);\n }", "function triangle(side1, side2, side3) {\n let [shortest, middle, longest] = [side1, side2, side3].sort((a, b) => a - b);\n if (isValidTriangle(shortest, middle, longest)) {\n return getTriangleType(side1, side2, side3);\n } else {\n return \"invalid\";\n }\n}", "function rightTriangle(sides) {\n let hypotenuse = Math.max(...sides);\n let legs = sides.filter(side => side !== hypotenuse);\n \n return Math.pow(legs[0], 2) + Math.pow(legs[1], 2) === Math.pow(hypotenuse, 2);\n}", "get triangles() {}", "getLongestCR(){\n let size=0;\n this.triples.forEach(triple => {\n let cValue = triple.constraint.toString().length;\n let rValue = triple.shapeRef.toString().length;\n let value = cValue+rValue;\n if(value>size)size = value;\n });\n return size;\n }", "getBottomRightDiagonals() {\n\t\tlet diagonals = [];\n\n\t\tfor (var i = 0; i < this.board[0].length; i++) {\n\t\t\tlet diagonal = [this.board[0][i]];\n\n\t\t\tfor (var j = 1; j < this.board[0].length - i; j++) {\n\t\t\t\tif (this.board[j]) {\n\t\t\t\t\tdiagonal.push(this.board[j][j + i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdiagonals.push(diagonal);\n\t\t}\n\n\t\tfor (var i = 1; i < this.board[0].length; i++) {\n\t\t\tif (this.board[i]) {\n\t\t\t\tlet diagonal = [this.board[i][0]];\n\n\t\t\t\tfor (var j = i + 1; j < this.board[0].length; j++) {\n\t\t\t\t\tif (this.board[j]) {\n\t\t\t\t\t\tdiagonal.push(this.board[j][j - i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdiagonals.push(diagonal);\n\t\t\t}\n\t\t}\n\n\t\treturn diagonals;\n\t}", "function longestSubArray1(arr) {\n var min, max, length = 0;\n for (var i = 0; i < arr.length; i++) {\n min = arr[i];\n max = arr[i];\n var hash = { i: true };\n for (var j = i; j < arr.length; j++) {\n if (hash[j] === true) {\n break;\n }\n if (arr[j] < min) {\n min = arr[j];\n }\n if (arr[j] > max) {\n max = arr[j];\n }\n var diff = max - min;\n if (diff === j - i && diff + 1 > length) {\n console.log(arr.slice(i, j + 1));\n length = diff + 1;\n }\n }\n }\n return length;\n}", "function longestPlateau(data) {\n\t\tvar maxLength = 1;\n\t\tvar length = 1;\t\t\n\t\tfor (var i = 0; i < data.length - 1; ++i) {\n\t\t\tif (data[i + 1] != data[i] || (i == data.length - 2)) {\n\t\t\t\tif (length >= maxLength) {\n\t\t\t\t\tmaxLength = length;\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\t\t\t\n\t\t\t\tlength = 1;\t\t\t\n\t\t\t} else \n\t\t\t\t++length;\n\t\t}\n\n\t\treturn maxLength;\n\t}", "function getLongestCollinearDistance (listOfTriplets) {\n \n let distances = [];\n for(let i = 0; i < listOfTriplets.length; i++) {\n\tdistances.push(subDistance(listOfTriplets[i]));\n }\n \n distances.sort(function(a,b){return a[0]-b[0];});\n \n return distances[distances.length-1];\n \n}", "function greatestProductDiagonal(arr, digits) {\n return Math.max(\n greatestProductDiagonalTopLeftToRightBottom(arr, digits),\n greatestProductDiagonalBottomLeftToTopRight(arr, digits)\n );\n}", "function triangle(side1, side2, side3) {\n let sides = [side1, side2, side3];\n sides.sort((a, b) => a - b);\n\n if ( sides.includes(0) || ((sides[0] + sides[1]) > sides[2])) {\n return 'invalid';\n } else {\n switch (sides.filter(side => side === sides[1]).length) {\n case 1: // All three sides are of different lengths.\n return 'scalene';\n case 2: // Two sides are of equal length.\n return 'isosceles';\n default:\n return 'equilateral'; // All three sides are of equal length.\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the simulation to be evening
evening() { this.time.setHours(17); }
[ "function _updateSimulation() {\n\n _updateTime(balls);\n _updatePositions(balls);\n _updateInfections(balls);\n\n _drawBackground();\n\n for(var i = 0; i < balls.length; ++i) {\n _drawBall(balls[i]);\n };\n\n document.getElementById(\"current_day_badge\").innerHTML = \"Day \" + currentDay;\n\n if(0 === _numberOfInfected(balls)) {\n _finishSimulation();\n }\n}", "function dayNight()\n{\n\tnightMode = !nightMode;\n\tapplyDayNightMode(nightMode);\n}", "get isEven() {\n return this.index % 2 === 0;\n }", "function step() {\n simulation.update()\n display_simulation_state()\n }", "function simulationModeInit() {\r\n console.log(\"=======Continuing in SIMULATION MODE!!!============\");\r\n pen.simulation = 1;\r\n}", "resetSimulation()\r\n {\r\n for (var i = 0; i < this.businesses.length; i++)\r\n {\r\n this.businesses[i].resetToSimulationStart();\r\n }\r\n }", "function oddOreven(){\nfor(var i =1;i<=20;i++){\nif (i % 2==0){\n\nconsole.log(i , 'i Is Even');\n} else{\n console.log(i, 'is odd');\n}\n\n}\n}", "function beginSimulation() {\n\tsimulating = true;\n\tsimulate(true);\n\tif(changes > 0 && !stopSim) {\n \tsetTimeout(beginSimulation, 40);\n\t} else {\n\t\tsimulating = false;\n\t\tstopSim = false;\n\t}\n}", "set differentOddAndEvenPages(value) {\n this.differentOddAndEvenPagesIn = value;\n this.notifyPropertyChanged('differentOddAndEvenPages');\n }", "isEven() {\n return (this.low & 1) === 0;\n }", "function randomEven(){\n let x = Math.random()*100;\n x = x.toFixed(1);\n console.log('The random number is', x);\n for ( i=0 ; i<x; i++){\n if(i%2===0){\n console.log (i)\n }\n }\n}", "function setIsolation(val) {\n ISOLATION = val; // change ISOLATION level\n start(); // (re)start the simulation\n\n // Recolour the balls\n for (var i = 0; i < BALL_COUNT; i++){\n if (balls[i].infected) {\n d3.select(\"circle#ball\"+i.toString()).style(\"fill\", INFECTED);\n } else {\n d3.select(\"circle#ball\"+i.toString()).style(\"fill\", HEALTHY);\n }\n }\n render();\n}", "generateEvenArray() {\n for (let i = this.generateRandomNum(); i >= 0; i--) {\n if (i % 2 > 0) {\n continue;\n }\n\n this.evenArray.push(i)\n }\n }", "_resetSimulation() {\n //reset all the things\n let i = this.entities.length;\n while (i--) {\n this.entities[i].score = 0;\n this.entities[i].gameTime = 0;\n this.entities[i].entityScore = 0;\n this.entities[i].wins = 0;\n this.entities[i].kills = 0;\n }\n\n this.state = DronesSimulation.STATE_IDLE;\n }", "setSimulationSpeed(speed) {\n this.speed = speed;\n }", "function stopSimulation() {\n running = false;\n worldContainer.animate({\n opacity: \"0\"\n }, 300, function () {\n clearTimeout(reset);\n pause = true;\n });\n}", "function updateSimulation() {\r\n if (shouldSkipUpdate()) return;\r\n\r\n g_ball.update();\r\n if (doubleBall){o_ball.update();}\r\n \r\n g_paddle1.update();\r\n if (doublePaddle) {o_paddle1.update();}\r\n\r\n}", "function set_body_night_mode(night_mode) {\n let body = document.getElementsByTagName(\"body\")[0];\n if (night_mode === \"night\") {\n body.classList.add(\"night-mode\");\n body.classList.remove(\"day-mode\");\n } else {\n body.classList.remove(\"night-mode\");\n body.classList.add(\"day-mode\");\n }\n}", "setDDRand() {\n this.directDrive = Math.random() >= 0.5 ? true : false;\n this.clockMath.directDrive = this.directDrive;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the component has an ngModel controller, unregister it when the scope is destroyed.
$onDestroy () { if (this[NG_MODEL_CTRL]) { this[FORM_CONTROLLER].$unregisterControl(this); } }
[ "function deregisterScope(model, $scope) {\n\t\t\tmodel = angular.isArray(model) ? model : [model];\n\t\t\tangular.forEach(model, function (m) {\n\t\t\t\tRepositoryService.get(m.className()).deregisterModel(m, $scope);\n\t\t\t});\n\t\t}", "$onDestroy() {\n this.scope = null;\n }", "$onDestroy() {\n this.scope = null;\n this.element = null;\n }", "function deregisterModel(model, $scope) {\n\t\t\treturn this._deregScope(model, $scope);\n\t\t}", "function _deregScope(model, $scope) {\n\t\t\tvar self = this;\n\t\t\tif (this._inMem(model)) {\n\t\t\t\tvar found = -1,\n\t\t\t\t\tid = _modelId(model);\n\n\t\t\t\tangular.forEach(this.$mem[id].s, function ($s, index) {\n\t\t\t\t\tif ($scope === $s) {\n\t\t\t\t\t\tfound = index;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (found !== -1) {\n\t\t\t\t\tself.$mem[id].s.splice(found, 1);\n\t\t\t\t\tthis.$mem[id].c--;\n\t\t\t\t}\n\t\t\t\tif (this.$mem[id].c < 1) {\n\t\t\t\t\tdelete self.$mem[id];\n\t\t\t\t}\n\t\t\t}\n\t\t}", "destroy() {\n this._model = null;\n this._view?.destroy();\n }", "destroy() {\n const input = this.input.nativeElement;\n input.parentElement.removeChild(input);\n }", "dispose() {\n this.model.dispose();\n }", "function onWillDisposeModel(listener) {\n return StaticServices.modelService.get().onModelRemoved(listener);\n}", "function onWillDisposeModel(listener) {\n return standaloneServices_StaticServices.modelService.get().onModelRemoved(listener);\n}", "function hookupNgModel(ngModel, component) {\n if (ngModel && supportsNgModel(component)) {\n ngModel.$render = () => { component.writeValue(ngModel.$viewValue); };\n component.registerOnChange(ngModel.$setViewValue.bind(ngModel));\n if (typeof component.registerOnTouched === 'function') {\n component.registerOnTouched(ngModel.$setTouched.bind(ngModel));\n }\n }\n}", "function hookupNgModel(ngModel, component) {\n if (ngModel && supportsNgModel(component)) {\n ngModel.$render = () => {\n component.writeValue(ngModel.$viewValue);\n };\n component.registerOnChange(ngModel.$setViewValue.bind(ngModel));\n if (typeof component.registerOnTouched === 'function') {\n component.registerOnTouched(ngModel.$setTouched.bind(ngModel));\n }\n }\n}", "dispose() {\n this.ng1Injector.get($ROOT_SCOPE).$destroy();\n this.ng2ModuleRef.destroy();\n }", "ngOnDestroy() {\n this.modalService.remove(this.id);\n this.element.remove();\n }", "function unbindViewFromModel() {\n var model = this.data;\n var listener = this._modelBindListener;\n\n if (!listener) { return; }\n\n if (model.on) {\n model.off('load', listener);\n model.off('change', listener);\n }\n}", "onDestroy(myModel, dispatch) {\n destroy(myModel.id);\n }", "function onWillDisposeModel(listener) {\n return __WEBPACK_IMPORTED_MODULE_5__standaloneServices_js__[\"b\" /* StaticServices */].modelService.get().onModelRemoved(listener);\n}", "destroy() {\n this._input.removeEventListener('input', this._onChange)\n this._input.removeEventListener('change', this._onChange)\n this._autocomplete.destroy()\n }", "onDestroy_() {\n if (this.scope_) {\n var item = /** @type {Listenable} */ (this.scope_['item']);\n item.unlisten(GoogEventType.PROPERTYCHANGE, this.onPropertyChange_, false, this);\n\n this.scope_ = null;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for each reward save multiple shipping options
function saveShippingOption(reward, rewardID) { var shipping = $scope.campaign.rewards[$scope.campaign.rewards.indexOf(reward)].shipping; angular.forEach(shipping, function(obj) { if (obj.shipping_option_type_id == 1) { delete obj.country_id; } //for each shipping options use post/put/delete based on different situations //if the shipping id is empty but there is type id, use post to create new type if (!(parseInt(obj.shipping_option_id)) && parseInt(obj.shipping_option_type_id)) { Restangular.one('campaign', campaign_id).one('pledge-level', rewardID).one('shipping-option').customPOST(obj).then(function(success) { // assign the id in response back to the object obj.shipping_option_id = success.id; }); } // if there is shipping id but the type id is empty, delete the type else if (obj.shipping_option_id && !obj.shipping_option_type_id) { Restangular.one('campaign', campaign_id).one('pledge-level', rewardID).one('shipping-option', obj.shipping_option_id).customDELETE(); } // if there are shipping id and type id, use put to update else { Restangular.one('campaign', campaign_id).one('pledge-level', rewardID).one('shipping-option', obj.shipping_option_id).customPUT(obj); } }); $scope.rlength++; }
[ "async addReward(values) {\n\t\tconst data = {\n\t\t\trequestId: this.requestId,\n\t\t\tfavourType: values.favourType,\n\t\t\tquantity: values.quantity\n\t\t};\n\t\tawait axios.patch('/request/add-reward', data, config);\n\t}", "function multiShippingAddresses() {\n var multiShippingForm = app.getForm('multishipping');\n\n multiShippingForm.handleAction({\n save: function () {\n var cart = Cart.get();\n\n var result = Transaction.wrap(function () {\n var MergeQuantities = require('app_storefront_core/cartridge/scripts/checkout/multishipping/MergeQuantities');\n var ScriptResult = MergeQuantities.execute({\n CBasket: cart.object,\n QuantityLineItems: session.forms.multishipping.addressSelection.quantityLineItems\n });\n return ScriptResult;\n });\n\n if (result) {\n Transaction.wrap(function () {\n cart.calculate();\n });\n\n multiShippingForm.setValue('addressSelection.fulfilled', true);\n\n startShipments();\n return;\n } else {\n app.getView({\n Basket: cart.object,\n ContinueURL: URLUtils.https('COShippingMultiple-MultiShippingAddresses')\n }).render('checkout/shipping/multishipping/multishippingaddresses');\n return;\n }\n }\n });\n}", "function saveReward() {\n localStorage.rewardOption = $('.btn-reward-option label.active').text().replace(/\\s/g, \"\");\n localStorage.rewardInput = $('#rewardInput').val();\n }", "function updateShippingMethodList() {\n var i, address, applicableShippingMethods, shippingCosts, currentShippingMethod, method;\n var cart = app.getModel('Cart').get();\n var TransientAddress = app.getModel('TransientAddress');\n\n if (!cart) {\n app.getController('Cart').Show();\n return;\n }\n address = new TransientAddress();\n address.countryCode = request.httpParameterMap.countryCode.stringValue;\n address.stateCode = request.httpParameterMap.stateCode.stringValue;\n address.postalCode = request.httpParameterMap.postalCode.stringValue;\n address.city = request.httpParameterMap.city.stringValue;\n address.address1 = request.httpParameterMap.address1.stringValue;\n address.address2 = request.httpParameterMap.address2.stringValue;\n\n applicableShippingMethods = cart.getApplicableShippingMethods(address);\n shippingCosts = new HashMap();\n currentShippingMethod = cart.getDefaultShipment().getShippingMethod() || ShippingMgr.getDefaultShippingMethod();\n\n // Transaction controls are for fine tuning the performance of the data base interactions when calculating shipping methods\n Transaction.begin();\n\n for (i = 0; i < applicableShippingMethods.length; i++) {\n method = applicableShippingMethods[i];\n\n cart.updateShipmentShippingMethod(cart.getDefaultShipment().getID(), method.getID(), method, applicableShippingMethods);\n cart.calculate();\n shippingCosts.put(method.getID(), cart.preCalculateShipping(method));\n }\n\n Transaction.rollback();\n\n Transaction.wrap(function () {\n cart.updateShipmentShippingMethod(cart.getDefaultShipment().getID(), currentShippingMethod.getID(), currentShippingMethod, applicableShippingMethods);\n cart.calculate();\n });\n\n session.forms.singleshipping.shippingAddress.shippingMethodID.value = cart.getDefaultShipment().getShippingMethodID();\n\n app.getView({\n Basket: cart.object,\n ApplicableShippingMethods: applicableShippingMethods,\n ShippingCosts: shippingCosts\n }).render('checkout/shipping/shippingmethods');\n}", "function setShippingInformationAmazon() {\n setShippingInformationAction().done(\n function () {\n stepNavigator.next();\n }\n );\n }", "prepareShippingMethods() {\n\n this.apiClient.get('/rule').then(rules => {\n\n if (rules === undefined || rules === null) {\n rules = [];\n }\n\n rules.forEach(rule => {\n\n // get the all customers rule\n // so we allow our shipping methods to be used by everybody\n if (rule.attributes.name === 'All customers') {\n\n this.apiClient.get('/shipping-method').then(shippingMethods => {\n\n if (shippingMethods === undefined || shippingMethods === null) {\n return;\n throw new Error('Attention, No shippingMethods trough Shopware API');\n }\n\n shippingMethods.forEach(element => {\n\n this.apiClient.get('/shipping-method/' + element.id + '/prices').then(price => {\n\n if (price === undefined) {\n return;\n }\n\n const shippingData = {\n \"id\": element.id,\n \"active\": true,\n \"availabilityRuleId\": rule.id,\n \"prices\": [\n {\n \"id\": price.id,\n \"currencyPrice\": [\n {\n \"currencyId\": price.attributes.currencyPrice[0].currencyId,\n \"net\": 4.19,\n \"gross\": 4.99,\n \"linked\": false\n }\n ]\n }\n ],\n \"translations\": {\n \"de-DE\": {\n \"trackingUrl\": \"https://www.carrier.com/de/tracking/%s\"\n },\n \"en-GB\": {\n \"trackingUrl\": \"https://www.carrier.com/en/tracking/%s\"\n }\n }\n };\n\n this.apiClient.patch('/shipping-method/' + element.id, shippingData);\n });\n });\n });\n }\n });\n });\n }", "showSavedData() {\n if (this.checkoutData.deliveryMode && !this.addressChanged) {\n checkoutEventBus.$emit('show-saved-mode');\n // this.selectedShippingMethod.deliveryDetails = data.deliveryDetails;\n this.selectedShippingMethod.instructions = this.checkoutData.deliveryMode.description;\n const savedData = this.deliveryMethods.filter(method => method.value === this.checkoutData.deliveryMode.code);\n if (savedData.length) {\n this.setData(savedData[0]);\n } else {\n this.selectedShippingMethod.name = this.checkoutData.deliveryMode.name;\n this.selectedShippingMethod.cost = this.checkoutData.deliveryMode.deliveryCost.formattedValue;\n }\n } else {\n checkoutEventBus.$emit('show-edit-mode');\n }\n }", "buildPaymentRequest(cart) {\n // Supported payment instruments\n const supportedInstruments = [{\n supportedMethods: ['basic-card'],\n data: {\n supportedNetworks: PAYMENT_METHODS\n }\n }];\n\n // Payment options\n const paymentOptions = {\n\n // TODO PAY-5 - add payment options\n\n };\n\n let shippingOptions = [];\n let selectedOption = null;\n\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n\n // TODO PAY-2 - initialize the PaymentRequest object\n\n // When user selects a shipping address, add shipping options to match\n request.addEventListener('shippingaddresschange', e => {\n e.updateWith((_ => {\n // Get the shipping options and select the least expensive\n shippingOptions = this.optionsForCountry(request.shippingAddress.country);\n selectedOption = shippingOptions[0].id;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n })());\n });\n\n // When user selects a shipping option, update cost, etc. to match\n request.addEventListener('shippingoptionchange', e => {\n e.updateWith((_ => {\n selectedOption = request.shippingOption;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n })());\n });\n\n return request;\n }", "send() {\n //add to shipment\n \n var sampleIDQuery = \"\";\n var numberSamplesQuery = \"\";\n\n for (var i = 0; i < this.state.samplesadded.length; i++) {\n sampleIDQuery = sampleIDQuery + \"id\" + (i + 1) + \"=\" + this.state.samplesadded[i][\"key_internal\"];\n\n numberSamplesQuery = numberSamplesQuery + \"num\" + (i + 1) + \"=\" + this.state.samplesadded[i][\"aliquots\"];\n\n if (i < (this.state.samplesadded.length - 1)) {\n sampleIDQuery = sampleIDQuery + \"&\";\n numberSamplesQuery = numberSamplesQuery + \"&\"; \n }\n }\n\t\t\n var getQuery =\n \"date=\" + this.getDateFormat(this.state.date) + \"&\" +\n //TODO: make from location specific to user\n \"from=University at Buffalo&\" + \n \"to=\" + this.state.to + \"&\" + \n \"samples=\" + this.state.samplesadded.length + \"&\" + \n \"shipping_conditions=\" + this.state.shippingconditions + \"&\" +\n\t\t\t\"other_shipping_conditions=\" + this.state.othershippingconditions + \"&\" + \n\t\t\t\"notes=\" + this.state.notes + \"&\" +\n\t\t\t sampleIDQuery + \"&\" + \n numberSamplesQuery;\n\t\t\t //TODO: Add other queries to either shipment_batch table, or\n //shipment_tubes table (whichever makes sense)\n\t\t\n\t\tvar sendReq;\n\t\tvar getReq = \"https://cse.buffalo.edu/eehuruguayresearch/app/scripts/addshipment.php?\" + getQuery;\n\t\tsendReq = new XMLHttpRequest();\n\t\tsendReq.open(\n\t\t \"GET\",\n\t\t getReq,\n\t\t\ttrue\n\t );\n\t\tsendReq.onload = function (e) {\n\t\t if (sendReq.readyState === 4 && sendReq.status === 200) {\n\t\t\t } else {\n \t this.setState({\n \t\t alertVariant: 'danger',\n \t\t alertText: \"There was an error connecting to the database: \" + sendReq.statusText,\n \t\t alertVisibility: true,\n \t });\n\t\t\t }\n\t\t }.bind(this);\n\n\t\tsendReq.send();\n\t}", "function saveArrivedShipment(obj) {\n if (tempArrivalDate == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter Arrival Date and Save Flight details.\");\n return;\n }\n\n if (tempATA == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter ATA and save flight details.\");\n return;\n }\n\n if (userContext.TerminalSNo == '0') {\n ShowMessage('warning', 'Warning', \"Terminal not assign for current user.\");\n return;\n }\n\n var dflightSNo = $(obj).closest(\"tr\").find(\"td[data-column='DailyFlightSNo']\").text();\n var GroupflightSNo = $(obj).closest(\"tr\").find(\"td[data-column='GroupFlightSNo']\").text();\n var fFlightMasterSNo = $(obj).closest(\"tr\").find(\"td[data-column='FFMFlightMasterSNo']\").text();\n var uNo = $(obj).closest(\"tr\").find(\"td[data-column='ULDNo']\").text();\n var ffmShipmentTrans1 = $(obj).closest(\"tr\").find(\"td[data-column='FFMShipmentTransSNo']\").text();\n var arrivedShipmentSNo = $(obj).closest(\"tr\").find(\"td[data-column='ArrivedShipmentSNo']\").text();\n var awbNo = $(obj).closest(\"tr\").find(\"td[data-column='AWBNo']\").text();\n var origin = $(obj).closest(\"tr\").find(\"td[data-column='ShipmentOriginAirportCode']\").text();\n var destination = $(obj).closest(\"tr\").find(\"td[data-column='ShipmentDestinationAirportCode']\").text();\n var commodity = $(obj).closest(\"tr\").find(\"td[data-column='NatureOfGoods']\").text();\n var shc = $(obj).closest(\"tr\").find(\"td[data-column='SPHC']\").text();\n var awbPieces = $(obj).closest(\"tr\").find(\"td[data-column='Pieces']\").text();\n var buildDetails = $(obj).closest(\"tr\").find(\"td[data-column='LoadDetails']\").text();\n var recvdPieces = $(obj).closest(\"tr\").find(\"#txtFAMAWBRcdPieces\").val();\n var recvVolumeweight = $(obj).closest(\"tr\").find(\"#txtVolumeWeight\").val();\n var grossWT = $(obj).closest(\"tr\").find(\"#txtGrossWt\").val();\n var volumeWT = $(obj).closest(\"tr\").find(\"#txtVolumeWeight\").val();\n var piecesGWT = $(obj).closest(\"tr\").find(\"#txtActualGrossWt\").val()\n var volumeGWT = $(obj).closest(\"tr\").find(\"#txtVolumeWeight\").val();\n var remarks = $(obj).closest(\"tr\").find(\"#txtFAMAWBRemarks\").val();\n var PosNo = $(obj).closest(\"tr\").find(('#txtPosNo_\"' + awbNo).replace(/[\"\"]/g, '')).val()\n var CCADetailsCheck = true;\n var Isrushhandling = $(obj).closest(\"tr\").find(\"input[type='checkbox'][id='chkIsRushHandling']:checked\").length;\n POMailSNo = parseInt($(obj).closest(\"tr\").find(\"td[data-column='POMailSNo']\").text());\n var POMArrivedShipmentSNo = $(obj).closest(\"tr\").find(\"td[data-column='POMArrivedShipmentSNo']\").text();//Added by akaram on 21 Aug 2017\n var shdesc = $(obj).closest(\"tr\").find(\"td[data-column='LoadDetails']\").text();\n var RevisedPcs = 0;\n var RevisedWt = 0.00;\n var RevisedVolWt = 0.00;\n var aviShpCount = 0;\n var arrivedPcs = 0;\n var ArrivedWt = 0.00;\n var ArrivedVolWt = 0.00;\n var retULDVal = confirm(\"Are you sure, you want to arrive this ?\");\n if (retULDVal == false) {\n return\n }\n\n cfi.SaveUpdateLockedProcess(\"0\", GroupflightSNo, \"\", \"\", userContext.UserSNo, \"0\", \"Inbound Flight\", 0, \"\");\n $.ajax({\n url: \"Services/Import/InboundFlightService.svc/GetCCADetails\", async: false, type: \"POST\", dataType: \"json\", cache: false,\n data: JSON.stringify({ AwbNo: awbNo, DailyFlightSNo: currentDailyFlightSno }),\n contentType: \"application/json; charset=utf-8\",\n success: function (result) {\n var Data = jQuery.parseJSON(result);\n var resData = Data.Table0;\n var resData1 = Data.Table1;\n if (resData.length > 0) {\n var resItem = resData[0];\n RevisedPcs = resItem.RevisedPcs;\n RevisedWt = resItem.RevisedWt;\n RevisedVolWt = resItem.ReviseVolWt;\n aviShpCount = resData1[0].aviShpCount;\n arrivedPcs = resData1[0].arrivedPcs;\n ArrivedWt = resData1[0].ArrivedWt;\n ArrivedVolWt = resData1[0].ArrivedVolWt;\n //var CCADetails = confirm(\"CCA raised for: \" + awbNo + \", Pieces: \" + resItem.RevisedPcs + \", Weight: \" + resItem.RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n //if (CCADetails == true && recvdPieces <= RevisedPcs && grossWT <= RevisedWt) {\n // CCADetailsCheck = false;\n // return\n //}\n\n if (userContext.SysSetting.ClientEnvironment.toUpperCase() == \"GA\") {\n if (recvdPieces <= RevisedPcs && grossWT <= RevisedWt) {\n CCADetailsCheck = false;\n }\n }\n\n //if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(RevisedWt) || parseFloat(volumeGWT) < parseFloat(RevisedVolWt)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n //}\n }\n },\n });\n\n if (!CCADetailsCheck) {\n $(obj).closest(\"tr\").find(\"#txtFAMAWBRcdPieces\").focus();\n }\n\n if (shdesc == 'T' && CCADetailsCheck == false) {\n\n }\n\n if (userContext.SysSetting.ClientEnvironment.toUpperCase() == \"GA\") {\n if (shdesc == 'T' && CCADetailsCheck == false) {\n if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(RevisedWt) || parseFloat(volumeGWT) < parseFloat(RevisedVolWt)) {\n ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n return;\n }\n }\n else if (shdesc == 'T' && CCADetailsCheck == true) {\n if (parseInt(awbPieces) < parseInt(recvdPieces) || parseFloat(grossWT) < parseFloat(piecesGWT) || parseFloat(volumeGWT) < parseFloat(volumeGWT)) {\n ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + recvdPieces + \", Weight: \" + piecesGWT + \", Volume Weight: \" + volumeGWT);\n return;\n }\n }\n //if ((shdesc == 'T' || shdesc == 'S') && CCADetailsCheck == false) {\n // if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(RevisedWt) || parseFloat(volumeGWT) < parseFloat(RevisedVolWt)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n // }\n //}\n //else if ((shdesc == 'P' || shdesc == 'D') && CCADetailsCheck == false) {\n // if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(RevisedWt) || parseFloat(volumeGWT) < parseFloat(RevisedVolWt)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n // }\n //}\n //else if ((shdesc == 'T' || shdesc == 'S') && CCADetailsCheck == true) {\n // if (parseInt(awbPieces) < parseInt(recvdPieces) || parseFloat(grossWT) < parseFloat(piecesGWT) || parseFloat(volumeGWT) < parseFloat(volumeGWT)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + recvdPieces + \", Weight: \" + piecesGWT + \", Volume Weight: \" + volumeGWT);\n // return;\n // }\n //}\n //else if ((shdesc == 'P' || shdesc == 'D') && CCADetailsCheck == true) {\n // if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(grossWT) || parseFloat(volumeGWT) < parseFloat(volumeWT)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + recvdPieces + \", Weight: \" + piecesGWT + \", Volume Weight: \" + volumeGWT);\n // return;\n // }\n //}\n\n }\n //if (shdesc == 'T' && CCADetailsCheck == false) {\n // if (parseInt(recvdPieces) < parseInt(RevisedPcs) || parseFloat(piecesGWT) < parseFloat(RevisedWt) || parseFloat(volumeGWT) < parseFloat(RevisedVolWt)) {\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n // }\n //}\n\n //if (shdesc != 'T' && aviShpCount == \"1\" && (parseFloat(recvdPieces) + parseFloat(arrivedPcs)) < parseFloat(RevisedPcs)) {\n // $(obj).closest(\"tr\").find(\"#txtFAMAWBRcdPieces\").focus();\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n //}\n\n\n //if (shdesc != 'T' && aviShpCount == \"1\" && (parseFloat(piecesGWT) + parseFloat(ArrivedWt)) < parseFloat(RevisedWt) && (parseFloat(volumeGWT) + parseFloat(ArrivedVolWt)) < parseFloat(RevisedVolWt)) {\n // $(obj).closest(\"tr\").find(\"#txtFAMAWBRcdPieces\").focus();\n // ShowMessage(\"warning\", \"Warning\", \"CCA raised for: \" + awbNo + \", Pieces: \" + RevisedPcs + \", Weight: \" + RevisedWt + \", Volume Weight: \" + RevisedVolWt);\n // return;\n //}\n\n if (recvdPieces == \"\")\n ShowMessage('warning', 'Warning', \"Received pieces can not be left blank.\");\n else if (recvVolumeweight == \"\")\n ShowMessage('warning', 'Warning', \"Volume can not be left blank.\");\n else {\n var ULDDetails = [];\n var uldData = {\n DailyFlightSNo: dflightSNo, FFMFlightMasterSNo: fFlightMasterSNo, FFMShipmentTransSNo: ffmShipmentTrans1, ULDNo: uNo, AWBNo: awbNo, Origin: origin, Destination: destination, Commodity: commodity, SHC: '1', AWBPieces: awbPieces, BuildDetails: buildDetails, FFM: '', RecvdPieces: recvdPieces, GrossWT: piecesGWT, Remarks: remarks, PosNo: PosNo, IsRushHandling: Isrushhandling, VolumeWeight: volumeWT\n }\n\n ULDDetails.push(uldData);\n $.ajax({\n url: \"Services/Import/InboundFlightService.svc/SaveULDDetails\", async: false, type: \"POST\", dataType: \"json\", cache: false,\n data: JSON.stringify({ UldData: ULDDetails, ArrivedShipmentSNo: (arrivedShipmentSNo == \"\") ? 0 : arrivedShipmentSNo, POMailDetailsArray: POMailDetailsArray, POMailSNo: POMailSNo, POMArrivedShipmentSNo: POMArrivedShipmentSNo }),\n contentType: \"application/json; charset=utf-8\",\n success: function (result) {\n var resultData = result.split(\",\")\n if (resultData[0] == \"0\") {\n $(obj).closest(\"tr\").find(\"td[data-column='ArrivedShipmentSNo']\").text(resultData[1]);\n $(obj).attr(\"value\", \"Arrived\");\n $(obj).attr(\"class\", \"btn btn-block btn-success btn-sm\");\n $(obj).prop('disabled', true); /// After Save Arrive Button shows as Disabled\n $('#selector').css('cursor', 'not-allowed') ///// After Save Arrive Button cursor\n $(\"#ATA\").prop('disabled', true);\n $(\"#ATA\").css(\"cursor\", \"not-allowed\");\n $(\"#ArrivalDate\").data(\"kendoDatePicker\").enable(false);\n $(\"#ArrivalDate\").css(\"cursor\", \"not-allowed\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='L']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='D']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='C']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"tr\").find(\"input[type='button'][value='E']\").prop('disabled', true).css(\"cursor\", \"not-allowed\").attr('class', '');\n if ($(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='checkbox'][id='chkThroughULD']\").length > 0) {\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='checkbox'][id='chkThroughULD']\").closest(\"td[data-column='IsThroughULD']\").text(\"No\");\n }\n\n if (userContext.SpecialRights.IMPORTSHIP == true) {\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamended']\").html('');\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamended']\").append(\"<input id='Chkamended' type='checkbox' />\");\n }\n\n if ($((obj.parentElement.parentNode)).find(\"td[data-column='Isamendedvalue']\").text() == \"0\") {\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamendedvalue']\").text('1');\n }\n\n if (resultData[2] == \"True\") {\n $(\"#AddShipment\").prop('disabled', true);\n }\n else {\n $(\"#AddShipment\").removeAttr(\"disabled\");\n }\n ShowMessage('success', 'Success', \"Details Saved Successfully\");\n\n var rushcheckedval = $(obj).closest(\"table\").closest(\"tr\").find(\"input[type='checkbox'][id='chkIsRushHandling']\").is(\":checked\");\n if (rushcheckedval) {\n if (userContext.SysSetting.ClientEnvironment.toUpperCase() == \"GA\") {\n $(obj).closest(\"table\").closest(\"tr\").find(\"input[type='checkbox'][id='chkIsRushHandling']\").prop('disabled', true);\n }\n }\n var rushawbsno = $(obj).closest(\"tr\").find(\"td[data-column='AWBSNo']\").text();\n var rushlloopawbso = \"\";\n $(obj.parentElement.parentNode).closest(\"table\").closest(\"tr\").closest(\"tbody\").closest(\"table\").closest(\"tr\").find(\"input[type='checkbox'][id='chkIsRushHandling']\").each(function (i, row) {\n rushlloopawbso = $(row).closest(\"tr\").find(\"td[data-column='AWBSNo']\").text();\n });\n }\n else if (resultData[0] == \"1\") {\n ShowMessage('warning', 'Warning', resultData[1]);\n return;\n }\n else if (resultData[0] == \"500\") {\n ShowMessage('warning', 'Warning', resultData[1]);\n return;\n }\n else if (resultData[0] == \"100\") {\n ShowMessage('warning', 'Warning', 'ULD Stock does not exist. Can not proceed with arrival.');\n return;\n }\n else\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n },\n error: function () {\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n }\n });\n IsAllShipmentArrived();\n }\n}", "static saveReward(load) {\n return axios.post(url+'savereward/', {load})\n }", "function handleShippingMethodSaveClicked(event) {\n // Delete unnecessary fields in model.\n delete methodModel.deliveryType;\n delete methodModel.parcelDestination;\n delete methodModel.parcelOrigin;\n delete methodModel.selected;\n delete methodModel.logoUrl;\n delete methodModel.title;\n\n if (isShippingMethodValid()) {\n utilityService.showSpinner();\n\n if (methodModel.pricePolicy === PRICING_POLICY_PACKLINK) {\n delete methodModel.fixedPriceByWeightPolicy;\n delete methodModel.fixedPriceByValuePolicy;\n delete methodModel.percentPricePolicy;\n } else if (methodModel.pricePolicy === PRICING_POLICY_PERCENT) {\n delete methodModel.fixedPriceByWeightPolicy;\n delete methodModel.fixedPriceByValuePolicy;\n } else if (methodModel.pricePolicy === PRICING_POLICY_FIXED_BY_VALUE) {\n delete methodModel.percentPricePolicy;\n delete methodModel.fixedPriceByWeightPolicy;\n } else {\n delete methodModel.percentPricePolicy;\n delete methodModel.fixedPriceByValuePolicy;\n }\n\n if (configuration.hasTaxConfiguration) {\n methodModel.taxClass = templateService.getComponent('pl-tax-selector', extensionPoint).value;\n }\n\n if (configuration.hasCountryConfiguration) {\n methodModel.isShipToAllCountries = countrySelector.isShipToAllCountries;\n\n if (!methodModel.isShipToAllCountries) {\n methodModel.shippingCountries = countrySelector.shippingCountries;\n } else {\n methodModel.shippingCountries = [];\n }\n\n countrySelector = {};\n }\n\n ajaxService.post(\n configuration.saveUrl,\n methodModel,\n function (response) {\n shippingMethods[response.id] = response;\n utilityService.showFlashMessage(Packlink.successMsgs.shippingMethodSaved, 'success');\n closeConfigForm();\n renderShippingMethods();\n if (shouldGetShopShippingMethodCount()) {\n getShopShippingMethodCount();\n } else {\n utilityService.hideSpinner();\n }\n },\n function (response) {\n if (response.message) {\n utilityService.showFlashMessage(response.message, 'danger');\n }\n\n utilityService.hideSpinner();\n }\n );\n }\n }", "function createShipment(destId) {\n\n var newShipment = {\n type: \"shipment\",\n _id: \"S8\",\n status: \"pending\",\n service: \"express\",\n desc: \"Rain gear\",\n distribution: \"D2\",\n retail: destId,\n curLoc : \"Cincinnati, Ohio, US\",\n curLat : 39.1045,\n curLon : -84.4958,\n estDel : \"Thu, 31 Oct 2015\",\n lastUpdate : \"Thu, 30 Oct 2015 12:15:37 GMT\",\n items : [\n {\n \"item\" : \"I7\",\n \"quantity\" : 75\n },\n {\n \"item\" : \"I8\",\n \"quantity\" : 120\n }\n ]\n };\n\n // Create new shipment in DB\n $.post(\"/api/v1/db/shipments\", newShipment,\n function(data, status){\n console.log(data)\n // Send a notification to manager and remove prediction from list\n if (status === \"success\") {\n remindManager(data.id, \"Jack Cracker\");\n removeShipment(destId + \"-prediction\", \"prediction-list\");\n }\n });\n}", "function getShipping() {\n inquirer.prompt([\n {\n type:\"input\",\n name:\"users-name\",\n message:\"What is your full name?\",\n validate: function(value) {\n if (value == \"\") {\n return \"Please enter your full name\"\n\n } else {\n return true\n }\n }\n },\n {\n type:\"input\",\n name:\"street-address\",\n message:\"What is your street address?\",\n validate: function(value) {\n if (value == \"\") {\n return \"Please enter your street address\"\n\n } else {\n return true\n }\n }\n },\n {\n type:\"input\",\n name:\"city\",\n message:\"What city do you live in?\",\n validate: function(value) {\n if (value == \"\") {\n return \"Please enter your city\"\n\n } else {\n return true\n }\n }\n },\n {\n type:\"input\",\n name:\"state\",\n message:\"What state do you live in? (initials)\",\n validate: function(value) {\n if (value == \"\") {\n return \"Please enter your state (initial)\"\n\n } else {\n return true\n }\n }\n },\n {\n type:\"input\",\n name:\"zip\",\n message:\"Please enter your zip code\",\n validate: function(value) {\n if (value == \"\") {\n return \"Please enter your zip code\"\n\n } else {\n return true\n }\n }\n },\n {\n type:\"list\",\n name:\"shipping\",\n message:\"Please select a shipping option: Overnight = $100, 2-3 days = $30, 5-6 days = $15\",\n choices:[100, 30, 15],\n }\n ]).then(function(response){\n let name = response[\"users-name\"];\n let street = response[\"street-address\"];\n let city = response.city;\n let state = response.state;\n let zip = response.zip;\n let shipping = response.shipping;\n shoppingCartTotal.push(shipping);\n\n let shippingAddress = [\n \"---------------------\\n\",\n name,\n street,\n city + \", \" + state + \" \" + zip,\n \"---------------------\\n\"\n ].join(\"\\n\\n\")\n\n console.log(chalk.magenta(\"\\n============================================\\n\"))\n console.log(\"\\n\" + chalk.blue.bold(\"Thanks for shopping with us!\") + \"\\n\")\n console.log(\"Today you purchased: \" + chalk.yellow.bold(shoppingCart));\n console.log(\"The total for these purchases with shipping: \" + chalk.green.bold.underline(shoppingCartTotal.reduce(addEmUp)));\n console.log(chalk.cyan(\"Shipping to: \\n\") + chalk.magenta(shippingAddress));\n console.log(\"\\n\" + chalk.blue.bold(\"Come back soon!\"));\n console.log(chalk.magenta(\"\\n============================================\\n\"))\n connection.end();\n\n })\n}", "async function addRewards(rewards) {\n for (var i=0; i<rewards.length; i++) {\n var reward = rewards[i];\n var rewardId = await addReward(reward, i);\n if (reward.ownerId) {\n await performPurchase(reward, rewardId);\n }\n }\n}", "buildPaymentDetails(cart, shippingOptions, shippingOptionId) {\n\n let displayItems = cart.items.map(item => {\n return {\n label: item.title,\n amount: { currency: 'USD', value: String(item.price * item.quantity) }\n }\n })\n\n let total = cart.total;\n\n // TODO PAY-7.3 - allow shipping options\n let displayedShippingOptions = [];\n if (shippingOptions.length > 0) {\n let selectedOption = shippingOptions.find(option => {\n return option.id === shippingOptionId;\n });\n displayedShippingOptions = shippingOptions.map(option => {\n return {\n id: option.id,\n label: option.label,\n amount: { currency: 'USD', value: String(option.price) },\n selected: option.id === shippingOptionId\n };\n });\n if (selectedOption) {\n total += selectedOption.price;\n }\n }\n\n let details = {\n displayItems: displayItems,\n total: {\n label: 'Total due',\n amount: { currency: 'USD', value: String(total) }\n },\n // TODO PAY-7.2 - allow shipping options\n shippingOptions: displayedShippingOptions\n };\n\n return details;\n }", "function updateSaveData() {\n if (currentMode == \"event\") {\n let saveData = missionData.Completed.Remaining.map(m => m.Id).join(',');\n setLocal(\"event\", \"Completed\", saveData);\n setLocal(\"event\", \"Id\", EVENT_ID);\n setLocal(\"event\", \"Version\", EVENT_VERSION);\n } else {\n \n // Motherland\n let curRankCompletedIds = missionData.Completed.Remaining.map(m => m.Id);\n let saveData = [...curRankCompletedIds, ...missionData.OtherRankMissionIds].join(',');\n setLocal(\"main\", \"Completed\", saveData);\n }\n \n setLocal(currentMode, \"CompletionTimes\", JSON.stringify(missionCompletionTimes));\n}", "function insertShippingRate() {\n\n nlapiSelectNewLineItem('item');\n\n /* important so that you know that the script was called from insertShippingRate() */ \n\n nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', true);\n nlapiSetCurrentLineItemText('item', 'item', 'Shipping');\n}", "function updateSaveData() {\n if (currentMode == \"event\") {\n let saveData = missionData.Completed.Remaining.map(m => m.Id).join(',');\n setLocal(\"event\", \"Completed\", saveData);\n } else {\n \n // Motherland\n let curRankCompletedIds = missionData.Completed.Remaining.map(m => m.Id);\n let saveData = [...curRankCompletedIds, ...missionData.OtherRankMissionIds].join(',');\n setLocal(\"main\", \"Completed\", saveData);\n }\n \n setLocal(currentMode, \"CompletionTimes\", JSON.stringify(missionCompletionTimes));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given Array of alternate Ext namespaces builds list of patterns for detecting Ext.define: ["Ext","Foo"] > ["Ext.define", "Ext.ClassManager.create", "Foo.define", "Foo.ClassManager.create"]
function build_ext_define_patterns(namespaces) { var mappedNamespaced = _.map(namespaces, function(ns) { [ns + ".define", ns + ".ClassManager.create"] }); return _.flatten(mappedNamespaced); }
[ "function detect_ext_define(cls, ast) {\n // defaults\n cls[\"extends\"] = \"Ext.Base\";\n cls[\"requires\"] = [];\n cls[\"uses\"] = [];\n cls[\"alternateClassNames\"] = [];\n cls[\"mixins\"] = [];\n cls[\"aliases\"] = [];\n cls[\"members\"] = [];\n cls[\"code_type\"] = \"ext_define\";\n \n each_pair_in_object_expression(ast[\"arguments\"][1], function(key, value, pair) {\n switch (key) {\n case \"extend\":\n cls[\"extends\"] = make_string(value);\n break;\n case \"override\":\n cls[\"override\"] = make_string(value);\n break;\n case \"requires\":\n cls[\"requires\"] = make_string_list(value);\n break;\n case \"uses\":\n cls[\"uses\"] = make_string_list(value);\n break;\n case \"alternateClassName\":\n cls[\"alternateClassNames\"] = make_string_list(value);\n break;\n case \"mixins\":\n cls[\"mixins\"] = make_mixins(value);\n break;\n case \"singleton\":\n cls[\"singleton\"] = make_singleton(value);\n break;\n case \"alias\":\n cls[\"aliases\"] += make_string_list(value);\n break;\n case \"see\":\n cls[\"see\"] += make_string_list(value);\n break;\n case \"xtype\":\n cls[\"aliases\"] += _.map(make_string_list(value), function(xtype) { return \"widget.\"+xtype });\n break;\n case \"config\":\n cls[\"members\"] += make_configs(value, {\"accessor\": true});\n break;\n case \"cachedConfig\":\n cls[\"members\"] += make_configs(value, {\"accessor\": true});\n break;\n case \"eventedConfig\":\n cls[\"members\"] += make_configs(value, {\"accessor\": true, \"evented\": true});\n break;\n case \"statics\":\n cls[\"members\"] += make_statics(value);\n break;\n case \"inheritableStatics\":\n cls[\"members\"] += make_statics(value, {\"inheritable\": true});\n break;\n default:\n detect_method_or_property(cls, key, value, pair);\n break;\n }\n });\n}", "function getExtraDefines(className) {\n\n className = className.replace(/\\./g, '_');\n if (!(className in classConfigs)) {\n throw new Error('invalid class name: ' + className);\n }\n\n const relativePath = classConfigs[className].relativePath;\n\n const shared = [];\n Object.keys(classConfigs).forEach(function(key) {\n if (key[0] === '_') {\n return; // continue\n }\n const config = classConfigs[key];\n if (config.relativePath === relativePath && key !== className) {\n shared.push(key);\n }\n });\n if (shared.length > 0) {\n console.log('extra defines found: ' + shared);\n }\n return shared;\n}", "function documentedClassnames(sources) {\n const classes = []\n const files = sources.reduce((acc, pattern) => {\n return acc.concat(glob.sync(pattern))\n }, [])\n\n files.forEach(file => {\n let match = null\n const content = fs.readFileSync(file, \"utf8\")\n\n classPatterns.forEach(pattern => {\n // match each pattern against the source\n while (match = pattern.exec(content)) {\n // get the matched classnames and split by whitespace into classes\n const klasses = match[1].trim().split(/\\s+/)\n classes.push(...klasses)\n }\n })\n })\n\n // return only the unique classnames\n return Array.from(new Set(classes))\n}", "function getAngularModuleNames(list) {\n var paths = [];\n list.forEach(function (item) {\n paths.push('app.' + item);\n });\n return paths;\n }", "async dependencyNamespaces() {\n\n let dependencyList = await this.dependencyList();\n\n let prefixes = dependencyList.map( dependency => dependency.referenceQName.split(\":\")[0] );\n let prefixSet = new Set(prefixes);\n\n // Make sure structures is in the dependency list\n prefixSet.add(\"structures\");\n\n /** @type {Namespace[]} */\n let namespaces = [];\n\n for (let prefix of prefixSet) {\n let namespace = await this.release.namespaces.get(prefix);\n namespaces.push(namespace);\n }\n\n return namespaces;\n\n }", "function helperFullyQualifiedNames(type) {\n var names = [\n \"io/qt/qbs/Artifact\",\n \"io/qt/qbs/ArtifactListJsonWriter\",\n \"io/qt/qbs/ArtifactListWriter\",\n \"io/qt/qbs/tools/JavaCompilerScannerTool\",\n \"io/qt/qbs/tools/utils/JavaCompilerOptions\",\n \"io/qt/qbs/tools/utils/JavaCompilerScanner\",\n \"io/qt/qbs/tools/utils/JavaCompilerScanner$1\",\n \"io/qt/qbs/tools/utils/NullFileObject\",\n \"io/qt/qbs/tools/utils/NullFileObject$1\",\n \"io/qt/qbs/tools/utils/NullFileObject$2\",\n ];\n if (type === \"java\") {\n return names.filter(function (name) {\n return !name.contains(\"$\");\n });\n } else if (type === \"class\") {\n return names;\n }\n}", "function scanSearchDefinitions (source, regexs, grunt)\n{\n var regexType = \"array\";\n var regexs_ = regexs;\n \n if (Object.prototype.toString.call(regexs) === \"[object Object]\")\n {\n regexs = [0];\n regexType = \"object\";\n }\n\n var contents = source;\n\n for (var i = 0; i < regexs.length; i++)\n {\n var regex = regexs[i];\n \n if (regexType !== \"array\")\n {\n regex = regexs_;\n }\n\n contents = contents.replace(regexps.all, function (match, definition, value)\n {\n definitions[definition] = value;\n grunt.verbose.write(\"Found \" + \"#define\".cyan + \" tag, setting \" + definition.cyan + \" to \" + value.cyan + \"\\n\");\n return \"\";\n });\n }\n\n return contents;\n}", "function getPossibleNames(baseName) {\n return [\n baseName,\n baseName.replace('.js', '.jsx'),\n baseName.replace('.js', '/index.js'),\n baseName.replace('.js', '/index.jsx'),\n ];\n}", "function extensionsPattern(extensions) {\n return new RegExp(`(${extensions.map(e => `${e.replace('.', '\\\\.')}`).join('|')})$`, 'i');\n}", "function parseDependencies(code) {\n\tvar ret = [];\n \n\tcode.replace(SLASH_RE, \"\")\n\t .replace(REQUIRE_RE, function(m, m1, m2) {\n\t\tif (m2) {\n\t\t ret.push(m2)\n\t\t}\n\t });\n\t \n\tret = ret.unique();\n\t \n\tvar reg = /define\\s*\\(\\s*[\"']([^\"']+)/g, result, index;\n\twhile ((result = reg.exec(code)) != null) {\n\t\tindex = ret.indexOf(result[1]);\n\t\tif(index > -1)\n\t\t\tret.splice(index, 1);\n\t}\n\t\n return ret\n}", "function getApplicationDefines() {\n var defines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n var count = 0;\n var sourceText = '';\n for (var define in defines) {\n if (count === 0) {\n sourceText += '\\n// APPLICATION DEFINES\\n';\n }\n count++;\n sourceText += '#define ' + define.toUpperCase() + ' ' + defines[define] + '\\n';\n }\n if (count === 0) {\n sourceText += '\\n';\n }\n return sourceText;\n}", "function scanReplaceDefinitions (source, regexs, grunt)\n{\n var regexType = \"array\";\n var regexs_ = regexs;\n \n if (Object.prototype.toString.call(regexs) === \"[object Object]\")\n {\n regexs = [0];\n regexType = \"object\";\n }\n\n var contents = source;\n\n for (var i = 0; i < regexs.length; i++)\n {\n var regex = regexs[i];\n \n if (regexType !== \"array\")\n {\n regex = regexs_;\n }\n\n for (var prop in definitions)\n {\n var amt = 0;\n contents = contents.replace(new RegExp('([ \\\\+\\\\-\\\\*\\\\!\\\\|\\\\[\\\\]\\\\\\'\\\\\"\\\\>\\\\<\\\\=\\\\(\\\\)\\n\\t])(' + prop + ')([\\\\\\'\\\\[\\\\]\\\\+\\\\-\\\\(\\\\) \\\\=\\\\*\\\\&\\\\>\\\\<\\\\{\\\\}\\n \\t\\!])', 'gi'), function (match, pre, include, post) {\n amt++;\n if(typeof(definitions[prop]) === 'string')\n return pre + '\"'+definitions[prop]+'\"' + post;\n else\n return pre + definitions[prop] + post;\n });\n grunt.verbose.write(\"Replaced definition \" + prop.cyan + \" with \" + definitions[prop].cyan + \" \" + amt.toString().yellow + \" time(s)..\\n\");\n }\n }\n\n return contents;\n}", "function ExpandDefines(str, defines, invariants)\n{\n\tfor(var name in defines) {\n\t\tvar res\n\t\tvar define = defines[name]\n\t\tvar name_re = new RegExp(define.name_restr, \"g\")\n\t\twhile(res = name_re.exec(str))\n\t\t{\n\t\t\tvar end\n\t\t\tif(define.args_restr)\n\t\t\t{\n\t\t\t\tvar args = GetArgs(str, res.index)\n\t\t\t\tif(define.type === \"define\")\n\t\t\t\t{\n\t\t\t\t\tvar repl = define.body.replace(define.re_args,\n\t\t\t\t\t\tfunction (entire_match, notweld_hash, stringize_hash, matched_arg) {\n\t\t\t\t\t\t\tvar ret = \"\"\n\t\t\t\t\t\t\tif(stringize_hash === \"#\") {\n\t\t\t\t\t\t\t\tif(notweld_hash !== undefined) {\n\t\t\t\t\t\t\t\t\t// This isn't part of the actual part we \n\t\t\t\t\t\t\t\t\t// want to replace, so stick it back in \n\t\t\t\t\t\t\t\t\t// the result.\n\t\t\t\t\t\t\t\t\t// This was captured in the regex so we can \n\t\t\t\t\t\t\t\t\t// distinguish stringinze (#) and weld (##)\n\t\t\t\t\t\t\t\t\tret += notweld_hash\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Stringize the replacement\n\t\t\t\t\t\t\t\tret += '\"'+args[define.args[matched_arg]]+'\"'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Stuff the unchanged replacement in there\n\t\t\t\t\t\t\t\tret += args[define.args[matched_arg]]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn ret\n\t\t\t\t\t\t})\n\n\t\t\t\t\trepl = RemoveInvariants(repl, invariants) \n\t\t\t\t\trepl = repl.replace(/\\s*##\\s*/g, \"\")\n\n\t\t\t\t\tstr = str.slice(0, res.index)+repl+str.slice(args.end)\n\t\t\t\t}\n\t\t\t\telse if(define.type === \"macro\")\n\t\t\t\t{\n\t\t\t\t\tvar exec_args = \"\"\n\t\t\t\t\tfor(var arg in define.args) {\n\t\t\t\t\t\tif(define.args[arg]>0) exec_args += \",\"\n\t\t\t\t\t\texec_args += args[define.args[arg]]\n\t\t\t\t\t}\n\t\t\t\t\texec_args = ReplaceInvariants(exec_args, invariants)\n\n\t\t\t\t\tvar answer = eval(define.exec_pre+exec_args+define.exec_post)\n\n\t\t\t\t\tanswer = RemoveInvariants(answer, invariants)\n\t\t\t\t\tstr = str.slice(0, res.index)+answer+str.slice(args.end)\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstr = str.slice(0, res.index)\n\t\t\t\t\t+define.body\n\t\t\t\t\t+str.slice(res.index+define.name.length)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn str\n}", "function processGlobPatterns(urls) {\r\n return urls.map((url) => {\r\n const positive = !url.startsWith('!');\r\n url = positive ? url : url.substr(1);\r\n return { positive, regex: `^${globToRegex(url)}$` };\r\n });\r\n}", "function assertNamespaces(namespaces, assert, checkStatic, checkInstance) {\n for (var i = 0; i < namespaces.length; i++) {\n assertNamespace(namespaces[i], assert, checkStatic, checkInstance);\n }\n }", "prepareConfiguredPaths (list) {\n\n const newList = [];\n\n for (let i = 0, ilen = list.length; i < ilen; i++) {\n const match = list[i].match(/^regexp:(?:([a-z]+):)?(.+)$/i); // e.g. \"regexp:i:[a-z]+\"\n\n newList.push(match ? new RegExp(match[2], match[1] || '') : list[i]);\n }\n\n return newList;\n\n }", "function getNamespacePrefixParts() {\n\tconst brLibFileName = join(process.cwd(), 'br-lib.conf');\n\n\ttry {\n\t\tconst brLibYAML = safeLoad(readFileSync(brLibFileName, 'utf8'));\n\n\t\treturn brLibYAML.requirePrefix.split('/');\n\t} catch (noBRLibConfFileError) {\n\t\t// Ignore.\n\t}\n\n\treturn [];\n}", "function getRequiredNamespaces(ns) {\n return [\n ...getFallbackArray(ns || getDefaultNs()),\n ...state.getRequiredNamespaces(),\n ];\n }", "buildMatchers() {\n var ext, l, results;\n results = [];\n for (ext in languages) {\n l = languages[ext];\n l.commentMatcher = RegExp(`^\\\\s*${l.symbol}\\\\s?`);\n l.commentFilter = /(^#![\\/]|^\\s*#\\{)/;\n results.push(languages);\n }\n return results;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print ClassBody, collapses empty blocks, prints body.
function ClassBody(node, print) { this.push("{"); if (node.body.length === 0) { print.printInnerComments(); this.push("}"); } else { this.newline(); this.indent(); print.sequence(node.body); this.dedent(); this.rightBrace(); } }
[ "function ClassBody(node, print) {\n this.push(\"{\");\n if (node.body.length === 0) {\n print.printInnerComments();\n this.push(\"}\");\n } else {\n this.newline();\n\n this.indent();\n print.sequence(node.body);\n this.dedent();\n\n this.rightBrace();\n }\n}", "function printTopBlock() {\n printLine('<span class=\"green\">==================</span>');\n printLine('<span class=\"cyan\">&nbsp;dhruv bhanushali</span>');\n printLine('<span class=\"green\">==================</span>');\n printLine(`<strong>software developer and technical writer</strong>`);\n printLine(`<strong>undergraduate, IIT Roorkee</strong>`);\n printLine('<br>');\n help();\n printLine('<br>');\n printTree();\n printLine('<br>');\n}", "function htmlStartBlock() {\n //print(\"<hr>\\n\");\n //print(\"\\t<hr />\\n\");\n //print(\"\\t<table width=\\\"100%\\\" class=\\\"wiki_body_container\\\">\\n\");\n //print(\"\\t<table class=\\\"wiki_body_container\\\">\\n\");\n //print(\"\\t\\t<tr>\\n\");\n //print(\"\\t\\t\\t<td>\\n\");\n print(\"\\n<!-- PAGE BODY -->\\n\");\n}", "function print() {\n console.log(blocks);\n }", "function htmlEndBlock() {\n print(\"<!-- END OF PAGE BODY -->\\n\\n\");\n //print(\"\\t\\t\\t</td>\\n\");\n //print(\"\\t\\t</tr>\\n\");\n //print(\"\\t</table>\\n\");\n //print(\"\\t<hr />\\n\");\n}", "function formatBlock()\n{\n\t// TODO: format a block, clear the contents of the block object and set the status to 00 and set\n\t// the location of the nextBlock to $$$.\n}", "function HTMLTestRunner_printHeader()\n{\n\tdocument.writeln( \"<pre>\" );\n\tthis._printHeader();\n}", "function printBlockInfo(block) {\n console.log(`id: ${block.id} - CSS classes: ${block.className}`); // just a log ...\n}", "function formatBody(classes) {\n let body = '';\n\n for (let [className, elmFunction] of classes) {\n body = body + formatFunction(className, elmFunction);\n }\n\n return body;\n}", "endClassDefinition() { this.endSection('};'); }", "function BlockStatement(node, print) {\n\t this.push(\"{\");\n\t if (node.body.length) {\n\t this.newline();\n\t print.sequence(node.body, { indent: true });\n\t if (!this.format.retainLines) this.removeLast(\"\\n\");\n\t this.rightBrace();\n\t } else {\n\t print.printInnerComments();\n\t this.push(\"}\");\n\t }\n\t}", "dump () {\n return classTemplate(this._name, this._body, this._head).substring(1)\n }", "print() {\n if (this._isEdge) {\n return this._printEdgeFriendly();\n }\n\n this._openGroup();\n\n this._logs.forEach((logDetails) => {\n this._printLogDetails(logDetails);\n });\n\n this._childGroups.forEach((group) => {\n group.print();\n });\n\n this._closeGroup();\n }", "writeClass(d) {\n var a = d.attributes;\n if (Parser.LOG_LEVEL > 2)\n console.info(\"Processing class \" + d.attributes.packageName + \".\" + a.name);\n this.writeExtendsClause(a);\n this.writeImplementsClause(a);\n this.runChildrenOfType(d, Types.Properties, (c) => {\n this.writeProperties(c.children);\n });\n this.runChildrenOfType(d, Types.Constructor, (c) => {\n this.writeConstructor(c.children);\n });\n this.runChildrenOfType(d, Types.MethodsStatic, (c) => {\n this.writeMethods(c.children, true);\n });\n this.runChildrenOfType(d, Types.Methods, (c) => {\n this.writeMethods(c.children);\n });\n write(\"\\n}\\n\");\n }", "print() {\n console.log('HEAD:', this.head);\n console.log('TAIL:', this.tail);\n console.log('SIZE:', this.size);\n console.log(JSON.stringify(this, null, 2));\n }", "function generateDebugBody( body ) {\n\n\t\t\tvar frameUnit = 2;// In pixels\n\t\t\tvar debugBody = Crafty.e( RenderingMode );\n\t var debugBodyBody = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyTopFrame = Crafty.e( RenderingMode + ', Color' );\n\t\t\tvar debugBodyRightFrame = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyDownFrame = Crafty.e( RenderingMode + ', Color' );\n\t var debugBodyLeftFrame = Crafty.e( RenderingMode + ', Color' );\n\n\t\t\tdebugBody.attach( debugBodyBody );\n\t\t\tdebugBody.attach( debugBodyTopFrame );\n\t\t\tdebugBody.attach( debugBodyRightFrame );\n\t\t\tdebugBody.attach( debugBodyDownFrame );\n\t\t\tdebugBody.attach( debugBodyLeftFrame );\n\n\t\t\t// TODO cleaner code.\n\t\t\tvar attr = {\n\t\t\t\tx: body.vertices[ 0 ].x,\n\t\t\t\ty: body.vertices[ 0 ].y,\n\t\t\t\tw: body.vertices[ 0 ].x,\n\t\t\t\th: body.vertices[ 0 ].y\n\t\t\t};\n\n\t\t\t//We iterate to have a square shape for circles and polygons/\n\t\t\tfor ( var i = 1; i < body.vertices.length; i++ ) {\n\t\t\t\tif ( body.vertices[ i ].x < attr.x ) {\n\t\t\t\t\tattr.x = body.vertices[ i ].x;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].y < attr.y ) {\n\t\t\t\t\tattr.y = body.vertices[ i ].y;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].x > attr.w ) {\n\t\t\t\t\tattr.w = body.vertices[ i ].x;\n\t\t\t\t}\n\n\t\t\t\tif ( body.vertices[ i ].y > attr.h ) {\n\t\t\t\t\tattr.h = body.vertices[ i ].y;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdebugBody.attr( {\n\t\t\t\tx: attr.x,\n\t\t\t\ty: attr.y,\n\t\t\t\tw: Math.abs( attr.w - attr.x ),\n\t\t\t\th: Math.abs( attr.h - attr.y )\n\t\t\t} );\n\n\t\t\tdebugBody.origin( 'center' );\n\n\t\t\tdebugBodyBody.color( 'blue' );\n\t\t\tdebugBodyBody.alpha = 0.5;\n\t\t\tdebugBodyBody.z = debugBody._z + 1;\n\t\t\tdebugBodyBody.origin( 'center' );\n\n\t\t\tdebugBodyTopFrame.color( 'blue' );\n\t\t\tdebugBodyTopFrame.h = frameUnit;\n\t\t\tdebugBodyTopFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyTopFrame.origin( 'center' );\n\n\t\t\tdebugBodyRightFrame.color( 'blue' );\n\t\t\tdebugBodyRightFrame.x = debugBodyBody._x + ( debugBodyBody._w - frameUnit );\n\t\t\tdebugBodyRightFrame.w = frameUnit;\n\t\t\tdebugBodyRightFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyRightFrame.origin( 'center' );\n\n\t\t\tdebugBodyDownFrame.color( 'blue' );\n\t\t\tdebugBodyDownFrame.y = debugBodyBody._y + ( debugBodyBody._h - frameUnit );\n\t\t\tdebugBodyDownFrame.h = frameUnit;\n\t\t\tdebugBodyDownFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyDownFrame.origin( 'center' );\n\n\t\t\tdebugBodyLeftFrame.color( 'blue' );\n\t\t\tdebugBodyLeftFrame.w = frameUnit;\n\t\t\tdebugBodyLeftFrame.z = debugBody._z + 1;\n\t\t\tdebugBodyLeftFrame.origin( 'center' );\n\n\t\t\treturn debugBody;\n\t\t}", "function generateDebugBody( body ) {\n\n\t\tvar frameUnit = 2;// In pixels\n\t\tvar debugBody = Crafty.e( RenderingMode );\n var debugBodyBody = Crafty.e( RenderingMode + ', Color' );\n var debugBodyTopFrame = Crafty.e( RenderingMode + ', Color' );\n\t\tvar debugBodyRightFrame = Crafty.e( RenderingMode + ', Color' );\n var debugBodyDownFrame = Crafty.e( RenderingMode + ', Color' );\n var debugBodyLeftFrame = Crafty.e( RenderingMode + ', Color' );\n\n\t\tdebugBody.attach( debugBodyBody );\n\t\tdebugBody.attach( debugBodyTopFrame );\n\t\tdebugBody.attach( debugBodyRightFrame );\n\t\tdebugBody.attach( debugBodyDownFrame );\n\t\tdebugBody.attach( debugBodyLeftFrame );\n\n\t\t// TODO cleaner code.\n\t\tvar attr = {\n\t\t\tx: body.vertices[ 0 ].x,\n\t\t\ty: body.vertices[ 0 ].y,\n\t\t\tw: body.vertices[ 0 ].x,\n\t\t\th: body.vertices[ 0 ].y\n\t\t};\n\n\t\t//We iterate to have a square shape for circles and polygons/\n\t\tfor ( var i = 1; i < body.vertices.length; i++ ) {\n\t\t\tif ( body.vertices[ i ].x < attr.x ) {\n\t\t\t\tattr.x = body.vertices[ i ].x;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].y < attr.y ) {\n\t\t\t\tattr.y = body.vertices[ i ].y;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].x > attr.w ) {\n\t\t\t\tattr.w = body.vertices[ i ].x;\n\t\t\t}\n\n\t\t\tif ( body.vertices[ i ].y > attr.h ) {\n\t\t\t\tattr.h = body.vertices[ i ].y;\n\t\t\t}\n\t\t}\n\n\t\tdebugBody.attr( {\n\t\t\tx: attr.x,\n\t\t\ty: attr.y,\n\t\t\tw: Math.abs( attr.w - attr.x ),\n\t\t\th: Math.abs( attr.h - attr.y )\n\t\t} );\n\n\t\tdebugBody.origin( 'center' );\n\n\t\tdebugBodyBody.color( 'blue' );\n\t\tdebugBodyBody.alpha = 0.5;\n\t\tdebugBodyBody.z = debugBody._z + 1;\n\t\tdebugBodyBody.origin( 'center' );\n\n\t\tdebugBodyTopFrame.color( 'blue' );\n\t\tdebugBodyTopFrame.h = frameUnit;\n\t\tdebugBodyTopFrame.z = debugBody._z + 1;\n\t\tdebugBodyTopFrame.origin( 'center' );\n\n\t\tdebugBodyRightFrame.color( 'blue' );\n\t\tdebugBodyRightFrame.x = debugBodyBody._x + ( debugBodyBody._w - frameUnit );\n\t\tdebugBodyRightFrame.w = frameUnit;\n\t\tdebugBodyRightFrame.z = debugBody._z + 1;\n\t\tdebugBodyRightFrame.origin( 'center' );\n\n\t\tdebugBodyDownFrame.color( 'blue' );\n\t\tdebugBodyDownFrame.y = debugBodyBody._y + ( debugBodyBody._h - frameUnit );\n\t\tdebugBodyDownFrame.h = frameUnit;\n\t\tdebugBodyDownFrame.z = debugBody._z + 1;\n\t\tdebugBodyDownFrame.origin( 'center' );\n\n\t\tdebugBodyLeftFrame.color( 'blue' );\n\t\tdebugBodyLeftFrame.w = frameUnit;\n\t\tdebugBodyLeftFrame.z = debugBody._z + 1;\n\t\tdebugBodyLeftFrame.origin( 'center' );\n\n\t\treturn debugBody;\n\t}", "print() {\n this.state.forEach((row, index) => {\n this.printRow(row)\n if (index < this.width - 1) {\n this.printDivider()\n }\n })\n }", "function emptyBody() {\n var node = document.body;\n while (node.hasChildNodes()) {\n node.removeChild(node.lastChild);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to get path of a demo image
function image(relativePath) { return "img/core-img/" + relativePath; }
[ "getPath() {\n let path = '' + this.theme+'-images'+ '/';\n return path;\n }", "function image(relativePath) {\n\treturn \"../../images/\" + relativePath;\n}", "function getImagePath(src) {\n const index = src.indexOf(twelvety.dir.images)\n const position = index >= 0 ? index + twelvety.dir.images.length : 0\n const imageFilename = src.substring(position)\n return path.join(process.cwd(), twelvety.dir.input, twelvety.dir.images, imageFilename)\n}", "function getImgDirectory(source) {\n return source.substring(0, source.lastIndexOf('/') + 1);\n}", "function catch_dir_img() {\n let path_tmp = __dirname;\n path_tmp = path.join(path_tmp, \"..\");\n path_tmp = path.join(path_tmp, \"public\");\n path_tmp = path.join(path_tmp, \"video\");\n path_tmp = path.join(path_tmp, \"images\");\n return path_tmp;\n}", "getImagePath() {\n this.imgPath = this.GlobalFactory.retriveData('genart-path');\n }", "function getImagePath(name) {\n return IMG_DIR + name + \".jpg\";\n}", "makeImagePath(product) {\n return require(`../assets/images/${product.images[0]}`);\n }", "get O_IMG_PATH() {\n return `./images/${this._theme}/circle.png`;\n }", "function imageUrl(path) {\n try {\n return require('text!gcli/ui/' + path);\n }\n catch (ex) {\n var filename = module.id.split('/').pop() + '.js';\n var imagePath;\n\n if (module.uri.substr(-filename.length) !== filename) {\n console.error('Can\\'t work out path from module.uri/module.id');\n return path;\n }\n\n if (module.uri) {\n var end = module.uri.length - filename.length - 1;\n return module.uri.substr(0, end) + '/' + path;\n }\n\n return filename + '/' + path;\n }\n}", "function imageName(src) {\n\tvar a = src.lastIndexOf(\"/\");\n\treturn src.substr(a + 1);\n}", "makeImagePath1(product) {\n return require(`../assets/images/${product.images[1]}`);\n }", "function imagesPath() {\n var href = $(\"link[href*=cleditor]\").attr(\"href\");\n return href.replace(/^(.*\\/)[^\\/]+$/, '$1') + \"images/\";\n }", "function imagesPath() {\n var href = $(\"link[href*=cleditor]\").attr(\"href\");\n return href.replace(/^(.*\\/)[^\\/]+$/, '$1') + \"images/\";\n }", "makeImagePath2(product) {\n return require(`../assets/images/${product.images[2]}`);\n }", "function imgPath (browser) {\n\tvar a = browser.options.desiredCapabilities;\n\tvar meta = [a.platform];\n\tmeta.push(a.browserName ? a.browserName : 'any');\n\tmeta.push(a.version ? a.version : 'any');\n\tmeta.push(a.name); // this is the test filename so always exists.\n\tvar metadata = meta.join('~').toLowerCase().replace(/ /g, '');\n\treturn SCREENSHOT_PATH + metadata + '_' + padLeft(FILECOUNT++) + '_';\n}", "srcPath ( string ) { return chalk.cyan.dim( string ); }", "function img(ref, lang_dependant) { //return (!lang_dependant ? localGraphicPack + \"img/un/\" + ref : localGraphicPack + \"img/\" + detectedLanguage + '/' + ref); }\r\n\t\tvar imgPath = '';\r\n\t\tif (ref == 'img/x.gif') {\r\n\t\t\timgPath = ref;\r\n\t\t} else if (!lang_dependant) {\r\n\t\t\timgPath = localGraphicPack + \"img/un/\" + ref;\r\n\t\t} else {\r\n\t\t\timgPath = localGraphicPack + \"img/\" + detectedLanguage + '/' + ref;\r\n\t\t}\r\n\t\treturn imgPath;\r\n\t}", "function imgpath(browser) {\n var a = browser.options.desiredCapabilities;\n var meta = [a.platform];\n meta.push(a.browserName ? a.browserName : 'any');\n meta.push(a.version ? a.version : 'any');\n meta.push(a.name); // this is the test filename so always exists.\n var metadata = meta.join('~').toLowerCase().replace(/ /g, '');\n return SCREENSHOT_PATH + metadata + '_' + padLeft(FILECOUNT++) + '_';\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a PointString3d from points.
static create(...points) { const result = new PointString3d(); result.addPoints(points); return result; }
[ "static createPoints(points) {\n const ps = new PointString3d();\n ps._points = PointHelpers_1.Point3dArray.clonePoint3dArray(points);\n return ps;\n }", "function Point3D(x, y, z) {\r\n this.x = x;\r\n this.y = y;\r\n this.z = z;\r\n}", "function toTHREE(points) {\r\n var cpoints = [];\r\n for(var p = 0; p != points.length; p++) {\r\n cpoints.push(new THREE.Vector2(points[p][0], points[p][1]));\r\n }\r\n return cpoints;\r\n}", "get points_geometry() {\r\n\t\t// Create an empty geometry\r\n\t\tlet geometry = new THREE.Geometry();\r\n\t\t// Add the vertices\r\n\t\tgeometry.vertices.push(...this.vertices3.map(e => new THREE.Vector3(...e.pos)));\r\n\t\treturn geometry;\r\n\t}", "function Point3D(x,y,z)\n{\n this.x = x \n this.y = y \n this.z = z \n\n}", "function makePoints (pts) {\n var points = [];\n for(var i = 0; i < pts.length; i++) {\n points.push(new THREE.Vector3(pts[i][0], pts[i][1], 0));\n }\n return points;\n }", "function Point3D(x, y, z) {\n this.x = x || 0;\n this.y = y || 0;\n this.z = z || 0;\n}", "static FromPoints(point1, point2, point3) {\n const result = new Plane(0.0, 0.0, 0.0, 0.0);\n result.copyFromPoints(point1, point2, point3);\n return result;\n }", "addPoints(...points) {\n const toAdd = PointString3d.flattenArray(points);\n for (const p of toAdd) {\n if (p instanceof Point3dVector3d_1.Point3d)\n this._points.push(p);\n }\n }", "function pcjsPoint3D(X, Y, Z) {\n this.x = X;\n this.y = Y;\n this.z = Z;\n }", "function CreatePointsInSpace(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n\n}", "function Curve3(points) {\r\n this._length = 0.0;\r\n this._points = points;\r\n this._length = this._computeLength(points);\r\n }", "createSVGPolygonPointsAttribute(points) {\n let pointsString = '';\n for (const i in points) {\n if (points.hasOwnProperty(i)) {\n pointsString += points[i].x;\n pointsString += ',';\n pointsString += points[i].y;\n pointsString += ' ';\n }\n }\n return pointsString;\n }", "function Curve3(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }", "static createFloat64Array(xyzData) {\n const ps = new PointString3d();\n for (let i = 0; i + 3 <= xyzData.length; i += 3)\n ps._points.push(Point3dVector3d_1.Point3d.create(xyzData[i], xyzData[i + 1], xyzData[i + 2]));\n return ps;\n }", "function Curve3(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }", "function Point3D(x, y, z) {\n Point2D.call(this, x, y);\n this._z = z;\n}", "function create3D() {\n scene.add(mesh3D);\n var index = 1;\n point3ds.forEach(point3d => {\n if (index < point3ds.length) {\n var seg = new Segment(point3d, point3ds[index], threeDMat, attributes.segmentHeight);\n mesh3D.add(seg.mesh3D);\n index++;\n }\n });\n perspOrbit.enabled = true;\n}", "function Point3(x,y,z) {\n\tif(!(this instanceof Point3)) return new Point3(x,y,z);\n\tif(typeof x === 'Object' && x.constructor == Point3) {y=x.y; z=x.z; x=x.x;}\n\tthis.x = x;\n\tthis.y = y;\n\tthis.z = z;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
defines a namespace object. This hides a "privates" object on object under the "key" namespace
function defineNamespace(object, namespace) { var privates = Object.create(object), base = object.valueOf; Object.defineProperty(object, 'valueOf', { value: function valueOf(value) { if (value !== namespace || this !== object) { return base.apply(this, arguments); } else { return privates; } } }); return privates; }
[ "function S_namespace (pre){ // if this is the first then the pre will be null\n this._map = new Map()\n this._pre = pre //pre could be another S_namespace instance or NULL\n}", "setNamespace(namespace){this._namespace=namespace;return this;}", "function setNamespace(_namespace){\n namespace = getNamespace(_namespace); \n}", "init() {\n this._ns = DEFAULT_NAMESPACE;\n }", "function addNamespace(namespace, obj){\n if(namespace === \"\") return obj;\n var namespaced={};\n var parts = namespace.split(\".\");\n var position = namespaced;\n var part= parts.shift();\n var nextPart;\n\n while(part) {\n if(typeof position[part] !== \"object\"){\n position[part]={};\n }\n nextPart= parts.shift();\n if(!nextPart) {\n position[part] = obj;\n }\n else {\n position = position[part];\n }\n part = nextPart;\n }\n return namespaced;\n}", "function _createNamespace(name){\n if(!name || typeof name!=\"string\") throw new Error('First parameter must be a string');\n return {\n localStorage:$.extend({},storage,{_type:'localStorage',_ns:name}),\n sessionStorage:$.extend({},storage,{_type:'sessionStorage',_ns:name})\n };\n }", "setNamespace(value) {\n this.namespace = value;\n }", "namespace (...namespaces) {\n const sub = new ConfigGetter()\n sub[PROTECTED_SET_TARGET](this._chain)\n sub[PROTECTED_SET_PATHS](['config', ...namespaces])\n\n return sub\n }", "function checkKeyNamespace(key) {\n\n\t var regDot = /\\./;\n\t if (regDot.test(key)) {\n\t var fullname = '';\n\t var names = key.split(/\\./);\n\t names.forEach(function (name, i) {\n\n\t if (i > 0) {\n\t fullname += '.';\n\t }\n\t fullname += name;\n\t if (eval('typeof ' + fullname + ' == \"undefined\"')) {\n\t eval(fullname + '={};');\n\t }\n\t });\n\t }\n\t}", "function checkKeyNamespace(key) {\r\n\tvar regDot = /\\./;\r\n\tif(regDot.test(key)) {\r\n\t\tvar fullname = '';\r\n\t\tvar names = key.split( /\\./ );\r\n\t\tfor(var i=0; i<names.length; i++) {\r\n\t\t\tif(i>0) {fullname += '.';}\r\n\t\t\tfullname += names[i];\r\n\t\t\tif(eval('typeof '+fullname+' == \"undefined\"')) {\r\n\t\t\t\teval(fullname + '={};');\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function _createNamespace(name) {\n if (!name || typeof name != \"string\") {\n throw new Error('First parameter must be a string');\n }\n if (storage_available) {\n if (!window.localStorage.getItem(name)) {\n window.localStorage.setItem(name, '{}');\n }\n if (!window.sessionStorage.getItem(name)) {\n window.sessionStorage.setItem(name, '{}');\n }\n } else {\n if (!window.localCookieStorage.getItem(name)) {\n window.localCookieStorage.setItem(name, '{}');\n }\n if (!window.sessionCookieStorage.getItem(name)) {\n window.sessionCookieStorage.setItem(name, '{}');\n }\n }\n var ns = {\n localStorage: _extend({}, apis.localStorage, {_ns: name}),\n sessionStorage: _extend({}, apis.sessionStorage, {_ns: name})\n };\n if (typeof Cookies !== 'undefined') {\n if (!window.cookieStorage.getItem(name)) {\n window.cookieStorage.setItem(name, '{}');\n }\n ns.cookieStorage = _extend({}, apis.cookieStorage, {_ns: name});\n }\n apis.namespaceStorages[name] = ns;\n return ns;\n }", "function _createNamespace(name) {\n if (!name || typeof name != \"string\") {\n throw new Error('First parameter must be a string');\n }\n if (storage_available) {\n if (!window.localStorage.getItem(name)) {\n window.localStorage.setItem(name, '{}');\n }\n if (!window.sessionStorage.getItem(name)) {\n window.sessionStorage.setItem(name, '{}');\n }\n } else {\n if (!window.localCookieStorage.getItem(name)) {\n window.localCookieStorage.setItem(name, '{}');\n }\n if (!window.sessionCookieStorage.getItem(name)) {\n window.sessionCookieStorage.setItem(name, '{}');\n }\n }\n var ns = {\n localStorage: _extend({}, apis.localStorage, {_ns: name}),\n sessionStorage: _extend({}, apis.sessionStorage, {_ns: name})\n };\n if (cookies_available) {\n if (!window.cookieStorage.getItem(name)) {\n window.cookieStorage.setItem(name, '{}');\n }\n ns.cookieStorage = _extend({}, apis.cookieStorage, {_ns: name});\n }\n apis.namespaceStorages[name] = ns;\n return ns;\n }", "function internalPrivateThing() {}", "function privateWithExample() {}", "function moduleMakeNsSetter(includeDefault) {\n var _module7 = this;\n // Discussion of why the \"default\" property is skipped:\n // https://github.com/tc39/ecma262/issues/948\n return function (namespace) {\n Object.keys(namespace).forEach(function (key) {\n if (includeDefault || key !== \"default\") {\n utils.copyKey(key, _module7.exports, namespace);\n }\n });\n };\n }", "setNamespace(namespace) {\n this.namespace = namespace;\n }", "function _createNamespace(name){\n\t\tif(!name || typeof name!=\"string\") throw new Error('First parameter must be a string');\n\t\tif(!window.localStorage.getItem(name)) window.localStorage.setItem(name,'{}');\n\t\tif(!window.sessionStorage.getItem(name)) window.sessionStorage.setItem(name,'{}');\n\t\tvar ns={\n\t\t\tlocalStorage:$.extend({},$.localStorage,{_ns:name}),\n\t\t\tsessionStorage:$.extend({},$.sessionStorage,{_ns:name})\n\t\t};\n\t\tif($.cookie){\n\t\t\tif(!window.cookieStorage.getItem(name)) window.cookieStorage.setItem(name,'{}');\n\t\t\tns.cookieStorage=$.extend({},$.cookieStorage,{_ns:name});\n\t\t}\n\t\t$.namespaceStorages[name]=ns;\n\t\treturn ns;\n\t}", "function Namespace(name,label,settingsData){\n this.name = name;\n this.label = label;\n this.settingsData = settingsData;\n }", "static setAPIKey(key){\r\n\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function translate() that will translate a text into "Rovarspraket". That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
function translate(phrase){ var newPhrase = ""; for (count=0; count<phrase.length; count++){ newPhrase = newPhrase + phrase[count]; if (!isVowel(phrase[count]) && phrase[count] !== " "){ newPhrase = newPhrase + "o" + phrase[count]; } } return newPhrase; }
[ "function translate(text) {\n var newText = '';\n for (var i = 0; i < text.length; i++) {\n if (text === ('a' || 'e' || 'i' || 'o' || 'u')) {\n return text[i];\n } else {\n return (text[i] + \"o\" + text[i])\n }\n }\n}", "function translate(phrase){\n\tvar newstr = \"\";\n\tfor (var i = 0; i < phrase.length; i+=1) {\n\t\tif (isVowel(phrase[i])) {\n\t\t\tnewstr += phrase[i];\n\t\t}\n\t\telse {\n\t\t\tnewstr += phrase[i] + \"o\" + phrase[i];\n\t\t}\n\t}\n\treturn newstr;\n\t\n}", "function translate(text) {\n var textArray = text.split('');\n //textArray= ['j','e','s','s'] //length is 4\n // console.log(textArray);\n var wordString = [];\n //add o each letter seperately\n for (var i = 0; i < textArray.length; i++) {\n if ( isVowel(textArray[i]) === false ) {\n //'j' becomes 'joj'\n var consonant = textArray[i] + 'o' + textArray[i];\n wordString.push(consonant);\n console.log(consonant);\n } else if ( isVowel(textArray[i]) === true ) {\n var vowel = textArray[i];\n wordString.push(vowel);\n console.log(vowel);\n }\n\n //check to see if letter is a vowel\n // textArray[i];\n // console.log(textArray[i]);\n // if (textArray === i) {\n // it is a add consonant write letter then add o then same letter\n// if it isnt a consonant just write the letter\n // }\n }\n var answer = wordString.join('');\n console.log(answer);\n return answer;\n}", "function Translate(text) {\n\n\tfor (var i = 0; i < english2pirate.length; i++) \n\t{\n\t\tvar toReplace = new RegExp(\"\\\\b\"+english2pirate[i][0]+\"\\\\b\", \"i\");\n\t\tvar index = text.search(toReplace);\n\t\t\n\t\t//If the english word is capitalized -- replace pirate word in array with captialized pirate word\n\t\twhile (index != -1)\n\t\t{\t\n\n\t\t\tif (text.charAt(index) >= \"A\" && text.charAt(index) <= \"Z\")\n\t\t\t{\t\t\t\n\t\t\t\ttext = text.replace(toReplace, Capitalize(english2pirate[i][1]));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttext = text.replace(toReplace, english2pirate[i][1]);//replace with the string in the second index spot of the array that it matched\n\t\t\t}\n\t\t\tindex = text.search(toReplace);\n\t\t}\n\t}\n\t//Pirates with tourets start each new sentence with Arrr!\n\t//text = text.replace(/(\\b\\w+\\b\\.)/, \"$1 Arrrr!\")\n\t\ttext = text.replace(/(\\b\\w+\\b[.!?])/, \"$1 WHERE HAS ALL TH' RUM GONE!?\");\n\t\ttext = text.replace(/(\\w+eter \\w+riffin)/, \"$1, Aye, Matey! Best bloody buccaneer that sailed th' seven seas!\"); \n\t//text = text.replace(/(\\b\\w+\\?\\b)/, \"$1 Ye serious? Why don't yee shove off me bloody poop deck an' go arsk Capn' Morgan?! Ye best not return without rum or ye'll walk the plank!\");\n\t\treturn text;\n}", "function translate(word, language) {\n\n}", "function translateWord(word) {\n return word.split('').map(translateLetters).join(' ');\n}", "function translate(string) {\n\tlet regexp = /([^aeioqu\\s]*(?:qu)*)([a-z]+)/gi;\n\treturn string.replace(regexp, `$2$1ay`);\n}", "function translate() {\r\n\r\n var translated = document.getElementById(\"output\").value;\r\n var sentence = input.value.trim();\r\n\r\n if(sentence.length > 0) {\r\n\r\n // Split the sentence into an array of words\r\n var sentences = sentence.split(\" \");\r\n\r\n for(var word in sentences) {\r\n\r\n var newWord = printLatinWord(sentences[word]);\r\n translated += newWord + \" \"\r\n } // end for\r\n\r\n translated += \"\\n\";\r\n output.value = translated;\r\n } // end if\r\n\r\n input.value = \"\";\r\n input.focus();\r\n} // end function translate", "function changeWord() {\n // split into words\n let words = RiTa.tokenize(txt); \n //console.log(words);\n \n let parole_odio = [\n \"nigger\",\n \"nigga\",\n \"faggor\",\n \"queer\",\n \"whore\",\n \"slut\",\n \"bitch\",\n \"gimpy\",\n ];\n\n \n for (let i = 0; i < words.length; i++) {\n for (let j = 0; j < parole_odio.length; j++) {\n // find related words\n let rhymes = RiTa.rhymes(parole_odio[j]);\n let change = RiTa.random(rhymes);\n\n if (words[i] == parole_odio[j]) {\n change;\n } else { continue; }\n\n if (change.includes(words[i]) || words[i].includes(change)) {\n continue; // skip substrings\n }\n\n if (/[A-Z]/.test(words[i][0])) {\n change = RiTa.capitalize(change); // keep capitals\n }\n\n console.log(\"replace(\" + i + \"): \" + words[i] + \" -> \" + change);\n\n words[i] = change; // do replacement\n break;\n }\n }\n\n // recombine into string and display\n txt = RiTa.untokenize(words);\n background(20, 30, 55);\n fill(250, 240, 230);\n text(txt, 50, 30, 500, height);\n}", "function translatePlantLatin(message) {\n\t/* Enter your solution here! */\n\tconst vowel = {\n\t\ta: 'tiva',\n\t\te: 'llia',\n\t\ti: 'mus',\n\t\to: 'phylum',\n\t\tu: 'rea',\n\t};\n\tconst result = message.split(\" \").map(word =>{\n\t\treturn word.split(\"\").map(char=>{\n\t\t\tconst lowercase = char.toLowerCase();\n\t\t\tif(vowel[lowercase]){\n\t\t\t\treturn char + vowel[lowercase];\n\t\t\t}\n\t\t\treturn char.toLowerCase();\n\t\t}).join(\"\");\n\t});\n\treturn result.join(\" \");\n}", "function replace(string){\n\tresultArray = [];\n\tArrayOfWords = RiTa.tokenize(string);\n\tPartsOfSpeech = RiTa.getPosTags(ArrayOfWords);\n\tfor (j = 0; j < ArrayOfWords.length; j++){\n\t\t//adjuctive\n\t\tif (PartsOfSpeech[j] === \"jj\" || PartsOfSpeech[j] === \"jjr\" || PartsOfSpeech[j] === \"jjs\" || PartsOfSpeech[j] === \"nn\" || PartsOfSpeech[j] === \"nns\" || PartsOfSpeech[j] === \"nnp\" || PartsOfSpeech[j] === \"nnps\"){\n\t\t\tif (j === ArrayOfWords.length - 1 && ArrayOfWords[j].length > 1){\n\t\t\t\tresultArray.push(fixRhyme(ArrayOfWords[j], PartsOfSpeech[j]))\n\t\t\t}\n\t\t\telse if (j === ArrayOfWords.length - 2 && ArrayOfWords[j+1].length === 1){\n\t\t\t\tresultArray.push(fixRhyme(ArrayOfWords[j], PartsOfSpeech[j]))\n\t\t\t}\n\t\t\t//noun\n\t\t\telse {\n\t\t\t\tif (PartsOfSpeech[j] === \"nns\"){ //\"nns\" includes plural nouns\n\t\t\t\tresultArray.push(RiTa.pluralize(lexicon.randomWord(\"nn\")));\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\tresultArray.push(lexicon.randomWord(PartsOfSpeech[j]));}\n\t\t\t\t}\n\t\t}\n\t\t// not noun or adjective\n\t\telse{\n\t\t\tresultArray.push(ArrayOfWords[j]);\n\t\t}\n\t}\n\tresultString = RiTa.untokenize(resultArray);\n\treturn resultString;\n}", "function translatePigLatin(str) {\n //check if srting start with consonant\n //convert str to array\n let arr = [...str.toLowerCase()];\n let vowels = ['a', 'e', 'i', 'o', 'u'];\n let firstConsonants = [];\n //if str strat with vowle add 'way' to the end\n if(vowels.indexOf(arr[0]) !== -1){\n return str + \"way\";\n }\n\n for (let char in arr) {\n if (!vowels.includes(arr[char])) {\n firstConsonants.push(arr[char]);\n } else {\n return arr.splice(char).join(\"\") + firstConsonants.join(\"\") + \"ay\";\n \n }\n } \n //if str start with consonant move the character to the end and add \"ay\" to the end of it \n\n}", "function translate(map, string) {\n \n // create a map mapping ciphered letters to original letters\n var newmap = reverseMap(map);\n \n var result = '';\n \n for (var i = 0; i < string.length; i++) {\n result += newmap[string[i]];\n }\n \n return result;\n}", "function translateToMeowish(str) {\n if (str.length === 0) {\n return 'Meow!';\n }\n\n const re = /[^\\r\\n.!?]+(:?(:?\\r\\n|[\\r\\n]|[.!?])+|$)/gi;\n const sentenceArray = str.trim().match(re);\n\n function meowifyWords(str) {\n return str\n .trim()\n .split(' ')\n .map(word => {\n const letters = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], ['i', 'k', 'l', 'm', 'n', 'o', 'p', 'q'], ['r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']];\n if (letters[0].some(char => word.charAt(0).toLowerCase().indexOf(char) >= 0)) {\n return 'meow';\n } else if (letters[1].some(char => word.charAt(0).toLowerCase().indexOf(char) >= 0)) {\n return 'miau';\n } else if (letters[2].some(char => word.charAt(0).toLowerCase().indexOf(char) >= 0)) {\n return 'purr';\n } else {\n return word;\n }\n })\n .join(' ');\n }\n\n return sentenceArray\n .map(sentence => {\n const punctuation = ['.', '?', '!'];\n if (punctuation.some(char => sentence.charAt(sentence.length - 1).indexOf(char) >= 0)) {\n return meowifyWords(sentence) + sentence.charAt(sentence.length - 1);\n } else {\n return meowifyWords(sentence);\n }\n })\n .join(' ');\n}", "function translator(x, y) {\n return \"translate(\" + x + \",\" + y + \")\";\n}", "function changeWord() {\n // split into words\n let words = RiTa.tokenize(canzone);\n\n // fa partire il loop da un punto random all'interno del testo\n let r = floor(random(0, words.length));\n for (let i = r; i < words.length + r; i++) {\n let idx = i % words.length;\n let word = words[idx].toLowerCase();\n if (word.length < 3) continue;\n\n // find related words\n let pos = RiTa.tagger.allTags(word)[0];\n let rhymes = RiTa.rhymes(word, { pos });\n let sounds = RiTa.soundsLike(word, { pos });\n let similars = [...rhymes, ...sounds];\n\n // only words with 2 or more similars\n if (similars.length < 2) {\n console.log(\"No sims for \" + word);\n continue;\n }\n\n // pick a random similar\n let next = RiTa.random(similars);\n\n if (next.includes(word) || word.includes(next)) {\n continue; // skip substrings\n }\n if (/[A-Z]/.test(words[idx][0])) {\n next = RiTa.capitalize(next); // keep capitals\n }\n \n\n\n console.log(\"replace(\" + idx + \"): \" + word + \" -> \" + next);\n\n words[idx] = next;\n // do replacement\n break;\n }\n\n // recombine into string and display\n canzone = RiTa.untokenize(words);\n background(255);\n fill(0);\n textSize(12);\n text(canzone, 50, 30, width - width/2, height);\n}", "function modernDictionaryTranslate(texto)\n{ \n\nvar smiley = /\\:\\)/gi;\nvar happy = /\\:D/gi;\nvar sad = /\\:\\(/gi;\nvar reallyHappy = /\\=D/gi;\n if(language==0)\n {\n texto=texto.replace(/\\bpz\\b/gi,\"pues\");\n texto=texto.replace(/\\bk\\b/gi,\"que\");\n texto=texto.replace(/\\bgad\\b/gi,\"Gracias a dios\");\n texto=texto.replace(/\\bntc\\b/gi,\"No te creas\");\n texto=texto.replace(/\\bbn\\b/gi,\"bien\");\n texto=texto.replace(/\\btmb\\b/gi,\"tambien\");\n texto=texto.replace(/\\bhm*\\b/gi,\"no me convences\");\n texto=texto.replace(/\\bvd\\b/gi,\"verdad\");\n // texto=texto.replace(/\\b[ha,he]+\\b/gi,\"jajaja\"); this one is failing when it finds an \"a\" alone, it replaces the \"a\" with the \"jajaja\"\n texto=texto.replace(smiley,\"estoy feliz\");\n texto=texto.replace(happy,\"estoy sonriendo,\");\n texto=texto.replace(sad,\"estoy triste,\");\n texto=texto.replace(reallyHappy,\"estoy muy feliz,\");\n \n }\n else if(language==1)\n {\n texto=texto.replace(/\\blmfao\\b/gi,\"laughing my fucking ass off\");\n texto=texto.replace(/\\bk\\b/gi,\"que\");\n texto=texto.replace(/\\bya\\b/gi,\"you\");\n texto=texto.replace(smiley,\"I feel happy\");\n texto=texto.replace(happy,\"I am smiling,\");\n texto=texto.replace(sad,\"I feel sad,\");\n texto=texto.replace(reallyHappy,\"I feel really happy,\");\n }\n texto=texto.replace(/\\bxD\\b/gi,\"me muero de risa\");\n texto=texto.replace(/\\b=D\\b/gi,\"estoy felíz\");\n texto=texto.replace(/\\b:D\\b/gi,\"sonrío\");\n\n\n return texto;\n}", "function pigLatin(sentence) {\n\n let sentenceArray = sentence.split(\" \")\n let translation = \"\"\n sentenceArray.forEach(function(word) {\n let chopOff = word.search(/[aeiou]/i)\n let head = \"\"\n let tail = \"\"\n if (word[chopOff] === word.charAt(0)) { chopOff = word.search(/[^aeiou]/i) }\n tail = word.slice(0, chopOff) + \"ay\";\n head = word.slice(chopOff);\n word = head + tail;\n translation += word + \" \"\n })\n return translation\n}", "transliterate(text) {\n\n return Sanscript.t(text, 'itrans', 'devanagari');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dialogElements all dialogs have elements define the controls of the dialog.
static get dialogElements() { SuiLayoutDialog._dialogElements = typeof(SuiLayoutDialog._dialogElements) !== 'undefined' ? SuiLayoutDialog._dialogElements : [{ smoName: 'applyToPage', parameterName: 'applyToPage', defaultValue: -1, control: 'SuiDropdownComponent', label: 'Apply to Page', dataType: 'int', options: [{ value: -1, label: 'All' }, { value: -2, label: 'All Remaining' }, { value: 1, label: 'Page 1' }] }, { smoName: 'leftMargin', parameterName: 'leftMargin', defaultValue: SmoScore.defaults.layout.leftMargin, control: 'SuiRockerComponent', label: 'Left Margin (px)' }, { smoName: 'rightMargin', parameterName: 'rightMargin', defaultValue: SmoScore.defaults.layout.rightMargin, control: 'SuiRockerComponent', label: 'Right Margin (px)' }, { smoName: 'topMargin', parameterName: 'topMargin', defaultValue: SmoScore.defaults.layout.topMargin, control: 'SuiRockerComponent', label: 'Top Margin (px)' }, { smoName: 'bottomMargin', parameterName: 'bottomMargin', defaultValue: SmoScore.defaults.layout.topMargin, control: 'SuiRockerComponent', label: 'Bottom Margin (px)' }, { smoName: 'interGap', parameterName: 'interGap', defaultValue: SmoScore.defaults.layout.interGap, control: 'SuiRockerComponent', label: 'Inter-System Margin' }, { smoName: 'intraGap', parameterName: 'intraGap', defaultValue: SmoScore.defaults.layout.intraGap, control: 'SuiRockerComponent', label: 'Intra-System Margin' }, { staticText: [ { label: 'Page Layouts' } ] }]; return SuiLayoutDialog._dialogElements; }
[ "static get dialogElements() {\n SuiLayoutDialog._dialogElements = typeof(SuiLayoutDialog._dialogElements) !== 'undefined' ? SuiLayoutDialog._dialogElements :\n [{\n smoName: 'pageSize',\n parameterName: 'pageSize',\n defaultValue: SmoScore.pageSizes.letter,\n control: 'SuiDropdownComponent',\n label: 'Page Size',\n options: [\n {\n value: 'letter',\n label: 'Letter'\n }, {\n value: 'tabloid',\n label: 'Tabloid (11x17)'\n }, {\n value: 'A4',\n label: 'A4'\n }, {\n value: 'custom',\n label: 'Custom'\n }]\n }, {\n smoName: 'pageWidth',\n parameterName: 'pageWidth',\n defaultValue: SmoScore.defaults.layout.pageWidth,\n control: 'SuiRockerComponent',\n label: 'Page Width (px)'\n }, {\n smoName: 'pageHeight',\n parameterName: 'pageHeight',\n defaultValue: SmoScore.defaults.layout.pageHeight,\n control: 'SuiRockerComponent',\n label: 'Page Height (px)'\n }, {\n smoName: 'orientation',\n parameterName: 'orientation',\n defaultValue: SmoScore.orientations.portrait,\n control: 'SuiDropdownComponent',\n label: 'Orientation',\n dataType: 'int',\n options: [{\n value: SmoScore.orientations.portrait,\n label: 'Portrait'\n }, {\n value: SmoScore.orientations.landscape,\n label: 'Landscape'\n }]\n }, {\n smoName: 'engravingFont',\n parameterName: 'engravingFont',\n defaultValue: SmoScore.engravingFonts.Bravura,\n control: 'SuiDropdownComponent',\n label: 'Engraving Font',\n options: [{\n value: 'Bravura',\n label: 'Bravura'\n }, {\n value: 'Gonville',\n label: 'Gonville'\n }, {\n value: 'Petaluma',\n label: 'Petaluma'\n }, {\n value: 'Leland',\n label: 'Leland'\n }]\n }, {\n smoName: 'leftMargin',\n parameterName: 'leftMargin',\n defaultValue: SmoScore.defaults.layout.leftMargin,\n control: 'SuiRockerComponent',\n label: 'Left Margin (px)'\n }, {\n smoName: 'rightMargin',\n parameterName: 'rightMargin',\n defaultValue: SmoScore.defaults.layout.rightMargin,\n control: 'SuiRockerComponent',\n label: 'Right Margin (px)'\n }, {\n smoName: 'topMargin',\n parameterName: 'topMargin',\n defaultValue: SmoScore.defaults.layout.topMargin,\n control: 'SuiRockerComponent',\n label: 'Top Margin (px)'\n }, {\n smoName: 'interGap',\n parameterName: 'interGap',\n defaultValue: SmoScore.defaults.layout.interGap,\n control: 'SuiRockerComponent',\n label: 'Inter-System Margin'\n }, {\n smoName: 'intraGap',\n parameterName: 'intraGap',\n defaultValue: SmoScore.defaults.layout.intraGap,\n control: 'SuiRockerComponent',\n label: 'Intra-System Margin'\n }, {\n smoName: 'noteSpacing',\n parameterName: 'noteSpacing',\n defaultValue: SmoScore.defaults.layout.noteSpacing,\n control: 'SuiRockerComponent',\n type: 'percent',\n label: 'Note Spacing'\n }, {\n smoName: 'zoomScale',\n parameterName: 'zoomScale',\n defaultValue: SmoScore.defaults.layout.zoomScale,\n control: 'SuiRockerComponent',\n label: '% Zoom',\n type: 'percent'\n }, {\n smoName: 'svgScale',\n parameterName: 'svgScale',\n defaultValue: SmoScore.defaults.layout.svgScale,\n control: 'SuiRockerComponent',\n label: '% Note size',\n type: 'percent'\n }, {\n staticText: [\n { label: 'Score Layout' }\n ]\n }];\n return SuiLayoutDialog._dialogElements;\n }", "static get dialogElements() {\n SuiScoreFontDialog._dialogElements = typeof(SuiScoreFontDialog._dialogElements) !== 'undefined' ? SuiScoreFontDialog._dialogElements :\n [{\n smoName: 'engravingFont',\n parameterName: 'engravingFont',\n defaultValue: SmoScore.engravingFonts.Bravura,\n control: 'SuiDropdownComponent',\n label: 'Engraving Font',\n options: [{\n value: 'Bravura',\n label: 'Bravura'\n }, {\n value: 'Gonville',\n label: 'Gonville'\n }, {\n value: 'Petaluma',\n label: 'Petaluma'\n }, {\n value: 'Leland',\n label: 'Leland'\n }]\n }, {\n smoName: 'chordFont',\n parameterName: 'chordFont',\n classes: 'chord-font-component',\n defaultValue: 0,\n control: 'SuiFontComponent',\n label: 'Chord Font'\n }, {\n smoName: 'lyricFont',\n parameterName: 'lyricFont',\n classes: 'lyric-font-component',\n defaultValue: 0,\n control: 'SuiFontComponent',\n label: 'Lyric Font'\n }, {\n staticText: [\n { label: 'Score Fonts' }\n ]\n }];\n return SuiScoreFontDialog._dialogElements;\n }", "dialog() {\n return this._getOrCreateSubset('dialog', dialog_1.default);\n }", "static get dialogElements() {\n SuiLayoutDialog._dialogElements = SuiLayoutDialog._dialogElements ? SuiLayoutDialog._dialogElements :\n [\n {\n smoName: 'pageSize',\n parameterName: 'pageSize',\n defaultValue: SmoScore.pageSizes.letter,\n control: 'SuiDropdownComponent',\n label:'Page Size',\n options: [{\n value: 'letter',\n label: 'Letter'\n }, {\n value: 'tabloid',\n label: 'Tabloid (11x17)'\n }, {\n value: 'A4',\n label: 'A4'\n }, {\n value: 'custom',\n label: 'Custom'\n }\n ]\n }, {\n smoName: 'pageWidth',\n parameterName: 'pageWidth',\n defaultValue: SmoScore.defaults.layout.pageWidth,\n control: 'SuiRockerComponent',\n label: 'Page Width (px)'\n }, {\n smoName: 'pageHeight',\n parameterName: 'pageHeight',\n defaultValue: SmoScore.defaults.layout.pageHeight,\n control: 'SuiRockerComponent',\n label: 'Page Height (px)'\n }, {\n smoName: 'orientation',\n parameterName: 'orientation',\n defaultValue: SmoScore.orientations.portrait,\n control: 'SuiDropdownComponent',\n label: 'Orientation',\n dataType:'int',\n options:[{\n value:SmoScore.orientations.portrait,\n label:'Portrait'\n }, {\n value:SmoScore.orientations.landscape,\n label:'Landscape'\n }]\n }, {\n smoName: 'engravingFont',\n parameterName: 'engravingFont',\n defaultValue: SmoScore.engravingFonts.Bravura,\n control: 'SuiDropdownComponent',\n label:'Engraving Font',\n options: [{\n value: 'Bravura',\n label: 'Bravura'\n }, {\n value: 'Gonville',\n label: 'Gonville'\n }, {\n value: 'Petaluma',\n label: 'Petaluma'\n }\n ]\n },{\n smoName: 'leftMargin',\n parameterName: 'leftMargin',\n defaultValue: SmoScore.defaults.layout.leftMargin,\n control: 'SuiRockerComponent',\n label: 'Left Margin (px)'\n }, {\n smoName: 'rightMargin',\n parameterName: 'rightMargin',\n defaultValue: SmoScore.defaults.layout.rightMargin,\n control: 'SuiRockerComponent',\n label: 'Right Margin (px)'\n }, {\n smoName: 'topMargin',\n parameterName: 'topMargin',\n defaultValue: SmoScore.defaults.layout.topMargin,\n control: 'SuiRockerComponent',\n label: 'Top Margin (px)'\n }, {\n smoName: 'interGap',\n parameterName: 'interGap',\n defaultValue: SmoScore.defaults.layout.interGap,\n control: 'SuiRockerComponent',\n label: 'Inter-System Margin'\n }, {\n smoName: 'intraGap',\n parameterName: 'intraGap',\n defaultValue: SmoScore.defaults.layout.intraGap,\n control: 'SuiRockerComponent',\n label: 'Intra-System Margin'\n }, {\n smoName: 'zoomScale',\n parameterName: 'zoomScale',\n defaultValue: SmoScore.defaults.layout.zoomScale,\n control: 'SuiRockerComponent',\n label: '% Zoom',\n type: 'percent'\n }, {\n smoName: 'svgScale',\n parameterName: 'svgScale',\n defaultValue: SmoScore.defaults.layout.svgScale,\n control: 'SuiRockerComponent',\n label: '% Note size',\n type: 'percent'\n }\n ];\n\n return SuiLayoutDialog._dialogElements;\n }", "function initDialogs(self){\n\t\tvar container = $('#dialogContainerElement');\n\n\t\tvar defaultDialogConf = { show: false, backdrop: false };\n\t\tself.dialogs = {};\n\n\t\tself.dialogs.openDialog = container.find(\".openMenu\").modal(defaultDialogConf);\n\t\tself.dialogs.renameDialog = container.find(\".renameDialog\").modal(defaultDialogConf);\n\t\tself.dialogs.newFileDialog = container.find(\".newFileDialog\").modal(defaultDialogConf);\n\t\tself.dialogs.gotoDialog = container.find(\".gotoDialog\").modal(defaultDialogConf);\n\t\tself.dialogs.importDialog = container.find(\".importDialog\").modal(defaultDialogConf);\n\n\t\t// .cmeditor-ui-dialog s have the defaultButton-thingie activated\n\t\t$.each(self.dialogs, function(key, val) {\n\t\t\tval.parent().addClass(\"cmeditor-ui-dialog\");\n\t\t});\n\t}", "getAllUIElements() {\n return [];\n }", "_constructDialog(dialogElements, parameters) {\n const id = parameters.id;\n const b = htmlHelpers.buildDom;\n const r = b('div').classes('attributeModal').attr('id', 'attr-modal-' + id)\n .css('top', parameters.top + 'px').css('left', parameters.left + 'px')\n .append(b('spanb').classes('draggable button').append(b('span').classes('icon icon-move jsDbMove')))\n .append(b('h2').classes('dialog-label').text(this.staticText.label));\n\n var ctrl = b('div').classes('smoControlContainer');\n dialogElements.filter((de) => de.control).forEach((de) => {\n var ctor = eval(de.control);\n var control = new ctor(this, de);\n this.components.push(control);\n ctrl.append(control.html);\n });\n r.append(ctrl);\n r.append(\n b('div').classes('buttonContainer').append(\n b('button').classes('ok-button button-left').text('OK')).append(\n b('button').classes('cancel-button button-center').text('Cancel')).append(\n b('button').classes('remove-button button-right').text('Remove').append(\n b('span').classes('icon icon-cancel-circle'))));\n $('.attributeDialog').html('');\n\n $('.attributeDialog').append(r.dom());\n\n const trapper = htmlHelpers.inputTrapper('.attributeDialog');\n $('.attributeDialog').find('.cancel-button').focus();\n return {\n element: $('.attributeDialog'),\n trapper\n };\n }", "findUiElements() {\n this.config.uiElements = traverseObjectAndChange(this.config.uiElements, value => document.getElementById(value));\n }", "function _initDialogs()\r\n{\r\n\t// adjust settings panel\r\n\t$(\"#settings_dialog\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 333});\r\n\t\r\n\t// adjust node inspector\r\n\t$(\"#node_inspector\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 366,\r\n\t\tmaxHeight: 300});\r\n\t\r\n\t// adjust edge inspector\r\n\t$(\"#edge_inspector\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 366,\r\n\t\tmaxHeight: 300});\r\n\t\r\n\t// adjust node legend\r\n\t$(\"#node_legend\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 440});\r\n\t\r\n\t// adjust drug legend\r\n\t$(\"#drug_legend\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 320});\r\n\t\r\n\t// adjust edge legend\r\n\t$(\"#edge_legend\").dialog({autoOpen: false, \r\n\t\tresizable: false, \r\n\t\twidth: 280,\r\n\t\theight: 152});\r\n}", "_constructDialog(dialogElements, parameters) {\n var id = parameters.id;\n var b = htmlHelpers.buildDom;\n var r = b('div').classes('attributeModal').attr('id','attr-modal-'+id)\n .css('top', parameters.top + 'px').css('left', parameters.left + 'px')\n .append(b('spanb').classes('draggable button').append(b('span').classes('icon icon-move jsDbMove')))\n .append(b('h2').text(parameters.label));\n\n var ctrl = b('div').classes('smoControlContainer');\n dialogElements.forEach((de) => {\n var ctor = eval(de.control);\n var control = new ctor(this, de);\n this.components.push(control);\n ctrl.append(control.html);\n });\n r.append(ctrl);\n r.append(\n b('div').classes('buttonContainer').append(\n b('button').classes('ok-button button-left').text('OK')).append(\n b('button').classes('cancel-button button-center').text('Cancel')).append(\n b('button').classes('remove-button button-right').text('Remove').append(\n b('span').classes('icon icon-cancel-circle'))));\n $('.attributeDialog').html('');\n\n $('.attributeDialog').append(r.dom());\n\n var trapper = htmlHelpers.inputTrapper('.attributeDialog');\n $('.attributeDialog').find('.cancel-button').focus();\n return {\n element: $('.attributeDialog'),\n trapper: trapper\n };\n }", "function _getElements()\n\t\t{\n\t\t\tvar inputs = _getForm().find('input, textarea');\n\t\t\tvar element = new Array();\n\t\t\tvar validation = true;\n\t\t\tfor(var i = 0; inputs.length >= i; i++) \n\t\t\t{\n\t\t\t\tif($(inputs[i]).attr('data-validation'))\n\t\t\t\t{\n\t\t\t\t\telement[$(inputs[i]).attr('name')] = $(inputs[i]).attr('data-validation');\n\t\t\t\t\t_removeErrorMessage($(inputs[i]));\n\t\t\t\t\t\n\t\t\t\t\tvar validations = _rulesElements($(inputs[i]), element[$(inputs[i]).attr('name')]);\n\t\t\t\t\t\n\t\t\t\t\tif(validations==false)\n\t\t\t\t\t{\n\t\t\t\t\t\tvalidation = validations;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tif(validation == true)\n\t\t\t{\n\t\t\t\t_submitForm(_getForm());\n\t\t\t}\n\t\t}", "buildControls() {\n for (let ctrl of this._dlgResource.controls()) {\n this.addControlFromResource(ctrl);\n }\n }", "function hideAllDialogs()\n{\n var dialogs = document.getElementsByClassName(\"dialog\");\n for (var i = 0; i < dialogs.length; i++) {\n dialogs[i].style.visibility = \"hidden\";\n } // for\n}", "function initDialogs(){\n $( '#dialog' ).dialog({\n dialogClass: 'no-close',\n autoOpen: false,\n height: 600,\n width: 600,\n buttons: [\n {\n text: 'OK',\n click: function() {\n $( this ).dialog( 'close' );\n }\n }\n ]\n });\n\n $( '#game-over' ).dialog({\n dialogClass: 'no-close',\n autoOpen: false,\n height: 600,\n width: 600,\n buttons: [\n {\n text: 'OK',\n click: function() {\n $( this ).dialog( 'close' );\n }\n }\n ]\n });\n}", "function getAllAliveControls() {\n\t\treturn Element.registry.all();\n\t}", "function initAddDialogs() {\n $(\".add_dialog\").each(function() {\n $(this).dialog({\n closeOnEscape: true,\n title: \"Add Assignment\", \n width: 'auto',\n draggable: true, \n resizable: false, \n modal: true, \n autoOpen: false,\n });\n });\n}", "function Dialogs() { }", "get elements() {\n return browser.elements(this._selector);\n }", "_validatableElements() {\n return Array.from(this._formElement.elements).filter(\n (element) => element.type === 'text' || element.type === 'select-one' || element.type === 'textarea'\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a single frame (1/60s NTSC, 1/50s PAL).
runFrame() { const cpu = this.cpu; const ppu = this.ppu; const apu = this.apu; while (!ppu.frameEnded) { cpu.tick(); ppu.tick(); ppu.tick(); ppu.tick(); if (this.tickAPU) { apu.tick(); } this.tickAPU = !this.tickAPU; } ppu.frameEnded = false; requestAnimationFrame(() => { if (!this.paused) { this.runFrame(); } }); }
[ "function drawLoop(){\n // Reset to beginning after reaching final frame\n if (Globals.frame > Globals.totalFrames) { Globals.frame = 0;}\n\n // Update range, draw simulation at that frame, and increment counter\n $(\"#simulatorFrameRange\").val(Globals.frame)\n \n // Assign a keyframe if the current frame is in the keyframes array \n Globals.keyframe = ($.inArray(parseInt(Globals.frame), Globals.keyframes) != -1)? kIndex(Globals.frame): false; \n updateRangeLabel();\n highlightKeycanvas(Globals.keyframe, \"yellow\");\n \n // Render the current frame and chart\n drawMaster();\n updatePVAChart();\n \n // Increment frame counter\n Globals.frame++;\n}", "step() { this.frame(); }", "function StepByFrame(frames) {\n return ATMPlayer.Step(frames);\n}", "set firstFrame(value) {}", "loop(){\n\t\tif (this.running) {\n\t\t\tlet tick = Clock.tick() / 1000;\n\t\t\tthis.processFrame(tick);\n\t\t\tthis.renderFrame(tick);\n\t\t\twindow.requestAnimationFrame(()=>{\n\t\t\t\tthis.loop();\n\t\t\t});\n\t\t}\n\t}", "function frame() {\n if (false == isRunning) {\n isRunning = true\n tick = regl.frame((_, ...args) => {\n reglContext = _\n ctx._reglContext = reglContext\n const {\n viewportWidth: width,\n viewportHeight: height,\n } = reglContext\n\n try {\n injectContext((_) => {\n ctx.reset()\n ctx.clear()\n lights.splice(0, lights.length)\n for (let refresh of queue) {\n if ('function' == typeof refresh) {\n refresh(reglContext, ...args)\n }\n }\n })\n } catch (e) {\n ctx.emit('error', e)\n cancel()\n }\n })\n }\n }", "function fps() {\n\tpush();\n\tmirror(); // Unmirror so we can read the text\n\ttextSize(14);\n\tfill(200);\n\ttext(floor(frameRate()), 20, height - 20);\n\tpop();\n}", "calculateFrame() {\n const nowTime = (new Date()).getTime();\n this.tick += 1;\n if (nowTime - this.beforeTime >= 1000) {\n console.log(`fps: ${this.tick}`);\n this.tick = 0;\n this.beforeTime = nowTime;\n }\n }", "function drawScreen ()\r\n {\r\n // draw the canvas or simulation area\r\n context.fillStyle = '#EEEEEE';\r\n context.fillRect (0, 0, theCanvas.width, theCanvas.height);\r\n\r\n // draw the frame\r\n context.strokeStyle = '#000000'; \r\n context.strokeRect (1, 1, theCanvas.width-2, theCanvas.height-2);\r\n\t\t\r\n if (_SimState == SIM_STATE_PLAY)\r\n {\r\n updateCalcs ();\r\n\r\n if ( Math.abs (_dCurrXPos - _dPrevXPos) < ZERO_TOLERANCE && \r\n Math.abs (_dCurrYPos - _dPrevYPos) < ZERO_TOLERANCE ) \r\n {\r\n _SimState = SIM_STATE_STOP;\r\n document.getElementById ('StartBtn').innerHTML = 'Start';\r\n\r\n SetParamsValues (false);\r\n\r\n DisableUI (false);\r\n clearTimeout (_SimTimerId);\r\n }\r\n }\r\n\r\n redrawSceen (); \r\n }", "drawFrame() {\n const term = this._terminal,\n width = term.getWidth(),\n height = term.getHeight();\n\n let chars = '',\n i;\n\n // generate the top and bottom frames\n for (i = 1; i < width - 1; i++) {\n chars += TerminalFrame.FRAME_SYMBOLS.HORIZONTAL;\n }\n\n term\n // print the top frame\n .move(2, 0)\n .print(chars)\n // print the bottom frame\n .move(2, height)\n .print(chars)\n ;\n\n const sideChar = TerminalFrame.FRAME_SYMBOLS.VERTICAL;\n\n // print the left and right frames\n for (i = 2; i < height; i++) {\n term\n // left frame\n .move(0, i)\n .print(sideChar)\n // right frame\n .move(width - 1, i)\n .print(sideChar)\n ;\n }\n\n // draw corners\n term\n // top left\n .move(0, 0)\n .print(TerminalFrame.FRAME_SYMBOLS.TOP_LEFT_CORNER)\n // top right\n .move(width, 0)\n .print(TerminalFrame.FRAME_SYMBOLS.TOP_RIGHT_CORNER)\n // bottom left\n .move(0, height)\n .print(TerminalFrame.FRAME_SYMBOLS.BOTTOM_LEFT_CORNER)\n // bottom right\n .move(width, height)\n .print(TerminalFrame.FRAME_SYMBOLS.BOTTOM_RIGHT_CORNER)\n ;\n }", "function frameReset() {\n myConsole.getVideo().clearBuffers(); // Clear frame buffers\n\n myFramePointer = 0; // Reset pixel pointer and drawing flag\n\n // Calculate color clock offsets for starting and stoping frame drawing\n //myStartDisplayOffset = JsConstants.CLOCKS_PER_LINE_TOTAL * getYStart();\n // myStopDisplayOffset = myStartDisplayOffset + (JsConstants.CLOCKS_PER_LINE_TOTAL * getDisplayHeight());\n\n // Reasonable values to start and stop the current frame drawing\n myClockWhenFrameStarted = mySystem.getCycles() * JsConstants.CLOCKS_PER_CPU_CYCLE; //now\n myClockStartDisplay = myClockWhenFrameStarted + (JsConstants.CLOCKS_PER_LINE_TOTAL * getYStart()); //what the clock will be when the visible part of the frame starts\n myClockStopDisplay = myClockWhenFrameStarted + (JsConstants.CLOCKS_PER_LINE_TOTAL * (getYStart() + getDisplayHeight())); //when the visible part of the frame stops\n myClockAtLastUpdate = myClockWhenFrameStarted;\n myClocksToEndOfScanLine = JsConstants.CLOCKS_PER_LINE_TOTAL; //currently at beginning of a line\n myVSYNCFinishClock = 0x7FFFFFFF;\n myScanlineCountForLastFrame = 0;\n myCurrentScanline = 0; //currently on the first line\n\n myFrameXStart = 0; // Hardcoded in preparation for new TIA class\n //myFrameWidth = JsConstants.CLOCKS_PER_LINE_VISIBLE; // Hardcoded in preparation for new TIA class\n }", "function frameRate(fps) {\n timer = window.setInterval(updateCanvas,1000/fps);\n }", "async start() {\n let path;\n try {\n path = await this.ffmpeg.frame(this.state, this.light.state);\n }\n catch (err) {\n this.log.error(err, 'FILMOUT', true, true);\n throw err;\n }\n if (this.server.displayImage(path)) {\n await delay_1.delay(20);\n return;\n }\n await this.display.show(path);\n await delay_1.delay(20);\n }", "loop() {\n if (document.hidden) { this.running = false }\n\n let now = Date.now(),\n delta = now - (this.lastRender || now)\n this.lastRender = now;\n\n if (this.running) {\n this.draw(delta)\n this.frames++\n }\n\n requestAnimationFrame(() => this.loop());\n\n // Display fps and position\n if (now - this.lastFps > 999) {\n this.fpsMeter.innerText = this.frames\n this.lastFps = now;\n this.frames = 0;\n }\n }", "function takeSampleShot( m, listener ){\n var w = m.sampleWaitTime;\n var p = m.splitPositions;\n var s = m.sampleShots;\n var dom = m.dom;\n var l = m.splitLength;\n var b = m.blockLength;\n var i = 0;\n\n //Create canvas for take shot\n var cnv = document.createElement( \"canvas\" );\n cnv.width = m.width;\n cnv.height = m.height;\n var ctx = cnv.getContext( '2d' );\n \n //Seek media to zero\n dom.currentTime = 0;\n \n (function(){\n var f = arguments.callee;\n dom.currentTime = p[i];\n dom.play();\n setTimeout( function(){\n //dom.pause();\n }, w/2 );\n setTimeout( function(){\n \n //to avoid issue( the first frame does not be captured ), render additional one frame\n ctx.drawImage( dom, 0, 0, 1, 1 );\n \n //Render frame on canvas and capture it\n ctx.drawImage( dom, 0, 0, m.width, m.height );\n s.push( ctx.getImageData( 0, 0, m.width, m.height ) );\n \n i++;\n \n //Repeat phase (use timer not to block browser content rendering)\n if( i < l ){\n setTimeout( f, 10 );\n \n //Move to netxt phase\n }else{\n dom.pause();\n listener( m );\n }\n \n }, w );\n \n //Show progress\n setProgress( 'Capturing frame shot...', i / l );\n \n })();\n \n}", "@action \n executeTicks(ticksToRun: number) {\n this.frameRateRecorder.recordFrame()\n for (var i = 0; i < ticksToRun; i++) {\n this.tick()\n }\n this.board.setDistanceToSelectedUnit()\n }", "_frame () {\n this._drawFrame()\n if (!this.paused) {\n if (this.frameCount % 4 === 0) {\n this._updateGeneration()\n this.matrix = this.nextMatrix\n this.nextMatrix = this._createMatrix()\n this.counter.innerText = 'Generation: ' + this.generationNumber\n }\n }\n this.frameCount++\n requestAnimationFrame(this._frame)\n }", "function FPS() {\n\t\tresize();\n\t\ttimeouts();\n\t\t(CS.tab === 'game' && S && S.firstTick && CS.enableGraphics) && R.drawCanvas();\n\t\t$timeout(FPS, Math.round(1000/CS.FPS));\n\t}", "beginFrame() {\n\t this.currentFrameNumber++;\n\t this.emit(GameEvent.BeginFrame, this.currentFrameNumber);\n\t this.beginTurn();\n\t }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getEmailSentUI shows the "email sent" page.
function getEmailSentUI() { fetch('/api/emailSent', { method: 'GET' }).then(response => response.text()) .then(res => { var mainBody = document.getElementById('main-body'); mainBody.innerHTML = res; selectIcon('home'); }); }
[ "function onEmailSent() {\n this.notifyAll(new Event(Config.DOWNLOAD_POPUP_VIEW.EVENT.EMAIL_SENT, {\n insertedEmail: this.emailInput.value,\n }));\n}", "function showEmail() {\n\tconst emailHTML = '<a href=\"mailto:contact@oxfordopenfreshers.online\">contact@oxfordopenfreshers.online</a>';\n\t$('.info-email').html(emailHTML);\n}", "function send() {\n if (!$('#hiddenAddThisForEmail').length)\n $('body').append('<div id=hiddenAddThisForEmail class=\"addthis_toolbox\" style=\"display: none;\"><a class=\"addthis_button_email\"></a></div>');\n $('#hiddenAddThisForEmail').attr({\n 'addthis:url': url,\n 'addthis:title': title\n });\n addthis.toolbox('#hiddenAddThisForEmail');\n $('#hiddenAddThisForEmail a.addthis_button_email').click();\n }", "function showVerificationEmailSentModal(username)\n{\n var header = labels.email_sent ;\n var body = '<p style=\"width:320px\">' + sprintf(labels.an_email_has_been_sent_to, username) + '</p>';\n \n var footer = '<div class=\"button\" onclick=\"hideModalContainer()\">' + labels.ok + '</div>';\n \n displayModalContainer(body, header, footer);\n}", "function onSendButtonClicked() {\n let event = new Event(Config.FORGOT_PASSWORD_VIEW.EVENT.SEND_BUTTON_CLICKED, this.emailField.value);\n this.notifyAll(event);\n}", "showEmail() {\n this.set('view', 'email');\n }", "function sendemail(){\t\n\t\n\t\t// make ajax request to post data to server; get the promise object for this API\n\t\tvar request = WmsPost.newAjaxRequest('/wms/x-services/email', formToJSON());\n\t\n\t\t// register a function to get called when the data is resolved\n\t\trequest.done(function(data,status,xhr){\n\t\t\tconsole.log(\"Email sent successfully!\");\n\t\t\tlocation.href = \"emailthankyou.html\";\n\t\t});\n\n\t\t// register the failure function\n\t\trequest.fail(function(xhr,status,error){\n\t\t\tconsole.error(\"The following error occured: \"+ status, error);\n\t\t\talert(\"Problem occured while sending email: \" + error);\n\t\t});\n\t\t//hideLoader();\n\n\t}", "function contactEmailSentAlert() {\n\t\t\t$(\".contact-email-sent-alert\").show();\n\t\t\tsetTimeout(function() {\n\t\t\t\t$(\".contact-email-sent-alert\").hide();\n\t\t\t}, 10000);\n\t\t}", "async renderEmail () {\n\t\tconst code = this.user.loginCode;\n\t\tthis.subject = `Your sign-in code is ${code}`;\n\t\tthis.content = `\n<html>\nPaste the following code in your IDE to sign into CodeStream.<br/><br/>\n${code}<br/><br/>\nTeam CodeStream<br/><br/>\n</html>\n`;\n\t}", "function sendTestMailClicked() {\n\tvar sendbutton = getObj('testmail_send_button');\n\tif(sendbutton) {\n\t\tsendbutton.value = \"sending...\";\n\t\tsendbutton.disabled = true;\n\t}\n\t\n\tsetTimeout(\"sendTestMail()\", 10);\n}", "function welcomeEmail(){\n emailParams.user_name = userPreferences.userName;\n emailParams.user_email = userPreferences.userEmail;\n emailParams.upcoming_event = \"\";\n emailParams.message = \"\";\n\n sendEmail(emailParams, templateWelcome);\n}", "ShowNotification() {\n this.sdk.ButterBar.showMessage({\n text: \"The email has been reported to your security team. Thank you for keeping us secure!\"\n })\n }", "async renderEmail () {\n\t\tthis.renderOptions = {\n\t\t\tlogger: this.logger,\n\t\t\tuser: this.user,\n\t\t\tuserData: this.userData,\n\t\t\tteamData: this.teamData,\n\t\t\tstyles: this.pseudoStyles,\t// only pseudo-styles go in the <head>\n\t\t\tideLinks: Utils.getIDELinks(),\n\t\t\tlatestNews: this.latestNews,\n\t\t\tunsubscribeLink: this.getUnsubscribeLink(this.user)\n\t\t}\n\t\tthis.content = new WeeklyEmailRenderer().render(this.renderOptions);\n\t\tthis.content = this.content.replace(/[\\t\\n]/g, '');\n\n\t\t// this puts our styles inline, which is needed for gmail's display of larger emails\n\t\tthis.content = Juice(`<style>${this.styles}</style>${this.content}`);\n\t}", "sendEmail() {\n email([EMAIL], null, null, null, null);\n }", "function showEmail(emailObj) {\n let html = '';\n const from = fromFormatter(emailObj.from).join(' ');\n const subject = emailObj.subject || '';\n const date = emailObj.date || '';\n const to = emailObj.to || '';\n const body = emailObj.body.trim() === '<div dir=\"ltr\"><br></div>' ? '<samp>This message could not be read (possibly because it contains an attachment). Please click on \"Open in Gmail\" button at the top to open this email in Gmail.</samp>' : emailObj.body;\n html += '<div id=\"backDiv\"><a class=\"btn btn-primary\" role=\"button\" id=\"backButton\">Back</a><a class=\"btn btn-danger\" role=\"button\" id=\"gmailButton\" href=\"https://mail.google.com/mail/u/0/#inbox/' + emailObj.id + '\" target=\"_blank\">Open In Gmail</a></div><table class=\"table table-bordered\" id=\"emailView\"><tbody><tr><th id=\"emailLabel\">From</th><td>' + from + '</td></tr><tr><th id=\"emailLabel\">To</th><td id=\"emailTo\"><div style=\"overflow:auto; max-height:100px;\">' + to + '</div></td></tr><tr><th id=\"emailLabel\">Date</th><td>' + date + '</td></tr><tr><th id=\"emailLabel\">Subject</th><td>' + subject + '</td></tr><tr><td colspan=\"2\" id=\"emailBody\">' + body + '</td></tbody></table>';\n\n $('#mailbox').hide();\n $('#message').html(html);\n $('#message').show();\n}", "function render_get_user_email() {\n return \"<div class=\\\"email-ask\\\">\" + ui_settings.email_message + \"\\n\" +\n \"<input class='email-address' id='email' onkeypress='bot.email_keypress(event)' type='text' placeholder='Email Address' />\" +\n \"<div class='send-email-button' onclick='bot.send_email()' title='send email'></div></div>\"\n}", "function displayEmailAddressUpdateDialog() {\n if( !ManageWorkOrder.isReadOnly() ) {\n currentEmailCCAddress = reviewViewModel.emailCCAddress();\n currentEmailToAddress = reviewViewModel.emailToAddress();\n\n debug && console.log( \"ManageWorkOrderReview.displayEmailAddressUpdateDialog: Displaying send to e-mail selection dialog\" );\n var dialogHtml = new EJS({url: 'templates/emailaddressupdatedialog' }).render();\n\n Dialog.showDialog({\n mode : 'blank',\n blankContent : dialogHtml,\n width : '700px'\n });\n\n $( '#emailToAddress' ).focus();\n\n // Apply knockout bindings to the dialog\n ko.applyBindings( reviewViewModel, $(\"#emailAddressUpdateDialog\")[0] );\n }\n }", "static sendApprovalRequestedMail(email) {\n let mailOptions = {\n to: email,\n subject: 'Ein neues Unternehmen hat sich registriert',\n html: `<div>\n <p>Hallo Admin,</p>\n <p>bitte melde dich <a href=\"https://ibc-job-portal.cfapps.io/admin/login\">hier</a> in deinem Account an, um neue, offene Registrierungsanfragen zu sehen!</p>\n <p>Viele Grüße</p>\n </div>`\n };\n\n transporter.sendMail(mailOptions, (error, info) => {\n if (error) console.log(error);\n });\n }", "function sendEmail(email) {\n var notifyFailSend = function() {\n $.fancybox.open('<div class=\"manual-email\">' + indiciaData.lang.verificationButtons.requestManualEmail +\n '<div class=\"ui-helper-clearfix\"><span>To:</span> <span>' + email.to + '</span></div>' +\n '<div class=\"ui-helper-clearfix\"><span>Subject:</span> <span>' + email.subject + '</span></div>' +\n '<div class=\"ui-helper-clearfix\"><span>Content:</span><div>' + email.body.replace(/\\n/g, '<br/>') + '</div></div>' +\n '</div>');\n }\n $.ajax({\n url: indiciaData.esProxyAjaxUrl + '/verificationQueryEmail/' + indiciaData.nid,\n method: 'POST',\n data: email\n })\n .done(function (response) {\n $.fancybox.close();\n if (response.status && response.status === 'OK') {\n alert(indiciaData.lang.verificationButtons.emailSent);\n } else {\n notifyFailSend();\n }\n })\n .fail(function() {\n $.fancybox.close();\n notifyFailSend();\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that overrides the default copy behavior. We get the selection and use it, dispose of this registered command (returning to the default editor.action.clipboardCopyAction), invoke
function overriddenClipboardCopyAction(textEditor, edit, params) { //use the selected text that is being copied here getCurrentSelectionEvents(); //dispose of the overridden editor.action.clipboardCopyAction- back to default copy behavior clipboardCopyDisposable.dispose(); //execute the default editor.action.clipboardCopyAction to copy vscode.commands.executeCommand("editor.action.clipboardCopyAction").then(function(){ //console.log("After Copy"); //add the overridden editor.action.clipboardCopyAction back clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction); //context.subscriptions.push(clipboardCopyDisposable); }); }
[ "copySelection() {\n let selectedText = window.getSelection().toString();\n let preparedText = this._prepareTextForClipboard(selectedText);\n atom.clipboard.write(preparedText);\n }", "copyCommand() {\n if (this.selectedKeywords.count > 0) {\n return clipboardCopyPlainText(this.getSelectionsAsJoinedString()).then(null, err => {\n if (!this.handleExceptions || !this.handleExceptions(err)) {\n throw err;\n }\n });\n } else return Promise.resolve();\n }", "copySelection() {\n const selectedText = this.xterm.getSelection();\n atom.clipboard.write(selectedText);\n }", "function copyHandler(){\n clipboardText = cm.getSelection();\n tool.className = '';\n }", "_copy() {\n let editorSession = this.getEditorSession()\n let sel = editorSession.getSelection()\n let doc = editorSession.getDocument()\n let clipboardDoc = null\n let clipboardText = \"\"\n let clipboardHtml = \"\"\n let htmlExporter = this._getExporter()\n if (!sel.isCollapsed()) {\n clipboardText = documentHelpers.getTextForSelection(doc, sel) || \"\"\n clipboardDoc = copySelection(doc, sel)\n clipboardHtml = htmlExporter.exportDocument(clipboardDoc)\n }\n return {\n doc: clipboardDoc,\n html: clipboardHtml,\n text: clipboardText\n }\n }", "_copy() {\n let editorSession = this.getEditorSession()\n let sel = editorSession.getSelection()\n let doc = editorSession.getDocument()\n let clipboardDoc = null\n let clipboardText = \"\"\n let clipboardHtml = \"\"\n if (!sel.isCollapsed()) {\n clipboardText = documentHelpers.getTextForSelection(doc, sel) || \"\"\n clipboardDoc = copySelection(doc, sel)\n clipboardHtml = this.htmlExporter.exportDocument(clipboardDoc)\n }\n return {\n doc: clipboardDoc,\n html: clipboardHtml,\n text: clipboardText\n }\n }", "handleCopyCut(event) {\n event.stopPropagation();\n let activeNode = this.getActiveNode();\n if(!activeNode) return;\n\n // If nothing is selected, say \"nothing selected\" for cut\n // or copy the clipboard to the text of the active node\n if(this.selectedNodes.size === 0) {\n if(event.type == 'cut') {\n this.say(\"Nothing selected\");\n return false;\n } else if(event.type == 'copy') {\n this.clipboard = this.cm.getRange(activeNode.from, activeNode.to);\n }\n // Otherwise copy the contents of selection to the buffer, first-to-last\n } else {\n let sel = [...this.selectedNodes].sort((a, b) => poscmp(a.from, b.from));\n this.clipboard = sel.reduce((s,n) => s + this.cm.getRange(n.from, n.to)+\" \",\"\");\n }\n\n this.say((event.type == 'cut'? 'cut ' : 'copied ') + this.clipboard);\n this.buffer.value = this.clipboard;\n this.buffer.select();\n try {\n document.execCommand && document.execCommand(event.type);\n } catch (e) {\n console.error(\"execCommand doesn't work in this browser :(\", e);\n }\n // if we cut selected nodes, clear them\n if (event.type == 'cut') { this.deleteSelectedNodes(); } // delete all those nodes\n event.altKey = event.ctrlKey = true; // fake the event so selection isn't lost...\n this.activateNode(activeNode, event); // ...during activateNode\n }", "onKeyPressed(event){\n switch(event.keyCode){\n case 27: /** ESCAPE pressed */\n this.command.reset();\n break;\n case 67: /** Key C pressed - perform Copy */\n if(event.isCtrlDown){\n this.command.context.chain.updatePixels();\n this.command.selectedData = this.command.context.chain.get(\n this.command.selectionBBox.x,\n this.command.selectionBBox.y,\n this.command.selectionBBox.width,\n this.command.selectionBBox.height\n );\n }\n break;\n case 86: /** Key V pressed - perform Paste */\n if(event.isCtrlDown){\n if(!this.command.selectedData) return; //If nothing is selected, don't move\n this.command.state = this.command.stateFactory.getPasteState(this.command);\n this.command.state.onKeyPressed(event);\n }\n break;\n case 88: /** Key X pressed - perform Cut */\n if(event.isCtrlDown){\n if(event.isCtrlDown){\n this.command.context.chain.updatePixels();\n\n this.command.selectedData = this.command.context.chain.get(\n this.command.selectionBBox.x,\n this.command.selectionBBox.y,\n this.command.selectionBBox.width,\n this.command.selectionBBox.height\n );\n\n /** Replace the selection with a rectangle, filled with background colour */\n this.command.context.chain.push();\n this.command.context.chain.fill(255);\n this.command.context.chain.noStroke();\n\n this.command.context.chain.rect(\n this.command.selectionBBox.x,\n this.command.selectionBBox.y,\n this.command.selectionBBox.width,\n this.command.selectionBBox.height\n );\n this.command.context.chain.pop();\n }\n }\n break;\n }\n }", "function copyToClipboard() {\n var node = $('#theModal .command-line').get(0);\n selectContent(node);\n document.execCommand('copy');\n }", "_copy() {\n this._clipboard.length = 0;\n algorithm_1.each(this.selectedItems(), item => {\n this._clipboard.push(item.path);\n });\n }", "onCopy() {\n this.commands.exec(\"copy\", this);\n }", "function copySelection() {\n\tcopiedEndX = endX;\n\tcopiedEndY = endY;\n\n\tcopiedStartX = startX;\n\tcopiedStartY = startY;\n\t// Getting the selected pixels\n\tclipboardData = currentLayer.context.getImageData(startX, startY, endX - startX + 1, endY - startY + 1);\n}", "_copy() {\n this._clipboard.length = 0;\n each(this.selectedItems(), item => {\n this._clipboard.push(item.path);\n });\n }", "pasteFromMenu() {\n var selection = this.selection,\n text = this.copyPasteHandler.copiedValue,\n caretPosition = this.caretPosition;\n\n if(text) {\n if(selection) {\n this.selection = undefined;\n this.sequence.deleteBases(\n selection[0],\n selection[1] - selection[0] + 1\n );\n }\n this.sequence.insertBases(text, caretPosition);\n this.displayCaret(caretPosition + text.length);\n this.focus();\n }\n }", "_copy() {\n let surface = this.getSurface()\n let sel = surface.getSelection()\n let doc = surface.getDocument()\n let clipboardDoc = null\n let clipboardText = \"\"\n let clipboardHtml = \"\"\n if (!sel.isCollapsed()) {\n clipboardText = documentHelpers.getTextForSelection(doc, sel) || \"\"\n clipboardDoc = surface.copy(doc, sel)\n clipboardHtml = this.htmlExporter.exportDocument(clipboardDoc)\n }\n return {\n doc: clipboardDoc,\n html: clipboardHtml,\n text: clipboardText\n }\n }", "shareResultForumCopyButtonClickHandler() {\n UI.$shareResultForum.select();\n document.execCommand(\"copy\");\n }", "function addExecCommand(document) {\n\n document.execCommand = (command) => {\n switch (command) {\n\n case 'copy':\n document._clipboard = document._selectedNode.textContent\n\n // No default\n\n }\n }\n}", "function Copy() {\n\tcanvas.getActiveObject().clone(function(cloned) {\n\t\t_clipboard = cloned;\n\t});\n}", "function copySelectedPureText(){\n copyToClipboard(getSelectedObject().innerText);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the input into an array of teams and into key value pairs of cities and scores. Returns null in case of a parsing error.
function parseInput( input_text ){ teams = []; scores = {}; cities = {}; const rows = input_text.split( "\n" ); if( rows.length < 2 ) return null; for( let i = 0; i < rows.length; i++ ){ console.log( "row = " + rows[i] ); if( rows[i] === "" ) continue; const columns = rows[i].split( ";" ); if( columns.length !== 2 ) return null; const teamName = $.trim( columns[0] ); teams.push( teamName ); // Can't have duplicate teams! if( teamName in cities ) return null; cities[teamName] = $.trim( columns[1] ); scores[teamName] = 0; } shuffle( teams ); return true; }
[ "parseForTeamsAndScores() {\n let skipIndexes = 0;\n\n // For every index in inputString, find groups of alphabetic letters\n // that correspond to team names. Additionally, find groups of numbers\n // that correspond to scores. Push both of these to arrays within the.\n // class. SkipIndexes is used to skip indexes already taken into\n // consideration in nested loops.\n for (let i = 0; i < this.inputString.length; i++) {\n if (skipIndexes) {\n skipIndexes--;\n continue;\n }\n\n if (this.inputString[i].match(/[a-z]/i)) {\n let teamName = '';\n let k = i;\n while (this.inputString[k].match(/[a-z]/i) || this.inputString[k] === ' ' || this.inputString[k] === '.' || this.inputString[k] === '-') {\n teamName += this.inputString[k];\n k++\n skipIndexes++;\n }\n\n teamName = teamName.substring(0, teamName.length - 1);\n this.gameTeams.push(teamName);\n skipIndexes--;\n continue;\n }\n\n if (this.inputString[i].match(/\\d+/g)) {\n let teamScore = '';\n let k = i;\n while (this.inputString[k].match(/\\d+/g)) {\n teamScore += this.inputString[k];\n k++\n skipIndexes++;\n }\n\n this.gameScores.push(teamScore);\n continue;\n }\n\n }\n }", "function parseTeamsNames(url) {\n return _.chain(url)\n .split('/') // split into an array of url segments\n .thru(function(arr) {\n return _.last(arr); // get 2 teams names in the last segment\n })\n .split('-') // split the teams names into an array\n .thru(function(arr) {\n return arr.slice(1).join(' ').split(' vs '); // remove the match id, returns array of 2 names\n })\n .map(function(name) {\n return name.replace(/\\w\\S*/g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n })\n .value();\n}", "resolve(players) {\n const scoresArray = [ ...this.computePlayerScores(players) ];\n\n // (1) Sort the |scoresArray| in descending order based on the scores. That gives us the\n // rankings based on which we can divide the teams.\n scoresArray.sort((left, right) => {\n if (left[1] === right[1])\n return 0;\n \n return left[1] > right[1] ? -1 : 1;\n });\n\n // (2) Now even/odd divide each of the players. Begin by assigning the top player to team\n // Alpha, and then work our way down the list. A future improvement on this algorithm would\n // be to allow uneven participant counts from initial division.\n const teams = [];\n\n let currentTeam = DeathmatchGame.kTeamAlpha;\n for (const [ player, score ] of scoresArray) {\n teams.push({ player, team: currentTeam });\n\n if (currentTeam === DeathmatchGame.kTeamAlpha) {\n this.#teamAlpha_.add(player);\n this.#teamAlphaScore_ += score;\n\n currentTeam = DeathmatchGame.kTeamBravo;\n\n } else {\n this.#teamBravo_.add(player);\n this.#teamBravoScore_ += score;\n\n currentTeam = DeathmatchGame.kTeamAlpha;\n }\n }\n\n // (3) Return the |teams| per the API contract, and we're done.\n return teams;\n }", "function parseGames(input, options = { startRule: \"games\" }) {\n\t function handleGamesAnomaly(parseTree) {\n\t if (!Array.isArray(parseTree))\n\t return [];\n\t if (parseTree.length === 0)\n\t return parseTree;\n\t let last = parseTree.pop();\n\t if ((last.tags !== undefined) || (last.moves.length > 0)) {\n\t parseTree.push(last);\n\t }\n\t return parseTree;\n\t }\n\t function postParseGames(parseTrees, input, options = { startRule: \"games\" }) {\n\t return handleGamesAnomaly(parseTrees);\n\t }\n\t const gamesOptions = Object.assign({ startRule: \"games\" }, options);\n\t let result = PegParser.parse(input, gamesOptions);\n\t if (!result) {\n\t return [];\n\t }\n\t postParseGames(result, input, gamesOptions);\n\t result.forEach((pt) => {\n\t postParseGame(pt, input, gamesOptions);\n\t });\n\t return result;\n\t}", "function TeamScore() {\n\tthis.team; // team name\n\tthis.season; // season year\n\tthis.type; // season type\n\tthis.w; // wins \n\tthis.l; // losses\n\tthis.t; // ties\n}", "function calculateScores(team) {\n let team_matches = stand_data[team];\n let overall_scores = []; // an array of each score for each match\n let num_hatches = []; // num of hatch for a match\n let num_cargo = []; // num of cargo for a match\n for (let match_index in team_matches) {\n let match = team_matches[match_index];\n overall_scores.push(calculateScore(match));\n num_hatches.push(calculateNumGamePieces(match, \"Hatch\"));\n num_cargo.push(calculateNumGamePieces(match, \"Cargo\"));\n }\n return [overall_scores, num_hatches, num_cargo];\n}", "function getScoreFromTeamNamePair(awayTeam, homeTeam, data)\n{\n\tvar idx = getGameDataJsonFragment('LineScore', data);\n\tvar abbrIdx = getIndexFromHeaderArray(data.resultSets[idx].headers, 'TEAM_ABBREVIATION');\n\tvar ptsIdx = getIndexFromHeaderArray(data.resultSets[idx].headers, 'PTS');\n\n\tvar awayScore;\n\tvar homeScore;\n\tfor(var i = 0; i < data.resultSets[idx].rowSet.length; i++)\n\t{\t\t\n\t\tif(data.resultSets[idx].rowSet[i][abbrIdx] == awayTeam)\n\t\t{\n\t\t\tawayScore = data.resultSets[idx].rowSet[i][ptsIdx];\n\t\t}\n\t\telse if(data.resultSets[idx].rowSet[i][abbrIdx] == homeTeam)\n\t\t{\n\t\t\thomeScore = data.resultSets[idx].rowSet[i][ptsIdx];\n\t\t}\n\n\t\tif(!!awayScore && !!homeScore)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t//if both are -1, the game hasn't started yet\n\tif(!awayScore && !homeScore)\n\t{\n\t\tawayScore = '&#8213;';\n\t\thomeScore = '&#8213;';\n\t}\n\n\tvar scoreObj = {};\n\tscoreObj.awayscore = String(awayScore);\n\tscoreObj.homescore = String(homeScore);\n\n\treturn scoreObj;\n}", "function buildTeamsArray()\n{\n TEAMS_ARRAY = new Array(N_TEAMS);\n for (var i = 0; i < N_TEAMS; ++i)\n {\n TEAMS_ARRAY[i] = new Array(4); // Contents: 'centreID', 'teamID', 'teamName'.\n\n TEAMS_ARRAY[i]['centreID' ] = Number(getNextWordFromCodedData());\n eatWhiteSpaceFromCodedData();\n TEAMS_ARRAY[i]['teamID' ] = Number(getNextWordFromCodedData());\n eatWhiteSpaceFromCodedData();\n TEAMS_ARRAY[i]['n_matches'] = Number(getNextWordFromCodedData());\n eatWhiteSpaceFromCodedData();\n TEAMS_ARRAY[i]['teamName' ] = getRemainingLineFromCodedData();\n\n // Find Country and State in which this team's centre resides.\n var countryAndStateIDs = getCountryIdByCentreId(TEAMS_ARRAY[i]['centreID']);\n if (countryAndStateIDs == undefined)\n error('No centre found for given centreID in \"icdb_title_page.php::buildTeamsArray()\".');\n\n // Set Country and State ID.\n TEAMS_ARRAY[i]['countryID'] = countryAndStateIDs[0];\n TEAMS_ARRAY[i]['stateID' ] = countryAndStateIDs[1];\n }\n}", "function parseTournament(data) {\r\n //Get our table body to add rows to it\r\n var tableBody = $(\"#standings\").find(\"tbody\")[0];\r\n\r\n //Go though each match and check the details\r\n $(data).find(\"match\").each(function() {\r\n //Get the details from the match\r\n var name1 = $(this).find(\"team\")[0].textContent;\r\n var name2 = $(this).find(\"team\")[1].textContent;\r\n var score1 = $(this).find(\"team\").eq(0).attr(\"score\");\r\n var score2 = $(this).find(\"team\").eq(1).attr(\"score\");\r\n\r\n //Check if we already have team1, if not create it and add it to our array\r\n if(!containsTeam(name1)) {\r\n teams.push(new Team(name1));\r\n }\r\n\r\n //Check if we already have team2, if not create it and add it to our array\r\n if(!containsTeam(name2)) {\r\n teams.push(new Team(name2));\r\n }\r\n\r\n //Check if the match has been played (there is a score) and update both teams details\r\n if(score1 !== undefined && score2 !== undefined) {\r\n updateTeam(getTeam(name1), score1, score2);\r\n updateTeam(getTeam(name2), score2, score1);\r\n }\r\n\r\n });\r\n\r\n //Work out the points for each team\r\n $.each(teams, function(index, team) {\r\n team.diff = team.gfor - team.gagainst;\r\n team.points = (2 * team.won) + team.drawn;\r\n });\r\n\r\n //Sort the teams by points (then difference) in descending order\r\n teams.sort(function(team1, team2) {\r\n //Sort first by points\r\n if(team1.points > team2.points) {\r\n return -1;\r\n }\r\n if(team1.points < team2.points) {\r\n return 1;\r\n }\r\n\r\n //If points are equal, sort by difference\r\n if(team1.diff > team2.diff){\r\n return -1;\r\n }\r\n if(team1.diff < team2.diff) {\r\n return 1;\r\n }\r\n\r\n //If everything is still equal, return no difference\r\n return 0;\r\n });\r\n\r\n //Add the teams to the results table\r\n $.each(teams, function(index, team) {\r\n //Add a plus sign to positive differences\r\n if(team.diff > 0) {\r\n team.diff = \"+\" + team.diff;\r\n }\r\n\r\n //Add the teams to the results table\r\n $(tableBody).append(\"<tr>\" +\r\n \"<td>\" + (index+1) + \"</td>\" +\r\n \"<td>\" + team.name + \"</td>\" +\r\n \"<td>\" + team.played + \"</td>\" +\r\n \"<td>\" + team.won + \"</td>\" +\r\n \"<td>\" + team.drawn + \"</td>\" +\r\n \"<td>\" + team.lost + \"</td>\" +\r\n \"<td>\" + team.gfor+ \"</td>\" +\r\n \"<td>\" + team.gagainst + \"</td>\" +\r\n \"<td>\" + team.diff + \"</td>\" +\r\n \"<td>\" + team.points + \"</td>\" +\r\n \"</tr>\");\r\n });\r\n }", "static parse(line) {\n\n let gameResult = null;\n\n if (line == null || typeof(line) !== 'string' || line.length === 0) {\n throw new Error(\"line is not a valid string\")\n }\n\n // single line format: Robots 3, Spammers 3\n const parts = line.split(\",\")\n if (parts.length === 2) {\n let firstTeamScore = GameResult._parseTeamScore(parts[0])\n let secondTeamScore = GameResult._parseTeamScore(parts[1])\n\n if (firstTeamScore != null && secondTeamScore != null) {\n gameResult = new GameResult(firstTeamScore.name, firstTeamScore.score, secondTeamScore.name, secondTeamScore.score)\n }\n }\n\n return gameResult\n }", "function parseMatchDetails()\n{\n var details = {};\n var championshipMatchRegex = /.*\\/championships\\/(\\d+)\\/match\\/(\\d+)/;\n var championship = window.location.pathname.match(championshipMatchRegex)[1];\n var matchId = window.location.pathname.match(championshipMatchRegex)[2];\n\n details.championship = championship;\n details.match = matchId;\n details.homeTeam = {};\n details.awayTeam = {};\n\n details.homeTeam.name = removeDiacritics($('div:regex(class, index__homeTeamClubName___.*) > span')[0].innerText);\n details.awayTeam.name = removeDiacritics($('div:regex(class, index__awayTeamClubName___.*) > span')[0].innerText);\n\n details.homeTeam.score = $('div:regex(class, index__scores___.*) > div > div')[0].innerText;\n details.awayTeam.score = $('div:regex(class, index__scores___.*) > div > div')[1].innerText;\n \n //looking for the home team scorers\n details.homeTeam.scorers = {};\n details.homeTeam.goleadores = {};\n $('div:regex(class, index__goalHome___.*) > div').each(function( i, el ) {\n var scorer = removeDiacritics(el.innerText.trim());\n var goals = $(this).find('span:regex(class, index__ball___.* )').length;\n details.homeTeam.scorers[scorer] = goals;\n details.homeTeam.goleadores[i] = {'player' : scorer, 'goals' : goals};\n });\n\n //looking for the away team scorers\n details.awayTeam.scorers = {};\n details.awayTeam.goleadores = {};\n $('div:regex(class, index__goalAway___.*) > div').each(function( i, el ) {\n var scorer = removeDiacritics(el.innerText.trim());\n var goals = $(this).find('span:regex(class, index__ball___.* )').length;\n details.awayTeam.scorers[scorer] = goals;\n details.awayTeam.goleadores[i] = {'player' : scorer, 'goals' : goals};\n });\n\n //looking for home team ratings and aggregating the goals\n details.homeTeam.players = {};\n var scoreNameRegex = /([0-9]+)\\s{2}(\\D+)/;\n $('div:regex(class, index__pitchHome___.*) > div').each(function( i, el ) {\n $(this).find('div:regex(class, index__player___.* )').each(function( i, element ) {\n var top = $(this).offset().top;\n var matchText = element.innerText.replace(/\\n/g,\" \");\n if(scoreNameRegex.test(matchText)) {\n var player = {};\n var matchData = scoreNameRegex.exec(matchText);\n player.name = removeDiacritics(matchData[2].trim());\n player.rating = matchData[1];\n player.starter = true;\n if (top > 800) {\n //change that someday, maybe take window height into account\n player.starter = false;\n }\n //did this guy score ? \n $.each(details.homeTeam.scorers, function(scorer, score) {\n if (scorer == player.name) {\n //yes, attaboy! let's add it to its match details\n player.goals = score;\n delete details.homeTeam.scorers[scorer];\n }\n });\n details.homeTeam.players[player.name] = player;\n }\n });\n });\n\n //looking for away team ratings and aggregating the goals\n details.awayTeam.players = {};\n $('div:regex(class, index__pitchAway___.*) > div').each(function( i, el ) {\n $(this).find('div:regex(class, index__player___.* )').each(function( i, element ) {\n var top = $(this).offset().top;\n var matchText = element.innerText.replace(/\\n/g,\" \");\n if(scoreNameRegex.test(matchText)) {\n var player = {};\n var matchData = scoreNameRegex.exec(matchText);\n player.name = removeDiacritics(matchData[2].trim());\n player.rating = matchData[1];\n player.starter = true;\n if (top > 800) {\n player.starter = false;\n }\n //did this guy score ? \n $.each(details.awayTeam.scorers, function(scorer, score) {\n if (scorer == player.name) {\n //yes, attaboy! let's add it to its match details\n player.goals = score;\n delete details.awayTeam.scorers[scorer];\n }\n });\n details.awayTeam.players[player.name] = player;\n }\n });\n });\n\n //if some scorers are still in the arrays it means that they scored against their own camp (suckers!)\n $.each(details.homeTeam.scorers, function(scorer, score) {\n details.awayTeam.players[scorer].ownGoals = score;\n delete details.homeTeam.scorers[scorer];\n });\n $.each(details.awayTeam.scorers, function(scorer, score) {\n details.homeTeam.players[scorer].ownGoals = score;\n delete details.awayTeam.scorers[scorer];\n });\n //we purged the scorers array to detect the o.g. let's make things clean now\n details.homeTeam.scorers = details.homeTeam.goleadores;\n details.awayTeam.scorers = details.awayTeam.goleadores;\n delete details.homeTeam.goleadores;\n delete details.awayTeam.goleadores;\n\n return JSON.stringify(details);\n}", "calculateTeamScores(msg, serverInfo, typeSolo, typeDuo, typeSquad){\n var teamPoints = [] // our array of teams and their total points, to be returned.\n\n // Pointers.\n var scrimGames = serverInfo.currentScrim // GAMEIDS\n\t\tvar scrimPlacements = serverInfo.scrimPlacements // PLACEMENTS\n\n // Grab our point structure and saved leaderboard info.\n var infos = teamModule.returnInfoTypes(serverInfo, typeSolo, typeDuo, typeSquad)\n var pointInfo = infos[0], leadInfo = infos[1]\n\n // For reference, this is what scrimPlacements looks like:\n /*\n scrimPlacements: [ - LEVEL 1\n \"game1\": [ - LEVEL 2\n \"cool gameid\": [ - LEVEL 3\n \"team1 data\": {} - LEVEL 4\n ]\n ]\n ]\n */\n\n // We rely on the fact that indexes between game number and placement number are the same - as in, if we are looking at placement game 1 (scrimPlacements), the currentScrim index should correlate to the same game.\n\n // Start at level 1, create a for loop to iterate over ever game (where game refers to a round - i.e. when all players press \"play\" that is the beginning of a game.)\n // Could be a .forEach() loop but I prefer this loop in this instance.\n for (var gameNum in scrimPlacements){\n var curPlacements = scrimPlacements[gameNum].placements\n for (var id in curPlacements){ // Level 2, looking at each specific gameid.\n var gameid = curPlacements[id].gameID // Grab the GameID for later use.\n for (var team in curPlacements[id].teams){ // Level 3, looking at each individual team now.\n var teamInfo = curPlacements[id].teams[team] // \"Now\" at Level 4, at each persons data. Realistically Level 1 doesn't really exist in this explanation and our first for loop actually starts at level 2. But anyway.\n\n var teamid = teamInfo.teamID\n var placement = teamInfo.placement\n var kills = teamInfo.kills\n\n // Copy-paste below.\n\n // Check how many people were in their lobby.\n\t\t\t\t\tvar lobbyAmount = 0\n\t\t\t\t\tfor (var j=0; j < scrimGames[gameNum].games.length; j++){ // for each gameid in currentScrim\n\t\t\t\t\t\tif (scrimGames[gameNum].games[j].teams.includes(teamid)){ // if the current iterated gameid group in currentScrim contains the teamID of the placement we're looking at:\n\t\t\t\t\t\t\tlobbyAmount = scrimGames[gameNum].games[j].teams.length\n\t\t\t\t\t\t\tbreak // shouldn't have anymore values anyway.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n // Let's just check that they actually have a valid lobby.\n if (lobbyAmount <= 0){\n if (typeSquad){\n msg.reply(\"something went wrong! Team \" + msg.guild.roles.get(teamid) + \" has a placement with no associated game!\")\n }\n else if (typeDuo){\n // TODO implement duo system.\n msg.reply(\"something went wrong! Team \" + getDuoInfo(serverInfo.duoTeams, teamid).name + \" has a placement with no associated game!\")\n }\n else{\n msg.reply(\"something went wrong! \" + msg.guild.members.get(teamid) + \" has a placement with no associated game!\")\n }\n }\n\n\t\t\t\t\t// At this point, we should have how many people were in their lobby.\n\t\t\t\t\t// Let's see how many points to give them.\n\t\t\t\t\tvar teamScore = 0\n\n var linearSystem = false\n\t\t\t\t\tvar linearSystemKills = false\n if (\"useLinear\" in serverInfo){\n if (serverInfo.useLinear){\n linearSystem = true\n }\n }\n\n\t\t\t\t\tif (\"useLinearKills\" in serverInfo){\n\t\t\t\t\t\tif (serverInfo.useLinearKills){\n\t\t\t\t\t\t\tlinearSystemKills = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n if (linearSystem && !typeSquad){ // could combine into one if, but it'd be not very neat.\n if (typeSolo){\n teamScore += lobbyAmount * Math.pow(0.9, (placement-1))\n\t\t\t\t\t\t\tif (linearSystemKills){\n\t\t\t\t\t\t\t\tteamScore += lobbyAmount * 0.15 * kills\n\t\t\t\t\t\t\t}\n }\n else if (typeDuo){\n teamScore += lobbyAmount * Math.pow(0.8, (placement-1))\n\t\t\t\t\t\t\tif (linearSystemKills){\n\t\t\t\t\t\t\t\tteamScore += lobbyAmount * 0.11 * kills\n\t\t\t\t\t\t\t}\n }\n else{\n return msg.reply(\"something went wrong! The linear scoring algorithm was being used in a squad game! This should not occur!\")\n }\n }\n else{\n for (var points in pointInfo){\n if (pointInfo[points].minTeams <= lobbyAmount){\n \t\t\t\t\t\t\tif (placement == 1){\n \t\t\t\t\t\t\t\tteamScore += pointInfo[points].firstPoints\n \t\t\t\t\t\t\t\t// Give them points for kills\n \t\t\t\t\t\t\t\tif (kills > 0 && pointInfo[points].killsPerPoints > 0){ // so we don't divide by 0.\n \t\t\t\t\t\t\t\t\t// I figured this out. If you divide by the amount of kills per points, then floor, you'll have many times points you want.\n \t\t\t\t\t\t\t\t\t// Then you multiply to get your total point kills.\n \t\t\t\t\t\t\t\t\tteamScore += (Math.floor((kills / pointInfo[points].killsPerPoints)) * pointInfo[points].pointsPerAmountKills)\n\n \t\t\t\t\t\t\t\t}\n\n \t\t\t\t\t\t\t\tbreak\n\n \t\t\t\t\t\t\t}\n\n \t\t\t\t\t\t\telse if (placement == 2){\n \t\t\t\t\t\t\t\tteamScore += pointInfo[points].secondPoints\n \t\t\t\t\t\t\t\tif (kills > 0 && pointInfo[points].killsPerPoints > 0){ // so we don't divide by 0.\n \t\t\t\t\t\t\t\t\tteamScore += (Math.floor((kills / pointInfo[points].killsPerPoints)) * pointInfo[points].pointsPerAmountKills)\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\tbreak\n \t\t\t\t\t\t\t}\n\n\n \t\t\t\t\t\t\telse if (placement == 3){\n \t\t\t\t\t\t\t\tteamScore += pointInfo[points].thirdPoints\n \t\t\t\t\t\t\t\tif (kills > 0 && pointInfo[points].killsPerPoints > 0){ // so we don't divide by 0.\n \t\t\t\t\t\t\t\t\tteamScore += (Math.floor((kills / pointInfo[points].killsPerPoints)) * pointInfo[points].pointsPerAmountKills)\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\tbreak\n \t\t\t\t\t\t\t}\n\n \t\t\t\t\t\t\telse{ // give them points for kills.\n \t\t\t\t\t\t\t\tif (kills > 0 && pointInfo[points].killsPerPoints > 0){ // so we don't divide by 0.\n \t\t\t\t\t\t\t\t\tteamScore += (Math.floor((kills / pointInfo[points].killsPerPoints)) * pointInfo[points].pointsPerAmountKills)\n\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n }\n\n\n\t\t\t\t\t// For now, we aren't going to save any data, simply add it and display it.\n\n\t\t\t\t\t// Because we are iterating over multiple games, we almost certainly will encounter a team twice.\n\t\t\t\t\t// So, if they already have a value in teamPoints, we want to add to it, otherwise we want to get their saved leaderboard info.\n\n\t\t\t\t\tvar exists = -1\n\t\t\t\t\tfor (var k=0; k < teamPoints.length; k++){\n\t\t\t\t\t\tif (teamPoints[k].team == teamid){\n\t\t\t\t\t\t\texists = k // So we don't have to reiterate over the entire array.\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (exists !== -1){ // they alreauhdy have a value, so add their additional points.\n\t\t\t\t\t\tteamPoints[exists].points += teamScore\n\t\t\t\t\t}\n\n\t\t\t\t\telse {\n\t\t\t\t\t\t// Get their leaderboard info\n\t\t\t\t\t\tvar teamPointInfo = 0\n\t\t\t\t\t\tfor (var teamPast in leadInfo){\n\t\t\t\t\t\t\tif (leadInfo[teamPast].team == teamid){ // if the selected team is the one we want\n\t\t\t\t\t\t\t\tteamPointInfo = leadInfo[teamPast].points // get their previous points.\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar obj = {\n\t\t\t\t\t\t\t\"team\": teamid,\n\t\t\t\t\t\t\t\"points\": Number(teamPointInfo + teamScore)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Push their data.\n\t\t\t\t\t\tteamPoints.push(obj)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n // We also need to iterate over the entire squadLeaderboard to see if the team wasn't a part of the scrims.\n\t\tfor (var leaderboardPlace = 0; leaderboardPlace < leadInfo.length; leaderboardPlace ++){\n\t\t\tvar teamAlreadyIn = false\n\t\t\tfor (var teamInformation in teamPoints){\n\t\t\t\tif (teamPoints[teamInformation].team == leadInfo[leaderboardPlace].team){\n\t\t\t\t\tteamAlreadyIn = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(teamAlreadyIn)){\n\t\t\t\tteamPoints.push(leadInfo[leaderboardPlace])\n\t\t\t}\n\t\t}\n\n\t\t// So hopefully at this point, we now have an array of teamPoints.\n\t\t// We should be able to iterate over this to create an embed.\n\t\t// However, we first want to sort them.\n\t\tteamPoints.sort(module.exports.comparePlacement)\n\t\treturn teamPoints\n\n }", "function result() {\r\n\t// Teams Names Array\r\n\tvar tn = document.getElementsByClassName('teamName');\r\n\tvar teams = [];\r\n\t// Teams First Map Stats Array\r\n\tvar m1k = document.getElementsByClassName('m1k');\r\n\tvar m1p = document.getElementsByClassName('m1p');\r\n\r\n\t// Teams Second Map Stats Array\r\n\tvar m2k = document.getElementsByClassName('m2k');\r\n\tvar m2p = document.getElementsByClassName('m2p');\r\n\t// Teams Second Map Stats Array\r\n\tvar m3k = document.getElementsByClassName('m3k');\r\n\tvar m3p = document.getElementsByClassName('m3p');\r\n\r\n\t// Kill and Placement Stats for All Teams\r\n\tvar kstats = [];\r\n\tvar pstats = [];\r\n\r\n\tvar results = [];\r\n\t// Set Teams that won the map (3 Teams)\r\n\tvar win = [];\r\n\tvar totalp = [];\r\n\tfor (var i = 0; i < tn.length; i++) {\r\n\t\tteams[i] = tn[i].value;\r\n\t\tvar Kills = 0;\r\n\t\tvar placePoints = [];\r\n\r\n\t\tkills = parseInt(m1k[i].value);\r\n\t\tkills += parseInt(m2k[i].value);\r\n\t\tkills += parseInt(m3k[i].value);\r\n\t\tvar place =[];\r\n\r\n\t\tplace.push(m1p[i].value); //[m1p[i].value, m2p[i].value, m3p[i].value];\r\n\t\tplace.push(m2p[i].value);\r\n\t\tplace.push(m3p[i].value);\r\n\r\n\t\tkstats[i] = kills;\r\n\t\t//pstats.push(placePoints);\r\n\r\n\t\tplacePoints = 0;\r\n\t\tfor (var e = 0; e < 3; e++) {\r\n\t\t \tswitch (parseInt(place[e])) {\r\n\t\t\t case 1:\r\n\t\t\t win.push(i);\r\n\t\t\t \tplacePoints += 15;\r\n\t\t\t break;\r\n\t\t\t case 2:\r\n\t\t\t placePoints += 12;\r\n\t\t\t break;\r\n\t\t\t case 3:\r\n\t\t\t placePoints += 10;\r\n\t\t\t break;\r\n\t\t\t case 4:\r\n\t\t\t placePoints += 8;\r\n\t\t\t break;\r\n\t\t\t case 5:\r\n\t\t\t placePoints += 6;\r\n\t\t\t break;\r\n\t\t\t case 6:\r\n\t\t\t placePoints += 4;\r\n\t\t\t break;\r\n\t\t\t case 7:\r\n\t\t\t placePoints += 2;\r\n\t\t\t break;\r\n\t\t\t case 8:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 9:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 10:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 11:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t case 12:\r\n\t\t\t placePoints += 1;\r\n\t\t\t break;\r\n\t\t\t default:\r\n\t\t\t placePoints += 0;\r\n\t\t\t} // End of SWITCH Statement\r\n\t\t} // End of FOR e Loop\r\n\t\tpstats[i] = placePoints;\r\n\r\n\t\ttotalp[i] = kills + placePoints;\r\n\t// Placement Stats for All Teams\r\n\t} // End of FOR i Loop \r\n\r\n\tfor (var c = 0; c < tn.length; c++) {\r\n\t\tresults[c] = {name: teams[c], kp: kstats[c], pp: pstats[c], tp: totalp[c], win: 0};\r\n\t\t// [teams[c], kstats[c], pstats[c], totalp[c], 0];\r\n\r\n\t}\r\n\tfor(var d = 0; d < win.length; d++){\r\n\t\tresults[win[d]].win += 1;\r\n\t}\r\n\r\n\tresults.sort(function (x, y) {\r\n \treturn y.tp - x.tp;\r\n\t});\r\n\t// Create a Loop to put Data from results into the HTML Table\r\n\t// Element\r\n\tfor(var s = 0; s < results.length; s++){\r\n\t\t// Put Team Name\r\n\t\tdocument.getElementsByClassName('tteam')[s].innerHTML = results[s].name\r\n\t\t// Put Team Win\r\n\t\tdocument.getElementsByClassName('twwcd')[s].innerHTML = results[s].win;\r\n\t\t// Put Team Kill Points\r\n\t\tdocument.getElementsByClassName('tkp')[s].innerHTML = results[s].kp;\r\n\t\t// Put Team Placement Points\r\n\t\tdocument.getElementsByClassName('tpp')[s].innerHTML = results[s].pp;\r\n\t\t// Put Total Points\r\n\t\tdocument.getElementsByClassName('ttp')[s].innerHTML = results[s].tp;\r\n\t}\r\n\tdocument.getElementsByClassName('rtable')[0].style.display = 'block';\r\n\tdocument.getElementsByClassName('datat')[0].style.display = 'none';\r\n}", "function getProjectTeams() {\n return {\n \"header\": \"Project Teams\",\n \"teams\": [{\n \"teamName\": \"Robotics\",\n \"description\": \"Here we will teach you from the ground up all the essential skills necessary to build an autonomous robot. You will have the opportunity to both create your own robot as well as contribute to some of the larger scale robotics projects, such as the Octocopter and Tachikoma. This year, we will also be entering the VEX Robotics Competition as well! While this the most intense project group, we are open to all skill levels and encourage you to check us out!\"\n }, {\n \"teamName\": \"Quadcopter\",\n \"description\": \"The Autonomous Quadcopter Drone team focuses on giving students hand's on experience applying techniques from electrical engineering and computer science. Students will get a chance to build and fly a drone using artificial intelligence and computer vision concepts. Eventually students will be able to enter their drone into collegiate competitions!\"\n }, {\n \"teamName\": \"Machine Learning (ML)\",\n \"description\": \"The ML/AI team focuses on teaching and implementing the powerful concepts, methods, and tools from the rapidly growing fields of machine learning, artificial intelligence, and data analysis. The teaching heavy emphasizes both practical usage and fundamental understanding of ML techniques, covering topics from CS to math and statistics. These skills are strengthened through participation in ML/AI competitions, where we code implementations that solve real-world problems.\"\n }, {\n \"teamName\": \"Intelligent Sensor Networks (ISN)\",\n \"description\": \"The ISN team is a new team that will begin in the Fall 2016 semester. Here we combine hardware and software skills to build a network of sensors that can be placed around any room to monitor noise, ambient temperature, record video and even control lights. The goal is to monitor and control these sensors remotely through a web application on your desktop or smartphone. This workshop will be well rounded, involving both full-stack web development for building the monitoring application as well as building and wiring the actual sensor network.\"\n }]\n };\n }", "function getTeamScores(game) {\n if (!game) {\n return [];\n }\n\n // Unpack the teams from the recieved gamestate\n const { teams } = game;\n\n return teams.map((team) => team.properties.score);\n}", "function parseTeamStatsForAbbrs(intext) {\r\n\tvar ptr1, ptr2, ptr3, ptr4, name, abbr; \r\n\r\n\tptr1 = intext.indexOf(\"class=\\\"whiter\\\"\", 0); \r\n\twhile (ptr1 >= 0) {\r\n\t\tptr2 = intext.indexOf(\"myteamno=\", ptr1); \r\n\t\tif (ptr2 < 0) {\r\n\t\t\tbreak; \r\n\t\t}\r\n\t\tptr3 = intext.indexOf(\"\\\">\", ptr2); \r\n\t\tptr4 = intext.indexOf(\"</a>\", ptr3); \r\n\t\tname = intext.substring(ptr3+2, ptr4); \r\n\r\n\t\tptr2 = intext.indexOf(\"<b>\", ptr4); \r\n\t\tptr3 = intext.indexOf(\"</b>\", ptr2+3); \r\n\t\tabbr = intext.substring(ptr2+3, ptr3); \r\n\r\n\t\tteamlist[teamlist.length]=name;\r\n\t\tabbrlist[abbrlist.length]=abbr;\r\n\r\n\t\tptr1=ptr3+4; \r\n\t}\r\n\r\n\tstartFunc();\r\n}", "function processTeamNumbers(data)\n{\n print(\"processTeamNumbers\");\n print(data);\n var dataArray = data.split(\";\");\n dataArray.pop();\n \n for(var dataIndex in dataArray)\n {\n var curData = dataArray[dataIndex];\n var matchNum = parseInt(curData.substring(0, curData.indexOf(\":\")));\n var teams = curData.substring(curData.indexOf(\":\") + 1).split(\",\");\n \n if(matchNum && teams.length === 6)\n teamNumbers[matchNum - 1] = [teams.slice(0, 3), teams.slice(3, 6)];\n \n else\n {\n var alertMsg = \"Oh noes, error reading the team numbers file!\\n\\n\";\n alertMsg += \"Incorrect format: \" + curData;\n alert(alertMsg);\n teamNumbers.push([[1, 2, 3], [4, 5, 6]]); \n }\n \n }\n \n print(teamNumbers);\n updateTeamNumbers();\n}", "function parseTeamStatsForAbbrs(intext) {\n\tvar ptr1, ptr2, ptr3, ptr4, name, abbr, idnum;\n\n\tptr1 = intext.indexOf(\"<th>ANYA</th>\", 0);\n\twhile (ptr1 >= 0) {\n\t\tptr2 = intext.indexOf(\"myteamno=\", ptr1);\n\t\tif (ptr2 < 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tptr3 = intext.indexOf(\"\\\">\", ptr2);\n\t\tidnum = intext.substring(ptr2+9, ptr3);\n\t\tptr4 = intext.indexOf(\"</a>\", ptr3);\n\t\tname = intext.substring(ptr3+2, ptr4);\n\n\t\tptr2 = intext.indexOf(\"<b>\", ptr4);\n\t\tptr3 = intext.indexOf(\"</b>\", ptr2+3);\n\t\tabbr = intext.substring(ptr2+3, ptr3);\n\n\t\tteamlist[idnum-1]=name;\n\t\tabbrlist[idnum-1]=abbr;\n\t\t\n\t\tptr1=ptr3+4;\n\t}\n\n\tstartFunc();\n}", "function parseHours(inputHours) {\r\n var daysOfTheWeek = {\r\n SS: ['saturdays', 'saturday', 'satur', 'sat', 'sa'],\r\n UU: ['sundays', 'sunday', 'sun', 'su'],\r\n MM: ['mondays', 'monday', 'mondy', 'mon', 'mo'],\r\n TT: ['tuesdays', 'tuesday', 'tues', 'tue', 'tu'],\r\n WW: ['wednesdays', 'wednesday', 'weds', 'wed', 'we'],\r\n RR: ['thursdays', 'thursday', 'thurs', 'thur', 'thu', 'th'],\r\n FF: ['fridays', 'friday', 'fri', 'fr']\r\n };\r\n var monthsOfTheYear = {\r\n JAN: ['january', 'jan'],\r\n FEB: ['february', 'febr', 'feb'],\r\n MAR: ['march', 'mar'],\r\n APR: ['april', 'apr'],\r\n MAY: ['may', 'may'],\r\n JUN: ['june', 'jun'],\r\n JUL: ['july', 'jul'],\r\n AUG: ['august', 'aug'],\r\n SEP: ['september', 'sept', 'sep'],\r\n OCT: ['october', 'oct'],\r\n NOV: ['november', 'nov'],\r\n DEC: ['december', 'dec']\r\n };\r\n var dayCodeVec = ['MM','TT','WW','RR','FF','SS','UU','MM','TT','WW','RR','FF','SS','UU','MM','TT','WW','RR','FF'];\r\n var tfHourTemp, tfDaysTemp, newDayCodeVec = [];\r\n var tempRegex, twix, tsix;\r\n var inputHoursParse = inputHours.toLowerCase();\r\n inputHoursParse = inputHoursParse.replace(/paste hours here/i, \"\"); // make sure something is pasted\r\n phlogdev(inputHoursParse);\r\n inputHoursParse = inputHoursParse.replace(/can\\'t parse\\, try again/i, \"\"); // make sure something is pasted\r\n if (inputHoursParse === '' || inputHoursParse === ',') {\r\n phlogdev('No hours');\r\n return false;\r\n }\r\n inputHoursParse = inputHoursParse.replace(/\\u2013|\\u2014/g, \"-\"); // long dash replacing\r\n inputHoursParse = inputHoursParse.replace(/[^a-z0-9\\:\\-\\. ~]/g, ' '); // replace unnecessary characters with spaces\r\n inputHoursParse = inputHoursParse.replace(/\\:{2,}/g, ':'); // remove extra colons\r\n inputHoursParse = inputHoursParse.replace(/closed/g, '99:99-99:99').replace(/not open/g, '99:99-99:99'); // parse 'closed'\r\n inputHoursParse = inputHoursParse.replace(/by appointment only/g, '99:99-99:99').replace(/by appointment/g, '99:99-99:99'); // parse 'appointment only'\r\n inputHoursParse = inputHoursParse.replace(/weekdays/g, 'mon-fri').replace(/weekends/g, 'sat-sun'); // convert weekdays and weekends to days\r\n inputHoursParse = inputHoursParse.replace(/12:00 noon/g, \"12:00\").replace(/12:00 midnight/g, \"00:00\"); // replace 'noon', 'midnight'\r\n inputHoursParse = inputHoursParse.replace(/12 noon/g, \"12:00\").replace(/12 midnight/g, \"00:00\"); // replace 'noon', 'midnight'\r\n inputHoursParse = inputHoursParse.replace(/noon/g, \"12:00\").replace(/midnight/g, \"00:00\"); // replace 'noon', 'midnight'\r\n inputHoursParse = inputHoursParse.replace(/every day/g, \"mon-sun\"); // replace 'seven days a week'\r\n inputHoursParse = inputHoursParse.replace(/seven days a week/g, \"mon-sun\"); // replace 'seven days a week'\r\n inputHoursParse = inputHoursParse.replace(/7 days a week/g, \"mon-sun\"); // replace 'seven days a week'\r\n inputHoursParse = inputHoursParse.replace(/daily/g, \"mon-sun\"); // replace 'open daily'\r\n inputHoursParse = inputHoursParse.replace(/open 24 ?ho?u?rs?/g, \"00:00-00:00\"); // replace 'open 24 hour or similar'\r\n inputHoursParse = inputHoursParse.replace(/open twenty\\-? ?four ho?u?rs?/g, \"00:00-00:00\"); // replace 'open 24 hour or similar'\r\n inputHoursParse = inputHoursParse.replace(/24 ?ho?u?rs?/g, \"00:00-00:00\"); // replace 'open 24 hour or similar'\r\n inputHoursParse = inputHoursParse.replace(/twenty\\-? ?four ho?u?rs?/g, \"00:00-00:00\"); // replace 'open 24 hour or similar'\r\n inputHoursParse = inputHoursParse.replace(/(\\D:)([^ ])/g, \"$1 $2\"); // space after colons after words\r\n // replace thru type words with dashes\r\n var thruWords = 'through|thru|to|until|till|til|-|~'.split(\"|\");\r\n for (twix=0; twix<thruWords.length; twix++) {\r\n tempRegex = new RegExp(thruWords[twix], \"g\");\r\n inputHoursParse = inputHoursParse.replace(tempRegex,'-');\r\n }\r\n inputHoursParse = inputHoursParse.replace(/\\-{2,}/g, \"-\"); // replace any duplicate dashes\r\n phlogdev('Initial parse: ' + inputHoursParse);\r\n\r\n // kill extra words\r\n var killWords = 'paste|here|business|operation|times|time|walk-ins|walk ins|welcome|dinner|lunch|brunch|breakfast|regular|weekday|weekend|opening|open|now|from|hours|hour|our|are|EST|and|&'.split(\"|\");\r\n for (twix=0; twix<killWords.length; twix++) {\r\n tempRegex = new RegExp('\\\\b'+killWords[twix]+'\\\\b', \"g\");\r\n inputHoursParse = inputHoursParse.replace(tempRegex,'');\r\n }\r\n phlogdev('After kill terms: ' + inputHoursParse);\r\n\r\n // replace day terms with double caps\r\n for (var dayKey in daysOfTheWeek) {\r\n if (daysOfTheWeek.hasOwnProperty(dayKey)) {\r\n var tempDayList = daysOfTheWeek[dayKey];\r\n for (var tdix=0; tdix<tempDayList.length; tdix++) {\r\n tempRegex = new RegExp(tempDayList[tdix]+'(?!a-z)', \"g\");\r\n inputHoursParse = inputHoursParse.replace(tempRegex,dayKey);\r\n }\r\n }\r\n }\r\n phlogdev('Replace day terms: ' + inputHoursParse);\r\n\r\n // Replace dates\r\n for (var monthKey in monthsOfTheYear) {\r\n if (monthsOfTheYear.hasOwnProperty(monthKey)) {\r\n var tempMonthList = monthsOfTheYear[monthKey];\r\n for (var tmix=0; tmix<tempMonthList.length; tmix++) {\r\n tempRegex = new RegExp(tempMonthList[tmix]+'\\\\.? ?\\\\d{1,2}\\\\,? ?201\\\\d{1}', \"g\");\r\n inputHoursParse = inputHoursParse.replace(tempRegex,' ');\r\n tempRegex = new RegExp(tempMonthList[tmix]+'\\\\.? ?\\\\d{1,2}', \"g\");\r\n inputHoursParse = inputHoursParse.replace(tempRegex,' ');\r\n }\r\n }\r\n }\r\n phlogdev('Replace month terms: ' + inputHoursParse);\r\n\r\n // replace any periods between hours with colons\r\n inputHoursParse = inputHoursParse.replace(/(\\d{1,2})\\.(\\d{2})/g, '$1:$2');\r\n // remove remaining periods\r\n inputHoursParse = inputHoursParse.replace(/\\./g, '');\r\n // remove any non-hour colons between letters and numbers and on string ends\r\n inputHoursParse = inputHoursParse.replace(/(\\D+)\\:(\\D+)/g, '$1 $2').replace(/^ *\\:/g, ' ').replace(/\\: *$/g, ' ');\r\n // replace am/pm with AA/PP\r\n inputHoursParse = inputHoursParse.replace(/ *pm/g,'PP').replace(/ *am/g,'AA');\r\n inputHoursParse = inputHoursParse.replace(/ *p\\.m\\./g,'PP').replace(/ *a\\.m\\./g,'AA');\r\n inputHoursParse = inputHoursParse.replace(/ *p\\.m/g,'PP').replace(/ *a\\.m/g,'AA');\r\n inputHoursParse = inputHoursParse.replace(/ *p/g,'PP').replace(/ *a/g,'AA');\r\n // tighten up dashes\r\n inputHoursParse = inputHoursParse.replace(/\\- {1,}/g,'-').replace(/ {1,}\\-/g,'-');\r\n inputHoursParse = inputHoursParse.replace(/^(00:00-00:00)$/g,'MM-UU$1');\r\n phlogdev('AMPM parse: ' + inputHoursParse);\r\n\r\n // Change all MTWRFSU to doubles, if any other letters return false\r\n if (inputHoursParse.match(/[bcdeghijklnoqvxyz]/g) !== null) {\r\n phlogdev('Extra words in the string');\r\n return false;\r\n } else {\r\n inputHoursParse = inputHoursParse.replace(/m/g,'MM').replace(/t/g,'TT').replace(/w/g,'WW').replace(/r/g,'RR');\r\n inputHoursParse = inputHoursParse.replace(/f/g,'FF').replace(/s/g,'SS').replace(/u/g,'UU');\r\n }\r\n phlogdev('MM/TT format: ' + inputHoursParse);\r\n\r\n // tighten up spaces\r\n inputHoursParse = inputHoursParse.replace(/ {2,}/g,' ');\r\n inputHoursParse = inputHoursParse.replace(/ {1,}AA/g,'AA');\r\n inputHoursParse = inputHoursParse.replace(/ {1,}PP/g,'PP');\r\n // Expand hours into XX:XX format\r\n for (var asdf=0; asdf<5; asdf++) { // repeat a few times to catch any skipped regex matches\r\n inputHoursParse = inputHoursParse.replace(/([^0-9\\:])(\\d{1})([^0-9\\:])/g, '$10$2:00$3');\r\n inputHoursParse = inputHoursParse.replace(/^(\\d{1})([^0-9\\:])/g, '0$1:00$2');\r\n inputHoursParse = inputHoursParse.replace(/([^0-9\\:])(\\d{1})$/g, '$10$2:00');\r\n\r\n inputHoursParse = inputHoursParse.replace(/([^0-9\\:])(\\d{2})([^0-9\\:])/g, '$1$2:00$3');\r\n inputHoursParse = inputHoursParse.replace(/^(\\d{2})([^0-9\\:])/g, '$1:00$2');\r\n inputHoursParse = inputHoursParse.replace(/([^0-9\\:])(\\d{2})$/g, '$1$2:00');\r\n\r\n inputHoursParse = inputHoursParse.replace(/(\\D)(\\d{1})(\\d{2}\\D)/g, '$10$2:$3');\r\n inputHoursParse = inputHoursParse.replace(/^(\\d{1})(\\d{2}\\D)/g, '0$1:$2');\r\n inputHoursParse = inputHoursParse.replace(/(\\D)(\\d{1})(\\d{2})$/g, '$10$2:$3');\r\n\r\n inputHoursParse = inputHoursParse.replace(/(\\D\\d{2})(\\d{2}\\D)/g, '$1:$2');\r\n inputHoursParse = inputHoursParse.replace(/^(\\d{2})(\\d{2}\\D)/g, '$1:$2');\r\n inputHoursParse = inputHoursParse.replace(/(\\D\\d{2})(\\d{2})$/g, '$1:$2');\r\n\r\n inputHoursParse = inputHoursParse.replace(/(\\D)(\\d{1}\\:)/g, '$10$2');\r\n inputHoursParse = inputHoursParse.replace(/^(\\d{1}\\:)/g, '0$1');\r\n }\r\n\r\n // replace 12AM range with 00\r\n inputHoursParse = inputHoursParse.replace( /12(\\:\\d{2}AA)/g, '00$1');\r\n // Change PM hours to 24hr time\r\n while (inputHoursParse.match(/\\d{2}\\:\\d{2}PP/) !== null) {\r\n tfHourTemp = inputHoursParse.match(/(\\d{2})\\:\\d{2}PP/)[1];\r\n tfHourTemp = parseInt(tfHourTemp) % 12 + 12;\r\n inputHoursParse = inputHoursParse.replace(/\\d{2}(\\:\\d{2})PP/,tfHourTemp.toString()+'$1');\r\n }\r\n // kill the AA\r\n inputHoursParse = inputHoursParse.replace( /AA/g, '');\r\n phlogdev('XX:XX format: ' + inputHoursParse);\r\n\r\n // Side check for tabular input\r\n var inputHoursParseTab = inputHoursParse.replace( /[^A-Z0-9\\:-]/g, ' ').replace( / {2,}/g, ' ');\r\n inputHoursParseTab = inputHoursParseTab.replace( /^ +/g, '').replace( / {1,}$/g, '');\r\n if (inputHoursParseTab.match(/[A-Z]{2}\\:?\\-? [A-Z]{2}\\:?\\-? [A-Z]{2}\\:?\\-? [A-Z]{2}\\:?\\-? [A-Z]{2}\\:?\\-?/g) !== null) {\r\n inputHoursParseTab = inputHoursParseTab.split(' ');\r\n var reorderThree = [0,7,14,1,8,15,2,9,16,3,10,17,4,11,18,5,12,19,6,13,20];\r\n var reorderTwo = [0,7,1,8,2,9,3,10,4,11,5,12,6,13];\r\n var inputHoursParseReorder = [], reix;\r\n if (inputHoursParseTab.length === 21) {\r\n for (reix=0; reix<21; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderThree[reix]]);\r\n }\r\n } else if (inputHoursParseTab.length === 18) {\r\n for (reix=0; reix<18; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderThree[reix]]);\r\n }\r\n } else if (inputHoursParseTab.length === 15) {\r\n for (reix=0; reix<15; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderThree[reix]]);\r\n }\r\n } else if (inputHoursParseTab.length === 14) {\r\n for (reix=0; reix<14; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderTwo[reix]]);\r\n }\r\n } else if (inputHoursParseTab.length === 12) {\r\n for (reix=0; reix<12; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderTwo[reix]]);\r\n }\r\n } else if (inputHoursParseTab.length === 10) {\r\n for (reix=0; reix<10; reix++) {\r\n inputHoursParseReorder.push(inputHoursParseTab[reorderTwo[reix]]);\r\n }\r\n }\r\n //phlogdev('inputHoursParseTab: ' + inputHoursParseTab);\r\n phlogdev('inputHoursParseReorder: ' + inputHoursParseReorder);\r\n if (inputHoursParseReorder.length > 9) {\r\n inputHoursParseReorder = inputHoursParseReorder.join(' ');\r\n inputHoursParseReorder = inputHoursParseReorder.replace(/(\\:\\d{2}) (\\d{2}\\:)/g, '$1-$2');\r\n inputHoursParse = inputHoursParseReorder;\r\n }\r\n\r\n }\r\n\r\n\r\n // remove colons after Days field\r\n inputHoursParse = inputHoursParse.replace(/(\\D+)\\:/g, '$1 ');\r\n\r\n // Find any double sets\r\n inputHoursParse = inputHoursParse.replace(/([A-Z \\-]{2,}) *(\\d{2}\\:\\d{2} *\\-{1} *\\d{2}\\:\\d{2}) *(\\d{2}\\:\\d{2} *\\-{1} *\\d{2}\\:\\d{2})/g, '$1$2$1$3');\r\n inputHoursParse = inputHoursParse.replace(/(\\d{2}\\:\\d{2}) *(\\d{2}\\:\\d{2})/g, '$1-$2');\r\n phlogdev('Add dash: ' + inputHoursParse);\r\n\r\n // remove all spaces\r\n inputHoursParse = inputHoursParse.replace( / */g, '');\r\n\r\n // Remove any dashes acting as Day separators for 3+ days (\"M-W-F\")\r\n inputHoursParse = inputHoursParse.replace( /([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})/g, '$1$2$3$4$5$6$7');\r\n inputHoursParse = inputHoursParse.replace( /([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})/g, '$1$2$3$4$5$6');\r\n inputHoursParse = inputHoursParse.replace( /([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})/g, '$1$2$3$4$5');\r\n inputHoursParse = inputHoursParse.replace( /([A-Z]{2})-([A-Z]{2})-([A-Z]{2})-([A-Z]{2})/g, '$1$2$3$4');\r\n inputHoursParse = inputHoursParse.replace( /([A-Z]{2})-([A-Z]{2})-([A-Z]{2})/g, '$1$2$3');\r\n\r\n // parse any 'through' type terms on the day ranges (MM-RR --> MMTTWWRR)\r\n while (inputHoursParse.match(/[A-Z]{2}\\-[A-Z]{2}/) !== null) {\r\n tfDaysTemp = inputHoursParse.match(/([A-Z]{2})\\-([A-Z]{2})/);\r\n var startDayIX = dayCodeVec.indexOf(tfDaysTemp[1]);\r\n newDayCodeVec = [tfDaysTemp[1]];\r\n for (var dcvix=startDayIX+1; dcvix<startDayIX+7; dcvix++) {\r\n newDayCodeVec.push(dayCodeVec[dcvix]);\r\n if (tfDaysTemp[2] === dayCodeVec[dcvix]) {\r\n break;\r\n }\r\n }\r\n newDayCodeVec = newDayCodeVec.join('');\r\n inputHoursParse = inputHoursParse.replace(/[A-Z]{2}\\-[A-Z]{2}/,newDayCodeVec);\r\n }\r\n\r\n // split the string between numerical and letter characters\r\n inputHoursParse = inputHoursParse.replace(/([A-Z])\\-?\\:?([0-9])/g,'$1|$2');\r\n inputHoursParse = inputHoursParse.replace(/([0-9])\\-?\\:?([A-Z])/g,'$1|$2');\r\n inputHoursParse = inputHoursParse.replace(/(\\d{2}\\:\\d{2})\\:00/g,'$1'); // remove seconds\r\n inputHoursParse = inputHoursParse.split(\"|\");\r\n phlogdev('Split: ' + inputHoursParse);\r\n\r\n var daysVec = [], hoursVec = [];\r\n for (tsix=0; tsix<inputHoursParse.length; tsix++) {\r\n if (inputHoursParse[tsix][0].match(/[A-Z]/) !== null) {\r\n daysVec.push(inputHoursParse[tsix]);\r\n } else if (inputHoursParse[tsix][0].match(/[0-9]/) !== null) {\r\n hoursVec.push(inputHoursParse[tsix]);\r\n } else {\r\n phlogdev('Filtering error');\r\n return false;\r\n }\r\n }\r\n\r\n // check that the dayArray and hourArray lengths correspond\r\n if ( daysVec.length !== hoursVec.length ) {\r\n phlogdev('Hour and Day arrays are not matched');\r\n return false;\r\n }\r\n\r\n // Combine days with the same hours in the same vector\r\n var newDaysVec = [], newHoursVec = [], hrsIX;\r\n for (tsix=0; tsix<daysVec.length; tsix++) {\r\n if (hoursVec[tsix] !== '99:99-99:99') { // Don't add the closed days\r\n hrsIX = newHoursVec.indexOf(hoursVec[tsix]);\r\n if (hrsIX > -1) {\r\n newDaysVec[hrsIX] = newDaysVec[hrsIX] + daysVec[tsix];\r\n } else {\r\n newDaysVec.push(daysVec[tsix]);\r\n newHoursVec.push(hoursVec[tsix]);\r\n }\r\n }\r\n }\r\n\r\n var hoursObjectArray = [], hoursObjectArrayMinDay = [], hoursObjectArraySorted = [], hoursObjectAdd, daysObjArray, toFromSplit;\r\n for (tsix=0; tsix<newDaysVec.length; tsix++) {\r\n hoursObjectAdd = {};\r\n daysObjArray = [];\r\n toFromSplit = newHoursVec[tsix].match(/(\\d{2}\\:\\d{2})\\-(\\d{2}\\:\\d{2})/);\r\n if (toFromSplit === null) {\r\n phlogdev('Hours in wrong format');\r\n return false;\r\n } else { // Check for hours outside of 0-23 and 0-59\r\n var hourCheck = toFromSplit[1].match(/(\\d{2})\\:/)[1];\r\n if (hourCheck>23 || hourCheck < 0) {\r\n phlogdev('Not a valid time');\r\n return false;\r\n }\r\n hourCheck = toFromSplit[2].match(/(\\d{2})\\:/)[1];\r\n if (hourCheck>23 || hourCheck < 0) {\r\n phlogdev('Not a valid time');\r\n return false;\r\n }\r\n hourCheck = toFromSplit[1].match(/\\:(\\d{2})/)[1];\r\n if (hourCheck>59 || hourCheck < 0) {\r\n phlogdev('Not a valid time');\r\n return false;\r\n }\r\n hourCheck = toFromSplit[2].match(/\\:(\\d{2})/)[1];\r\n if (hourCheck>59 || hourCheck < 0) {\r\n phlogdev('Not a valid time');\r\n return false;\r\n }\r\n }\r\n // Make the days object\r\n if ( newDaysVec[tsix].indexOf('MM') > -1 ) {\r\n daysObjArray.push(1);\r\n }\r\n if ( newDaysVec[tsix].indexOf('TT') > -1 ) {\r\n daysObjArray.push(2);\r\n }\r\n if ( newDaysVec[tsix].indexOf('WW') > -1 ) {\r\n daysObjArray.push(3);\r\n }\r\n if ( newDaysVec[tsix].indexOf('RR') > -1 ) {\r\n daysObjArray.push(4);\r\n }\r\n if ( newDaysVec[tsix].indexOf('FF') > -1 ) {\r\n daysObjArray.push(5);\r\n }\r\n if ( newDaysVec[tsix].indexOf('SS') > -1 ) {\r\n daysObjArray.push(6);\r\n }\r\n if ( newDaysVec[tsix].indexOf('UU') > -1 ) {\r\n daysObjArray.push(0);\r\n }\r\n // build the hours object\r\n hoursObjectAdd.fromHour = toFromSplit[1];\r\n hoursObjectAdd.toHour = toFromSplit[2];\r\n hoursObjectAdd.days = daysObjArray.sort();\r\n hoursObjectArray.push(hoursObjectAdd);\r\n // track the order\r\n if (hoursObjectAdd.days.length > 1 && hoursObjectAdd.days[0] === 0) {\r\n hoursObjectArrayMinDay.push( hoursObjectAdd.days[1] * 100 + parseInt(toFromSplit[1][0])*10 + parseInt(toFromSplit[1][1]) );\r\n } else {\r\n hoursObjectArrayMinDay.push( (((hoursObjectAdd.days[0]+6)%7)+1) * 100 + parseInt(toFromSplit[1][0])*10 + parseInt(toFromSplit[1][1]) );\r\n }\r\n }\r\n sortWithIndex(hoursObjectArrayMinDay);\r\n for (var hoaix=0; hoaix < hoursObjectArrayMinDay.length; hoaix++) {\r\n hoursObjectArraySorted.push(hoursObjectArray[hoursObjectArrayMinDay.sortIndices[hoaix]]);\r\n }\r\n if ( !checkHours(hoursObjectArraySorted) ) {\r\n phlogdev('Overlapping hours');\r\n return false;\r\n } else {\r\n for ( var ohix=0; ohix<hoursObjectArraySorted.length; ohix++ ) {\r\n phlogdev(hoursObjectArraySorted[ohix]);\r\n if ( hoursObjectArraySorted[ohix].days.length === 2 && hoursObjectArraySorted[ohix].days[0] === 0 && hoursObjectArraySorted[ohix].days[1] === 1) {\r\n // separate hours\r\n phlogdev('Splitting M-S entry...');\r\n hoursObjectArraySorted.push({days: [0], fromHour: hoursObjectArraySorted[ohix].fromHour, toHour: hoursObjectArraySorted[ohix].toHour});\r\n hoursObjectArraySorted[ohix].days = [1];\r\n }\r\n }\r\n }\r\n return hoursObjectArraySorted;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enter a parse tree produced by AgtypeParsertypeAnnotation.
enterTypeAnnotation(ctx) { }
[ "enterAgType(ctx) {\n }", "enterType_declaration(ctx) {\n\t}", "function TypeofTypeAnnotation(node, print) {\n\t this.push(\"typeof \");\n\t print.plain(node.argument);\n\t}", "function TypeofTypeAnnotation(node, print) {\n this.push(\"typeof \");\n print.plain(node.argument);\n}", "enterSubtype_declaration(ctx) {\n\t}", "enterProc_decl_in_type(ctx) {\n\t}", "function TypeAnnotation(node, print) {\n\t this.push(\":\");\n\t this.space();\n\t if (node.optional) this.push(\"?\");\n\t print.plain(node.typeAnnotation);\n\t}", "enterType_definition(ctx) {\n\t}", "function TypeAnnotation(node, print) {\n this.push(\":\");\n this.space();\n if (node.optional) this.push(\"?\");\n print.plain(node.typeAnnotation);\n}", "enterSubprog_decl_in_type(ctx) {\n\t}", "parse(parseType) {}", "enterTypeSpecifier(ctx) {\n\t}", "tryInsertTypeAnnotation(sourceFile, node, type) {\n let endNode2;\n if (isFunctionLike(node)) {\n endNode2 = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile);\n if (!endNode2) {\n if (!isArrowFunction(node))\n return false;\n endNode2 = first(node.parameters);\n }\n } else {\n endNode2 = (node.kind === 259 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) ?? node.name;\n }\n this.insertNodeAt(sourceFile, endNode2.end, type, { prefix: \": \" });\n return true;\n }", "enterType_spec(ctx) {\n\t}", "enterObject_type_def(ctx) {\n\t}", "enterType_body(ctx) {\n\t}", "visit(type, iterator) {\n visit(this.ast, type, iterator)\n }", "function traverseASTForTypeChecking() {\n\tconsole.log(\"\\n\\nType Checking console messages are below \\n\\n\");\n\t\n\tdocument.getElementById(\"taOutput\").value += \"\\n\\n*****TYPE CHECKING*****\\n\\n\";\n\t\n\tvar tempNode = _ASTRoot;\n\tsecondExpandOfAST(tempNode);\n\t\n\tdocument.getElementById(\"taOutput\").value += \"\\n\\n*****END TYPE CHECKING*****\\n\\n\";\n}", "function wrap(type,p) {\n var wrapparser = action(p, function(ast) {\n var node = new Node(type);\n if (ast instanceof Array) {\n for (var i=0; i<ast.length; i++)\n if (ast[i] instanceof Named)\n node[ast[i].name] = ast[i].ast;\n else if (ast[i] instanceof Rule)\n throw('Sorry, mixing of parse tree and asts currently not recommended.');\n else\n ; // dropping/losing info here ??\n } else if (ast instanceof Named)\n node[ast.name] = ast.ast;\n else if (ast instanceof Rule)\n throw('Sorry, mixing of parse tree and asts currently not recommended.');\n else\n ; // dropping/losing info here ??\n node.ast = ast; // preserve full parse tree info, for faithful unparsing\n // TODO: investigate storage efficiency\n return node;\n } );\n wrapparser.toString = function() { return (toString_AST\n ? 'wrap(\"'+type+'\",'+p+')'\n : p.toString()); }\n return wrapparser;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the game board
function createBoard() { const board = document.querySelector('.game'); const rows = document.createElement('tr'); //Create the head row rows.setAttribute('id', 'HeaderRow'); rows.classList.add('row'); rows.addEventListener('click', (e) => { gamePlay(e); }); //Create the header column and append to header row for (let col = 0; col < WIDTH; col++) { const cols = document.createElement('td'); cols.setAttribute('id', `c${col}`); cols.classList.add('colHead'); rows.append(cols); } // Append to board board.append(rows); //Create the remaining boards for (let myRow = 0; myRow < HEIGHT; myRow++) { const row = document.createElement('tr'); for (let myCol = 0; myCol < WIDTH; myCol++) { const cols = document.createElement('td'); cols.setAttribute('id', `r${myRow}c${myCol}`); cols.dataset.row = myRow; cols.dataset.col = myCol; cols.classList.add('col'); row.append(cols); } board.append(row); } }
[ "function createBoard() {\n board = new Gameboard(6,5);\n for (let i = 0; i < board.width; i++) {\n for (let j = 0; j < board.height; j++) {\n if (gameState.level < 6 )\n {\n createLevel1(board, i, j);\n }\n else {\n createLevel6(board, i, j);\n }\n }\n }\n placeBoard(board, gameState.gameType);\n return board;\n}", "function createBoard() {\n \t// Create the Matrix\n\tvar board = createMat(BOARD_SIZE, BOARD_SIZE);\n\n\t// Put SKY everywhere and EARTH on the bottom\n\tfor (var i = 0; i < board.length; i++) {\n\t\tfor (var j = 0; j < board[0].length; j++) {\n\t\t\t// Put SKY in a regular cell\n\t\t\tvar cell = { type: SKY, gameElement: '' };\n\t\t\tboard[i][j] = cell;\n\t\t\t// Place Walls at edges\n\t\t\tif (i === (board.length - 1)) {\n\t\t\t\tcell.type = EARTH;\n\t\t\t\tcell.gameElement = EARTH;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n gBoard = board;\n // console.log(board);\n addHeroToBoard(board);\n addAliensToBoard(board);\n\taddBirdsToBoard(board);\n gBoard = board;\n return board;\n \n}", "function createBoard() {\n\t\tctx.beginPath();\n\t\tctx.rect(boardX, canvas.height - boardHeight, boardWidth, boardHeight);\n\t\tctx.fillStyle = 'blue';\n\t\tctx.fill();\n\t\tctx.closePath();\n\t}", "function createBoard() {\n\tfor (var i = 0; i < cards.length; i++) {\n\t\tconst section = createSection();\n\t\tconst cardDiv = createCardDiv(i)\n\t\tconst frontDiv = createFrontCard(i, usersPick);\n\t\tconst backDiv = createBackCard();\n\t\tsection.appendChild(cardDiv);\n\t\tcardDiv.appendChild(frontDiv);\n\t\tcardDiv.appendChild(backDiv);\n\t\tdocument.getElementById(\"game-board\").appendChild(section);\n\t\taddEventListenerToCards();\n\t}\n\tshuffleCards();\n\thideBtns();\n\treturn;\n}", "function createGameBoard(){\n // Create HTML table\n table = document.getElementById('game');\n table.cellPadding = \"0\";\n table.cellSpacing = \"0\";\n var tableBody = document.createElement('tbody');\n\t\n // increment y-coordinate for cell\n for (var yStart = -1; yStart < 2; yStart++){\n // Create row\n var row = document.createElement(\"tr\");\n\n // increment x-coordinate for cell\n for (var xStart = -1; xStart < 2; xStart++){\n // Create column\n var cell = document.createElement(\"td\");\n // Adds an ID for each cell of table\n\t\tcell.id = ((xStart.toString()).concat(\",\")).concat((yStart.toString()));\n // Add blank image for each cell\n var emptyCell = document.createElement('img');\n emptyCell.src = \"TileAssets/FreeTile.png\";\n emptyCell.className = \"unplaced\";\n\t\temptyCell.style.zIndex= \"1\";\n emptyCell.style.visibility = \"hidden\";\n cell.appendChild(emptyCell);\n\t\trow.appendChild(cell);\n\n // Increment cell position\n }\n // Increment cell position\n tableBody.appendChild(row);\n }\n // Add table to container div and set a border\n table.appendChild(tableBody);\n board.appendChild(table);\n table.setAttribute(\"border\", \"1\");\n }", "createBoard() {\n\t\tfor (let i = 0; i < 6; i++) {\n\t\t\tfor (let j = 0; j < 6; j++) {\n\t\t\t\tlet tile = new MyTile(this.scene, this);\n\t\t\t\tlet pieceSize = 0.395 + 0.005;\n\t\t\t\ttile.addTransformation(['translation', -3 * pieceSize + pieceSize * j, -3 * pieceSize + pieceSize * i, 0]);\n\t\t\t\tthis.tiles.push(tile);\n\t\t\t}\n\t\t}\n\t\tfor (let i = 0; i < 8; i++) {\n\t\t\tthis.whitePieces.push(new MyPieceWhite(this.scene, 'whitePiece'));\n\t\t\tthis.blackPieces.push(new MyPieceBlack(this.scene, 'blackPiece'));\n\t\t}\n\t}", "function createBoard() {\n // Create the Matrix\n\tvar board = createMat(BOARD_SIZE, BOARD_SIZE);\n\n\t// Put SKY everywhere and EARTH on the bottom\n\tfor (var i = 0; i < board.length; i++) {\n\t\tfor (var j = 0; j < board[0].length; j++) {\n\n\t\t\t// Put SKY in a regular cell\n\t\t\tvar cell = { type: SKY, gameElement: '' };\n\t\t\tboard[i][j] = cell;\n\n\t\t\t// Place Walls at edges\n\t\t\tif (i === (board.length - 1)) {\n\t\t\t\tcell.type = EARTH;\n\t\t\t\tcell.gameElement = EARTH;\n\t\t\t}\n\t\t}\n\t}\n\n gBoard = board;\n\t// Following functions are called to deal with creating the game elements\n addHeroToBoard(board);\n addAliensToBoard(board);\n\taddBirdsToBoard(board);\n gBoard = board;\n\n return board;\n}", "function makeBoard(){\n\t\ttimerButton = gameBox.appendChild(document.createElement(\"button\"));\n\t\ttimerButton.setAttribute(\"id\", \"timerButton\");\n\t\ttimerButton.appendChild(document.createTextNode(\"Timer\"));\n\n\t\tvar startButton = gameBox.appendChild(document.createElement(\"button\"));\n\t\tstartButton.setAttribute(\"id\", \"newGame\");\n\t\tstartButton.appendChild(document.createTextNode(\"New Game\"));\n\n\t\tshuffle();\n\t\tfor(var i=0; i< 6; i++){\n\t\t\tvar row = document.createElement(\"section\");\n\t\t\tfor(var j=0; j< 6; j++){\n\t\t\t\tvar col = document.createElement(\"div\");\n\t\t\t\tcol.className = \"tile\";\n\t\t\t\tcol.setAttribute(\"id\", cardNums[6*i +j]);\n\t\t\t\n\t\t\t\tcol.style.backgroundImage = \"url('images/cards/card0.jpg')\";\n\t\t\t\trow.appendChild(col);\n\t\t\t}\n\t\t\tgameBox.appendChild(row);\n\t\t}\n\t}", "function create_boards() {\n\t\tenemy_board = new Game_board(get2DArray(size));\n\t\thome_board = new Game_board(get2DArray(size));\n\t}", "function makeBoard() {\n // Game mechanics code -- to keep track of the game state\n for (let row = 0; row < HEIGHT; row++) {\n let currentRow = [];\n for (let columns = 0; columns < WIDTH; columns++) {\n currentRow.push(null);\n }\n board.push(currentRow);\n }\n}", "function create_board () {\n\tboard = []\n\tfor (var y = 0; y < board_size.height; y++) {\t\t\n\t\tboard[y] = []\n\t\tfor (var x = 0; x < board_size.width; x++) {\n\t\t\tboard[y][x] = false\n\t\t}\n\t}\n}", "function makeGameBoard() {\n\n // Resetting the gameBoardList to just be an empty array.\n gameBoardList = [[null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null]];\n}", "function _makeBoard() {\n if (players[0].getBoard() === undefined) {\n _board = new Board(config.height, config.width);\n players[0].setBoard(_board);\n _fillBoard(_board);\n \n } else {\n _board = players[0].getBoard();\n }\n // display board for debug purposes\n players[0].score = 0;\n }", "function createGameBoard() {\n if (!initialized) {\n var x, y;\n\n board = document.createElement(\"div\");\n board.className = \"board\";\n container.appendChild(board);\n\n // Populate the Board with Squares\n for (y = 0; y < GRID_SIZE; y += 1) {\n for (x = 0; x < GRID_SIZE; x += 1) {\n board.appendChild(getNewBoardSquare(x, y));\n }\n }\n\n squares = board.getElementsByClassName(\"square\");\n }\n}", "function createBoard() {\n window.board = new Board(4, 13);\n createCards();\n window.board.placeCards();\n}", "function makeBoard() {\n var tmp = -1\n for (x=7;x>-1; x--) { // make the board squares\n for (y=0;y<8; y++) {\n if (tmp == -1) {\n $('.board').append($(`<div id='${y+1}-${x+1}' x='${y+1}' y='${x+1}' class=\"square ${ ((y+1)%2) ? 'light' : 'dark'}\"><div class='pos'>${chars[y+1]}${x+1}</div> <div class='indicator'></div> </div>`))\n \n }\n else {\n $('.board').append($(`<div id='${y+1}-${x+1}' x='${y+1}' y='${x+1}' class=\"square ${ (y%2) ? 'light' : 'dark'}\"><div class='pos'>${chars[y+1]}${x+1}</div> <div class='indicator'></div> </div>`))\n }\n }\n tmp = tmp*-1;\n \n }\n gameSize(); // set game size on page load\n}", "function generateGameBoard () {\n // Four tables, for each Z position\n for (var z = 0; z < 4; z++) {\n var $column = $('<div>').addClass('col-sm-3')\n var $table = $('<table>').addClass('table table-bordered text-center')\n var $tableBody = $('<tbody>')\n\n // Add header row\n var $tableHead = $('<thead>').append($('<tr>').append($('<th>').attr('colspan', '4').html(`Z = ${z}`)))\n\n // Add table rows (Y-axis)\n for (var y = 3; y >= 0; y--) {\n var $row = $('<tr>')\n\n // Add cells (X-axis)\n for (var x = 0; x < 4; x++) {\n var $cell = $('<td>').addClass(`board-cell-${x}${y}${z}`)\n $cell.html('&nbsp;')\n $row.append($cell)\n }\n\n $tableBody.append($row)\n }\n\n $table.append($tableHead)\n $table.append($tableBody)\n $column.append($table)\n $('#board').append($column)\n }\n }", "function createBoard() {\n for(let i=0; i<width*width; i++){\n const square = document.createElement(\"div\");\n square.innerHTML = 0;\n grid.appendChild(square);\n squares.push(square);\n }\n generate();\n generate();\n }", "function createBoard(){\n let matches =game.boardSize/2;\n let color ='gray #ceb40e brown blue green red purple magenta orange black'.split(' ');\n let sym = '! @ # $ % \" \\' ^ & * = + - _ ( ) { } < > ~ / \\\\ | [ ] ? ; . , :'.split(' ');\n let boardTemplate = [];\n\n for( let i=0; i < matches; i++){\n //pick random combo of color/sym\n boardTemplate.push([color[randomNumber(color.length)],sym[randomNumber(sym.length)]]);\n }\n //creates 2 of every card\n boardTemplate.push(...boardTemplate);\n fillBoard(shuffleBoard(boardTemplate));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FragmentName : Name but not `on`
function parseFragmentName(parser) { if (parser.token.value === 'on') { throw unexpected(parser); } return parseName(parser); }
[ "parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n\n return this.parseName();\n }", "parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n return this.parseName();\n }", "parseFragmentName() {\n if (this._lexer.token.value === \"on\") {\n throw this.unexpected();\n }\n return this.parseName();\n }", "function parseFragmentName(lexer) {\n\t if (lexer.token.value === 'on') {\n\t throw unexpected(lexer);\n\t }\n\t return parseName(lexer);\n\t}", "function Fragment(name) {\n EventEmitter.call(this); // Call parent's constructor.\n this._name = name;\n}", "function getFragmentNameParts(fragmentName) {\n\t var match = fragmentName.match(/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/);\n\t if (!match) {\n\t throw new Error('BabelPluginGraphQL: Fragments should be named ' + '`ModuleName_fragmentName`, got `' + fragmentName + '`.');\n\t }\n\t var module = match[1];\n\t var propName = match[2];\n\t if (propName === DEFAULT_PROP_NAME) {\n\t throw new Error('BabelPluginGraphQL: Fragment `' + fragmentName + '` should not end in ' + '`_data` to avoid conflict with a fragment named `' + module + '` ' + 'which also provides resulting data via the React prop `data`. Either ' + 'rename this fragment to `' + module + '` or choose a different ' + 'prop name.');\n\t }\n\t return [module, propName || DEFAULT_PROP_NAME];\n\t}", "parseFragment() {\n const start = this._lexer.token;\n this.expectToken(_tokenKind.TokenKind.SPREAD);\n const hasTypeCondition = this.expectOptionalKeyword('on');\n if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) {\n return this.node(start, {\n kind: _kinds.Kind.FRAGMENT_SPREAD,\n name: this.parseFragmentName(),\n directives: this.parseDirectives(false)\n });\n }\n return this.node(start, {\n kind: _kinds.Kind.INLINE_FRAGMENT,\n typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet()\n });\n }", "function UniqueFragmentNames(context) {\n var knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: function OperationDefinition() {\n return false;\n },\n FragmentDefinition: function FragmentDefinition(node) {\n var fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n }\n };\n}", "parseFragment() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.SPREAD);\n const hasTypeCondition = this.expectOptionalKeyword('on');\n\n if (!hasTypeCondition && this.peek(TokenKind.NAME)) {\n return this.node(start, {\n kind: Kind.FRAGMENT_SPREAD,\n name: this.parseFragmentName(),\n directives: this.parseDirectives(false),\n });\n }\n\n return this.node(start, {\n kind: Kind.INLINE_FRAGMENT,\n typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }", "function UniqueFragmentNames(context) {\n var knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: function OperationDefinition() {\n return false;\n },\n FragmentDefinition: function FragmentDefinition(node) {\n var fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new _error_GraphQLError__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n }\n };\n}", "function UniqueFragmentNamesRule(context) {\n const knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: () => false,\n FragmentDefinition(node) {\n const fragmentName = node.name.value;\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new _GraphQLError.GraphQLError(`There can be only one fragment named \"${fragmentName}\".`, {\n nodes: [knownFragmentNames[fragmentName], node.name]\n }));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n return false;\n }\n };\n}", "function UniqueFragmentNamesRule(context) {\n var knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: function OperationDefinition() {\n return false;\n },\n FragmentDefinition: function FragmentDefinition(node) {\n var fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new _GraphQLError.GraphQLError(\"There can be only one fragment named \\\"\".concat(fragmentName, \"\\\".\"), [knownFragmentNames[fragmentName], node.name]));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n }\n };\n}", "function UniqueFragmentNamesRule(context) {\n const knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: () => false,\n\n FragmentDefinition(node) {\n const fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(\n new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\n `There can be only one fragment named \"${fragmentName}\".`,\n [knownFragmentNames[fragmentName], node.name],\n ),\n );\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n },\n };\n}", "function UniqueFragmentNamesRule(context) {\n var knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: function OperationDefinition() {\n return false;\n },\n FragmentDefinition: function FragmentDefinition(node) {\n var fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new GraphQLError(\"There can be only one fragment named \\\"\".concat(fragmentName, \"\\\".\"), [knownFragmentNames[fragmentName], node.name]));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n }\n };\n}", "parseFragment() {\n const start = this._lexer.token;\n this.expectToken(_tokenKind_mjs__WEBPACK_IMPORTED_MODULE_6__[\"TokenKind\"].SPREAD);\n const hasTypeCondition = this.expectOptionalKeyword('on');\n\n if (!hasTypeCondition && this.peek(_tokenKind_mjs__WEBPACK_IMPORTED_MODULE_6__[\"TokenKind\"].NAME)) {\n return this.node(start, {\n kind: _kinds_mjs__WEBPACK_IMPORTED_MODULE_3__[\"Kind\"].FRAGMENT_SPREAD,\n name: this.parseFragmentName(),\n directives: this.parseDirectives(false),\n });\n }\n\n return this.node(start, {\n kind: _kinds_mjs__WEBPACK_IMPORTED_MODULE_3__[\"Kind\"].INLINE_FRAGMENT,\n typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }", "function UniqueFragmentNamesRule(context) {\n var knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: function OperationDefinition() {\n return false;\n },\n FragmentDefinition: function FragmentDefinition(node) {\n var fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"There can be only one fragment named \\\"\".concat(fragmentName, \"\\\".\"), [knownFragmentNames[fragmentName], node.name]));\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n }\n };\n}", "function KnownFragmentNames(context) {\n return {\n FragmentSpread: function FragmentSpread(node) {\n var fragmentName = node.name.value;\n var fragment = context.getFragment(fragmentName);\n if (!fragment) {\n context.reportError(new _error.GraphQLError(unknownFragmentMessage(fragmentName), [ node.name ]));\n }\n }\n };\n }", "function Fragment(){}", "function KnownFragmentNamesRule(context) {\n return {\n FragmentSpread(node) {\n const fragmentName = node.name.value;\n const fragment = context.getFragment(fragmentName);\n\n if (!fragment) {\n context.reportError(\n new _GraphQLError.GraphQLError(\n `Unknown fragment \"${fragmentName}\".`,\n {\n nodes: node.name,\n },\n ),\n );\n }\n },\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
expand first level if the tree has only one item visible
function treeExpandFirstLevel(tree) { if ($('#node-groups-tree li.folder').length == 1) { var itemId = $('#node-groups-tree li.folder').attr('id'); tree.open_node(itemId); } }
[ "expandNodeRecursive(){this._selectedField.expandRecursive()}", "_expandItemsByDefault(collapseBeforehand) {\n const that = this;\n\n if (that._menuItemsGroupsToExpand.length === 0 && !collapseBeforehand ||\n that.mode !== 'tree' && !that._minimized) {\n return;\n }\n\n const restoreAnimation = that.hasAnimation,\n animationType = that.animation;\n\n if (restoreAnimation) {\n that.animation = 'none';\n }\n\n if (collapseBeforehand) {\n that._collapseAll(false);\n }\n\n for (let i = 0; i < that._menuItemsGroupsToExpand.length; i++) {\n that.expandItem(that._menuItemsGroupsToExpand[i].path, undefined, false);\n }\n\n if (restoreAnimation) {\n that.animation = animationType;\n }\n\n that._menuItemsGroupsToExpand = [];\n }", "expandItem(item){if(!this._isExpanded(item)){this.push('expandedItems',item);}}", "expandItem(item){if(!this._isExpanded(item)){this.push(\"expandedItems\",item)}}", "function expandLevel() {\n instance.collapse(1);\n instance.expand(1);\n}", "function expandTree(){\n\tvar nodes = _getNodes(\"subtreeHIDE\");\n\t\n\n\tfor(var i=0; i<nodes.length; i++) {\n\t\tswitch(nodes[i].tagName){\n\t\t\tcase \"DIV\":\tnodes[i].className=\"subtreeSHOW\"; break;\n\t\t\tcase \"IMG\":\tnodes[i].src=imgPath+imgMINUS; break;\n\t\t}\n\t}\n\t\n\treturn false;\n}", "ExpandAll() {\n if (this.IsNode) {\n for (let i = 0, ln = this.fItems.length; i < ln; i++) {\n this.fItems[i].ExpandAll();\n }\n\n this.Expand();\n }\n }", "function expandGridToLevel(grid) {\r\n\tif (grid.getDataProvider() && grid.getDataProvider().length > 0) {\r\n\t\tif (grid.expandLevel !== undefined && null !== grid.expandLevel && grid.expandLevel < grid.getMaxDepth()) {\r\n\t\t\tgrid.expandToLevel(grid.expandLevel);\r\n\t\t} else {\r\n\t\t\tgrid.expandAll();\r\n\t\t}\r\n\t}\r\n}", "function expandItem(){\n vm.expanded = !vm.expanded;\n }", "function expandObjTree(data) {\n\n\tif (!resp) return false;\n\n\tvar curchild = data;\n\tvar i = 0;\n\tvar subdiv = document.getElementById(curchild.expandSingle);\n\t\n\tsubdiv.innerHTML = \"\";\n\tsubdiv.appendChild(createTree(curchild));\n\n}", "function firstTree() {\n hideAllWindows();\n if (currentTreeIndex != 0) {\n moveToTreeHelper(0);\n }\n}", "expandAll() {\n const expandTree = (items, expandedIds) => {\n items.forEach((itm) => {\n if (itm.children.length) {\n expandedIds[itm.id] = true;\n expandTree(itm.children, expandedIds);\n }\n });\n };\n\n const expandedIds = {};\n\n expandTree(this.state.root, expandedIds);\n\n this.setState({\n expandedIds\n });\n }", "function expand1Level(d) {\n var q = [d]; // non-recursive\n var cn;\n var done = null;\n while (q.length > 0) {\n cn = q.shift();\n if (done !== null && done < cn.depth) { return; }\n if (cn._children) {\n done = cn.depth;\n cn.children = cn._children;\n cn._children = null;\n cn.children.forEach(collapse);\n }\n if (cn.children) { q = q.concat(cn.children); }\n }\n // no nodes to open\n }", "expand() {\n const args = {\n owner: this.tree,\n node: this,\n cancel: false\n };\n this.tree.nodeExpanding.emit(args);\n if (!args.cancel) {\n this.treeService.expand(this, true);\n this.cdr.detectChanges();\n this.playOpenAnimation(this.childrenContainer);\n }\n }", "get isExpanded() {}", "function hasBeenExpanded(theNode) {\n if(theNode.children.length === 1 && theNode.children[0].type===\"loading\") {\n return false;\n }\n return true;\n }", "function expandChildren(depth) {\t\n\tvar node = this;\n\n\tif (depth)\n\t\tdepth--;\n\n\tnode.expanded = true;\n\tif (node.childCount > 0) {\n\t\tnode.button.src = node.MSrc;\n\t\tif (!node.isitblank) {\n\t\t\tnode.img.src = node.openFolder;\n\t\t}\n\t}\n \n\tfor (var i = 0; i < node.childCount; i++) {\n\t\tvar cnode = node.children[i];\n\n\t\tdocument.all[\"Item\"+cnode.id].style.display = \"block\";\n\t\tcnode.visible = true;\n\t\t\n\t\tif (depth == null && cnode.expanded) {\n\t\t\tcnode.expandChildren();\n\t\t} else {\n\t\t\tif (depth != null && depth != 0) {\n\t\t\t\tcnode.expandChildren(depth);\n\t\t\t}\n\t\t}\n\t}\n}", "function expandInfo() {\n\n var activePass = app.getPassActive();\n var expandedItem = d3.select('.expanded'); //current open <li>\n var activeItem = d3.select(d3.select(activePass.rootID).node().parentNode); //soon to open <li>\n\n if (expandedItem.empty()) { //no panel expanded\n openExpander(activeItem);\n } else if (isExpanded()) { //a panel is already expanded\n closeExpander(expandedItem);\n } else if (activeItem.node().offsetTop == expandedItem.node().offsetTop) { //selection in same row\n moveExpander(expandedItem, activeItem);\n } else { //selection in new row\n closeExpander(expandedItem);\n openExpander(activeItem);\n }\n\n\n }", "function initializeExpandCollapse () {\n var topLi = $('li').first()\n collapseTree(topLi)\n expandLiOneLevel(topLi)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deleting using both class_id and subject_id
static async deleteByboth(class_id, subject_id) { this.class_id = class_id this.subject_id = subject_id this.result = await pool.query( 'DELETE FROM subject_combination_tbl WHERE class_id =$1 AND subject_id = $2', [class_id, subject_id] ) return this.result.rowCount }
[ "function deleteSubject(req, res) {\n Subject.findByIdAndRemove(ObjectID(req.params.id), (err, subject) => {\n if (err) {\n res.send(err);\n }\n res.json({ message: `${subject.name} deleted` });\n });\n}", "function deleteSubject(subjectId) {\n return SubjectCollection.findByIdAndDelete(subjectId)\n}", "function deleteSubject(callback, subjectGuid) {\n validateArgs(arguments, 'deleteSubject', 2, 2, [null, String]);\n mc.db.deleteSubject(subjectGuid, function(e) {\n callback.resume(e);\n });\n }", "function delSubj() {\n\t\n\tdelCurrentSubject();\n\t\n\tsetSubjectVals();\n\tsetSubjSelect();\n\t\n}", "function deleteClass(id) {\n return db(\"classes\").where({ id }).del();\n}", "function deleteSubjectInTransaction(transaction, subjectGuid, callback, keepAttachments) {\n mc.db.getSubjectInTransaction(transaction, subjectGuid, function(trx, subject, e) {\n var i, n, process, processName;\n trx = undefined;\n function deleted(e) {\n if (!e) {\n if (!keepAttachments && mc.replstore !== undefined) {\n mc.replstore.delete_attachment_date(subjectGuid);\n }\n if (process && process.version !== mc.db.getLatestProcessVersion(process.id)) {\n if (process.subjectGuids === undefined || process.subjectGuids.length === 0) {\n deleteProcess(processName);\n }\n }\n if (callback) {\n callback();\n }\n updateUsedProcessVersionsCookie(function() { });\n } else if (callback) {\n callback(e);\n }\n }\n subjectGuid = mc.db.getSubjectGuid(subjectGuid);\n if (subject !== undefined && subject !== null) {\n processName = mc.db.makeProcessName({\n 'id': subject._meta.processId,\n 'version': subject._meta.processVersion\n });\n if (currentProcess !== undefined && currentProcess.name !== undefined && currentProcess.name === processName) {\n process = currentProcess.value;\n } else {\n process = mc.db.getProcess(processName);\n }\n if (process !== undefined) {\n if (process.subjectGuids !== undefined) {\n n = process.subjectGuids.length;\n for (i = 0; i < n; i += 1) {\n if (process.subjectGuids[i] === subjectGuid) {\n process.subjectGuids.splice(i, 1);\n if (process.currentSubjectGuid === subjectGuid) {\n delete process.currentSubjectGuid;\n }\n mc.db.setProcess(processName, process);\n break;\n }\n }\n }\n }\n mc.db._deleteSubjectInTransaction(transaction, subjectGuid, keepAttachments, deleted);\n } else {\n if (callback) {\n callback(e);\n }\n }\n });\n }", "function onClickDeleteClassroom() {\n var $tr = $( this ).closest( 'tr' );\n var id = $tr.data( 'classroomId' );\n if ( window.confirm( 'Are you sure you want to delete the ' + Classrooms.records[ id ].name + ' classroom?' ) ) {\n ClassroomController.remove( id );\n }\n }", "function deleteClassroom(classroomid) {\n\tif (classrooms[classroomid]) {\n\t\tdelete classrooms[classroomid];\n\t}\n}", "function deleteClass(id) {\n return db(\"classes\").where({ id }).delete();\n}", "function removeSubjectToTeacher(subject){\n\t\tvar deferred = $q.defer();\n\t\tvar data = subject;\n\t\tif(data!=null){\n\t\t\t$http.post(\"./subject/remove\",JSON.stringify(data))\n\t\t\t.then(function complete(response){\n\t\t\t\tif(response.data.type==\"OK\"){\n\t\t\t\t\t$scope.teacherS.subjects.splice($scope.teacherS.subjects.indexOf(subject),1);\n\t\t\t\t\tdeferred.resolve(response.data);\n\t\t\t\t}else{\n\t\t\t\t\tdeferred.resolve(response.data);\n\t\t\t\t}\n\t\t\t},\n\t\t\tfunction error(response){\n\t\t\t\tdeferred.resolve({type:\"error\"});\n\t\t\t});\n\t\t}else{\n\t\t\tdeferred.resolve({type:\"error\"});\n\t\t}\n\t\treturn deferred.promise;\n\t}", "function deleteClass(req, res) {\n deleteClassFromDB(req.params.id).exec((err) => {\n if (err) {\n res.status(500).send();\n } else {\n res.sendStatus(204);\n }\n });\n}", "function deleteClass(id) {\n return db(\"classes\")\n .where(\"id\", id)\n .del();\n}", "function quitclazz(selected) {\n var uid = data.user().Id();\n var cid = selected().Id();\n\n // TODO: delete this record from UserClasses table\n }", "function deleteStudents() {\n\t$(\"#list-students li\").each( function() {\n\t\tvar selection = $(this); \n\t\tif (selection.hasClass('active')) { \n\t\t\tvar selectionContent = selection.html(); \n\t\t\tvar locate = selectionContent.lastIndexOf(\"<span\");\n\t\t\tvar thestudent;\n\t\t\tif (locate == -1) {\n\t\t\t\tthestudent = selectionContent;\n\t\t\t} else { \n\t\t\t\tthestudent = selectionContent.substring(0,locate);\n\t\t\t} \n\t\t\tdb.transaction(function (tx) { \n\t\t\t\ttx.executeSql(\"SELECT studentId FROM students WHERE studentName = ?;\", [thestudent], function(tx, result) {\n\t\t\t\t\tvar studentID = result.rows.item(0).studentId; \n\t\t\t\t\ttx.executeSql(\"DELETE FROM class_students WHERE classId =? AND studentId =?;\", [classID,studentID]);\n\t\t\t\t});\n\t\t\t});\t\t\t//need to specify if delete from students table when is not used for any class\n\t\t}\n\t});\n\tshowStudents();\n}", "function deleteClass() {\n db.collection(\"Classes\").doc(className)\n .delete()\n .then(() => {\n console.log(\"Class successfully deleted!\");\n db.collection(\"Students\")\n .where(\"Student_Class\", \"==\", className)\n .get()\n .then((querySnapshot) => {\n if (querySnapshot.size == 0) {\n location.href = \"./educator-home.html\";\n }\n querySnapshot.forEach((doc) => {\n resetStudentClass(doc.id);\n })\n })\n }).catch((error) => {\n console.error(\"Error deleting class: \", error);\n });\n}", "function deleteSubject(subjectGuid, callback, keepAttachments) {\n mc.db.getSubject(subjectGuid, function(subject, e) {\n var i, n, process, processName;\n function deleted(e) {\n if (!e) {\n if (!keepAttachments && mc.replstore !== undefined) {\n mc.replstore.delete_attachment_date(subjectGuid);\n }\n if (process && process.version !== mc.db.getLatestProcessVersion(process.id)) {\n if (process.subjectGuids === undefined ||\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprocess.subjectGuids.length === 0) {\n deleteProcess(processName);\n }\n }\n updateUsedProcessVersionsCookie(function() {\n if (callback) {\n callback();\n }\n });\n } else {\n if (callback) {\n callback(e);\n }\n }\n }\n subjectGuid = mc.db.getSubjectGuid(subjectGuid);\n if (subject !== undefined && subject !== null) {\n processName = mc.db.makeProcessName({ 'id': subject._meta.processId,\n 'version': subject._meta.processVersion\n });\n if (currentProcess !== undefined && currentProcess.name !== undefined\n\t\t\t\t\t\t&& currentProcess.name === processName) {\n process = currentProcess.value;\n } else {\n process = mc.db.getProcess(processName);\n }\n if (process !== undefined) {\n if (process.subjectGuids !== undefined) {\n n = process.subjectGuids.length;\n for (i = 0; i < n; i += 1) {\n if (process.subjectGuids[i] === subjectGuid) {\n process.subjectGuids.splice(i, 1);\n if (process.currentSubjectGuid === subjectGuid) {\n delete process.currentSubjectGuid;\n }\n mc.db.setProcess(processName, process);\n break;\n }\n }\n }\n }\n mc.db._deleteSubject(subjectGuid, keepAttachments, deleted);\n } else {\n if (callback) {\n callback(e);\n }\n }\n });\n }", "function teacherClassDelete(teacherClasses) {\r\n var url = getBaseURL() + \"TeacherClass/BulkDelete\";\r\n //return $http.delete(url);\r\n return $http({\r\n method: \"POST\",\r\n url: url,\r\n data: teacherClasses\r\n });\r\n }", "'click #delete'(event, instance) {\n \tPrimary.remove(this._id)\n }", "function deleteSubjects(id) {\n let r = confirm(\n \"Deleting a Subject will delete All the Data Associated With It\"\n );\n if (r == true) {\n let f = confirm(\"Are you Sure\");\n if (f == true) {\n let subref = firebase\n .database()\n .ref(\"portal_db/courses\")\n .child(_courseID)\n .child(\"subjects\");\n subref.child(id).remove();\n listSubjectList();\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To collect droped users
drop(e) { this.setState({ selectedUsers: [ ...this.state.selectedUsers, // keeping old records ...this.state.users.filter( u => u.uuid === e.dataTransfer.getData("item") //filtering current droped record ) ] }); }
[ "visitDropUser(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "dropUser(name) {\n const drop = this.query({name: name});\n\n UserStore.signOutUser(drop);\n\n this.users = this.users.filter(user => user.name !== drop.name);\n this.updateUsersFile();\n }", "getRemovedUsers () {\n\t\treturn [this.users[2].user];\n\t}", "getRemovedUsers () {\n\t\treturn [this.currentUser.user];\n\t}", "function onGroupZoneDrop( event ){\n if( event.target ){\n var atd = JSON.parse( event.dataTransfer.getData('atd') ),\n groupId = event.target.getAttribute('data-group-id');\n\n if( groupId && ctrl.groups[groupId] ){\n\n if( atd.grp ){\n ctrl.groups[atd.grp].users.splice(ctrl.groups[atd.grp].users.indexOf(atd.id),1);\n }else{\n ctrl.availableAttendees.splice(ctrl.availableAttendees.indexOf(atd.id),1);\n }\n\n ctrl.groups[groupId].users.push(atd.id);\n ctrl.isUpdated = true;\n }\n }\n }", "function dropData() {\n accounts.length = 0;\n}", "function dropTestUsers() {\n return new Promise((resolve, reject) => {\n Users.root.orderByChild('public/testuser').equalTo(true).once(\"value\", snapshot => {\n let list = snapshot.val();\n if (!list) {\n resolve();\n } else {\n let ids = Object.keys(list);\n let deleteUser = function() {\n let id = ids.shift();\n return Users.root.removeUser({email: list[id].private.email, password: 'testuser'})\n .then(ok => {\n return Users.root.child(id).remove();\n });\n };\n resolve(repeat(ids.length, deleteUser));\n }\n }, error => {\n reject(err);\n });\n });\n}", "static getUserIdsExceptMe() {\n return game.users\n .filter((user) => {\n return user.id !== game.userId;\n })\n .map((user) => user.id);\n }", "function onAvailableAtdDrop( event ){\n if( event.dataTransfer ){\n var atd = JSON.parse( event.dataTransfer.getData('atd') );\n if( atd.grp ){\n ctrl.groups[atd.grp].users.splice(ctrl.groups[atd.grp].users.indexOf(atd.id),1);\n ctrl.availableAttendees.push( atd.id );\n ctrl.isUpdated = true;\n }\n }\n }", "exitDropUser(ctx) {\n\t}", "getAddedUsers () {\n\t\treturn this.users.slice(2).map(user => user.user);\n\t}", "function dragAndDropUsers() {\n const draggables = document.querySelectorAll('.table-users tr:not(.tableRow-heading)');\n // Dragstart and Dragend\n draggables.forEach(draggable => {\n draggable.addEventListener('dragstart', () => {\n draggable.classList.add('dragging');\n });\n\n draggable.addEventListener('dragend', () => {\n draggable.classList.remove('dragging');\n });\n });\n\n // Drop row\n const containers = document.querySelectorAll('.table-users tr:not(.tableRow-heading, .dragging)');\n\n containers.forEach(container => {\n container.addEventListener('dragover', e => {\n e.preventDefault();\n const draggable = document.querySelectorAll('.dragging');\n container.before(draggable[0]);\n });\n });\n \n}", "removeUsers(users) {\n if (typeof users === 'string') {\n users = [users];\n }\n\n for (let i = 0; i < users.length; i++) {\n }\n }", "function users_(){this.users=( []);}", "getAddedAdmins () {\n\t\treturn this.users.splice(1).map(data => data.user);\n\t}", "function unblock_user() {\n var username = $(this).data(\"username\"), target_idx = bad_users.indexOf(username);\n if (target_idx !== -1) {\n bad_users.splice(target_idx, 1);\n }\n refresh_user(username);\n save_users();\n}", "applyToUsers(){\n\t\tlet listName = [, \"collection\", \"trade\", \"wish\"][this.type];\n\t\tlet releaseID = this.release.id;\n\t\t\n\t\tfor(let i of this.data){\n\t\t\tlet [groupID, username, version, notes] = i;\n\t\t\tlet user = new User(username.match(/>([^<]+)<\\/a>\\s*$/i)[1]);\n\t\t\tlet list = user.lists[listName];\n\t\t\t\n\t\t\t/** User owns this particular version */\n\t\t\tif(+groupID === 0){\n\t\t\t\tif(!list.some(i => i.version == releaseID))\n\t\t\t\t\tlist.push({\n\t\t\t\t\t\tid: this.release.getParent().id,\n\t\t\t\t\t\tversion: releaseID,\n\t\t\t\t\t\tnotes: notes\n\t\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t\t/** User never specified the release's version */\n\t\t\telse if(\"Unspecified\" === version && !this.release.parent){\n\t\t\t\tif(!list.some(i => i.id == releaseID))\n\t\t\t\t\tlist.push({\n\t\t\t\t\t\tid: releaseID,\n\t\t\t\t\t\tnotes: notes\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}", "function processUserRemoved (event) {\n let ativeUsers = $('#active-users').children('.participant')\n ativeUsers.map((user) => {\n if (ativeUsers[user].textContent === event.username) { ativeUsers[user].remove() }\n let messagesList = $('#chat-board')\n let messageToAdd = '<p style=color:red;>*** ' + event.username + ' left this chat room! ***</p>'\n messagesList.append(messageToAdd)\n $('#chat-board').scrollTop($('#chat-board')[0].scrollHeight)\n })\n}", "function userRemoveUnwanted(users) {\n const result = [];\n for (let i = 0; i < users.length; i++) {\n const temp = users[i];\n const obj = {\n _id: temp._id,\n name: temp.name,\n age: temp.age,\n gender: temp.gender,\n };\n result.push(obj);\n }\n return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the basic instruments using Gibberish
function createInstruments (Gibberish) { // The actual instruments const kick = new Gibberish.Kick({ decay: 0.2 }).connect() const snare = new Gibberish.Snare({ snappy: 1.5 }).connect() const hat = new Gibberish.Hat({ amp: 1.5 }).connect() const conga = new Gibberish.Conga({ amp: 0.25, freq: 400 }).connect() const tom = new Gibberish.Tom({ amp: 0.25, freq: 400 }).connect() const pluck = new Gibberish.PolyKarplusStrong({maxVoices: 32}).connect() const bass = new Gibberish.MonoSynth({ attack: 44, decay: Gibberish.Time.beats(0.25), filterMult: 0.25, octave2: 0, octave3: 0 }).connect() const sampleRate = Gibberish.sampleRate // The instrument trigger functions return { kick: perc(kick, 0.5), snare: perc(snare, 0.25), hat: perc(hat, 1), conga: pitched(conga, 0.25), tom: pitched(tom, 0.25), pluck: (ctx) => { const amp = ctx.get("amp") const freq = ctx.get("freq") if (freq > 0) { // this is not in any way accurate, just a hack to make @set-dur do something semi-meaningful pluck.damping = 1 - (-6 / Math.log(freq / sampleRate)) // pluck by default seem too quiet: pluck.note(freq, amp * amp * 2) } }, bass: (ctx) => { const velocity = ctx.get("amp") const freq = ctx.get("freq") if (freq > 0) bass.note(freq, velocity) } } }
[ "function setupInstruments () {\n\n // Initialise Gibber\n Gibber.init();\n\n // Create our drums loop, at 1/8 note length\n // x = kick\n // o = snare\n // * = hihat closed\n // - = hihat open (I think?)\n // . = nothing\n var drums = EDrums('x.o.x*o.x.oxx-o.',1/8);\n var bassSynth = Mono('bass').note.seq( [0,7], 1/8 )\n}", "function createGrammar(){\n for (var i = 1; i < 6; i++) {\n //pushing 100 words for each syllable type in the grammar\n for (var j = 0; j < 100; j++) {\n grammarJSON[\"<\"+i+\">\"].push(RiTa.randomWord(i))\n }\n }\n rg = new RiGrammar()\n rg.load(grammarJSON)\n}", "function createString(i) {\n i = i || 0;\n var string = {\n gainNode: audioContext.createGain(),\n panner: audioContext.createPanner()\n };\n\n var pan = ((2/strings.length) * i+1) - 2;\n var volume = ((0.16/strings.length) * i*2)+0.2;\n string.panner.panningModel = \"equalpower\";\n string.panner.setPosition(pan,0,0);\n string.gainNode.gain.value = 0;\n string.gainNode.gain.toValue = 0.16;\n\n string.panner.connect(audioContext.destination);\n string.gainNode.connect(string.panner);\n\n return string;\n\n }", "genererMenuInstruments() {\n\n }", "function createStartInstruction () {\n currentInstruction = \"createStartInstruction\";\n saveData();\n beforeShowInstruction();\n var text = strings.practiceIntro(); // (1)\n var button = ex.createButton(0, 0, strings.okButtonText());\n introBox = ex.textbox112(text,\n {\n stay: true,\n color: instrColor\n }, instrW, instrX);\n button.on(\"click\", function () {\n saveData();\n introBox.remove();\n currentInstruction = \"\";\n afterCloseInstruction();\n createIterationQ();\n saveData();\n });\n ex.insertButtonTextbox112(introBox, button, \"BTNA\");\n saveData();\n }", "function setupSequencer() {\n for(var i=0; i<sequencer.instruments.length; i++) {\n //console.log(\"instruments:\"+instruments.length)\n var seqBar = document.createElement(\"div\");\n \n //bar.classList.add(\"bar\");\n seq.append(seqBar);\n for(var j = 0; j < sequencer.numOfBeats; j++) {\n var b = document.createElement(\"button\")\n b.classList.add(\"box\")\n //b.innerText = \"\"+i+j\n seqBar.append(b)\n }\n \n }\n}", "function instrument_setup() {\r\n\tbass = new Tone.DuoSynth().toMaster();\r\n\tpad = new Tone.DuoSynth().toMaster();\r\n\r\n\tsynth = new Tone.PolySynth(6, Tone.Synth, {\r\n\t\t\"oscillator\" : {\r\n\t\t\t\"type\" : \"square\"\r\n\t\t}\r\n\t}).toMaster();\r\n\r\n // Samples were purchased from Samples from Mars\r\n\t// https://samplesfrommars.com/\r\n\tsampler = new Tone.Sampler({\r\n\t\t\"C3\" : \"Kick.wav\",\r\n\t\t\"E3\" : \"Snare.wav\",\r\n\t\t\"F#3\": \"CH.wav\",\r\n\t\t\"G3\" : \"Cowbell.wav\",\r\n\t}).toMaster();\r\n\r\n\t// instrument volume control\r\n\tpad.volume.value = -10;\r\n\tsynth.volume.value = -20;\r\n\tbass.volume.value = -5;\r\n\tsampler.volume.value = -5;\r\n}", "generateBasicInfo() {\n this.generateGender();\n this.generateName();\n this.generateAppearance();\n }", "function generateBird() {\r\n // Create a generator object from this data\r\n const generator = new Improv(grammarData, {\r\n filters: [Improv.filters.mismatchFilter(), Improv.filters.unmentioned()],\r\n reincorporate: true\r\n });\r\n\r\n const model = {};\r\n // Generate text and print it out\r\n try {\r\n var bird = generator.gen('root', model).trim();\r\n } catch (e) {\r\n console.log(model);\r\n throw e;\r\n }\r\n\r\n // Hacks to clean up some grammar\r\n bird = bird.replace(/\\s+/g, \" \");\r\n bird = bird.replace(\" the an \", \" the \");\r\n bird = bird.replace(\" the a \", \" the \");\r\n bird = bird.replace(\" its an \", \" its \");\r\n bird = bird.replace(\" its a \", \" its \");\r\n bird = bird.replace(\" a u\", \" an u\");\r\n bird = bird.replace(\" .\", \".\");\r\n\r\n return bird;\r\n\r\n}", "function createCodeSample(script) {\n \n //\n // Parse the text of the script. We should have a sequence of \n // code samples by language with delimiters that look like \n // \n // !! <language> \n // \n // We split this into a map from language to sample. \n //\n\n var codeList = new Array();\n var language = \"\";\n var text = new Array();\n var options = {};\n\n var lineList = script.text.split(/\\n/);\n lineList[lineList.length] = \"!!\";\n\n for (var i = 0; i < lineList.length; i++) {\n \n line = lineList[i];\n\n if (line.substring(0, 2) == \"::\") {\n\n words = line.split(/\\s+/);\n options[words[1]] = words[2];\n continue;\n\n }\n \n if (line.substring(0, 2) == \"!!\") {\n\n while (text.length > 0 && text[0].match(/^\\s*$/)) {\n text.shift();\n }\n \n while (text.length > 0 && text[text.length - 1].match(/^\\s*$/)) {\n text.pop();\n }\n \n if (text.length > 0) {\n codeList[codeList.length] = { language: language,\n text: text.join(\"\\n\") };\n }\n\n language = line.split(/\\s+/)[1];\n text = new Array();\n\n continue;\n\n }\n \n line = line.replace(\"&\", \"&amp;\");\n line = line.replace(\"<\", \"&lt;\");\n line = line.replace(\">\", \"&gt;\");\n\n text[text.length] = line;\n\n }\n\n var classRoot = \"code_sample\";\n if (options[\"class\"]) {\n classRoot = options[\"class\"];\n }\n\n //\n // Start laying out the widget. \n //\n\n var table = document.createElement(\"table\");\n table.className = classRoot;\n var tr = document.createElement(\"tr\");\n tr.className = classRoot;\n var td = document.createElement(\"td\");\n td.className = classRoot + \"_code\";\n \n if (codeList.length > 1) {\n td.colSpan = 2;\n }\n\n var codeDiv = document.createElement(\"div\");\n codeDiv.className = classRoot;\n codeDiv.innerHTML = \"<code><pre>\" + codeList[0].text + \"</pre></code>\";\n td.appendChild(codeDiv);\n tr.appendChild(td);\n table.appendChild(tr);\n\n if (codeList.length > 1) {\n\n var tr = document.createElement(\"tr\");\n var codeTd = document.createElement(\"td\");\n codeTd.className = classRoot + \"_language\";\n codeTd.innerHTML = \"language\";\n var td = document.createElement(\"td\");\n td.className = classRoot + \"_buttons\";\n codeTd.innerHTML = \"<b>\" + codeList[0].language + \"</b>\"; \n\n for (var i = 0; i < codeList.length; i++) {\n\n var button = document.createElement(\"button\");\n button.innerHTML = codeList[i].language;\n\n button.onclick = (function(td, language, div, text) {\n return function() {\n td.innerHTML = \"<b>\" + language + \"</b>\"; \n div.innerHTML = \"<code><pre>\" + text + \"</pre></code>\";\n }\n })(codeTd, codeList[i].language, codeDiv, codeList[i].text);\n\n td.appendChild(button);\n\n }\n\n tr.appendChild(codeTd);\n tr.appendChild(td);\n table.appendChild(tr);\n\n }\n\n script.parentNode.replaceChild(table, script);\n\n }", "static fromScratch(instruments,numOfBeats) {\n let sequence = [];\n instruments.forEach( () => {\n sequence.push(new Array(numOfBeats).fill(0));\n });\n this.sequence = sequence;\n return new Sequencer(sequence,instruments,numOfBeats)\n }", "genererMenuInstruments() {\n //console.log(\"Nouvel Instrument du fichier : initcube.xml\");\n $(\"#Instrument\").empty();\n for (var i = 0; i < this.listeInstruments.length; i++) {\n $(\"#Instrument\").append('<div class=\"Instrument_1\"><a href=\"#page' \n + this.listeInstruments[i].ref + '\"><img src=\"images/' \n + this.listeInstruments[i].ref + '.png\"/><br/><span>' \n + this.listeInstruments[i].nom + '</span></a></div>');\n }\n \n }", "function render_instructions() {\n var p_tag = document.createElement('p');\n p_tag.appendChild(document.createTextNode('The process here is simple. You will be shown three characters from the Game of Thrones tv show. Just pick which of the three you believe is the most likely to be killed off next!'));\n document.body.appendChild(p_tag);\n p_tag = document.createElement('p');\n p_tag.appendChild(document.createTextNode('After you\\'ve gone through 16 sets of photos, you will have the option of seeing the statistics you chose!'));\n document.body.appendChild(p_tag);\n}", "function generateHaiku() {\n // Make a DIV with the new sentence\n var expansion = cfree.getExpansion('<start>');\n expansion = expansion.replace(/%/g, '<br/>');\n var par = createP(expansion);\n par.class('text');\n}", "function createInstruments() {\n const stepColor = [\"red\", \"orange\", \"yellow\", \"white\"];\n\n let diff = 0;\n\n instruments.forEach(instrument => {\n let instrumentDiv = document.createElement(\"div\");\n instrumentDiv.classList.add(\"instrument\");\n $(\".sequencer\").append(instrumentDiv);\n\n let colorIndex = 0;\n for (let i = 0; i < 16; i++) {\n let div = document.createElement(\"div\");\n div.classList.add(\n \"step\",\n \"step-\" + stepColor[colorIndex],\n \"step-\" + instrument\n );\n div.id = i + diff;\n instrumentDiv.append(div);\n\n if ((i + 1) % 4 === 0) {\n colorIndex++;\n }\n }\n console.log(instrumentDiv);\n\n diff += 16;\n });\n}", "function on_build_demo_signals()\n{\n var samples_to_build = ScanaStudio.builder_get_maximum_samples_count();\n var silence_period_samples = 1000 + (samples_to_build / 125);\n var uart_builder = ScanaStudio.BuilderObject;\n reload_dec_gui_values();\n uart_builder.config(\n Number(ScanaStudio.gui_get_value(\"ch\")),\n Number(ScanaStudio.gui_get_value(\"baud\")),\n Number(ScanaStudio.gui_get_value(\"nbits\")),\n Number(ScanaStudio.gui_get_value(\"parity\")),\n Number(ScanaStudio.gui_get_value(\"stop\")),\n Number(ScanaStudio.gui_get_value(\"order\")),\n Number(ScanaStudio.gui_get_value(\"invert\")),\n Number(ScanaStudio.builder_get_sample_rate())\n );\n\n uart_builder.put_silence(10);\n uart_builder.put_str(\"Hello world, this is a test!\");\n counter = 0;\n while(ScanaStudio.builder_get_samples_acc(channel) < samples_to_build)\n {\n if (ScanaStudio.abort_is_requested())\n \t\t{\n \t\t\tbreak;\n \t\t}\n random_size = Math.floor(Math.random()*10) + 1;\n for (w = 0; w < random_size; w++)\n {\n uart_builder.put_c(counter);\n counter++;\n if (ScanaStudio.builder_get_samples_acc(channel) >= samples_to_build)\n {\n break;\n }\n }\n uart_builder.put_silence_samples(silence_period_samples);\n }\n}", "function createInstruction() {\n createElement('h1', 'Runway im2txt(image to text) model with p5.js');\n createElement('p', '1. Open Runway, add im2txt model to your workspace <br>2. Select \"Network\" as input and ouput, Run the model<br>3. Update the \"port\" variable in the \"sketch.js\" file to the number shown in Runway input \"Network\" window, e.g. http://localhost:8000<br>4. Run the sketch<br>5. Click the \"image to text\" button get a caption of the image from your webcam.');\n}", "function createInstructions() {\n var clickAndDragMessage = $.i18n('clickAndDrag');\n instructions = draw.text(clickAndDragMessage).x(20).y(20).font({size: 28, family: 'Chewy'});\n}", "function main(){\r\n createIngredientList(startingIngredientFields);\r\n createInstructionList(startingInstructionAreas);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
==== create the rooms ==== load everything from the configuration and wire the properties into real files.
function setupRooms () { var roomConfig = game.gameData.room; // split the options from the rest of the settings object: _options = roomConfig.options; delete roomConfig.options; // save the variables from the options: currentRoom = _options.currentRoom; // make rooms from the rest of the array: for (var roomName in roomConfig) { if (roomConfig.hasOwnProperty(roomName)) { new Room (roomName, roomConfig[roomName]); /*.image, roomConfig[roomName].width, roomConfig[roomName].height, roomName, roomConfig[roomName].options);*/ } } console.log ('Room: List of rooms. ', roomList); }
[ "setupRooms() {\n\t\tconst startingRoom = sessionStorage.ta\n\t\t\t? JSON.parse(sessionStorage.ta).rooms\n\t\t\t: 'Lobby';\n\t\tconst roomsStateConfig = {\n\t\t\troom: {\n\t\t\t\tvalue: startingRoom,\n\t\t\t\ttriggers: [],\n\t\t\t},\n\t\t};\n\n\t\tthis.rooms = {};\n\t\tObject.keys(ROOMS.default).forEach((room) => {\n\t\t\tconst roomConfig = ROOMS.default[room];\n\t\t\troomConfig.name = room;\n\t\t\tthis.rooms[room] = new Room(roomConfig);\n\n\t\t\troomsStateConfig.room.triggers.push({\n\t\t\t\tname: room,\n\t\t\t\tevent: `taEnter${room[0].toUpperCase() + room.substring(1)}`,\n\t\t\t\ton: 'onEnterRoom',\n\t\t\t});\n\t\t});\n\n\t\tthis.roomsState = new StateMachine(this, roomsStateConfig);\n\t}", "static load_all() {\n server.log(\"Loading rooms...\", 2);\n\n server.modules.fs.readdirSync(server.settings.data_dir + '/rooms/').forEach(function(file) {\n if (file !== 'room_connections.json') {\n var data = server.modules.fs.readFileSync(server.settings.data_dir +\n '/rooms/' + file, 'utf8');\n\n data = JSON.parse(data);\n server.log(\"Loading room \" + data.name, 2);\n Room.load(data);\n }\n });\n\n server.log(\"Loading Room Connections\", 2);\n try {\n var connections = JSON.parse(server.modules.fs.readFileSync(server.settings.data_dir +\n '/rooms/room_connections.json'));\n\n for (var room_id in connections) {\n var room = Room.get_room_by_id(room_id);\n for (let adj_id of connections[room_id]) {\n var adj = Room.get_room_by_id(adj_id);\n room.connect_room(adj, false);\n }\n }\n }\n catch(err) {\n server.log(err, 1);\n }\n\n server.log(\"Rooms loaded.\", 2);\n }", "function initializeRoomMemory(roomName) {\n console.log('initializing room - ', roomName);\n if ( !Memory.rooms ) { Memory.rooms = {} }\n Memory.rooms[roomName] = {};\n if ( !Memory.rooms[roomName].layout ) { Memory.rooms[roomName].layout = {}; }\n if ( !Memory.rooms[roomName].layout.status ) { Memory.rooms[roomName].layout.status = {}; }\n if ( !Memory.rooms[roomName].layout.status.prelimPathing )\n {\n Memory.rooms[roomName].layout.status.prelimPathing = {} ;\n }\n if ( !Memory.rooms[roomName].layout.prelimPathing )\n {\n Memory.rooms[roomName].layout.prelimPathing = {} ;\n }\n let room = Game.rooms[roomName];\n\n\n //console.log('room.controller ' + room.controller)\n Memory.rooms[roomName].controller = null;\n if ( room.controller ) {\n Memory.rooms[roomName].controller = room.controller.id;\n controllerThingamajig.confirmControllerInitialized(room.controller);\n }\n\n let roomSources = room.find(FIND_SOURCES);\n //let firstSource = room.find(FIND_SOURCES);\n Memory.rooms[roomName].sources = [];\n\n for (let index in roomSources) {\n let s = roomSources[index];\n Memory.rooms[roomName].sources.push(s.id);\n energySources.confirmSourceInitialized(s);\n }\n}", "function initializeRoomData() {\n\tvar rooms = JSONData.rooms;\n\tfor (var i = 0; i < rooms.length; i++) {\n\t\tvar newRoom = {};\n\t\tnewRoom[\"_id\"] = generateUUID();\n\t\tnewRoom.title = rooms[i].prefix + \" \" + rooms[i].number;\n\t\tnewRoom.classes = [];\n\t\troomData.push(newRoom);\n\t}\n}", "function configureRoom(room) {\n room.isPlayable = true;\n room.hasStarted = false;\n room.playerTurn = 1;\n room.cards = require('./cards');\n }", "function loadRoomsAndProcess(filenames, static_roomnames)\n{\n var temp_rooms = {},\n k;\n\n for (k in filenames)\n {\n if (filenames.hasOwnProperty(k)) {\n watchFile(filenames[k]);\n }\n }\n}", "createRooms(){\n let walls = [\n [ 0, 0,40, 1], [39, 0,40,25], [ 0,24,40,25], [ 0, 0, 1,24], // outer walls\n [14,10,12, 5], // inner block\n [ 1,12, 6, 1], [ 8,12, 6, 1], [26,12, 6, 1], [33,12, 6, 1], // horizontal walls\n [14, 1, 1, 2], [14, 4, 1, 6], [25, 1, 1, 6], [25, 8, 1, 2], // vertical walls inkl.door\n [14,15, 1, 2], [14,18, 1, 6], [25,15, 1, 6], [25,22, 1, 2] // vertical walls inkl.door\n ];\n walls.map( (wallData) => {\n this.wallObjects.push( new Wall((wallData[0]).mx(),(wallData[1]).mx(),\n (wallData[2]).mx(),(wallData[3]).mx(),this.colorList[this.curColor],this.ctx));\n } );\n }", "function setup_default_room(){\n var list = ['Java is the best', 'C++/C is the best', 'Python is the best', 'PHP is the best', 'JavaScript is the best'];\n for (var i =0, size = list.length; i < size; i++){\n console.log(list[i]);\n rooms[list[i]] = { room: list[i], users : { admin : 'admin' } };\n }\n console.log(rooms)\n}", "function PopulateMapRooms() {\n\trNW = Dice(3) - 11 + Dice(3) * 10; // NW room\n\tgridArr[rNW].open = 1;\n\tgridArr[rNW].room = \"NW\";\n\trNE = Dice(3) - 4 + Dice(3) * 10; // NE room\n\tgridArr[rNE].open = 1;\n\tgridArr[rNE].room = \"NE\";\n\trCN = Dice(2) + 33 + Dice(2) * 10; // Central room\n\tgridArr[rCN].open = 1;\n\tgridArr[rCN].room = \"CN\";\n\trSW =Dice(3) + 59 + Dice(3) * 10; // SW room\n\tgridArr[rSW].open = 1;\n\tgridArr[rSW].room = \"SW\";\n\trSE = Dice(3) + 66 + Dice(3) * 10; // SE room\n\tgridArr[rSE].open = 1;\n\tgridArr[rSE].room = \"SE\";\n\trST = Dice(2) + 3; // Start room\n\tgridArr[rST].open = 1;\n\tgridArr[rST].room = \"ST\";\n\tgridArr[rST].explored = 1;\n\tgridArr[rST].pathValue = 1;\n}", "function makeRoomList() {\n //note return of derferred object\n return $.ajax({\n url: \"./xml/hotelRooms.xml\",\n type: \"GET\",\n cache: false,\n success: function (data) {\n $(data).find(\"hotelRoom\").each(function () {\n rooms.push(new Constructors.Room(\n $(this).find(\"number\").text(),\n $(this).find(\"roomType\").text(),\n $(this).find(\"description\").text(),\n $(this).find(\"pricePerNight\").text()));\n });\n },\n error: function () {\n alert(\"Couldn't find file\");\n }\n });\n }", "function run() {\n Memory.architect = Memory.architect || {\n maps: {},\n buildLists: {}\n };\n\n for (let name in Game.rooms) {\n let room = Game.rooms[name];\n\n build(room);\n }\n\n}", "createRooms (roomFileNames) {\n // roomFileNames.forEach((filename) => {\n // var name = filename.replace(/.dae/, '').replace(/[\\-_]/g, ' ')\n // this.rooms.push(new Room(name, filename))\n // })\n for (let filename of roomFileNames) {\n let name = filename.replace(/.dae/, '').replace(/[\\-_]/g, ' ')\n this.rooms.push(new Room(name, filename))\n }\n }", "async function makeRoom() {\n setLoading(true);\n try {\n const createRes = await createRoom();\n if (createRes.status !== 200) {\n throw new Error(ERROR_TYPE.hostRoom);\n }\n const roomID = createRes.data.gameID;\n await enterRoom(roomID, true);\n } catch (error) {\n setLoading(false);\n setError(ERROR_MESSAGE[error.message]);\n }\n }", "createFoyer () {\n this.rooms.push(new Room('foyer', 'foyer.dae'))\n }", "function createRoom(){\r\n container.removeAllChildren(); //clear all tiles\r\n weathercontainer.removeAllChildren(); //clear all weather effects\r\n weathereffectcontainer.removeAllChildren();\r\n weatherList = [];\r\n lastDialog = []; // dialogues are reset on room exit\r\n tileArray = [];\r\n enemyList = [];\r\n checkMusic(); // this used to be in ticker, but here is even better, right?\r\n stage.update();\r\n if(player_location == '11' || player_location == '12' || player_location == '17'){snowList = []} // resets snowballs\r\n if(player_location == '45' || player_location == '42' || player_location == '44'){fishList = []} // resets fish\r\n\r\n // build tiles\r\n lum = eval(\"props_room\" + player_location)[0][1]; // read from room properties\r\n curarray = eval(\"room\" + player_location); // just a holder for what the current room array is. saves some cpu time\r\n for(r = 0; r < curarray.length; r ++){\r\n for(c = 0; c < curarray[r].length; c ++){\r\n if(curarray[r][c] > 200){\r\n bitmap = new createjs.Sprite(ss_volcano, \"tile\" + curarray[r][c]); // volcano tiles are numbered from 200 on\r\n } else {\r\n bitmap = new createjs.Sprite(ss_world, \"tile\" + curarray[r][c]);\r\n if(lum < 1){bitmap.alpha = lum / 8}\r\n }\r\n bitmap.x = c * tilesize;\r\n bitmap.y = r * tilesize;\r\n container.addChild(bitmap);\r\n tileArray.push(bitmap); // basically this adds all tiles to the array so we can find them back later\r\n }\r\n }\r\n\r\n // show area name\r\n areaname.text = eval(\"props_room\" + player_location)[0][0];\r\n\r\n //build objects\r\n items = eval(\"props_room\" + player_location)[1];\r\n sceneries = eval(\"props_room\" + player_location)[4];\r\n interactions = eval(\"props_room\" + player_location)[3];\r\n enemies = eval(\"props_room\" + player_location)[2];\r\n\r\n for(a = 0; a < items.length; a ++){\r\n new Item(items[a][0], items[a][1], items[a][2]); // x,y,tileid\r\n }\r\n\r\n for(a=0; a < sceneries.length; a ++){\r\n new Scenery(sceneries[a][0], sceneries[a][1], sceneries[a][2]); // x,y,tileid\r\n }\r\n\r\n for(a=0; a < interactions.length; a ++){\r\n new Interaction(interactions[a][0], interactions[a][1], interactions[a][2], interactions[a][3]); // x,y,tileid,dialogueid\r\n }\r\n\r\n for(a=0; a < enemies.length; a ++){\r\n new Enemy(enemies[a][0], enemies[a][1], enemies[a][2], enemies[a][3], enemies[a][4], enemies[a][5]); // x,y,strength,life,speed,tileid\r\n }\r\n}", "addRooms(state, rooms) {\n for (let r of rooms) {\n if (state.rooms.hasOwnProperty(r.id)) { continue; }\n Vue.set(state.rooms, r.id, new Room(r.id, r.name, r.users, r.picture_url));\n }\n }", "function iniRoomsDB() {\n //ROOMS database:\n _dbrooms.info().then(function (result) {\n // Now, if it is the first time, a local document is created for updating purposes, otherwise, we will look for changes:\n if (result.doc_count == 0) {_firstTime = true; createLocalDocument(_dbrooms); syncDB(_dbrooms, _roomsdb_name);} else {checkMapChanges(0, _dbrooms_alias, checkMapChanges);} // \"CheckChanges\" is callled within the \"CheckMapchanges\" function to\n // avoid updating the rooms database before the map images were able to\n // be updated.\n }).catch(function (err) {\n console.log(\"error getting info about database:\");\n console.log(err);\n });\n iniBeaconsDB();\n}", "function _generateRooms()\n{\n // place the first room\n _placeFirstRoom();\n\n let targetNumberOfRooms = _randomIntFromInterval(config.rooms[0], config.rooms[0]);\n let attempts = 0;\n\n // add next level of rooms\n while(_addNextLevelRooms(targetNumberOfRooms) || attempts >= 10)\n {\n // make sure we don't get stuck in an infinite loop\n attempts++\n };\n}", "createRooms() {\n // Generates all the rooms and hallways for this Leaf and all of its children\n if (this.leftChild !== null || this.rightChild !== null) {\n // This leaf has been split, so go into the children leafs\n if (this.leftChild !== null) this.leftChild.createRooms();\n if (this.rightChild !== null) this.rightChild.createRooms();\n\n // If there are both left and right children in this Leaf, create a hallway between them\n if (this.leftChild !== null && this.rightChild !== null) {\n this.createHall(this.leftChild.getRoom(), this.rightChild.getRoom());\n }\n } else {\n // This Leaf is ready to make a room\n let roomSize = new Vector2();\n let roomPos = new Vector2();\n // The room can be between 3 x 3 tiles to the size of the leaf - 2\n roomSize = new Vector2(randomRegInt(3, this.width - 2), randomRegInt(3, this.height - 2));\n\n // Place the room within the Leaf, but don't put it right against the side of the Leaf (that would merge rooms together)\n roomPos = new Vector2(\n randomRegInt(1, this.width - roomSize.x - 1),\n randomRegInt(1, this.height - roomSize.y - 1)\n );\n\n // this.room = {x: this.x + roomPos.x, y: this.y + roomPos.y, width: roomSize.x, height: roomSize.y}\n // this.room = new Rect(this.x + roomPos.x, this.y + roomPos.y, roomSize.x, roomSize.y);\n const rect = new Rect(this.x + roomPos.x, this.y + roomPos.y, roomSize.x, roomSize.y);\n const area = this.generateRectArea(rect);\n this.room = {\n rect,\n area,\n };\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates HTML for the favorite button
function generateFavoriteButton(user, story) { const isFavorite = user.isFavorite(story); const heartType = isFavorite ? 'fas' : 'far'; return `<div class="favorite"> <i class="${heartType} fa-heart"></i> </div>`; }
[ "function viewFavorites(favorite) {\n $(\"<h4 class='favorites-title'>\" + favorite.data().firstName + \"</h4>\").appendTo(\".favorites-body\");\n $(\"<p class='favorites-text'> Email: \" + favorite.data().email + \"</p>\").appendTo(\".favorites-body\");\n $(\"<p class='favorites-text'> Phone: \" + favorite.data().phoneNumber + \"</p>\").appendTo(\".favorites-body\");\n $(\"<input type='button' class='btn btn-white btn-animation-1 middled-button' value='View Profile'></input>\").appendTo(\".favorites-body\");\n $(\"<hr>\").appendTo(\".favorites-body\");\n\n // Redirect to worker's profile when you click the \"View profile\" button\n $(\"input\").click(function() {\n window.location.href= \"/profile/?profile=\" + favorite.data().userKey;\n })\n }", "function renderButtons() {\n $(\"#buttons-view\").empty();\n for (var i = 0; i < favorites.length; i++) {\n var a = $(\"<button>\");\n a.addClass(\"favorite\");\n a.attr(\"data-name\", favorites[i]);\n a.text(favorites[i]);\n $(\"#buttons-view\").append(a);\n }\n }", "favoriteListItemTemplate(filmData) {\n return `<div class=\"fav__film\">\n <button class=\"fav__open js-open-details\" data-id=\"${filmData.id}\" \n aria-label=\"Open film details\"></button>\n ${filmData.name}\n <button class=\"fav__remove js-remove-from-fav\" data-id=\"${filmData.id}\" \n aria-label=\"Remove film from favorites\"></button>\n </div>`;\n }", "static favoriteButton(restaurant) {\r\n const button = document.createElement('button');\r\n button.innerHTML = `<i class=\"fas fa-star\"></i>`;\r\n button.className = \"fav\";\r\n button.dataset.id = restaurant.id;\r\n button.setAttribute('aria-label', `Mark ${restaurant.name} as a favorite.`);\r\n button.setAttribute('aria-pressed', restaurant.is_favorite);\r\n button.onclick = DBHelper.handleClick;\r\n\r\n return button;\r\n }", "function favouriteListHTML(){\n var favouriteFromLocalStorage=JSON.parse(localStorage.getItem('favourite'));\n var str='';\n if(favouriteFromLocalStorage==null || favouriteFromLocalStorage.length==0){\n str+=`<p>Turn on the coin's toggle for add to the favourite</p>`;\n }\n else{\n for(var i=0;i<favouriteFromLocalStorage.length;i++){\n str+=`<li id=\"${favouriteFromLocalStorage[i]}\">${favouriteFromLocalStorage[i].toUpperCase()}<span class=\"glyphicon glyphicon-remove\"></span></li>`;\n }\n // str+=`<button>SHOW</button>`;\n }\n return str;\n }", "function addFavoriteButton() {\n\n}", "function generateFavorites() {\n // empty out that part of the page\n $favoritedArticles.empty();\n\n if (currentUser.favorites.length === 0) {\n const msg = \"<h5>No favorites added!</h5>\";\n $favoritedArticles.append(msg);\n }\n\n // loop through all of our favorites and generate HTML for them\n for (let favorite of currentUser.favorites) {\n const result = generateStoryHTML(favorite);\n $favoritedArticles.append(result);\n }\n highlightFavorites();\n }", "function generateFavorites() {\n const myFavs = currentUser.favorites;\n if (myFavs.length === 0) {\n const $noFavs = $(`<h4>You haven't favorited any stories yet!</h4>`);\n $favoritedArticles.append($noFavs);\n }\n for (let story of myFavs) {\n const $newStory = generateStoryHTML(story);\n $favoritedArticles.append($newStory);\n }\n }", "function generateFavoriteHTML(story) {\n let hostName = getHostName(story.url);\n let starClass = \"fas\";\n // if (story has been favorited by user){\n // starClass = \"fas\";\n // }\n // console.log('story is ', story);\n // render favorite markup\n const favoriteMarkup = $(`\n <li id=\"${story.storyId}\">\n <span class=\"star\">\n <i class=\"${starClass} fa-star\"></i>\n </span>\n <a class=\"article-link\" href=\"${story.url}\" target=\"a_blank\">\n <strong>${story.title}</strong>\n </a>\n <small class=\"article-author\">by ${story.author}</small>\n <small class=\"article-hostname ${hostName}\">(${hostName})</small>\n <small class=\"article-username\">posted by ${story.username}</small>\n </li>\n `);\n return favoriteMarkup;\n }", "function generateFavoritesList(){\n $favorites.empty()\n\n if(currentUser.favorites !== 0){\n for(let story of currentUser.favorites){\n const $story = generateStoryMarkup(story);\n $favorites.append($story);\n }\n }\n $favorites.show();\n}", "function displayFavorites() {\n\tif (localStorage.getItem('favoritesList')) {\n\t\tlet parseList = JSON.parse(localStorage.getItem('favoritesList'));\n\t\tfor (let { storyId } of parseList) {\n\t\t\t$(`#${storyId} button.icon`).addClass('favorite');\n\t\t\t$(`#${storyId} button.icon`).data('favorite', true);\n\t\t}\n\t}\n}", "function addFavorite (event) {\n event.preventDefault();\n var button = event.currentTarget,\n name = button.getAttribute('data-name'),\n oid = button.getAttribute('data-oid'),\n xhttp = new XMLHttpRequest(),\n urlString = '/favorites/' + oid + '?name=' + name;\n xhttp.onreadystatechange = function () {\n if (xhttp.readyState === 4 && xhttp.status === 200) {\n var parentEl = button.parentElement,\n favEl = document.createElement('p'),\n content = document.getElementById('content');\n button.remove();\n favEl.innerText = \"This title is in your favorites!\";\n parentEl.appendChild(favEl);\n }\n };\n xhttp.open('get', urlString);\n xhttp.send();\n }", "updateFavs() {\n document.getElementById('favorites_results').innerHTML = this.render();\n }", "function putFavoritesOnPage() {\n // console.debug(\"putFavoritesOnPage\");\n const favorites = currentUser.favorites;\n $favStoriesList.empty();\n\n // loop through all of fav stories and generate HTML for them\n for (let favorite of favorites) {\n const $favorite = generateStoryMarkup(favorite);\n $favStoriesList.append($favorite);\n }\n\n $favStoriesList.show();\n}", "function addFavoriteButton() {\n\n postElement.forEach((el, index) => {\n const favoriteButton = createFavoriteButton(index)\n\n el.appendChild(favoriteButton)\n })\n }", "function app_render_favorites() {\r\n\r\n $('.app_favorites_content').empty();\r\n\r\n for (let i = 0; i < appData.favList.length; i++) {\r\n let imgSource = appData.favList[i];\r\n let myHTML = `\r\n <div class=\"app_content_cell app_favorites_cell fade-in\">\r\n <div class=\"app_content_cell_options\" onclick=\"app_fav_remove(this, ${i})\">\r\n <i class=\"fas fa-times\"></i>\r\n </div>\r\n <img class=\"fade-in-fwd\" src=\"${imgSource}\">\r\n </div>`;\r\n\r\n // Append Favorite\r\n $('.app_favorites_content').prepend(myHTML);\r\n }\r\n}", "function putFavoritesOnPage() {\n console.debug('putFavoritesOnPage');\n\n $favoritesList.empty();\n\n if (currentUser.favorites.length === 0) {\n $favoritesList.append('<h5>No favorites added!</h5>');\n }\n\n // loop through all of the favorited stories and generate HTML for them\n for (let story of currentUser.favorites) {\n const $favorite = generateStoryMarkup(story);\n $favoritesList.append($favorite);\n }\n\n $favoritesList.show();\n}", "function generateFavStoryPage() {\n //hide other forms/pages\n //create new page of only favorited stories\n //loop through user.favorites array and generate the html markup\n //then append to page\n $favStoriesList.empty();\n hidePageComponents();\n console.log(currentUser.favorites)\n for (let story of currentUser.favorites) {\n const $story = generateStoryMarkup(story);\n $favStoriesList.append($story);\n }\n $favStoriesList.show();\n}", "function renderFavorites() {\r\n removeBooksFromDOM();\r\n favorites.forEach(function (book) {\r\n insertNewBook(book.id, book.title, book.author, book.subject, book.photoURL, book.vendorURL, book.favorite);\r\n })\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get each asset tag for the given plugin
function getAssets(p, platform) { return getAllElements(p, platform, 'asset'); }
[ "get assetNames() {}", "function getAllPluginVersions() {\n developer.Api('/plugins/' + FS__API_PLUGIN_ID + '/tags.json', 'GET', [], [], function (e) {\n logResponse(e, developer);\n });\n}", "getTags() {\n const tagList = [];\n for (const tag in this.tagDictionary) {\n tagList.push(tag);\n }\n return tagList;\n }", "getAccountTags() {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.request(\"get_account_tags\", {});\n });\n }", "getTags() {\n let tickets = Array.from(this.root.querySelector(this.ticketsBlock).children);\n let tags = [];\n for (let i = 0; i < tickets.length; i++) {\n let ticketTags = tickets[i].querySelectorAll(this.tagElement);\n tags.push(Array.from(ticketTags));\n }\n return tags;\n }", "function allTagsArray() {\n\n var allTags = products[product].tags;\n\n return $(allTags).toArray();\n\n }", "get sourceTags() { return []; }", "assetsInStage(stage) {\n const assets = new Map();\n for (const stack of stage.stacks) {\n for (const asset of stack.assets) {\n assets.set(asset.assetSelector, asset);\n }\n }\n return Array.from(assets.values());\n }", "function fetchTagsOfAsset(assetType, assetId, masterTags) {\n\n $.ajax({\n url: TAG_API + assetType + '/' + assetId,\n type: 'GET',\n success: function (response) {\n var tags = JSON.parse(response);\n\n //Initialize the tag container\n $(TAG_CONTAINER).tokenInput(masterTags, {theme: TAG_THEME, prePopulate: tags, preventDuplicates: false,\n onAdd: onAdd,\n allowFreeTagging: true,\n onDelete: onRemove});\n\n }\n });\n\n }", "get Assets() {}", "function getTags() {\n \n $.getJSON('js/test-data.json').success(function(data) {\n \n $.each(data.data, function(k,v) {\n $.each(v.tags, function(k,v) {\n availableTags.push(v);\n });\n });\n \n $.unique(availableTags);\n \n appendTags();\n \n });\n \n }", "getTrelloPlugins() {\n let needle;\n return _.chain(this.plugins)\n .filter(\n (plugin) => (\n (needle = 'made-by-trello'),\n Array.from(plugin.get('tags')).includes(needle)\n ),\n )\n .sortBy((plugin) => PluginIOCache.get(plugin).getName().toLowerCase())\n .value();\n }", "getBonusPlugins() {\n let needle;\n return _.chain(this.plugins)\n .filter(\n (plugin) => (\n (needle = 'promotional'),\n Array.from(plugin.get('tags')).includes(needle)\n ),\n )\n .sortBy((plugin) => PluginIOCache.get(plugin).getName().toLowerCase())\n .value();\n }", "function getTags() {\n\ttags = [];\n\tdata.forEach(element => { tags = _.union(tags, element.tags); });\n\treturn tags;\n}", "function getTags() {\n Clarifai.getTagsByUrl([imageTagSearch]).then(\n handleResponse,\n handleError\n );\n }", "getAllTags() { \n var tags = [];\n var i=1;\n for (var x = 0; x < this.props.products.length; x++) {\n for (var y = 0; y < this.props.products[x].tags.length; y++) {\n if ( this.isTagMissing(tags, this.props.products[x].tags[y])) {\n var tag={id:i,name:this.props.products[x].tags[y].name};\n tags.push(tag);\n i++;\n }\n }\n }\n\n return tags;\n }", "function initTags() {\n\t\tvar tagArray = {};\n\n\t\t// Build an array of possible tags.\n\t\t$.each( settings.tags, function( index, tag ) {\n\t\t\ttag = tag.replace( /[^a-zA-Z]/g, '' );\n\t\t\t\n\t\t\ttagArray[ tag.toLowerCase() ] = {\n\t\t\t\ttag: tag.toLowerCase(),\n\t\t\t\tname: tag,\n\t\t\t\tcount: 0,\n\t\t\t\tvisible: true\n\t\t\t};\n\t\t} );\n\t\t\n\t\treturn tagArray;\n\t}", "function getTags() {\n getTagNames()\n .then(tagNames => listOfTags = formatOptions(tagNames))\n .catch(error => console.log(error));\n}", "function getAssets() { return _assets; }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A command where perform(), undo(), redo() all update the order bar. Intended to be augmented onto other commands that modify the order bar.
function updateOrderBarCommand () { return new Command(updateOrderBar,updateOrderBar,updateOrderBar); }
[ "execute(command) {\r\n command.execute();\r\n this.commandStack.push(command);\r\n this.redoStack = [];\r\n \r\n }", "function goUpdateUndoEditMenuItems()\n{\n goUpdateCommand('cmd_undo');\n goUpdateCommand('cmd_redo');\n}", "undo() {\r\n if (this.commandStack.length == 0)\r\n return;\r\n var command = this.commandStack.pop();\r\n command.undo();\r\n this.redoStack.push(command);\r\n }", "redo() {\r\n if (this.redoStack.length == 0)\r\n return;\r\n var command = this.redoStack.pop();\r\n command.redo();\r\n this.commandStack.push(command);\r\n }", "redo() {\n if (this.#position < this.#commands.length - 1) {\n this.#position += 1;\n\n // Avoid to insert something during the redo execution.\n this.#locked = true;\n this.#commands[this.#position].cmd();\n this.#locked = false;\n }\n }", "commit() {\n if (this.mode === this.MODES.NORMAL || this.mode === this.MODES.REDOING) {\n if (this.undoRoutine.length !== 0) {\n this.undoStack.push(this.undoRoutine);\n this.undoRoutine = [];\n }\n }\n else if (this.mode === this.MODES.UNDOING) {\n if (this.redoRoutine.length !== 0) {\n this.redoStack.push(this.redoRoutine);\n this.redoRoutine = [];\n }\n }\n this.mode = this.MODES.NORMAL;\n\n this.computeCounters();\n }", "function updateRefillBarCommand () {\n return new Command(updateRefillBar,updateRefillBar,updateRefillBar);\n}", "_updateCommands() {\n goUpdateCommand(\"cmd_popQuickFilterBarStack\");\n goUpdateCommand(\"cmd_showQuickFilterBar\");\n goUpdateCommand(\"cmd_toggleQuickFilterBar\");\n }", "modifyOrder() {\n\t\tlet index = prompt(\"Enter the index of the order you wish to view:\");\n\t\t//line below is user input validation\n\t\tif (index > -1 && index < this.viewOrders.length) {\n\t\t\tthis.selectedOrder = this.viewOrders[index];\n\t\t\tlet description =\n\t\t\t\t\"Order Details: \" +\n\t\t\t\tthis.selectedOrder.name +\n\t\t\t\t\", \" +\n\t\t\t\tthis.selectedOrder.order +\n\t\t\t\t\"\\n\";\n\n\t\t\tlet selection = this.showModifyMenuOptions(description);\n\t\t\tswitch (selection) {\n\t\t\t\tcase \"1\":\n\t\t\t\t\tthis.deleteOrder();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"2\":\n\t\t\t\t\tthis.changeOrder();\n\t\t\t}\n\t\t}\n\t}", "undo() {\n if (this.#position === -1) {\n // Nothing to undo.\n return;\n }\n\n // Avoid to insert something during the undo execution.\n this.#locked = true;\n this.#commands[this.#position].undo();\n this.#locked = false;\n\n this.#position -= 1;\n }", "function undo() {\n\t\tvar length = undoArr.length;\n\t\tif(length < 1) {\n\t\t\tconsole.log(\"nothing to undo!\");\n\t\t}\n\n\t\telse {\n\t\t\tvar func = undoArr[length - 1];\n\t\t\t\t\t\t//console.log(undoArr);\n\t\t\t\t\t\tredoArr.push(func);\n\t\t\t\t\t\tconsole.log(\"nya redo\");\n\t\t\t\t\t\tconsole.log(redoArr);\n\t\t\t\t\t\tundoArr.splice(length-1, 1);\n\t\t\t\t\t\tconsole.log(\"nya undo\");\n\t\t\t\t\t\tconsole.log(undoArr);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(func == \"placeOrder\"){\n\t\t\t\t\t\t\tvar tmp = orderArr.slice();\n\t\t\t\t\t\t\ttmpOrderArr.push(tmp);\n\t\t\t\t\t\t\tvar length = orderArr.length;\n\t\t\t\t\t\t\tvar index = (length - 3);\n\t\t\t\t\t\t\torderArr.splice(index, 3);\n\t\t\t\t\t\t\tupdatePlaceOrder();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*Both cancelOrder and deleteFromList*/\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\torderArr = tmpOrderArr.slice();\n\t\t\t\t\t\t\tvar length = tmpOrderArr.length;\n\t\t\t\t\t\t\tvar tmp = tmpOrderArr.splice(length-1, 1);\n\t\t\t\t\t\t\torderArr = tmp[0];\n\t\t\t\t\t\t\tupdatePlaceOrder();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}", "function redo() {\n\t\tvar length = redoArr.length;\n\n\t\tif(length < 1){\n\t\t\tconsole.log(\"nothing to redo!\");\n\t\t}\t\n\n\t/* check latest undo and push latest redo to undoArr again*/\n\t\telse{\n\t\t\tvar redo = redoArr.splice(length-1, 1);\n\t\t\tundoArr.push(redo[0]);\n\n\t/*set latest push to tmpOrderArr as OrderArr and updated the view by calling updatePlaceOrder*/\n\t\t\tif(redo == \"placeOrder\"){\n\t\t\t\tvar redo = redoArr[length - 1];\n\t\t\t\tvar length = tmpOrderArr.length;\n\n\t\t\t\tvar tmp = tmpOrderArr[length -1];\n\t\t\t\torderArr = tmp.slice();\n\t\t\t\ttmpOrderArr.splice(length -1, 1);\n\t\t\t\tupdatePlaceOrder();\n\t\t\t}\n\n\t\t\telse if(redo == \"cancelOrder\"){\n\t\t\t\tcancelOrder();\n\t\t\t}\n\t\n\t/*If redo == deleteFromList. delete selected row and update the view by calling updatelaceOrder */\n\t\t\telse{\n\t\t\t\tvar length = deleteList.length;\n\t\t\t\tvar txt = deleteList[length -1];\n\t\t\t\tdeleteFromlist(txt);\n\t\t\t\tupdatePlaceOrder();\n\t\t\t}\n\t\t}\n\t}", "function logCommand(command) {\r\n if (initialized === true) {\r\n if (command.savedState === undefined)\r\n command.savedState = false;\r\n if (redoStack.length > 0) {\r\n redoStack = []; // when should do this?\r\n $('.redoButton').css({ 'opacity': '0.4' });\r\n console.log(\"clear redoStack?\");\r\n }\r\n undoStack.push(command);\r\n $('.undoButton').css({ 'opacity': '1.0' });\r\n if (undoStack.length > stackSize) {\r\n var diff = undoStack.length - stackSize;\r\n undoStack.splice(0, diff);\r\n }\r\n\r\n // console.log(\"SAVED STATE //TOP//FROM log command// ===\" + undoStack[undoStack.length - 1].savedState);\r\n }\r\n\r\n //Check to see if there have been any changes and update save button accordingly\r\n if (undoStack.length) {\r\n $('#tourSaveButton').css('opacity', '1');\r\n $('#tourSaveButton').prop('disabled', false);\r\n }\r\n }", "rearrangeProgression({commit}, chords) {\n commit(\"commitProgression\", chords);\n }", "redo() {\n if (this.redoStack.length === 0) return;\n \n const action = this.redoStack.pop();\n this.undoStack.push(action);\n console.log(`Redo: ${action}`);\n }", "function performMove() {\r\n\t\r\n\t\r\n\t// This code should be at the bottom of the perform move.\r\n\tdrawInterface();\r\n\tstoreCurrentPosition(currentPosition);\r\n\tredoMoves = new Array();\r\n}", "showModifyMenuOptions(orderInfo) {\n\t\treturn prompt(`\n 0) Back\n 1) Delete Order\n 2) Change Order\n ---------------\n ${orderInfo}\n `);\n\t}", "function undoCommand() {\n\tif ((nd = getNavDiv()) == null) return;\n\tvar menu = nd.querySelector('.moreClass');\n\tif (menu == null) return;\n\tif (getContext() == '') return;\n\tmenu.click();\n\tvar n = 0;\n\tvar t = setInterval(function () {\n\t\tvar mc = document.querySelectorAll('.menuClass');\n\t\tif (mc != null) {\n\t\t\tfor (var i = 0; i < mc.length; i++) {\n\t\t\t\tfor (var j = 0; j < mc[i].children.length; j++) {\n\t\t\t\t\tif (isUndoCommand(mc[i].children[j].textContent)) {\n\t\t\t\t\t\tclearInterval(t);\n\t\t\t\t\t\tmc[i].children[j].firstChild.click();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tn++;\n\t\tif (n == 10) clearInterval(t);\n\t}, 100);\n}", "undo() {\n if (this.undoStack.length === 0) return;\n \n const action = this.undoStack.pop();\n this.redoStack.push(action);\n console.log(`Undo: ${action}`);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if enemy has dead
isDead (){ if (this.health <= 0){ this.dead(); return true; } return false; }
[ "checkDeath(enemy) {\n const yBottomCheck = this.colliderPosY + this.colliderY > enemy.colliderPosY && this.colliderPosY + this.colliderY < enemy.colliderPosY + enemy.colliderY;\n const yTopCheck = this.colliderPosY > enemy.colliderPosY && this.colliderPosY < enemy.colliderPosY + enemy.colliderY;\n const xRightCheck = this.colliderPosX + this.colliderX > enemy.colliderPosX && this.colliderPosX + this.colliderX < enemy.colliderPosX + enemy.colliderX;\n const xLeftCheck = this.colliderPosX > enemy.colliderPosX && this.colliderPosX < enemy.colliderPosX + enemy.colliderX;\n if ((yBottomCheck || yTopCheck) && (xRightCheck || xLeftCheck)) {\n this.dead = true;\n }\n }", "function checkDead() {\n if (player.health < 1) {\n view();\n death();\n return;\n }\n\n if (enemy.current.health < 1) {\n view();\n reward();\n return;\n }\n\n}", "function allEnemiesDead() {\n return enemies.getFirstAlive() == null;\n}", "function isDead()\n{\n\treturn health <= 0;\n}", "checkAlive()\n { \n if(this.isAlive === false)\n {\n this.enemyLevel++;//increases what level enemy the player is on \n this.reset();//reset the enemy \n return false;//retrun that the enemy is dead\n }\n return true;\n }", "checkDeath() {\n if (this.heroHealth < 0) {\n this.hero.remove();\n this.playerWin = false;\n this.gameOver = true;\n this.faceLeft = false;\n clearTimeout(this.cycle);\n clearInterval(this.enemyCombat);\n this.runAnimation(this.animations[3]);\n setTimeout(this.winLose.bind(this), 3000);\n }\n if (this.enemyHealth < 0) {\n this.playerWin = true;\n clearTimeout(this.enemyMove);\n clearInterval(this.enemyCombat);\n this.enemyFaceRight = false;\n this.runEnemyAnimation(this.animations[6]);\n setTimeout(this.winLose.bind(this), 3000);\n }\n }", "enemyAlive() {\n for(let i = 0; i < enemies.length; i++) {\n if (enemies[i].health <= 0) {\n enemies[i].isEnemyAlive = false;\n }\n }\n }", "isDead() {\n return this.hp <= 0;\n }", "checkDead ( ) {\n if (this.health <= 0) {\n this.isDead = true;\n }\n return this.isDead;\n }", "checkDead() {\n return this.attributeComponent.HP <= 0 || this.entity.removeFromWorld\n }", "checkIfCharacterIsDead() {\n if (this.character.dead) {\n this.endBoss.killedCharacter = true;\n }\n }", "isPlayerDead() {\n \n return !this.player.exist;\n }", "function checkForDead(){\n maxTurn = 0;\n for(person in team){\n if(team[person].health > 0){\n maxTurn +=1;\n }\n }\n }", "function checkCollisions() {\n allEnemies.forEach(function(enemy) {\n var diffX = Math.abs(enemy.x - player.x);\n var diffY = Math.abs(enemy.y - player.y);\n if (diffX <= 75 && diffY === 0) {\n youAreDead();\n }\n });\n}", "function allEnemiesDead() {\n var deaths = 0;\n for (var i = 0; i < enemies.length; i++) {\n if (enemies[i].HP <= 0) {\n deaths++;\n }\n }\n return deaths === enemies.length;\n}", "dead() {\n return (this.health < 0);\n }", "function checkIfDead(fighter){\n if (fighter.health > 0){\n return true;\n } else {\n fighter.isDead = true;\n }\n }", "get isDead(){\n\t\treturn this.health <= 0;\n\t}", "everyoneDead(){\r\n\t\tfor(let i=0; i<this.n; i++){\r\n\t\t\tif(this.players[i].game.alive == true){\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
uploads the track GPX file and displays it on the map. NO route recalculation! required HTML5 file api
function handleUploadTrack(file) { ui.showImportRouteError(false); //clean old track from map (at the moment only one track is supported) map.clearMarkers(map.TRACK); if (file) { if (!window.FileReader) { // File APIs are not supported, e.g. IE ui.showImportRouteError(true); } else { var r = new FileReader(); r.readAsText(file); r.onload = function(e) { var data = e.target.result; //remove gpx: tags; Firefox cannot cope with that. data = data.replace(/gpx:/g, ''); var track = map.parseStringToTrack(data); if (!track) { ui.showImportRouteError(true); } else { //add features to map map.addTrackToMap(track); } }; } } else { ui.showImportRouteError(true); } }
[ "function loadGPXFileIntoGoogleMap(map, filepath, altLatLong) {\n $.ajax({url: filepath,\n dataType: \"xml\",\n success: function (data) {\n var parser = new GPXParser(data, map);\n\n parser.setTrackColour(\"blue\"); // Set the track line colour\n parser.setTrackWidth(6); // Set the track line width\n parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points\n parser.centerAndZoom(data);\n parser.addTrackpointsToMap(); // Add the trackpoints\n\n parser.setTrackColour(\"#71acf0e6\"); // Set the track line colour\n parser.setTrackWidth(4); // Set the track line width\n parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points\n parser.centerAndZoom(data);\n parser.addTrackpointsToMap(); // Add the trackpoints\n parser.addRoutepointsToMap(); // Add the routepoints\n parser.addWaypointsToMap(); // Add the waypoints\n },\n error: function () {\n map.setCenter(altLatLong);\n new google.maps.Marker({\n position: altLatLong,\n title: \"No map available for the trail\",\n map: map\n });\n }\n });\n}", "function report_from_gpx() {\n reset_progress();\n $('#progress-dialogue').modal('show');\n\n let pedasi_app_api_key = $('#mapParamsAppKey').val();\n let file = $('#upload-gpx').prop('files')[0];\n if (!file) {\n return;\n }\n\n let reader = new FileReader();\n reader.onload = function(e) {\n let all_waypoints = convert_gpx(e.target.result);\n let waypoints = simplify_waypoints(all_waypoints);\n generate_route_report(waypoints, map, pedasi_app_api_key);\n }\n reader.readAsText(file);\n}", "function setFileContent(metadata, track, route, waypoints) {\n\n var xml = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n' +\n '<gpx xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 ' +\n 'http://www.topografix.com/GPX/1/1/gpx.xsd\" ' +\n 'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' +\n 'version=\"1.1\" creator=\"gpxmake.js\" ' +\n 'xmlns=\"http://www.topografix.com/GPX/1/1\">\\n';\n\n xml += metadata;\n xml += track;\n xml += route;\n xml += waypoints;\n xml += '</gpx>';\n\n return xml;\n }", "function handleFileSelect(evt) {\n\t\t\n\t\tvar routeFile = evt.target.files[0]; //Uploaded File\n\t\t\t\t\t\n\t\tif(routeFile){\n\t\t\treader.onload=function(){\n\t\t\tvar text = reader.result;\n\t\t\tconvertToDOM(text);\n\t\t}\n\n\t\treader.onerror=function(){\n\t\t\talert('File Could Not Be Read!');\n\t\t}\n\t\t\n\t\treader.readAsText(routeFile);\t\n\t\t}\n\t\n\t\n\t\tfunction convertToDOM(file){\n\t\t\t\n\t\t\tvar pathsArray=[]; //Holds The parsed GPX Coordinates\n\t\t\tvar lineColor;\n\t\t\t\n\t\t\txmlDoc = parser.parseFromString(file,\"text/xml\")//Parse Files\n\t\t\t\n\t\t\t//Get Track and Route Node List\n\t\t\tvar trkptNodeList=xmlDoc.getElementsByTagName('trkpt');\n\t\t\tvar rteptNodeList=xmlDoc.getElementsByTagName('rtept');\n\t\t\t\n\t\t\t//Add Track first if it exists\n\t\t\tif(trkptNodeList.length>1){\n\t\t\t\t//Orange for Tracks\n\t\t\t\tlineColor = [226,119,40];\n\t\t\t\tfor(var i =0;i<trkptNodeList.length;i++){\n\t\t\t\t\tvar lat=parseFloat(trkptNodeList[i].getAttribute(\"lat\"));\n\t\t\t\t\tvar lon=parseFloat(trkptNodeList[i].getAttribute(\"lon\"));\t\t\t\t\t\t\n\t\t\t\t\tpathsArray.push([lon,lat]);\n\t\t\t\t}\n\t\t\t//Add Route if Track doesn't exist\t\t\t\n\t\t\t}else if(rteptNodeList.length>1){\n\t\t\t\tlineColor = [0, 191, 255];\n\t\t\t\tfor(var i =0;i<rteptNodeList.length;i++){\n\t\t\t\t\tvar lat=parseFloat(rteptNodeList[i].getAttribute(\"lat\"));\n\t\t\t\t\tvar lon=parseFloat(rteptNodeList[i].getAttribute(\"lon\"));\t\t\t\t\t\t\n\t\t\t\t\tpathsArray.push([lon,lat]);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\talert('File Could Not Be Read!');\n\t\t\t}\n\t\t\t\n\t\t\t//Line Vectors\n\t\t\tvar polyline = {\n\t\t\t\ttype: \"polyline\", // autocasts as new Polyline()\n\t\t\t\tpaths:pathsArray \n\t\t\t\t};\n\n\t\t\t//Line Details\n\t\t\tlineSymbol = {\n\t\t\t type: \"simple-line\", // autocasts as SimpleLineSymbol()\n\t\t\t color: [226, 119, 40],\n\t\t\t width: 4\n\t\t\t};\n\n\t\t\t//Graphic Object(Vectors + Line Details)\n\t\t\tvar polylineGraphic = new Graphic({\n\t\t\t geometry: polyline,\n\t\t\t symbol: lineSymbol\n\t\t\t});\n\t\t\t\t\n\t\t\t//Coordinates to Move Camera Too\n\t\t\tvar goToLat=Number.parseFloat(pathsArray[0][1]).toFixed(2);\n\t\t\tvar goToLon=Number.parseFloat(pathsArray[0][0]).toFixed(2)\n\t\t\t\t\n\n\t\t\t//Camera Object(holds details of a View)\t\n\t\t\tvar cam = new Camera({\n\t\t\t\tposition: new Point({\n\t\t\t\t\tx: goToLon, // lon\n\t\t\t\t\ty: goToLat, // lat\n\t\t\t\t\tz: 30000, // elevation in meters\n\t\t\t\t}),\n\t\t\t\theading: 180, // facing due south\n\t\t\t\ttilt: 0 // bird's eye view\n\t\t\t});\n\n\t\t\t//Move Camera to route/trk added\t\n\t\t\tview.goTo(cam);\t\n\n\t\t\t//Add The route to the graphics layer\n\t\t\tgraphicsLayer.add(polylineGraphic);\n\t\t\t\n\n\n\t\t}\n\t}", "function importerGPX() {\r\n importeGPX();\r\n}", "function getTrack(fileUrl) {\n var track;\n $.ajax({\n url: \"gpx/\" + fileUrl,\n dataType: \"xml\",\n async: false,\n success: function(xml) {\n\n var name;\n var activityType;\n var points = [];\n var centroid;\n var distance_m = 0.0;\n let elevations = [];\n let elevationGain_m = 0.0;\n let elevationLoss_m = 0.0;\n var estimatedTime_s = 0.0;\n let elevationGains = [];\n let elevationLosses = [];\n var estimatedTimes = [];\n var times = [];\n\t\t\tvar distances = [];\n let gpx = \"gpx/\" + fileUrl;\n\n // Get name\n $(xml).find(\"name\").each(function(){\n name = $(this).text();\n });\n\n // Get activity type\n $(xml).find(\"type\").each(function(){\n var code = $(this).text();\n\n for (var i in ActivityType) {\n if (code == ActivityType.properties[ActivityType[i]].code) {\n activityType = ActivityType[i];\n break;\n }\n }\n });\n\n // Get points, elevations and times\n $(xml).find(\"trkpt\").each(function() {\n var lat = $(this).attr(\"lat\");\n var lon = $(this).attr(\"lon\");\n points.push({lat: parseFloat(lat), lng: parseFloat(lon)});\n $(this).find(\"ele\").each(function(){\n elevations.push(parseFloat($(this).text()));\n });\n $(this).find(\"time\").each(function(){\n times.push(Date.parse($(this).text()));\n });\n });\n\n // Compute compute Centroid\n var centroid = computeCentroid(points);\n\n // Compute distance average and distances between each points\n var delta;\n for(var j = 0; j < points.length - 1; j++){\n // distance\n\t\t\t\tvar d = GCDistance(points[j].lat, points[j].lng, points[j+1].lat, points[j+1].lng);\n distance_m += d;\n\t\t\t\tdistances.push(distance_m);\n }\n\n\t\t\t// Compute speeds with jump 60\n\t\t\tvar speeds_jump_60 = [];\n var jump = 60;\n for(var j = jump; j < distances.length; j+=jump){\n\t\t\t\tvar d = distances[j] - distances[j-jump];\n speeds_jump_60.push((d/1000)/((times[j]-times[j-jump]) / 1000 / 3600));\n }\n\n\t\t\t// Compute altitudes with jump 60\n\t\t\tvar altitudes_jump_60 = [];\n var jump = 60;\n for(var j = 0; j < elevations.length; j+=jump){\n // altitudes\n altitudes_jump_60.push(elevations[j]);\n if (j+jump > elevations.length){\n altitudes_jump_60.push(elevations[elevations.length - 1]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n }\n\n // We can't compute elevation at each point because it becomes\n // irrelevant (usually to high) as the GPS hasn't a trustable\n // precision.\n // So we decided to take elevation at every 60 points which\n // represent one minute\n var len = elevations.length;\n var jump = 60;\n for(var j = 0; j < elevations.length - 1; j+=jump){\n // elevations\n if (j+jump > len)\n break;\n delta = elevations[j+jump] - elevations[j];\n\t\t\t\televationGains.push(elevationGain_m);\n\t\t\t\televationLosses.push(elevationLoss_m);\n if (delta > 0)\n elevationGain_m += delta;\n else\n elevationLoss_m -= delta;\n }\n\t\t\televationGains.push(elevationGain_m);\n\t\t\televationLosses.push(elevationLoss_m);\n\n\t\t\t// Calculate estimated times at each points\n\t\t\tfor(var j = 0; j < distances.length; j++){\n\t\t\t\testimatedTimes.push(timeEstimation_s(activityType, distances[j],\n\t\t\t\t\televationGains[Math.floor(j/60)], elevationLosses[Math.floor(j/60)]));\n\t\t\t}\n\n // Compute time estimation\n estimatedTime_s = timeEstimation_s(activityType, distance_m,\n elevationGain_m, elevationLoss_m);\n\n track = new Track(name, activityType, points, distance_m, elevations,\n centroid, elevationGain_m, elevationLoss_m, estimatedTime_s,\n elevationGains, elevationLosses, estimatedTimes, times,\n distances, speeds_jump_60, altitudes_jump_60, gpx);\n }\n });\n return track;\n}", "function displaySingleTrail() {\n // Get the trail's information\n var trail = JSON.parse(document.getElementById(\"jsonData\").value).trails[0];\n var trailLatLong = new google.maps.LatLng(trail.latitude, trail.longitude);\n\n // Fetch the GPX file for the trail and display it on the map.\n var gpxFile = document.getElementById(\"trailGPX\").value;\n loadGPXFileIntoGoogleMap(map, gpxFile, trailLatLong)\n\n // If there is location data, show location on map\n var geocodeInput = document.getElementById(\"geocodedData\");\n if (geocodeInput && geocodeInput.value) {\n var data = eval(\"(\" + geocodeInput.value + \")\");\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(data.lat, data.lng),\n title: data.filename,\n map: map\n });\n\n var infoWindow = new google.maps.InfoWindow();\n google.maps.event.addListener(marker, \"click\", function () {\n infoWindow.setContent(\"<img src='..\" + data.filepath + \"' width=150 />\");\n infoWindow.open(map, this);\n });\n }\n}", "function loadGPX(fn) {\n var gpxFile = 'gpx/'+fn;\n new L.GPX(gpxFile, {async: true}).on('loaded', function(e) {\n map.fitBounds(e.target.getBounds());\n }).addTo(map);\n}", "function controlLoadGPX(opt) {\n\tconst options = {\n\t\t\tlabel: '&#x1F4C2;',\n\t\t\tsubmenuHTML: '<p>Importer un fichier au format GPX:</p>' +\n\t\t\t\t'<input type=\"file\" accept=\".gpx\" ctrlOnChange=\"loadFile\" />',\n\t\t\t...opt,\n\t\t},\n\t\tcontrol = controlButton(options);\n\n\tcontrol.loadURL = async function(evt) {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('GET', evt.target.href);\n\t\txhr.onreadystatechange = function() {\n\t\t\tif (xhr.readyState == 4 && xhr.status == 200)\n\t\t\t\tloadText(xhr.responseText);\n\t\t};\n\t\txhr.send();\n\t};\n\n\t// Load file at init\n\tif (options.initFile) {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('GET', options.initFile);\n\t\txhr.onreadystatechange = function() {\n\t\t\tif (xhr.readyState == 4 && xhr.status == 200)\n\t\t\t\tloadText(xhr.responseText);\n\t\t};\n\t\txhr.send();\n\t}\n\n\t// Load file on demand\n\tcontrol.loadFile = function(evt) {\n\t\tconst reader = new FileReader();\n\n\t\tif (evt.type == 'change' && evt.target.files)\n\t\t\treader.readAsText(evt.target.files[0]);\n\t\treader.onload = function() {\n\t\t\tloadText(reader.result);\n\t\t};\n\t};\n\n\tfunction loadText(text) {\n\t\tconst map = control.getMap(),\n\t\t\tformat = new ol.format.GPX(),\n\t\t\tfeatures = format.readFeatures(text, {\n\t\t\t\tdataProjection: 'EPSG:4326',\n\t\t\t\tfeatureProjection: 'EPSG:3857',\n\t\t\t}),\n\t\t\tadded = map.dispatchEvent({\n\t\t\t\ttype: 'myol:onfeatureload', // Warn layerEditGeoJson that we uploaded some features\n\t\t\t\tfeatures: features,\n\t\t\t});\n\n\t\tif (added !== false) { // If one used the feature\n\t\t\t// Display the track on the map\n\t\t\tconst gpxSource = new ol.source.Vector({\n\t\t\t\t\tformat: format,\n\t\t\t\t\tfeatures: features,\n\t\t\t\t}),\n\t\t\t\tgpxLayer = new ol.layer.Vector({\n\t\t\t\t\tsource: gpxSource,\n\t\t\t\t\tstyle: function(feature) {\n\t\t\t\t\t\tconst properties = feature.getProperties();\n\n\t\t\t\t\t\treturn new ol.style.Style({\n\t\t\t\t\t\t\tstroke: new ol.style.Stroke({\n\t\t\t\t\t\t\t\tcolor: 'blue',\n\t\t\t\t\t\t\t\twidth: 3,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\timage: properties.sym ? new ol.style.Icon({\n\t\t\t\t\t\t\t\tsrc: '//chemineur.fr/ext/Dominique92/GeoBB/icones/' + properties.sym + '.svg',\n\t\t\t\t\t\t\t}) : null,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\tmap.addLayer(gpxLayer);\n\t\t}\n\n\t\t// Zoom the map on the added features\n\t\tconst extent = ol.extent.createEmpty();\n\n\t\tfor (let f in features)\n\t\t\tol.extent.extend(extent, features[f].getGeometry().getExtent());\n\n\t\tif (ol.extent.isEmpty(extent))\n\t\t\talert('Fichier GPX vide');\n\t\telse\n\t\t\tmap.getView().fit(extent, {\n\t\t\t\tmaxZoom: 17,\n\t\t\t\tsize: map.getSize(),\n\t\t\t\tpadding: [5, 5, 5, 5],\n\t\t\t});\n\n\t\t// Close the submenu\n\t\tcontrol.element.classList.remove('myol-display-submenu');\n\t}\n\n\treturn control;\n}", "function generateFeatureCollectionFromGPX(fileName) {\n console.log(\"Creating features from the GPX...\")\n var name = fileName.split(\".\");\n // Chrome and IE add c:\\fakepath to the value - we need to remove it\n name = name[0].replace(\"c:\\\\fakepath\\\\\", \"\");\n // Show loading\n mapFrame.loading.show();\n\n // Define the input parameters for generate features\n var params = {\n 'name': name,\n 'targetSR': mapFrame.map.spatialReference\n };\n\n // Generalize features for display\n var extent = scaleUtils.getExtentForScale(mapFrame.map, 40000);\n var resolution = extent.getWidth() / mapFrame.map.width;\n params.generalize = true;\n params.maxAllowableOffset = resolution;\n params.reducePrecision = true;\n params.numberOfDigitsAfterDecimal = 0;\n\n var myContent = {\n 'filetype': \"gpx\",\n 'publishParameters': JSON.stringify(params),\n 'f': 'json',\n 'callback.html': 'textarea'\n };\n\n // Use the rest generate operation to generate a feature collection\n request({\n url: mapFrame.config.portalURL + '/sharing/rest/content/features/generate',\n content: myContent,\n form: dom.byId('uploadForm'),\n handleAs: 'json',\n load: lang.hitch(this, function (response) {\n if (response.error) {\n showError(response.error);\n }\n // Add the feature collection to the map\n addFeaturesToMap(response.featureCollection,name);\n }),\n error: lang.hitch(this, showError)\n });\n }", "function gpxToPath(data) {\n\n // if ( data.indexOf('\\n' !== -1 ) {\n // newlineChar = '\\n'\n // } elseif\n\n var a = 0; // start of interesting feature\n var b = data.indexOf(\"\\r\",a); // end of interesting feature\n var i = 0; // counter\n var pathType = '';\n var nameOfPath = ''; // \"route\" or \"path\"\n const maxIters = 100000; // will only process this number of points\n var latValue, lngValue, eleValue, timeValue;\n\n\n /**\n * Loop until we find track or route start\n */\n do {\n\n lineData = data.slice(a,b)\n a = b + 2;\n b = data.indexOf(\"\\r\",a);\n\n if ( lineData.indexOf(\"<trk>\") !== -1 ) {\n // console.log('getPathFromGpx says: found a track');\n pathType = \"track\";\n typeTag = \"trkpt\";\n break;\n }\n\n if ( lineData.indexOf(\"<rte>\") !== -1 ) {\n // console.log('getPathFromGpx says: found a route');\n pathType = \"route\";\n typeTag = \"rtept\";\n break;\n }\n\n } while ( i < maxIters )\n\n /**\n * Try to find a name\n */\n lineData = data.slice(a,b)\n a = lineData.indexOf(\"<name>\");\n b = lineData.indexOf(\"</name>\");\n if ( a !== -1 && b !== -1 ) {\n nameOfPath = lineData.slice(a + 6, b);\n }\n\n path = new gpsfun.Path(nameOfPath, pathType, []);\n\n /**\n * If this is a track file....\n */\n\n ptEnd = b;\n\n do {\n\n // get the start and end of the current track point, break from loop if not found\n ptStart = data.indexOf(typeTag,ptEnd);\n ptEnd = data.indexOf('/' + typeTag,ptStart);\n if ( ptStart == -1 || ptEnd == -1 ) {\n break;\n }\n ptData = data.slice(ptStart,ptEnd)\n i++;\n\n // lat and long\n a = ptData.indexOf(\"lat=\");\n b = ptData.indexOf(\"lon=\");\n if ( a !== -1 && b !== -1 ) {\n if ( b > a ) {\n latValue = parseFloat(ptData.slice(a, b).match(/[-0123456789.]/g).join(\"\"));\n lngValue = parseFloat(ptData.slice(b).match(/[-0123456789.]/g).join(\"\"));\n } else {\n lngValue = parseFloat(ptData.slice(b, a).match(/[-0123456789.]/g).join(\"\"));\n latValue = parseFloat(ptData.slice(a).match(/[-0123456789.]/g).join(\"\"));\n }\n }\n\n // elevation\n a = ptData.indexOf(\"<ele>\");\n b = ptData.indexOf(\"</ele>\");\n if (a != -1 && b != -1) {\n eleValue = parseFloat(ptData.slice(a,b).match(/[-0123456789.]/g).join(\"\"));\n }\n\n // time\n a = ptData.indexOf(\"<time>\");\n b = ptData.indexOf(\"</time>\");\n if (a != -1 && b != -1) {\n timeValue = ptData.slice(a,b).match(/[-0123456789.TZ:]/g).join(\"\");\n }\n\n // create point and push to path\n path.points.push(new gpsfun.Point(i, [latValue, lngValue], eleValue, timeValue, null, null));\n\n } while ( i < maxIters )\n\n // If route then simplify\n if ( pathType === 'route' ) {\n path = gpsfun.simplifyPath(path);\n }\n\n // Now we have a full path, determine path type and update name\n if ( nameOfPath === '' ) {\n path.name = path.category() + ' ' + path.type;\n }\n\n // console.log(path);\n return path;\n\n}", "function handleImportTrackSelection() {\n\t\t\tvar file;\n\t\t\tvar fileInput = $$('#gpxUploadTrack input[type=\"file\"]')[0];\n\t\t\tif (fileInput && fileInput.files && fileInput.files.length > 0) {\n\t\t\t\tfile = fileInput.files[0];\n\t\t\t} else if (fileInput && fileInput.value) {\n\t\t\t\t//IE doesn't know x.files\n\t\t\t\tfile = fileInput.value;\n\t\t\t}\n\n\t\t\tif (file) {\n\t\t\t\ttheInterface.emit('ui:uploadTrack', file);\n\t\t\t\t//TODO to support multiple GPX tracks, use data-attributes containing the OL-Feature-Id of the element (see search/waypoints)\n\t\t\t}\n\t\t}", "createFromGPX(gpxTrack){\n let pointNodes = $(\"trkpt\", gpxTrack);\n\n $.each(pointNodes, (i, curPoint)=> {\n let trkpt;\n const exki = \"http://ki.ujep.cz/ns/gpx_extension\";\n let lat = parseFloat($(curPoint).attr(\"lat\").toString());\n let lon = parseFloat($(curPoint).attr(\"lon\").toString());\n let ele = parseFloat($(\"ele\", curPoint).text());\n\n let origin = curPoint.getAttributeNS(exki,'origin') || 'ORIGINAL';\n let agl = parseFloat($(\"agl\", curPoint).text() || 0 );\n let eres = parseFloat($(\"eres\", curPoint).text() || 0);\n let speed = parseFloat($(\"speed\", curPoint).text() || 0);\n\n trkpt = new Waypoint(lat, lon, ele, agl, eres, speed, origin);\n this.appendWaypoint(trkpt);\n });\n\n }", "function loadSelectedTrack() {\r\n\r\n statusMessage.textContent = \"\";\r\n\r\n // Clears existing layer\r\n if (trackLayer != null) {\r\n map?.removeLayer(trackLayer);\r\n trackLayer = null;\r\n }\r\n\r\n // Selected track file\r\n let trackFile = trackFiles.value;\r\n document.title = trackFile ? pageTitle + \" | \" + trackFile : pageTitle;\r\n if (!trackFile)\r\n return;\r\n\r\n // Track format depends on file extension\r\n let trackFormat, formatOptions = { extractStyles: false, showPointNames: false };\r\n if (trackFile.endsWith(\".kml\"))\r\n trackFormat = new ol.format.KML(formatOptions);\r\n else if (trackFile.endsWith(\".kmz\"))\r\n trackFormat = new KMZ(formatOptions);\r\n else if (trackFile.endsWith(\".gpx\"))\r\n trackFormat = new ol.format.GPX(formatOptions);\r\n else {\r\n alert(\"Unsupported file format\");\r\n return;\r\n }\r\n\r\n statusMessage.textContent = \"Loading...\";\r\n\r\n // Layer source (refers track file)\r\n /*let layerSource;\r\n if (trackFile.endsWith(\".kmz\")) {\r\n layerSource = new ol.source.Vector({\r\n format: trackFormat,\r\n // KMZ loader\r\n loader: function(extent, resolution, projection) {\r\n let onError = function() {\r\n layerSource.removeLoadedExtent(extent);\r\n }\r\n fetch(\"tracks/\" + trackFile)\r\n .then(response => {\r\n if (response.ok) {\r\n return response.blob();\r\n }\r\n else\r\n onError();\r\n })\r\n .then(blob => {\r\n return blob.arrayBuffer();\r\n })\r\n .then(data => {\r\n let zip = new JSZip();\r\n zip.load(data);\r\n let kmlFile = zip.file(/.kml$/i)[0];\r\n if (kmlFile) \r\n layerSource.addFeatures(layerSource.getFormat().readFeatures(kmlFile.asText().substring(1)));\r\n else\r\n onError(); \r\n })\r\n .catch(() => onError);\r\n }\r\n });\r\n }\r\n else {\r\n layerSource = new ol.source.Vector({\r\n format: trackFormat,\r\n url: \"tracks/\" + trackFile\r\n });\r\n }*/\r\n\r\n\r\n // Layer source (refers track file)\r\n let layerSource = new ol.source.Vector({\r\n url: \"tracks/\" + trackFile,\r\n format: trackFormat\r\n });\r\n\r\n // Track stroke style\r\n let layerStyle = [\r\n new ol.style.Style({\r\n stroke: new ol.style.Stroke({\r\n color: '#163b56',\r\n width: 5,\r\n })\r\n }),\r\n new ol.style.Style({\r\n stroke: new ol.style.Stroke({\r\n color: '#3a96dd',\r\n width: 3,\r\n })\r\n })\r\n ];\r\n\r\n // Track layer\r\n trackLayer = new ol.layer.Vector({\r\n source: layerSource,\r\n style: layerStyle\r\n });\r\n\r\n // Departure / arrival icons\r\n let styleDeparture = new ol.style.Style({ text: new ol.style.Text({ text: \"🛫\", scale: [3, 3] }) });\r\n let styleArrival = new ol.style.Style({ text: new ol.style.Text({ text: \"🛬\", scale: [3, 3] }) });\r\n\r\n // Tile source\r\n let tileSource;\r\n switch (tileSources.value) {\r\n case \"BingMaps\":\r\n tileSource = new ol.source.BingMaps({\r\n key: bingMapKey,\r\n imagerySet: 'AerialWithLabelsOnDemand'\r\n })\r\n break;\r\n case \"Stamen\":\r\n tileSource = new ol.source.Stamen({layer: 'terrain'});\r\n break;\r\n default:\r\n tileSource = new ol.source.OSM();\r\n break;\r\n }\r\n\r\n // Map creation\r\n if (!map) {\r\n map = new ol.Map({\r\n target: 'map',\r\n layers: [new ol.layer.Tile({ source: tileSource })],\r\n view: new ol.View({\r\n center: ol.proj.fromLonLat([37.41, 8.82]),\r\n zoom: 4\r\n })\r\n });\r\n }\r\n\r\n // Add the Layer with the GPX Track\r\n map.addLayer(trackLayer);\r\n\r\n layerSource.once('change', function (e) {\r\n try {\r\n if (layerSource.getState() === 'ready') {\r\n \r\n // Sets the view\r\n if (savedView) {\r\n map.setView(savedView);\r\n savedView = null;\r\n }\r\n else\r\n // Zooms in on the track\r\n map.getView().fit(layerSource.getExtent(), { padding: [50, 50, 50, 50] });\r\n\r\n // Departure node\r\n layerSource.getFeatureById(1)?.setStyle(styleDeparture);\r\n\r\n // Looking for arrival node id\r\n let arrivalId = layerSource.getFeatures().length;\r\n while (!layerSource.getFeatureById(arrivalId) && arrivalId > 1) arrivalId--;\r\n if (arrivalId > 1) layerSource.getFeatureById(arrivalId).setStyle(styleArrival);\r\n }\r\n } finally {\r\n statusMessage.textContent = \"\";\r\n }\r\n });\r\n}", "function generateGPX(pathArray,routeName){\n\t\t\n\t\tvar doc = document.implementation.createDocument(\"\", \"\", null);\n\n\t\t//GPX\n\t\tvar gpx = doc.createElement(\"gpx\");\n\t\tgpx.setAttribute(\"xmlns\",\"http://www.topografix.com/GPX/1/1\");\n\t\tgpx.setAttribute(\"xmlns:xsi\",\"http://www.w3.org/2001/XMLSchema-instance\");\n\t\tgpx.setAttribute(\"xsi:schemaLocation\",\"http://www.topografix.com/GPX/1/1/gpx.xsd\");\n\t\t\n\t\t//METADATA\n\t\tvar metaData = doc.createElement(\"metadata\");\n\t\t\n\t\t\t//METADATA:BOUNDS\n\t\t\tvar lonArray=[];\n\t\t\tvar latArray=[];\n\t\t\t\n\t\t\tfor(var i=0;i<createdPath.length;i++){\n\t\t\t\tlonArray.push(createdPath[i][1]);\n\t\t\t\tlatArray.push(createdPath[i][0]);\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tvar maxLat=Math.max.apply(null,latArray);\n\t\t\tvar minLat=Math.min.apply(null,latArray);\n\t\t\tvar maxLon=Math.max.apply(null,lonArray);\n\t\t\tvar minLon=Math.min.apply(null,lonArray);\n\t\t\t\n\t\t\t\t\t\n\t\t\tvar bounds = doc.createElement('bounds');\n\t\t\tbounds.setAttribute(\"maxLat\",maxLat);\n\t\t\tbounds.setAttribute(\"maxLon\",maxLon);\n\t\t\tbounds.setAttribute(\"minLat\",minLat);\n\t\t\tbounds.setAttribute(\"minLon\",minLon);\n\t\t\tmetaData.appendChild(bounds);\n\n\t\t//TRK SETTINGS\n\t\tvar trk = doc.createElement(\"trk\");\n\t\tvar trkName = doc.createElement(\"name\");\n\t\t\n\t\ttrkName.textContent=routeName;\n\t\ttrk.appendChild(trkName);\n\t\t\n\t\tvar trkExtension = doc.createElement(\"extensions\");\n\t\tvar gpxxtrkExt=doc.createElement(\"gpxx:TrackExtension\");\n\t\t\n\t\tgpxxtrkExt.setAttribute(\"xmlns:gpxx\",\"http://www.garmin.com/xmlschemas/GpxExtensions/v3\");\n\t\t\n\t\tvar trkColor = doc.createElement(\"gpxx:DisplayColor\");\n\t\ttrkColor.textContent='DarkBlue';\n\t\t\n\t\tgpxxtrkExt.appendChild(trkColor);\n\t\ttrkExtension.appendChild(gpxxtrkExt);\n\t\ttrk.appendChild(trkExtension);\n\n\t\t//TRKSEG\n\t\tvar trkseg=doc.createElement(\"trkseg\");\n\t\tfor(var i=0; i<pathArray.length;i++){\n\t\t\tvar trkpt=doc.createElement(\"trkpt\");\n\t\t\t//0 is lat, 1 is lon\n\t\t\ttrkpt.setAttribute(\"lat\",pathArray[i][0]);\n\t\t\ttrkpt.setAttribute(\"lon\",pathArray[i][1]);\n\t\t\ttrkseg.appendChild(trkpt);\n\t\t}\n\n\t\ttrk.appendChild(trkseg);\n\t\tgpx.appendChild(metaData);\n\t\tgpx.appendChild(trk);\n\t\tdoc.appendChild(gpx);\n\n\t\tdownload();\n\n\t\tfunction download(){\n\t\t\t\n\t\t\tvar header='<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>';\n\t\t\tvar xmlText = header+new XMLSerializer().serializeToString(doc);\n\n\t\t\tvar bb = new Blob([xmlText],{type:\"text/xml\"});\n\t\t\tvar url = URL.createObjectURL(bb);\n\n\t\t\tvar lnk = document.createElement('a'), e;\n\t\t\tlnk.download = routeName+\".gpx\";\n\t\t\tlnk.href = url;\n\t\t\tif (document.createEvent) {\n\t\t\t\te = document.createEvent(\"MouseEvents\");\n\t\t\t\te.initMouseEvent(\"click\", true, true, window,\n\t\t\t\t\t\t\t\t\t0, 0, 0, 0, 0, false, false, false,\n\t\t\t\t\t\t\t\t\tfalse, 0, null);\n\t\t\t\t\t lnk.dispatchEvent(e);\n\t\t\t} else if (lnk.fireEvent) {\n\t\t\t\tlnk.fireEvent(\"onclick\");\n\t\t\t}\n\t\t}\n\t}", "function save() {\n var data = map.toDataURL({\n 'mimeType' : 'image/jpeg', // or 'image/png'\n 'save' : true, // to pop a save dialog\n 'fileName' : 'map' // file name\n });\n}", "function uploadMap(map, e) {\n let reader = new window.FileReader();\n\n reader.readAsText(e.target.files[0]);\n\n reader.onload = function () {\n let data = JSON.parse(event.target.result);\n map.new(data);\n };\n}", "function controlDownloadGPX(o) {\n\tconst options = ol.assign({\n\t\t\tlabel: '&dArr;',\n\t\t\ttitle: 'Obtenir un fichier GPX contenant les éléments visibles dans la fenêtre.',\n\t\t\tfileName: 'trace.gpx'\n\t\t}, o),\n\t\thiddenElement = document.createElement('a');\n\n\t//HACK for Moz\n\thiddenElement.target = '_blank';\n\thiddenElement.style = 'display:none;opacity:0;color:transparent;';\n\t(document.body || document.documentElement).appendChild(hiddenElement);\n\n\toptions.activate = function(evt) {\n\t\tlet features = [],\n\t\t\textent = this.group.map_.getView().calculateExtent();\n\n\t\t// Get all visible features\n\t\tthis.group.map_.getLayers().forEach(function(layer) {\n\t\t\tif (layer.getSource() && layer.getSource().forEachFeatureInExtent) // For vector layers only\n\t\t\t\tlayer.getSource().forEachFeatureInExtent(extent, function(feature) {\n\t\t\t\t\tfeatures.push(feature);\n\t\t\t\t});\n\t\t});\n\n\t\t// Write in GPX format\n\t\tconst gpx = new ol.format.GPX().writeFeatures(features, {\n\t\t\t\tdataProjection: 'EPSG:4326',\n\t\t\t\tfeatureProjection: 'EPSG:3857',\n\t\t\t\tdecimals: 5\n\t\t\t}),\n\t\t\tfile = new Blob([gpx.replace(/>/g, \">\\n\")], {\n\t\t\t\ttype: 'application/gpx+xml'\n\t\t\t});\n\n\t\t//HACK for IE/Edge\n\t\tif (typeof navigator.msSaveOrOpenBlob !== 'undefined')\n\t\t\treturn navigator.msSaveOrOpenBlob(file, options.fileName);\n\t\telse if (typeof navigator.msSaveBlob !== 'undefined')\n\t\t\treturn navigator.msSaveBlob(file, options.fileName);\n\n\t\thiddenElement.href = URL.createObjectURL(file);\n\t\thiddenElement.download = options.fileName;\n\n\t\t// Simulate the click & download the .gpx file\n\t\tif (typeof hiddenElement.click === 'function')\n\t\t\thiddenElement.click();\n\t\telse\n\t\t\thiddenElement.dispatchEvent(new MouseEvent('click', {\n\t\t\t\tview: window,\n\t\t\t\tbubbles: true,\n\t\t\t\tcancelable: true\n\t\t\t}));\n\t}\n\n\treturn new ol.control.Button(options);\n}", "function showExternalFile() {\n $.get(document.getElementById('externalfile').value, function(response) {\n L.geoJSON(JSON.parse(response)).addTo(map);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inline the contents of the html document returned by the link tag's href at the location of the link tag and then remove the link tag. If the link is a `lazyimport` link, content will not be inlined.
_inlineHtmlImport(linkTag) { return __awaiter(this, void 0, void 0, function* () { const isLazy = dom5.getAttribute(linkTag, 'rel').match(/lazy-import/i); const importHref = dom5.getAttribute(linkTag, 'href'); const resolvedImportUrl = this.bundler.analyzer.urlResolver.resolve(this.assignedBundle.url, importHref); if (resolvedImportUrl === undefined) { return; } const importBundle = this.manifest.getBundleForFile(resolvedImportUrl); // We don't want to process the same eager import again, but we want to // process every lazy import we see. if (!isLazy) { // Just remove the import from the DOM if it is in the stripImports Set. if (this.assignedBundle.bundle.stripImports.has(resolvedImportUrl)) { parse5_utils_1.removeElementAndNewline(linkTag); return; } // We've never seen this import before, so we'll add it to the // stripImports Set to guard against inlining it again in the future. this.assignedBundle.bundle.stripImports.add(resolvedImportUrl); } // If we can't find a bundle for the referenced import, we will just leave // the import link alone. Unless the file was specifically excluded, we // need to record it as a "missing import". if (!importBundle) { if (!this.bundler.excludes.some((u) => u === resolvedImportUrl || resolvedImportUrl.startsWith(url_utils_1.ensureTrailingSlash(u)))) { this.assignedBundle.bundle.missingImports.add(resolvedImportUrl); } return; } // Don't inline an import into itself. if (this.assignedBundle.url === resolvedImportUrl) { parse5_utils_1.removeElementAndNewline(linkTag); return; } const importIsInAnotherBundle = importBundle.url !== this.assignedBundle.url; // If the import is in another bundle and that bundle is in the // stripImports Set, we should not link to that bundle. const stripLinkToImportBundle = importIsInAnotherBundle && this.assignedBundle.bundle.stripImports.has(importBundle.url) && // We just added resolvedImportUrl to stripImports, so we'll exclude // the case where resolved import URL is not the import bundle. This // scenario happens when importing a file from a bundle with the same // name as the original import, like an entrypoint or lazy edge. resolvedImportUrl !== importBundle.url; // If the html import refers to a file which is bundled and has a // different URL, then lets just rewrite the href to point to the bundle // URL. if (importIsInAnotherBundle) { // We guard against inlining any other file from a bundle that has // already been imported. A special exclusion is for lazy imports, // which are not deduplicated here, since we can not infer developer's // intent from here. if (stripLinkToImportBundle && !isLazy) { parse5_utils_1.removeElementAndNewline(linkTag); return; } const relative = this.bundler.analyzer.urlResolver.relative(this.assignedBundle.url, importBundle.url) || importBundle.url; dom5.setAttribute(linkTag, 'href', relative); this.assignedBundle.bundle.stripImports.add(importBundle.url); return; } // We don't actually inline a `lazy-import` because its loading is // intended to be deferred until the client requests it. if (isLazy) { return; } // If the analyzer could not load the import document, we can't inline it, // so lets skip it. const htmlImport = utils_1.find(this.document.getFeatures({ kind: 'html-import', imported: true, externalPackages: true }), (i) => i.document !== undefined && i.document.url === resolvedImportUrl); if (htmlImport === undefined || htmlImport.document === undefined) { return; } // When inlining html documents, we'll parse it as a fragment so that we // do not get html, head or body wrappers. const importAst = parse5_1.parseFragment(htmlImport.document.parsedDocument.contents, { locationInfo: true }); this._rewriteAstToEmulateBaseTag(importAst, resolvedImportUrl); this._rewriteAstBaseUrl(importAst, resolvedImportUrl, this.document.url); if (this.bundler.sourcemaps) { const reparsedDoc = new polymer_analyzer_1.ParsedHtmlDocument({ url: this.assignedBundle.url, baseUrl: this.document.parsedDocument.baseUrl, contents: htmlImport.document.parsedDocument.contents, ast: importAst, isInline: false, locationOffset: undefined, astNode: undefined, }); yield this._addOrUpdateSourcemapsForInlineScripts(this.document, reparsedDoc, resolvedImportUrl); } const nestedImports = dom5.queryAll(importAst, matchers.htmlImport); // Move all of the import doc content after the html import. parse5_utils_1.insertAllBefore(linkTag.parentNode, linkTag, importAst.childNodes); parse5_utils_1.removeElementAndNewline(linkTag); // Record that the inlining took place. this.assignedBundle.bundle.inlinedHtmlImports.add(resolvedImportUrl); // Recursively process the nested imports. for (const nestedImport of nestedImports) { yield this._inlineHtmlImport(nestedImport); } }); }
[ "function removeLink() {\n var selection,\n $link;\n\n // Aloha's unlink command only removes the href attribute, but\n // if there are other attributes, the anchor element is not\n // removed - we must do that manually\n selection = $window.getSelection();\n $link = $(selection.anchorNode).closest('a');\n\n if ($link.length > 0) {\n $link.replaceWith($link.html());\n }\n\n linkPresent = false;\n }", "function removeLink(editor) {\n editor.focus();\n editor.addUndoSnapshot(function (start, end) {\n editor.queryElements('a[href]', 1 /* OnSelection */, roosterjs_editor_dom_1.unwrap);\n editor.select(start, end);\n }, \"Format\" /* Format */);\n}", "function cleanLink(a) {\n // remove all attributes except for href,\n // target (to support \"Open each selected result in a new browser window\"),\n // class, style and ARIA attributes\n for (let i = a.attributes.length - 1; i >= 0; --i) {\n const attr = a.attributes[i];\n if (attr.name !== 'href' && attr.name !== 'target' &&\n attr.name !== 'class' && attr.name !== 'style' &&\n !attr.name.startsWith('aria-')) {\n a.removeAttribute(attr.name);\n }\n }\n a.rel = \"noreferrer noopener\";\n\n // block event listeners on the link\n a.addEventListener(\"click\", function (e) { e.stopImmediatePropagation(); }, true);\n a.addEventListener(\"mousedown\", function (e) { e.stopImmediatePropagation(); }, true);\n}", "async embedLinkedStylesheet(link, document) {\n const href = link.getAttribute('href');\n const media = link.getAttribute('media');\n\n const preloadMode = this.options.preload;\n\n // skip filtered resources, or network resources if no filter is provided\n if (this.urlFilter ? this.urlFilter(href) : !(href || '').match(/\\.css$/)) {\n return Promise.resolve();\n }\n\n // the reduced critical CSS gets injected into a new <style> tag\n const style = document.createElement('style');\n style.$$external = true;\n const sheet = await this.getCssAsset(href, style);\n\n if (!sheet) {\n return;\n }\n\n style.textContent = sheet;\n style.$$name = href;\n style.$$links = [link];\n link.parentNode.insertBefore(style, link);\n\n if (this.checkInlineThreshold(link, style, sheet)) {\n return;\n }\n\n // CSS loader is only injected for the first sheet, then this becomes an empty string\n let cssLoaderPreamble =\n \"function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}\";\n const lazy = preloadMode === 'js-lazy';\n if (lazy) {\n cssLoaderPreamble = cssLoaderPreamble.replace(\n 'l.href',\n \"l.media='print';l.onload=function(){l.media=m};l.href\"\n );\n }\n\n // Allow disabling any mutation of the stylesheet link:\n if (preloadMode === false) return;\n\n let noscriptFallback = false;\n\n if (preloadMode === 'body') {\n document.body.appendChild(link);\n } else {\n link.setAttribute('rel', 'preload');\n link.setAttribute('as', 'style');\n if (preloadMode === 'js' || preloadMode === 'js-lazy') {\n const script = document.createElement('script');\n const js = `${cssLoaderPreamble}$loadcss(${JSON.stringify(href)}${\n lazy ? ',' + JSON.stringify(media || 'all') : ''\n })`;\n // script.appendChild(document.createTextNode(js));\n script.textContent = js;\n link.parentNode.insertBefore(script, link.nextSibling);\n style.$$links.push(script);\n cssLoaderPreamble = '';\n noscriptFallback = true;\n } else if (preloadMode === 'media') {\n // @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26\n link.setAttribute('rel', 'stylesheet');\n link.removeAttribute('as');\n link.setAttribute('media', 'print');\n link.setAttribute('onload', `this.media='${media || 'all'}'`);\n noscriptFallback = true;\n } else if (preloadMode === 'swap-high') {\n // @see http://filamentgroup.github.io/loadCSS/test/new-high.html\n link.setAttribute('rel', 'alternate stylesheet preload');\n link.setAttribute('title', 'styles');\n link.setAttribute('onload', `this.title='';this.rel='stylesheet'`);\n noscriptFallback = true;\n } else if (preloadMode === 'swap') {\n link.setAttribute('onload', \"this.rel='stylesheet'\");\n noscriptFallback = true;\n } else {\n const bodyLink = document.createElement('link');\n bodyLink.setAttribute('rel', 'stylesheet');\n if (media) bodyLink.setAttribute('media', media);\n bodyLink.setAttribute('href', href);\n document.body.appendChild(bodyLink);\n style.$$links.push(bodyLink);\n }\n }\n\n if (this.options.noscriptFallback !== false && noscriptFallback) {\n const noscript = document.createElement('noscript');\n const noscriptLink = document.createElement('link');\n noscriptLink.setAttribute('rel', 'stylesheet');\n noscriptLink.setAttribute('href', href);\n if (media) noscriptLink.setAttribute('media', media);\n noscript.appendChild(noscriptLink);\n link.parentNode.insertBefore(noscript, link.nextSibling);\n style.$$links.push(noscript);\n }\n }", "function insertDocLinks (html) {\n return extractLinks.replace(html, renderLink);\n}", "function cleanTheLink(a) {\n if (a.dataset['cleaned'] == 1) // Already cleaned\n return;\n\n /* Set clean flag */\n var need_clean = false;\n\n /* Find the original url */\n var result = /\\/(?:url|imgres).*[&?](?:url|q|imgurl)=([^&]+)/i.exec(a.href);\n\n if (result) {\n need_clean = true;\n a.href = result[1]; // Restore url to original one\n }\n\n /* Remove the onmousedown attribute if found */\n var val = a.getAttribute('onmousedown') || '';\n\n if (val.indexOf('return rwt(') != -1) {\n need_clean = true;\n a.removeAttribute('onmousedown');\n }\n\n /* FIXME: check the link class name */\n var cls = a.className || '';\n\n if (cls.indexOf('irc_') != -1) need_clean = true;\n\n /*\n * Remove all event listener added to this link\n */ \n if (need_clean) {\n var clone = a.cloneNode(true);\n a.parentNode.replaceChild(clone, a);\n clone.dataset['cleaned'] = 1;\n }\n }", "function linkTag(path) {\n return '<link rel=\"import\" href=\"' + path + '\">';\n}", "function removeLink(link) {\n var index = dataset.links.indexOf(link);\n if(index >= 0) {\n dataset.links.splice(index, 1);\n update();\n }\n}", "function processHyperlinks() {\n context.trace(\"Called processHyperlinks\")\n var hyperlinks = context.document.body.getRange().getHyperlinkRanges();\n hyperlinks.load();\n\n return context.sync().then(function () {\n for (var i = 0; i < hyperlinks.items.length; i++) {\n var link = hyperlinks.items[i];\n var mdLink = '[' + link.text + '](' + link.hyperlink + ') ';\n link.hyperlink = \"\";\n link.insertText(mdLink, 'Replace');\n }\n });\n }", "function updateLinkHref() {\n\tvar codeHeader = \"(function() {\";\n\tvar codeFooter = \"})(); void 0;\";\n\tvar codeBody = editor.getSession().getValue();\n\n\t// minify\n\tvar full_code = codeHeader + codeBody + codeFooter;\n\tfull_code = full_code.replace(/\\n/g, '').replace(/ /g, '');\n\n\tlink.href = 'javascript: ' + full_code;\n\n\tvar baseUrl = '';\n\tstatic_link.href = baseUrl + '#' + utf8_to_b64(codeBody);\n\n}", "static _resetLoader(link) {\n link.classList.remove(LINK_LOADING_CLASS);\n const icon = link.querySelector(LOADING_ICON_SELECTOR);\n if (icon && icon._linkIcon) {\n icon.innerHTML = icon._linkIcon;\n }\n }", "function tokenizeLink(src) {\n if (!this._marked_forms_patched_link_rule) {\n var rules = this.rules.inline;\n rules.link = new RegExp(rules.link.source.replace('|[^\\\\s\\\\x00-\\\\x1f', '|[^\"\\\\x00-\\\\x1f'));\n this._marked_forms_patched_link_rule = true;\n }\n return false;\n }", "_inlineStylesheet(cssLink) {\n return __awaiter(this, void 0, void 0, function* () {\n const stylesheetHref = dom5.getAttribute(cssLink, 'href');\n const resolvedImportUrl = this.bundler.analyzer.urlResolver.resolve(this.assignedBundle.url, stylesheetHref);\n if (resolvedImportUrl === undefined) {\n return;\n }\n if (this.bundler.excludes.some((e) => resolvedImportUrl === e ||\n resolvedImportUrl.startsWith(url_utils_1.ensureTrailingSlash(e)))) {\n return;\n }\n const stylesheetImport = // HACK(usergenic): clang-format workaround\n utils_1.find(this.document.getFeatures({ kind: 'html-style', imported: true, externalPackages: true }), (i) => i.document !== undefined &&\n i.document.url === resolvedImportUrl) ||\n utils_1.find(this.document.getFeatures({ kind: 'css-import', imported: true, externalPackages: true }), (i) => i.document !== undefined &&\n i.document.url === resolvedImportUrl);\n if (stylesheetImport === undefined ||\n stylesheetImport.document === undefined) {\n this.assignedBundle.bundle.missingImports.add(resolvedImportUrl);\n return;\n }\n const stylesheetContent = stylesheetImport.document.parsedDocument.contents;\n const media = dom5.getAttribute(cssLink, 'media');\n let newBaseUrl = this.assignedBundle.url;\n // If the css link we are about to inline is inside of a dom-module, the\n // new base URL must be calculated using the assetpath of the dom-module\n // if present, since Polymer will honor assetpath when resolving URLs in\n // `<style>` tags, even inside of `<template>` tags.\n const parentDomModule = parse5_utils_1.findAncestor(cssLink, dom5.predicates.hasTagName('dom-module'));\n if (!this.bundler.rewriteUrlsInTemplates && parentDomModule &&\n dom5.hasAttribute(parentDomModule, 'assetpath')) {\n const assetPath = (dom5.getAttribute(parentDomModule, 'assetpath') ||\n '');\n if (assetPath) {\n newBaseUrl =\n this.bundler.analyzer.urlResolver.resolve(newBaseUrl, assetPath);\n }\n }\n const resolvedStylesheetContent = this._rewriteCssTextBaseUrl(stylesheetContent, resolvedImportUrl, newBaseUrl);\n const styleNode = dom5.constructors.element('style');\n if (media) {\n dom5.setAttribute(styleNode, 'media', media);\n }\n dom5.replace(cssLink, styleNode);\n dom5.setTextContent(styleNode, resolvedStylesheetContent);\n // Record that the inlining took place.\n this.assignedBundle.bundle.inlinedStyles.add(resolvedImportUrl);\n return styleNode;\n });\n }", "function stripPage() {\n const elements = document.querySelectorAll('script, link[rel=import]');\n elements.forEach((e) => e.remove());\n }", "function unhighlightLink(link) {\n //console.info(\"unhighlightLink\");\n link.removeClass('highlight');\n link.data('myBodyLinks').removeClass('highlight');\n }", "function cleanLinks(linkParser) {\n observe(function() {\n for (let a of document.links) {\n if (a.cleaned) \n continue;\n\n if (a.protocol && a.protocol.startsWith('http'))\n linkParser(a);\n\n a.cleaned = 1;\n }\n });\n}", "function replaceLinkWithEmbed(link) {\n // The link's text may or may not be percent encoded. The `link.href` property\n // will always be percent encoded. When comparing the two we need to be\n // agnostic as to which representation is used.\n if (\n link.href !== link.textContent &&\n decodeURI(link.href) !== link.textContent\n ) {\n return;\n }\n const embed = embedForLink(link);\n if (embed) {\n link.parentElement.replaceChild(embed, link);\n }\n}", "static deleteLink(link) {\n link.remove();\n }", "function stripPage() {\n const elements = document.querySelectorAll('script, link[rel=import]');\n for (const e of Array.from(elements)) {\n e.remove();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
goes through the token list checks if there are active buy/sell orders places orders if no active orders found all orders have an expiration block based on the orderLife value so we don't have to bother to cancel them
async sendOrders() { var currentBlock = await EtherMiumApi.getCurrentBlockNumber(); try { for (let token of this.tokensList) { var found_buy_order = false; var found_sell_order = false; // check if there active orders var orders = await EtherMiumApi.getMyTokenOrders(token[0]); for (let order of orders) { if (order.is_buy) { found_buy_order = true; } else { found_sell_order = true; } } if (found_buy_order && found_sell_order) continue; // get the latest ticker for the token var ticker = await EtherMiumApi.getTickers(token[0], this.ethAddress); if (!found_buy_order) { var balance = await EtherMiumApi.getMyBalance(this.ethAddress); if (balance.decimal_adjusted_balance - balance.decimal_adjusted_in_orders < 0.2) { console.error(`[updateOrders] Insufficient balance to place BUY order`); } var highestBid = ticker.highestBid; var orderPrice = new BigNumber(highestBid).times(1-this.buyOrderMarkUp); var amount = new BigNumber(this.orderEthValue).div(orderPrice).toFixed(8); var result = await EtherMiumApi.placeLimitOrder( 'BUY', orderPrice.toFixed(0), amount, token[0], token[1], this.ethAddress, 18, currentBlock+this.orderLife ); } if (!found_sell_order) { var balance = await EtherMiumApi.getMyBalance(token[0]); var lowestAsk = ticker.lowestAsk; if ((balance.decimal_adjusted_balance - balance.decimal_adjusted_in_orders)*lowestAsk < 0.2) { console.error(`[updateOrders] Insufficient balance to place SELL order`); } var orderPrice = new BigNumber(lowestAsk).times(1+this.sellOrderMarkUp); var amount = new BigNumber(this.orderEthValue).div(orderPrice).toFixed(8); var result = await EtherMiumApi.placeLimitOrder( 'SELL', orderPrice.toFixed(0), amount, token[0], token[1], this.ethAddress, 18, currentBlock+this.orderLife ); } } } catch (error) { console.error(`[updateOrders] Error=${error.message}`); } }
[ "function checkActiveOrders(orders) {\n // TODO if cllosed - close\n if (!tradingIsClosed) {\n orders = JSON.parse(orders);\n let isNoOrders = _.isEmpty(orders);\n \n let sellOrders = _.filter(orders[CURRENCY_PAIR], { type: 'sell' });\n let buyOrders = _.filter(orders[CURRENCY_PAIR], { type: 'buy' });\n \n // To check active orders\n if (!isNoOrders && _.has(orders, CURRENCY_PAIR)) {\n processExistingOrders(sellOrders, buyOrders);\n } else {\n logger.info('No active orders. Need to sell or buy.');\n // to get conts of currency_1 and currency_2\n TRADE.api_query('user_info', {}, sellBuyCallback);\n }\n }\n else {\n logger.info('Trading closed by user.');\n }\n}", "async function maintenance_check_buy_orders() {\n\n if (myOrders.bids.count != 0) { // If I have at least 1 order on the books\n if (myOrders.bids.volumeAboveMe > average_wave_size) { // If I have at least 0.15 ETH worth of tokens\n console2.log(`There is ${myOrders.bids.volumeAboveMe} in ETH above me, which is greater than the Wave size of ${average_wave_size}. Rebuying. Note: rebuy not yet coded`);\n\n hash_to_cancel = fs.readFileSync('order_hash_bid.json', \"utf8\");\n await idex.cancel_order(hash_to_cancel);\n await get_balances(address);\n\n var input_ETH_amount = parseFloat(my_balance_ETH);\n input_ETH_amount = input_ETH_amount.toFixed(4) - 0.0001;\n await idex.execute_buy_order(myOrders.bids.priceAboveWave, input_ETH_amount, target_contract, precision);\n\n }\n else {\n console2.log(`There is a BUY ORDER for ${myOrders.bids.orderAmount} tokens at ${myOrders.bids.orderPrice} with ${myOrders.bids.volumeAboveMe} in ETH above me. No action needed.`);\n };\n }\n else {\n console2.log(`I don't have any buy orders on the order book.`);\n };\n}", "async function maintenance_check_sell_orders() {\n\n if (myOrders.asks.count != 0) { // If I have at least 1 order on the books\n if (((my_balance_tokens + parseFloat(myOrders.asks.orderAmount)) * last_order_price) > 0.15) { // If I have at least 0.15 ETH worth of tokens\n if (last_order_price > stoploss) { // If the price is higher than the stop loss\n if (parseFloat(myOrders.asks.volumeAboveMe) > average_wave_size) {\n console2.log(`There is ${myOrders.asks.volumeAboveMe} in ETH above me, which is greater than the Wave size of ${average_wave_size}. Rebuying. Note: rebuy not yet coded`);\n\n hash_to_cancel = fs.readFileSync('order_hash_ask.json', \"utf8\");\n await idex.cancel_order(hash_to_cancel);\n var input_ETH_amount = ((my_balance_tokens.toFixed(4) - 0.0001) + myOrders.asks.orderAmount) * myOrders.asks.priceAboveWave; // Input the amount in ETH to sell\n console2.log(\"input_ETH_amount is: \" + input_ETH_amount);\n\n await setTimeout(() => {\n idex.execute_sell_order(myOrders.asks.priceAboveWave, input_ETH_amount, target_contract, precision); \n\n },2000);\n\n }\n\n else {\n console2.log(`I have a SELL ORDER for ${myOrders.asks.orderAmount} tokens at ${myOrders.asks.orderPrice} with ${myOrders.asks.volumeAboveMe} in ETH above me. No action needed.`);\n };\n\n }\n\n else {\n console2.log(`The price is below stoploss. I should cancel and rebuy - No action for now.`);\n };\n\n }\n else {\n console2.log(`I don't have enough tokens to process a sell order.`);\n // console.log(`I have ${my_balance_tokens} in my account and ${myOrders.asks.orderAmount} in orders.` + (my_balance_tokens + parseFloat(myOrders.asks.orderAmount)) * last_order_price);\n\n };\n }\n else {\n console2.log(`I don't have any sell orders on the order book.`);\n };\n}", "refreshActiveOrders () {\n const page = this.page\n const metaOrders = this.metaOrders\n const market = this.market\n for (const oid in metaOrders) delete metaOrders[oid]\n const orders = app.orders(market.dex.host, marketID(market.baseCfg.symbol, market.quoteCfg.symbol))\n\n Doc.empty(page.liveList)\n for (const ord of orders) {\n const row = page.liveTemplate.cloneNode(true)\n metaOrders[ord.id] = {\n row: row,\n order: ord\n }\n updateUserOrderRow(row, ord)\n if (ord.type === Order.Limit) {\n if (ord.tif === Order.StandingTiF && ord.status < Order.StatusExecuted) {\n const icon = Doc.tmplElement(row, 'cancelBttn')\n Doc.show(icon)\n bind(icon, 'click', e => {\n e.stopPropagation()\n this.showCancel(row, ord.id)\n })\n }\n }\n const link = Doc.tmplElement(row, 'link')\n link.href = `order/${ord.id}`\n app.bindInternalNavigation(row)\n page.liveList.appendChild(row)\n app.bindTooltips(row)\n }\n }", "async function processPendingOrders() {\n if (!checkTurn()) return\n\n const orders = Pool.list()\n const transactions = []\n\n // Create transactions of orders\n orders.forEach(order => {\n const transaction = new Transaction(order)\n transactions.push(transaction)\n })\n\n if (transactions.length === 0) return\n // Add block on blockchain\n const block = Blockchain.commitTransactions(transactions)\n\n const orderIds = _.map(orders, 'id')\n Pool.remove(orderIds)\n\n await shareState(SUPPORTED_STATES.SYNC_BLOCK, block)\n}", "async cancelOrders(){\n try{\n const market = await this.veil.getMarket(this.market);\n const orders = await this.veil.getUserOrders(market);\n // prob want to check for orders first before mapping\n orders.results.map((order) => {\n if(order.status === 'open'){\n this.veil.cancelOrder(order.uid);\n }\n })\n return \"orders canceled\"\n } catch(e) {\n console.log(\"error \" + e);\n return e;\n }\n }", "function StoreTokensAndGetOrders(tokenArray) {\n\n var access_token = tokenArray[0];\n //var refresh_token = tokenArray[1];\n\n return new Promise(function (resolve, reject) {\n request;\n var options = {\n method: 'POST',\n url: 'https://bandcamp.com/api/merchorders/3/get_orders',\n headers:\n {\n 'cache-control': 'no-cache',\n Authorization: 'Bearer ' + access_token,\n 'Content-Type': 'application/json'\n },\n body: { band_id: config.band_id, start_time: '2019-01-31' },\n json: true\n };\n\n request(options, function (error, response, body) {\n if (error) throw new Error(error);\n\n var orders = body.items;\n\n for (var i = 0; i < orders.length; i++) {\n\n if (orders[i].item_name === 'The More You Void Shirt (Black) by Forming the Void') {\n switch (orders[i].option) {\n case \"small\":\n orders[i].variant_id = '189081623';\n break;\n case \"medium\":\n orders[i].variant_id = '189081626';\n break;\n case \"large\":\n orders[i].variant_id = '189081629';\n break;\n case \"xl\":\n orders[i].variant_id = '189081632';\n break;\n case \"2x\":\n orders[i].variant_id = '189081635';\n break;\n case \"3x\":\n orders[i].variant_id = '5c3faf02b09df1';\n break;\n default:\n console.log(\"Unusual shirt size unaccounted for\");\n }\n } else if (orders[i].item_name === 'The More You Void Shirt (Grey) by Forming the Void') {\n switch (orders[i].option) {\n case \"small\":\n orders[i].variant_id = '184479802';\n break;\n case \"medium\":\n orders[i].variant_id = '184479805';\n break;\n case \"large\":\n orders[i].variant_id = '184479808';\n break;\n case \"xl\":\n orders[i].variant_id = '5c5ca089f2ce44';\n break;\n case \"2x\":\n orders[i].variant_id = '184479814';\n break;\n case \"3x\":\n orders[i].variant_id = '5c3fafcce44b73';\n break;\n default:\n console.log(\"Unusual shirt size unaccounted for\");\n }\n }\n };\n //console.log(orders);\n resolve(orders);\n });\n });\n}", "function buyTokens() {\r\n\r\n if (!handlePassword(\"buy-tokens-modal\", 2)) return;\r\n\r\n\r\n\r\n var tokenAmount = $(\"#token-amount\").val();\r\n\r\n singleTokenCost = ldHandle.singleTokenCost();\r\n\r\n\r\n\r\n var totalTokenCost = singleTokenCost * tokenAmount;\r\n var userBalance = web3.fromWei(web3.eth.getBalance(currAccount), \"wei\");\r\n\r\n var maxTokenToBuy = userBalance / singleTokenCost;\r\n\r\n\r\n if (totalTokenCost >= userBalance) {\r\n\r\n alert(\"You don't have enough funds in your account to buy this amount of tokens. You can buy max \" + maxTokenToBuy + \" of tokens.\");\r\n } else {\r\n\r\n\r\n\r\n\r\n try {\r\n ldHandle.buyTokens(tokenAmount, { from: currAccount, gasprice: gasPrice, gas: gasAmount, value: totalTokenCost });\r\n }\r\n catch (err) {\r\n displayExecutionError(err);\r\n return;\r\n }\r\n\r\n progressActionsBefore();\r\n\r\n setTimeout(function () {\r\n\r\n var logEvent = ldHandle.BuyTokens({ numOfTokens: numOfTokens, buyer: buyer, value: amountSpent });\r\n logEvent.watch(function (error, res) {\r\n\r\n // if (tokenAmount == res.args.numOfTokens ) {\r\n\r\n var message = '<B><BR>\tYou bought ' + res.args.numOfTokens + ' tokens and you have spent ' + res.args.value / 1000000000000000000 + \" Eth\";\r\n progressActionsAfter(message, true);\r\n // }\r\n\r\n });\r\n }, 3);\r\n }\r\n\r\n}", "function nfyLPBuyOrder() {\n if ($('#price-buy-lp').val() <= 0) {\n alert('Price needs to be more than 0!');\n return;\n }\n\n nfyToken.methods\n .allowance(accounts[0], tradingPlatformAddress)\n .call()\n .then(function (res) {\n if (res == 0) {\n nfyToken.methods\n .approve(tradingPlatformAddress, BigInt(maxAllowance).toString())\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n } else {\n var lpToBuyVal = $('#quantity-buy-lp').val();\n var lpPriceVal = $('#price-buy-lp').val();\n\n var lpToBuy = web3.utils.toWei(lpToBuyVal, 'ether');\n var lpPrice = web3.utils.toWei(lpPriceVal, 'ether');\n\n tradingPlatform.methods\n .createLimitOrder('nfylp', lpToBuy, lpPrice, 0)\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n }\n });\n}", "function allOrders(q, id, order) {\n console.log(order.order_time);\n if(q.isEmpty()) {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n } else {\n var pos = getAllPrice(q, order.qty, order.minq);\n if(pos === -1) {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n } else if (order.type === 0 && order.category === 0 && q.elements[pos].price > order.price) {\n qb.enqueue(order);\n msg = \"Order waiting! No sellers at this price\\n\"\n return;\n } else if (order.type === 0 && order.category === 1 && q.elements[pos].price < order.price) {\n qb.enqueue(order);\n msg = \"Order waiting! No buyers at this price\\n\"\n return;\n } else if(q.elements[pos].qty >= order.qty) {\n //trade executes\n if(order.category === 0) {\n acceptOrder(id, q.elements[pos].order_id, q.elements[pos].price, order.qty);\n } else {\n acceptOrder(q.elements[pos].order_id, id, q.elements[pos].price, order.qty);\n }\n msg = \"Order executed!\";\n updateAcceptStatus(id);\n q.elements[pos].qty -= order.qty;\n if(q.elements[pos].qty === 0 ) {\n if(q.elements[pos].description === 3) {\n if(q.elements[pos].left > 0) {\n if(q.elements[pos].left < q.elements[pos].mindis) {\n q.elements[pos].qty = q.elements[pos].left;\n q.elements[pos].left = 0;\n } else {\n q.elements[pos].qty = q.elements[pos].mindis;\n q.elements[pos].left -= q.elements[pos].mindis;\n }\n }\n }\n if(q.elements[pos].qty === 0 ){\n updateAcceptStatus(q.elements[pos].order_id);\n q.elements[pos].category = -1;\n if(pos === 0) {\n q.dequeue();\n }\n }\n }\n if (q.elements[pos].description === 2) {\n q.elements[pos].minq = 1;\n }\n order.qty=0;\n } else {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n }\n }\n}", "checkOrders() {\n if (!this.orders.length) return null;\n return this.currentTime === this.orders[this.orders.length - 1].order_time ? this.orders.pop() : null;\n }", "check () {\n\n if (priceStore.prices[this.from]) {\n\n // current price of this exchange\n const currentPrice = priceStore.prices[this.from][this.to];\n\n // comparing order price with current price\n if (currentPrice <= this.price && !this.completed) {\n\n wallet.funds[this.from].reservedAmount -= this.amount;\n wallet.charge(this.to, this.amount * currentPrice);\n this.completed = true;\n\n // canceling the order\n this.cancel();\n\n }\n }\n\n }", "function nfyBuyOrder() {\n if ($('#price-buy-nfy').val() <= 0) {\n alert('Price needs to be more than 0!');\n return;\n }\n\n nfyToken.methods\n .allowance(accounts[0], tradingPlatformAddress)\n .call()\n .then(function (res) {\n if (res == 0) {\n nfyToken.methods\n .approve(tradingPlatformAddress, BigInt(maxAllowance).toString())\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n } else {\n var nfyToBuyVal = $('#quantity-buy-nfy').val();\n var nfyPriceVal = $('#price-buy-nfy').val();\n\n var nfyToBuy = web3.utils.toWei(nfyToBuyVal, 'ether');\n var nfyPrice = web3.utils.toWei(nfyPriceVal, 'ether');\n\n tradingPlatform.methods\n .createLimitOrder('nfy', nfyToBuy, nfyPrice, 0)\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n }\n });\n}", "function cancelAllActiveOrders(callback){\n geminiClient.cancelAllActiveOrders()\n .then(_res => {\n callback(_res)\n })\n .catch(console.error);\n}", "function BinDoOrdersOpen() {\n let lock_retries = 5; // Max retries to acquire lock\n\n /**\n * Returns this function tag (the one that's used for BINANCE function 1st parameter)\n */\n function tag() {\n return \"orders/open\";\n }\n\n /**\n * Returns true if the given operation belongs to this code\n */\n function is(operation) {\n return operation === tag();\n }\n\n /**\n * Returns this function period (the one that's used by the refresh triggers)\n */\n function period() {\n return BinScheduler().getSchedule(tag()) || \"5m\";\n }\n \n /**\n * Returns current open oders.\n *\n * @param {[\"BTC\",\"ETH\"..]} range_or_cell If given, will filter by given symbols (regexp).\n * @param options Ticker to match against (none by default) or an option list like \"ticker: USDT, headers: false\"\n * @return A list of current open orders for given criteria.\n */\n function run(range_or_cell, options) {\n const bs = BinScheduler();\n try {\n bs.clearFailed(tag());\n return execute(range_or_cell, options);\n } catch(err) { // Re-schedule this failed run!\n bs.rescheduleFailed(tag());\n throw err;\n }\n }\n\n function execute(range_or_cell, options) {\n const ticker_against = options[\"ticker\"] || \"\";\n Logger.log(\"[BinDoOrdersOpen] Running..\");\n const lock = BinUtils().getUserLock(lock_retries--);\n if (!lock) { // Could not acquire lock! => Retry\n return execute(range_or_cell, options);\n }\n\n let data = fetch();\n BinUtils().releaseLock(lock);\n Logger.log(\"[BinDoOrdersOpen] Found \"+data.length+\" orders to display.\");\n const range = BinUtils().getRangeOrCell(range_or_cell);\n if (range.length) { // Apply filtering\n const pairs = range.map(symbol => new RegExp(symbol+ticker_against, \"i\"));\n data = data.filter(row => pairs.find(pair => pair.test(row.symbol)));\n Logger.log(\"[BinDoOrdersOpen] Filtered to \"+data.length+\" orders.\");\n }\n\n const parsed = parse(data, options);\n Logger.log(\"[BinDoOrdersOpen] Done!\");\n return parsed;\n }\n\n function fetch() {\n const bw = BinWallet();\n const opts = {CACHE_TTL: 55, \"discard_40x\": true}; // Discard 40x errors for disabled wallets!\n const dataSpot = fetchSpotOrders(opts); // Get all SPOT orders\n const dataCross = bw.isEnabled(\"cross\") ? fetchCrossOrders(opts) : []; // Get all CROSS MARGIN orders\n const dataIsolated = bw.isEnabled(\"isolated\") ? fetchIsolatedOrders(opts) : []; // Get all ISOLATED MARGIN orders\n const dataFutures = bw.isEnabled(\"futures\") ? fetchFuturesOrders(opts) : []; // Get all FUTURES orders\n return [...dataSpot, ...dataCross, ...dataIsolated, ...dataFutures];\n }\n\n function fetchSpotOrders(opts) {\n Logger.log(\"[BinDoOrdersOpen][SPOT] Fetching orders..\");\n const orders = new BinRequest(opts).get(\"api/v3/openOrders\");\n return orders.map(function(order) {\n order.market = \"SPOT\";\n return order;\n });\n }\n\n function fetchCrossOrders(opts) {\n Logger.log(\"[BinDoOrdersOpen][CROSS] Fetching orders..\");\n const orders = new BinRequest(opts).get(\"sapi/v1/margin/openOrders\") || []; // It may fail if wallet isn't enabled!\n return orders.map(function(order) {\n order.market = \"CROSS\";\n return order;\n });\n }\n\n function fetchIsolatedOrders(opts) {\n const wallet = BinWallet();\n const symbols = Object.keys(wallet.getIsolatedPairs());\n return symbols.reduce(function(acc, symbol) {\n Logger.log(\"[BinDoOrdersOpen][ISOLATED] Fetching orders for '\"+symbol+\"' pair..\");\n const qs = \"isIsolated=true&symbol=\"+symbol;\n const orders = new BinRequest(opts).get(\"sapi/v1/margin/openOrders\", qs) || []; // It may fail if wallet isn't enabled!\n const data = orders.map(function(order) {\n order.market = \"ISOLATED\";\n return order;\n });\n return [...acc, ...data];\n }, []);\n }\n\n function fetchFuturesOrders(opts) {\n Logger.log(\"[BinDoOrdersOpen][FUTURES] Fetching orders..\");\n const options = Object.assign({futures: true}, opts);\n const orders = new BinRequest(options).get(\"fapi/v1/openOrders\") || []; // It may fail if wallet isn't enabled!\n return orders.map(function(order) {\n order.market = \"FUTURES\";\n return order;\n });\n }\n\n function parse(data, {headers: show_headers}) {\n const header = [\"Date\", \"Pair\", \"Market\", \"Type\", \"Side\", \"Price\", \"Amount\", \"Executed\", \"Total\"];\n const parsed = data.reduce(function(rows, order) {\n const symbol = order.symbol;\n const price = BinUtils().parsePrice(order.price);\n const amount = parseFloat(order.origQty);\n const row = [\n new Date(parseInt(order.time)),\n symbol,\n order.market,\n order.type,\n order.side,\n price,\n amount,\n parseFloat(order.executedQty),\n price*amount\n ];\n rows.push(row);\n return rows;\n }, []);\n\n const sorted = BinUtils().sortResults(parsed, 0, true);\n return BinUtils().parseBool(show_headers) ? [header, ...sorted] : sorted;\n }\n\n // Return just what's needed from outside!\n return {\n tag,\n is,\n period,\n run\n };\n}", "watch() {\n const { watchlist } = this.meta;\n const { config } = this;\n const { state } = this;\n\n for (const orderId in watchlist) {\n const order = watchlist[orderId];\n const orderPrice = Number(order.price);\n const orderQuantity = Number(order.quantity);\n const currentPrice = this.ticker.meta.bid;\n let shouldSell = false;\n\n if (currentPrice >= (orderPrice + (orderPrice * config.profitPercentage))) {\n shouldSell = true; // profit percentage trigger\n }\n\n if (state.paranoid && (currentPrice <= orderPrice + (orderPrice * config.profitLockPercentage))) { // profit lock trigger\n console.log(' [ALARM]::: Price dipped below PROFIT_LOCK_PERCENTAGE while in paranoid mode. Selling.');\n state.profitLockPercentageMet = true; // used for mocha testing\n shouldSell = true;\n }\n\n if (config.profitLockPercentage && (currentPrice >= orderPrice + (orderPrice * config.profitLockPercentage))) { // profit lock trigger\n console.log(' [ALARM]::: PROFIT_LOCK_PERCENTAGE REACHED. Now in paranoid mode.');\n state.paranoid = true;\n }\n\n if (config.stopLimitPercentage && (currentPrice <= orderPrice - (orderPrice * config.stopLimitPercentage))) { // stop limit trigger\n console.log(' [ALARM]::: STOP_LIMIT_PERCENTAGE REACHED. Exiting position.');\n state.stopLimitPercentageMet = true;\n shouldSell = true;\n }\n\n if (shouldSell) {\n this.bot.sell(orderQuantity, currentPrice);\n state.paranoid = false;\n this.remove(orderId);\n }\n }\n }", "function nfySellOrder() {\n if ($('#price-sell-nfy').val() <= 0) {\n alert('Price can not be less than 0!');\n return;\n }\n\n nfyToken.methods\n .allowance(accounts[0], tradingPlatformAddress)\n .call()\n .then(function (res) {\n if (res == 0) {\n nfyToken.methods\n .approve(tradingPlatformAddress, BigInt(maxAllowance).toString())\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n } else {\n var nfyToSellVal = $('#quantity-sell-nfy').val();\n var nfyPriceVal = $('#price-sell-nfy').val();\n\n var nfyToSell = web3.utils.toWei(nfyToSellVal, 'ether');\n var nfyPrice = web3.utils.toWei(nfyPriceVal, 'ether');\n\n tradingPlatform.methods\n .createLimitOrder('nfy', nfyToSell, nfyPrice, 1)\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n }\n });\n}", "activeTokens() {\n return this.getTokens({ where: { updatedAt: { $gt: THIRTY_DAYS_AGO } } })\n }", "async function cancelOrders() {\n try {\n const orders = await searchOrders();\n if (!orders) {\n console.log(\"No orders to cancel\");\n return;\n }\n for (const order of orders) {\n await ordersApi.updateOrder(\n order.id,\n {\n idempotencyKey: uuidv4(),\n order: {\n locationId: process.env.LOCATION_ID,\n state: \"CANCELED\",\n version: order.version\n }\n }\n );\n }\n console.log(\"Successfully canceled orders\", orders.map(o => o.id));\n } catch (error) {\n console.error(\"Error occurred when canceling orders\", error);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse Solr search results into HTML
function parseSolrResults(resultJson) { var docs = resultJson["response"]["docs"]; var html = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var row = "slide name: " + doc["ppt_name"]+" slide page: " + doc["slide_number"] + " with title: "+doc["title_text"]+"<br>"; var imgurl = doc["img_url"]; var img = "<img src=" + imgurl + " style='width: 80%; height: 80%' />"; var box = "<div >" + row + img +"</div>"; //html.push(row); //html.push(img); html.push(box); } if (html.length) { return html.join("\n"); } else { return "<p>Your search returned no results.</p>"; } }
[ "function parseSolrResults(resultJson) {\n var docs = resultJson[\"response\"][\"docs\"];\n var html = [];\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n var names = doc[\"origin\"].join(\", \") + \" \";\n var date = \"(Published \" + doc[\"datePublished\"].slice(0, 10) + \")\";\n var link = doc[\"resourceMap\"][0];\n if (link.slice(0, 4) === \"doi:\") {\n link = \"http://dx.doi.org/\" + link.slice(4);\n }\n var title = '<a rel=\"external\" href=\"' + link + '\" target=\"_blank\">' + \n doc[\"title\"].trim() + '</a>';\n var row = '<p><span class=\"dataset-title\">' + title + \n '</span><br><span class=\"dataset-author\">' + names + date +\n '</span></p>';\n html.push(row);\n }\n if (html.length) {\n return html.join(\"\\n\");\n }\n else {\n return \"<p>Your search returned no results.</p>\";\n }\n}", "function solrWriteResults() {\nvar resultsHtml = \"\";\nfor (var i=0; i<slr_resultList.length;i++) {\nvar result = slr_resultList[i];\nvar metatags = null;\nif (result.Metatags != undefined) {\nmetatags = solrGetMetatags(result.Metatags);\n}\nvar hightlightKey = result.url;\nvar highlight = slr_highlightList[hightlightKey];\nresultsHtml+=solrGetPlainResultHtml(result,highlight,metatags,i);\n}\n$(\".searchResultsContainer ul\").html(resultsHtml);\n$(\".searchResultsContainer\").css(\"visibility\",\"visible\");\n}", "function solrGetPlainResultHtml(result,highlight,metatags,index) {\nvar html=\"\";\nhtml+=\"<li>\";\nif (metatags != null && metatags != undefined && metatags.resultthumb != \"\" && metatags.resultthumb != null) {\nhtml+=\" <div class='thumb'>\";\nhtml+=\" <img class='photo' width='138' height='78' border='0' alt='thumbnail' src='\"+metatags.resultthumb+\"'>\";\nhtml+=\" </div>\";\n}\nhtml+=\"\t<div class='title'><a href='\"+result.url+\"'>\"+result.htsearch+\"</a>\"+getSearchWeight(result.score,index)+\"</div>\";\nhtml+=\"\t<div class='summary'>\";\nhtml+=\" <span class='date'>\"+solrGetDate(result)+\"</span>\";\nhtml+=\" &nbsp;&nbsp;\" + highlight.noindexcontent + \" ...\";\nhtml+=\" </div>\";\nhtml+=\"</li>\";\nreturn html;\n}", "function updatepage(str){\n var resp = eval(\"(\"+str+\")\"); // use eval to parse Solr's JSON response\n //printing the raw json data\n document.getElementById(\"raw\").innerHTML = str;\n var html= \"<br>Number of Results=\" + resp.response.numFound+\"<br>\";\n // if (resp.response.numFound != 0) {\n // html += \"Displaying results for \" + generate_stem ((document.forms['f1'].query.value)).join (\", \") +\"<br><br>\";\n // }\n document.getElementById(\"result\").innerHTML = html;\n var first = resp.response.docs[0];\n // print all the results\n for(var i = 0; i < resp.response.docs.length; i++){\n var curdoc = resp.response.docs[i];\n // html += \"<h4>\"+curdoc.title+\"</h4>\";\n // html += curdoc.description+\"<br>\";\n var resource_name = curdoc.resourcename[0];\n var found_index = resource_name.search (\"/./\");\n var link = \".\" + resource_name.substring(found_index + 1, resource_name.length);\n // console.log(link);\n html += \"<a href=\"+link+\">\"+curdoc.title+\"</a>\";\n html += \"<br>\";\n } \n \n // dunno what this highlighting shit is. stuff on bottom of page\n var hl=resp.highlighting[first.id];\n if (hl.name != null) { html += \"<br>name highlighted: \" + hl.name[0]; }\n if (hl.features != null) { html += \"<br>features highligted: \" + hl.features[0]; }\n document.getElementById(\"result\").innerHTML = html;\n}", "function parseLunrResults(results) {\n var html = [];\n for (var i = 0; i < results.length; i++) {\n var id = results[i][\"ref\"];\n var item = PREVIEW_LOOKUP[id]\n var title = item[\"t\"];\n var preview = item[\"p\"];\n var link = item[\"l\"];\n var result = ('<p><span class=\"result-title\"><a href=\"' + link + '\">'\n + title + '</a></span><br><span class=\"result-preview\">'\n + preview + '</span></p>');\n html.push(result);\n }\n if (html.length) {\n return html.join(\"\");\n }\n else {\n return \"<p>Your search returned no results.</p>\";\n }\n}", "function parseLunrResults(results) {\n var html = [];\n for (var i = 0; i < results.length; i++) {\n var id = results[i][\"ref\"];\n var item = PREVIEW_LOOKUP[id];\n var title = item[\"t\"];\n var preview = item[\"p\"];\n var link = item[\"l\"];\n if (title === \"\") {\n title = link.replace(/\\.[^/.]+$/, \"\");\n }\n var result =\n '<p><span class=\"result-title\"><a href=\"' +\n link +\n '\">' +\n title +\n '</a></span><br><span class=\"result-preview\">' +\n preview +\n \"</span></p>\";\n html.push(result);\n console.log(result);\n }\n if (html.length) {\n return html.join(\"\");\n } else {\n return \"<p>Your search returned no results.</p>\";\n }\n}", "function renderSearchResults(){\n if (!searchResults || searchResults.length === 0) {\n searchList.innerHTML = '<li class=\"no-results\">No results found!</li>';\n return;\n }\n\n searchResults.forEach((element)=>{\n const li = document.createElement('li');\n li.classList.add('search-result');\n li.innerHTML= `\n <div class=\"query\">\n <h2>${element.query}</h2>\n </div>\n <div class=\"Topic\">\n <h3>Topic : ${element.topic} </h3>\n\n </div>\n <div class=\"Tags\">\n <p>Tags : ${element.tags} </p>\n </div>\n `;\n searchList.appendChild(li);\n });\n }", "function querySolr() {\n var url = \"http://localhost:8983/solr/select\";\n var request = {};\n \n window.resultsLoading = true;\n \n var state = getState();\n console.log(state);\n \n var query = \"\";\n \n if(state.text.length) {\n query += \"+\" + state.text;\n }\n \n if(state.roles.length) {\n query += facetQuery(\"role\", state.roles);\n }\n \n if(state.tags.length) {\n query += facetQuery(\"tag\", state.tags);\n }\n \n if(state.groups.length) {\n query += facetQuery(\"groupname\", state.groups);\n }\n \n if(query === \"\") {\n query = \"*:*\";\n }\n \n request.q = query;\n request.start = (state.page * state.rows) - state.rows;\n request.rows = state.rows;\n request.fl = \"*\";\n request.wt = \"json\";\n request.sort = sortQuery(state.roles);\n request.facet = \"true\";\n request['facet.field'] = [\"role\", \"tag\", \"groupname\"];\n request['f.tag.facet.limit'] = \"5\";\n request.spellcheck = \"true\";\n\n \n jQuery.ajaxSettings.traditional = true;\n \n $.ajax({\n type: \"POST\",\n dataType: \"json\",\n url: url,\n data: request,\n error: function () {\n displayError(\"The server doesn't respond.\");\n },\n success: function (data) {\n console.log(data);\n window.nbOfResult = data.response.numFound;\n\n if(state.page === 1) {\n $(\"#results\").trigger(\"newResults\", data);\n \n } else {\n $(\"#results\").trigger(\"moreResults\", data);\n }\n }\n });\n}", "function solrSearch(searchTerm) {\n//facet query is used to get the counts for the categories.\n//var facetQuery = 'facet=true&facet.query=Metatags:\"resulttype:A\"&facet.query=Metatags:\"resulttype:P\"&facet.query=Metatags:\"resulttype:V\"';\n// set the global vars\nslr_curSearchTerm = searchTerm;\t\t\nvar sort = \"\";\nif (slr_curSort!=undefined) {\nsort=\"&sort=\"+slr_curSort+\" desc\";\n}\nif (searchTerm.length > 0 && searchTerm!=\"Enter Keywords\" && searchTerm!=\"Search\") {\n// make the ajax call\nvar searchUrl = slr_searchContext+\"select?indent=on&version=2.2&q=(htsearch:Players \"+searchTerm+\"~0.5 AND title:\"+searchTerm+\")^5 OR (htsearch:\"+searchTerm+\" OR title:\"+searchTerm+\") OR \"+searchTerm+\"&start=\"+slr_start+\"&rows=\"+slr_numRows+\"&fl=title,url,tstamp,mtime,htsearch,Metatags,score&qt=&wt=json&explainOther=&hl=on&hl.fl=title,url,noindexcontent&hl.fragsize=\"+slr_fragSize + sort;\n$.ajax( {\nurl : encodeURI(searchUrl),\ntype :'GET',\ntimeout :10000,\ndataType :'json',\ncontentType : 'application/json',\ncache : true,\nasync :false,\nerror : function(jqXHR, textStatus, errorThrown) {\nsolrSetMessage(slr_requestError);\n},\nsuccess: function (data, textStatus, jqXHR) {\n// if we get data back, then process the results\nslr_resultList = null;\nslr_numAll = data.response.numFound;\nslr_maxScore = data.response.maxScore;\nif (data.response.numFound > 0) {\n// set the resultList array\nslr_resultList = data.response.docs;\n// set the highlightList array\nslr_highlightList = data.highlighting;\n// write the results\nsolrWriteResults();\n} else {\nsolrSetMessage(slr_noResults);\n$(\".searchResultsContainer ul\").html(\"\");\n}\n}\n});\n} else {\nsolrSetMessage(slr_emptyTerm);\n}\n}", "function parseresults (dataobj, cleanup) {\n var resultobj = {};\n resultobj.records = [];\n resultobj.start = '';\n resultobj.found = '';\n resultobj.aggregations = {};\n var temp, item_source, item_val;\n for (var item = 0; item < dataobj.hits.hits.length; item++) {\n if (options.fields) {\n resultobj.records.push(dataobj.hits.hits[item].fields);\n } else if (options.partial_fields) {\n var keys = [];\n for (var key in options.partial_fields) {\n keys.push(key);\n }\n resultobj.records.push(\n dataobj.hits.hits[item].fields[keys[0]]);\n } else {\n if (!cleanup) {\n resultobj.records.push(dataobj.hits.hits[item]._source);\n }\n else {\n item_source = dataobj.hits.hits[item]._source;\n // 90612 remove html tags from string results when we render the results\n for (var i in item_source) {\n item_val = item_source[i];\n\n if (typeof(item_val) === 'string') {\n item_source[i] = item_val.replace(/(<([^>]+)>)/ig, \"\");\n }\n }\n if (window.isInDebugMode){\n item_source['_explanation'] = parseExplanation(dataobj.hits.hits[item]._explanation);\n }\n resultobj.records.push(item_source);\n }\n if (options.highlight_enabled){\n if (dataobj.hits.hits[item].highlight !== undefined){\n var tmp_resultobj = resultobj.records[resultobj.records.length - 1];\n jQuery.each(dataobj.hits.hits[item].highlight, function(key, value){\n var should_add = false;\n if ((options.highlight_whitelist.indexOf(key) !== -1) || ((options.highlight_whitelist.length === 0) && (options.highlight_blacklist.length === 0))){\n should_add = true;\n }\n if (options.highlight_blacklist.indexOf(key) !== -1){\n should_add = false;\n }\n if (should_add){\n tmp_resultobj[key] = value;\n }\n });\n }\n }\n }\n }\n resultobj.start = '';\n if (settings_es_version === 'es6'){\n resultobj.found = dataobj.hits.total;\n }\n if (settings_es_version === 'es7'){\n resultobj.found = dataobj.hits.total.value;\n }\n for (var item in dataobj.aggregations) {\n resultobj.aggregations[item] = parsefacet(dataobj.aggregations[item]);\n }\n return resultobj;\n }", "function _printSearchResults(doc, qagent) {\n\n\tif(!qagent.hasCachedResults()) {\n\t\t// page was reloaded; return to the main page...\n\t\twindow.open(\"blank.html\", \"qaview\");\n\t\treturn;\n\t}\n\n\tvar totalHits = 0;\n\tfor (var x=0; x<hits.length; x++) {\n\t\ttotalHits += hits[x];\n\t}\n\n\tvar msgCount = qagent.getLogMessagesCount();\n\n\tdoc.open();\n\n\tif(msgCount > 0) {\n\t\tdoc.writeln('<ul>');\n\t\t\n\t\tfor(var i = 0; i < msgCount; i++) {\n\t\t\tvar t = qagent.getLogMessageType(i);\n\t\t\tif(t<4) {\n\t\t\t\tdoc.writeln('<li>' + qagent.getLogMessage(i) + '</li>');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdoc.writeln('<li><b>' + qagent.getLogMessage(i) + '</b></li>');\n\t\t\t}\n\t\t}\n\t\tdoc.writeln('</ul>');\n\t\tdoc.writeln('<br>');\n\t}\n\n\tif(totalHits == 0) {\n\t\tdoc.write('<b>' + nothingFoundText + '</b>');\n\t}\n\n\telse {\n\t\tif (selectedCollections.length == 1) {\n\t\t\tdoc.write('<font class=\"title2\">' + collections[selectedCollections[0]].name + ': <font color=\"#808080\">' + hits[0] + ' ' + useDocs + '</font></font><br><br>');\n\t\t}\n\t\telse if(selectedCollections.length > 1) {\n\t\t\tdoc.write('<ul><font class=\"title2\">');\n\t\t\tfor (var i=0; i<selectedCollections.length; i++) {\n\t\t\t\tdoc.write('<li><b><a href=#' + i + '>' + collections[selectedCollections[i]].name + ': <font color=\"#808080\">' + hits[i] + ' ' + useDocs + '</font></a></b></li>');\n\t\t\t}\n\t\t\tdoc.write('</ul></font>');\n\t\t}\n\t\tdoc.write(results);\n\t}\n\t\n}", "function renderResults(results, allResults) {\n if (results.length <1 && allResults && allResults.length < 1) {\n return;\n }\n\n function displayableScore(score) {\n return (100 - (score * 100)).toFixed(2);\n }\n\n function shorten(str, maxLen=80, separators = '/[\\.\\?]/') {\n if (str.length <= maxLen) return str;\n var shorter;\n var pos = str.replace(/^.{80}/,\"\").match(/[^a-z ]/i)['index'] + maxLen;\n shorter = str.substr(0, pos);\n if (shorter.charAt(shorter.len -1) != '.') {\n shorter += \" ...\";\n }\n return shorter;\n }\n\n function summarize(item, score) {\n var parts = item.contents.split(/[\\n\\r]/g);\n var summary;\n if (showCategoryAndTags) {\n var category = item.categories ? \"In the \" + item.categories[0] + \" gallery\" : \"\";\n var description = shorten(parts[0]);\n summary = category + \" with tags \" + item.tags.join(\", \") + \": \" + description;\n } else {\n summary = shorten(parts[0]);\n }\n if (showScores) {\n summary += \" - Score:\" + displayableScore(score);\n }\n return summary;\n }\n\n function list_item(result) {\n var li = document.createElement('li');\n var classes = li.getAttribute('class');\n li.setAttribute('class', classes ? classes + ' ' : '' + 'search_item');\n var ahref = document.createElement('a');\n ahref.href = result.item.permalink;\n ahref.text = result.item.title;\n li.append(ahref);\n li.append(document.createTextNode(\" - \" + summarize(result.item, result.score)));\n return li;\n }\n\n // Show the first maxResults matches\n var resultsSoFar = [],\n remaining = results.length;\n\n results.slice(0, maxResults).forEach(function (result) {\n var li = list_item(result);\n searchResultsList.appendChild(li);\n resultsSoFar.push(result.item.permalink);\n });\n\n if (resultsSoFar.length < maxResults && useAllContent) {\n // Fill in additional from allResults, filtering those included in results\n allResults = allResults.filter(function(value, index, arr) {\n return ! resultsSoFar.includes(value.item.permalink);\n });\n allResults.slice(resultsSoFar.length, maxResults).forEach(function (result) {\n // Maybe you want to filter out low scoring results too?\n // Maybe anything less than 20% of the top scoring item?\n // Or perhaps when the score is less than half of the preceeding score?\n var li = list_item(result);\n searchResultsList.appendChild(li);\n resultsSoFar.push(result.item.permalink);\n });\n remaining = allResults.length - resultsSoFar.length;\n } else {\n remaining -= resultsSoFar.length;\n }\n if (remaining > 0 && showScores) {\n // Tell user there are more yet\n // Bonus yak-shaving points for stats on score distribution\n // see https://stackoverflow.com/questions/48719873/how-to-get-median-and-quartiles-percentiles-of-an-array-in-javascript-or-php\n var li = document.createElement('li');\n var p = document.createElement('p');\n p.appendChild(document.createTextNode(\"... and \" + remaining + \" more\"));\n li.append(p);\n searchResultsList.appendChild(li);\n };\n}", "function SearchResults(data){this.resultsCount=data.PrimaryQueryResult.RelevantResults.TotalRows;this.items=convertRowsToObjects(data.PrimaryQueryResult.RelevantResults.Table.Rows.results,this.resultsCount)}", "function putResultsOnPage(results)\n{\n //get search results div\n var theDiv = document.getElementById('search-results');\n \n //clear current content\n theDiv.innerHTML = '';\n \n //reset Y position because it might have changed after some touch scrolling frenzy!\n theDiv.style.top = '0';\n \n //might be no matches\n if(results.rows.length === 0)\n {\n theDiv.innerHTML = 'No matches found in the common words dictionary.\\\n Tweet @japxlate yourAdvancedWord for advanced word definitions.';\n buttonSpinnerVisible(false); //stop the loading spinner\n return;\n }\n \n //some results so loop through and print\n for(var loop = 0; loop < results.rows.length; loop++)\n {\n var item = results.rows.item(loop);\n \n var theRomaji = kana_to_romaji(item.kana);\n //var theRomaji = item.kana;\n var formattedDefinition = format_slashes(item.definition);\n \n var defText = item.kanji + ' / ' + item.kana + ' (' + theRomaji + ') / ' + formattedDefinition;\n defText = defText.replace(new RegExp(global_searchTerm, 'ig'), '<span style=\"color:#990000;\">$&</span>');\n \n var defLine = '<img src=\"img/j.png\" style=\"vertical-align:middle;\"> ' + defText + '<hr>';\n //var defLine = '<p class=\"def-line\"> ' + defText + '</p>'; //had CSS styling issues (mostly text overflow)\n \n theDiv.innerHTML += defLine;\n }\n \n buttonSpinnerVisible(false); //stop the loading spinner\n}", "function displaySearchResults(query){\n\t// create the complete url\n\tvar wiki_url = base_url + query;\n\tconsole.log(wiki_url);\n\t$.getJSON(wiki_url, function(json){\n\t\tvar result = json[\"query\"][\"search\"];\n\t\tfor(var i=0; i<result.length; i++){\n\t\t\tconsole.log(result[i]);\n\t\t\turl_link = base_redirect + result[i].title.replace(\" \", \"%20\");\n\t\t\t$(\"#content\").append(\"<a href='\" + url_link + \"' class='list-group-item' target='_blank'><h3>\"\n\t\t\t+ result[i].title + \"</h3><br>\" + result[i].snippet + \"<br></a>\");\n\t\t}\n\t});\n\t\n}", "function parseSearchResults(jsonData) {\n\tif (jsonData['error'] || jsonData['warning']) {\n\t\t// either a warning or an error are a bit fatal so we stop right here\n\t\ttarget.style.display = \"none\";\n\t\treturn;\n\t}\n\t// if we have no results there is no need to continue\n\tif (jsonData['results'] == null || jsonData['results'].length == 0) {\n\t\tsearchData = new Array();\n\t\tlastHitCount = 0;\n\t\tprintTags(null);\n\t\treturn;\n\t}\n\t// this will make sure we invalidate the query.\n\tquery = jsonData['query'];\n\t// add this term to the query list\n\tupdateQueryListCache(query);\n\tvar re = /\\s/; \n\tvar patterns = query.toLowerCase().split(re);\n\tvar plen = patterns.length;\n\tvar target = document.getElementById(\"layout-search\");\n\tvar type = target.getElementsByTagName(\"select\")[0].value;\n\t// we need to take care of repititions\n\tvar results = new Array();\n\tvar tmp = new Array(); // array for valid tags\n\tvar tmpSearchData = jsonData['results'];\n\tvar tmpObject = new Object();\n\t// indicates whether or not we have types, default is false\n\tvar typeSearch = false;\n\t// order by which we want prioritize the results\n\tvar orderArray = null;\n\t// relation key for when we are searching by types\n\tvar relKey = \"\";\n\tswitch(type) {\n\t\tcase \"mangalist\": typeSearch = true; relKey = \"mangaid\"; orderArray = [\"4\",\"2\",\"3\"]; break;\n\t\tcase \"animelist\": typeSearch = true; relKey = \"aid\"; orderArray = [\"4\",\"2\",\"3\"]; break;\n\t\tcase \"characterlist\": typeSearch = true; relKey = \"charid\"; orderArray = [\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\"]; break;\n\t\tcase \"collectionlist\": typeSearch = true; relKey = \"collectionid\"; orderArray = [\"2\",\"3\"]; break;\n\t\tcase \"creatorlist\": typeSearch = true; relKey = \"creatorid\"; orderArray = [\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]; break;\n\t\tcase \"songlist\": typeSearch = true; relKey = \"songid\"; orderArray = [\"2\",\"3\"]; break;\n\t\tcase \"animetags\":\n\t\tcase \"chartags\":\n\t\tcase \"clublist\": typeSearch = true; relKey = \"clubid\"; orderArray = [\"2\"]; break;\n\t\tcase \"userlist\": typeSearch = true; relKey = \"uid\"; orderArray = []; break;\n\t\tcase \"grouplist\": // groups need pre-processing because of the short and long names\n\t\t\tfor (var n = 0; n < tmpSearchData.length; n++) {\n\t\t\t\tvar name = tmpSearchData[n]['name'];\n\t\t\t\tvar shortName = tmpSearchData[n]['shortname'];\n\t\t\t\ttmpSearchData[n]['name'] = name + \" (\"+shortName+\")\";\n\t\t\t}\n\t\t\ttypeSearch = true; relKey = \"id\"; orderArray = []; break;\n\t\t\tbreak;\n\t}\n\tlastSearch\n\tif (typeSearch) {\n\t\t// for anime and char results we do special handling\n\t\t// we group by aid/charid first, then by title type\n\t\t// just take care or remove repetitions\n\t\tvar deflangid = jsonData['deflangid'] || 0;\n\t\tsearchTypeDefaultLanguageId = deflangid;\n\t\tfor(var n = 0; n < tmpSearchData.length; n++) {\n\t\t\tif (type == \"songlist\") tmpSearchData[n]['song_type'] = \"Song\";\n\t\t\tif (type == \"userlist\") {\n\t\t\t\ttmpSearchData[n]['type'] = \"1\";\n\t\t\t\ttmpSearchData[n]['user_type'] = tmpSearchData[n]['role'];\n\t\t\t}\n\t\t\tvar topGroup = tmpObject[tmpSearchData[n][relKey]];\n\t\t\tif (topGroup == null) {\n\t\t\t\ttopGroup = new Object();\n\t\t\t\ttopGroup['link'] = tmpSearchData[n]['link'];\n\t\t\t\tif (tmpSearchData[n]['picurl'] != null) topGroup['picurl'] = tmpSearchData[n]['picurl'];\n\t\t\t\tif (tmpSearchData[n]['restricted'] != null) topGroup['restricted'] = tmpSearchData[n]['restricted'];\n\t\t\t\tif (tmpSearchData[n]['is_spoiler'] != null) topGroup['is_spoiler'] = tmpSearchData[n]['is_spoiler'];\n\t\t\t\tif (tmpSearchData[n][jsonData['type']+'_type'] != null) topGroup['type'] = tmpSearchData[n][jsonData['type']+'_type'];\n\t\t\t\tif (tmpSearchData[n]['eps'] != null) topGroup['eps'] = tmpSearchData[n]['eps'];\n\t\t\t\tif (tmpSearchData[n]['rating'] != null) topGroup['rating'] = tmpSearchData[n]['rating'];\n\t\t\t\tif (tmpSearchData[n]['votes'] != null) topGroup['votes'] = tmpSearchData[n]['votes'];\n\t\t\t\tif (tmpSearchData[n]['year'] != null) topGroup['year'] = tmpSearchData[n]['year'];\n\t\t\t\tif (tmpSearchData[n]['chapters'] != null) topGroup['chapters'] = tmpSearchData[n]['chapters'];\n\t\t\t\tif (tmpSearchData[n]['volumes'] != null) topGroup['volumes'] = tmpSearchData[n]['volumes'];\n\t\t\t\tif (tmpSearchData[n]['birthdate'] != null && tmpSearchData[n]['birthdate'] != \"\") topGroup['birthdate'] = tmpSearchData[n]['birthdate'];\n\t\t\t\tif (tmpSearchData[n]['deathdate'] != null && tmpSearchData[n]['deathdate'] != \"\") topGroup['deathdate'] = tmpSearchData[n]['deathdate'];\n\t\t\t\tif (tmpSearchData[n]['founded'] != null) topGroup['founded'] = tmpSearchData[n]['founded'];\n\t\t\t\tif (tmpSearchData[n]['age'] != null) topGroup['age'] = tmpSearchData[n]['age'];\n\t\t\t\tif (tmpSearchData[n]['gender'] != null && tmpSearchData[n]['gender'] != \"-\") topGroup['gender'] = tmpSearchData[n]['gender'];\n\t\t\t\tif (tmpSearchData[n]['bloodtype'] != null && tmpSearchData[n]['bloodtype'] != \"-\") topGroup['bloodtype'] = tmpSearchData[n]['bloodtype'];\n\t\t\t\tif (tmpSearchData[n]['state'] != null) topGroup['state'] = tmpSearchData[n]['state'];\n\t\t\t\tif (tmpSearchData[n]['membercnt'] != null) topGroup['membercnt'] = tmpSearchData[n]['membercnt'];\n\t\t\t\tif (tmpSearchData[n]['commentcnt'] != null) topGroup['commentcnt'] = tmpSearchData[n]['commentcnt'];\n\t\t\t\tif (tmpSearchData[n]['tracks'] != null) topGroup['tracks'] = tmpSearchData[n]['tracks'];\n\t\t\t\tif (tmpSearchData[n]['playlength'] != null) topGroup['playlength'] = tmpSearchData[n]['playlength'];\n\t\t\t\tif (tmpSearchData[n]['role'] != null) topGroup['role'] = tmpSearchData[n]['role'];\n\t\t\t\ttopGroup[relKey] = tmpSearchData[n][relKey];\n\t\t\t\ttmpObject[tmpSearchData[n][relKey]] = topGroup;\n\t\t\t\ttmp.push(topGroup[relKey]);\n\t\t\t}\n\t\t\tvar dataType = tmpSearchData[n]['type'];\n\t\t\t// this is to make sure we don't have to update this script whenever we add a new type (though it would be faster without this)\n\t\t\tif (orderArray.indexOf(dataType) < 0) orderArray.push(dataType);\n\t\t\tvar secondGroup = topGroup[dataType];\n\t\t\tif (secondGroup == null) {\n\t\t\t\tsecondGroup = new Object();\n\t\t\t\tsecondGroup[\"-1\"] = new Array();\n\t\t\t\ttopGroup[dataType] = secondGroup;\n\t\t\t}\n\t\t\tvar langid = tmpSearchData[n]['langid'];\n\t\t\tvar title = secondGroup[langid];\n\t\t\tif (title == null) {\n\t\t\t\ttitle = new Object();\n\t\t\t\ttitle['langid'] = langid;\n\t\t\t\ttitle['names'] = new Array();\n\t\t\t\tsecondGroup[langid] = title;\n\t\t\t}\n\t\t\ttitle['names'].push(tmpSearchData[n]['name']);\n\t\t\tif (secondGroup[\"-1\"].indexOf(langid) < 0)\n\t\t\t\tsecondGroup[\"-1\"].push(langid);\n\t\t}\n\t\t// okay, done, now for the results pick the best title\n\t\tfor (var n = 0; n < tmp.length; n++) {\n\t\t\tvar relId = tmp[n];\n\t\t\tvar entry = tmpObject[relId];\n\t\t\tentry = updateSearchEntry(entry,patterns, orderArray, deflangid);\n\t\t\tif (entry['name'] == null) continue;\n\t\t\tresults.push(entry);\n\t\t}\n\t\tsearchNoChange = updateSearchCache(results, relKey) == 0;\n\t\t// a minor hack is needed for when the last char is a space\n\t\tvar lc = query.charAt(query.length-1);\n\t\tif (lc.match(re)) // this will ensure we keep requesting stuff\n\t\t\tsearchNoChange = false;\n\t} else {\n\t\t// just take care or remove repetitions\n\t\tfor (var n = 0; n < tmpSearchData.length; n++) {\n\t\t\tvar name = tmpSearchData[n]['name'];\n\t\t\tif (tmp.indexOf(name) < 0) {\n\t\t\t\tresults.push(tmpSearchData[n]);\n\t\t\t\ttmp.push(name);\n\t\t\t}\n\t\t}\n\t\tsearchNoChange = updateSearchCache(results, null) == 0;\n\t}\n\tsearchData = results;\n\tlastHitCount = tmpSearchData.length;\n\t// this way printTags can know if it should ignore or not\n\tprintTags(query);\n}", "function displayResults(data){\r\n // remove all past results\r\n $(\".results\").remove();\r\n // lift WikiSearch title to top of page\r\n $(\".titleClass\").css(\"padding-top\",\"0px\");\r\n // show results\r\n \r\n const result = data[\"query\"][\"search\"][0][\"title\"];\r\n // create div for all search results\r\n $(\".searchMenu\").append(\"<div class = 'searchResults results'></div>\");\r\n // main search result title\r\n $(\".searchResults\").append(\"<div class='searchTitle'></div>\");\r\n $(\".searchTitle\").html(\"Search Results for <a target=\\\"_blank\\\" href = \\'https://en.wikipedia.org/wiki/\"+result+\"\\'>\"+result+\"</a>\"); // push titleClass to top of page\r\n \r\n // results\r\n for (var ii =1; ii < data[\"query\"][\"search\"].length -1; ii++){\r\n // create div for each result\r\n $(\".searchResults\").append(\"<div class='key\" + ii + \" result'></div>\");\r\n // append to div\r\n var searchResult = data[\"query\"][\"search\"][ii][\"title\"];\r\n $(\".key\" + ii).append(\"<p class = 'resultTitle'><a target=\\\"_blank\\\" href = \\'https://en.wikipedia.org/wiki/\"+searchResult+\"\\'>\"+searchResult+\"</a></p>\");\r\n $(\".key\"+ii).append(\"<p class = 'resultText'>\" + data[\"query\"][\"search\"][ii][\"snippet\"]+\"...\" + \"</p>\");\r\n }\r\n}", "function searchinTotalContentForSinglepageRendering(pgnum){\n\t var word=$(\"#searchInput\").val();\n\t\t\t var fullresults = [];\n\t $(\"#instmaintable\"+pgnum+\" div.canbesearch\").each(function (i) {\n\t\t\t\t\t\t\t\t //var pagobj = new Object();\n\t\t\t\t\t\t\t\t var str = $(this).text();\t\t\t \n\t results = searchForWord(str, word);\t \n\t for (var m = 0; m < results.length; m++) {\n\t fullresults.push(\"<div pageid='instmaintable\"+pgnum+\"' class='resultlink'>\" + results[m] + \"</div>\");\n\t }\n\t });\n\t for (var k = 0; k < fullresults.length; k++) {\n\t $(\"ul.searchresults\").append(\"<li>\" + fullresults[k] + \"</li>\");\n\t\t\t\t\t\t\t\t //breaking loop for showing 1 result for page\n\t { break }\n\t }\n}", "function displaySearchResults(_query, documentResults, lunrResults){\n resetResultList();\n documentResults.forEach((dobj) => {\n results_list.appendChild(buildSearchResult(dobj));\n });\n\n if (lunrResults[0].score <= 5){\n if (lunrResults.length > 500){\n setWarning(\"Your search yielded a lot of results! and there aren't many great matches. Maybe try with other terms?\");\n }\n else{\n setWarning(\"Unfortunately, it looks like there aren't many great matches for your search. Maybe try with other terms?\");\n }\n }\n else {\n if (lunrResults.length > 500){\n setWarning(\"Your search yielded a lot of results! Maybe try with other terms?\");\n }\n }\n\n let publicResults = documentResults.filter(function(value){\n return !value.querySelector('.privacy').innerHTML.includes(\"PRIVATE\");\n })\n\n if (publicResults.length==0){\n setStatus('No results matches \"' + htmlEncode(_query) + '\". Some private objects matches your search though.');\n }\n else{\n setStatus(\n 'Search for \"' + htmlEncode(_query) + '\" yielded ' + publicResults.length + ' ' +\n (publicResults.length === 1 ? 'result' : 'results') + '.');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns object with x,y coordinates of donut chart label
function labelPosition(ctx, v) { ctx.font="300 14px Open Sans, sans-serif"; var l = new Object(); l.x = [0,0,0]; l.y = []; for(var i=0, len=v.length; i<len; i++) { var radPos = 0; if (i == 0) { radPos = 2-(v[0]/2); } else { radPos = 2-(v[i]/2+v[i-1]/2); } l.x[i] = (graphWidth/2+Math.cos(radPos*Math.PI)*70); l.x[i] -= ctx.measureText(yearCreated).width/2; l.y[i] = (graphWidth/2+Math.sin(radPos*Math.PI)*70); l.y[i] += 7; // Font height offset var radPosTemp = 0; // Label offset l.x[i] += Math.cos(radPos*Math.PI) * 23; l.y[i] += Math.sin(radPos*Math.PI) * 23; } return l; }
[ "determine_label(x, y) {\n if (x == 0) return [\"left\", 5, 5];\n if (x == scopeList[this.id].layout.width) return [\"right\", -5, 5];\n if (y == 0) return [\"center\", 0, 13];\n return [\"center\", 0, -6];\n }", "calcTextPosition() {\n let coords = this.circle.calcOCoords();\n let x = ((coords.tl.x + coords.tr.x) / 2);\n let y = ((coords.tl.y + coords.bl.y) / 2);\n\n if (this.circle.group != null) {\n x = x + this.circle.group.left + (this.circle.group.width / 2);\n y = y + this.circle.group.top + (this.circle.group.height / 2);\n }\n \n return [x, y];\n }", "getLabel() {\n return this.canvas.getLabel().length > 0\n ? this.canvas.getLabel().getValue()\n : String(this.canvas.index + 1);\n }", "function labelXcalc(d,i){\n var tickAngle = d + 90;\n var tickAngleRad = dToR(tickAngle);\n var absXCorr = opt.labelFontSize * (tickLabelText[i].length - minLabelLength) / 2;\n var xCorr = opt.outerTicks ? absXCorr : - absXCorr;\n var x1 = originX + labelStart * Math.cos(tickAngleRad)+xCorr;\n return x1\n }", "function calcLabelPos (pos, SliderID) {\n var slider=d3.select('#'+String(SliderID));\n var increments=slider.node().max-slider.node().min;\n var percentage=(100/(slider.node().max-slider.node().min)*(pos));\n var posX=slider.node().getBoundingClientRect().width;\n var offset=((30/increments)*pos);\n posX=((posX/100)*percentage)-offset;\n return posX;\n }", "function componentDonutLabels () {\n\n /* Default Properties */\n var width = 300;\n var height = 300;\n var transition = { ease: d3.easeBounce, duration: 500 };\n var radius = 150;\n var innerRadius = void 0;\n var classed = \"donutLabels\";\n\n /**\n * Initialise Data and Scales\n *\n * @private\n * @param {Array} data - Chart data.\n */\n function init(data) {\n if (typeof radius === \"undefined\") {\n radius = Math.min(width, height) / 2;\n }\n\n if (typeof innerRadius === \"undefined\") {\n innerRadius = radius / 4;\n }\n }\n\n /**\n * Constructor\n *\n * @constructor\n * @alias donutLabels\n * @param {d3.selection} selection - The chart holder D3 selection.\n */\n function my(selection) {\n selection.each(function (data) {\n init(data);\n\n // Pie Generator\n var pie = d3.pie().value(function (d) {\n return d.value;\n }).sort(null).padAngle(0.015);\n\n // Arc Generator\n var arc = d3.arc().innerRadius(innerRadius).outerRadius(radius).cornerRadius(2);\n\n // Outer Arc Generator\n var outerArc = d3.arc().innerRadius(radius * 0.9).outerRadius(radius * 0.9);\n\n // Mid Angle\n var midAngle = function midAngle(d) {\n return d.startAngle + (d.endAngle - d.startAngle) / 2;\n };\n\n // Update series group\n var seriesGroup = d3.select(this);\n seriesGroup.classed(classed, true);\n\n // Text Labels\n var labelsGroupSelect = seriesGroup.selectAll(\"g.labels\").data(function (d) {\n return [d];\n });\n\n var labelsGroup = labelsGroupSelect.enter().append(\"g\").attr(\"class\", \"labels\").merge(labelsGroupSelect);\n\n var labels = labelsGroup.selectAll(\"text.label\").data(function (d) {\n return pie(d.values);\n });\n\n labels.enter().append(\"text\").attr(\"class\", \"label\").attr(\"dy\", \".35em\").merge(labels).transition().duration(transition.duration).text(function (d) {\n return d.data.key;\n }).attrTween(\"transform\", function (d) {\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function (t) {\n var d2 = interpolate(t);\n var pos = outerArc.centroid(d2);\n pos[0] = radius * (midAngle(d2) < Math.PI ? 1.2 : -1.2);\n return \"translate(\" + pos + \")\";\n };\n }).styleTween(\"text-anchor\", function (d) {\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function (t) {\n var d2 = interpolate(t);\n return midAngle(d2) < Math.PI ? \"start\" : \"end\";\n };\n });\n\n labels.exit().remove();\n\n // Text Label to Slice Connectors\n var connectorsGroupSelect = seriesGroup.selectAll(\"g.connectors\").data(function (d) {\n return [d];\n });\n\n var connectorsGroup = connectorsGroupSelect.enter().append(\"g\").attr(\"class\", \"connectors\").merge(connectorsGroupSelect);\n\n var connectors = connectorsGroup.selectAll(\"polyline.connector\").data(function (d) {\n return pie(d.values);\n });\n\n connectors.enter().append(\"polyline\").attr(\"class\", \"connector\").merge(connectors).transition().duration(transition.duration).attrTween(\"points\", function (d) {\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function (t) {\n var d2 = interpolate(t);\n var pos = outerArc.centroid(d2);\n pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1.2 : -1.2);\n return [arc.centroid(d2), outerArc.centroid(d2), pos];\n };\n });\n\n connectors.exit().remove();\n });\n }\n\n /**\n * Width Getter / Setter\n *\n * @param {number} _v - Width in px.\n * @returns {*}\n */\n my.width = function (_v) {\n if (!arguments.length) return width;\n width = _v;\n return this;\n };\n\n /**\n * Height Getter / Setter\n *\n * @param {number} _v - Height in px.\n * @returns {*}\n */\n my.height = function (_v) {\n if (!arguments.length) return height;\n height = _v;\n return this;\n };\n\n /**\n * Radius Getter / Setter\n *\n * @param {number} _v - Radius in px.\n * @returns {*}\n */\n my.radius = function (_v) {\n if (!arguments.length) return radius;\n radius = _v;\n return this;\n };\n\n /**\n * Inner Radius Getter / Setter\n *\n * @param {number} _v - Inner radius in px.\n * @returns {*}\n */\n my.innerRadius = function (_v) {\n if (!arguments.length) return innerRadius;\n innerRadius = _v;\n return this;\n };\n\n return my;\n }", "function labelXcalc(d, i) {\n var tickAngle = d + 90,\n tickAngleRad = dToR(tickAngle),\n labelW = opt.labelFontSize / (tickLabelText[i].toString().length / 2)\n let x1 = originX + ((labelStart - labelW) * Math.cos(tickAngleRad));\n return x1\n }", "function labelXcalc(d, i) {\n var tickAngle = d + 90,\n tickAngleRad = dToR(tickAngle),\n labelW = opt.labelFontSize / (tickLabelText[i].toString().length / 2)\n x1 = originX + ((labelStart - labelW) * Math.cos(tickAngleRad));\n return x1\n }", "getLabel() {\r\n\r\n\t\tlet offset = [0, 0];\r\n\t\tconst [X_OFFSET, Y_OFFSET] = [MAPCONFIG.labelOffset, MAPCONFIG.labelOffset / 2];\r\n\r\n\t\t// set label offset based on direction\r\n\t\tswitch (LABEL_POSITIONS[this.labelPos]) {\r\n\t\t\tcase \"top\":\r\n\t\t\t\toffset = [0, -Y_OFFSET];\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"bottom\":\r\n\t\t\t\toffset = [0, Y_OFFSET];\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"left\":\r\n\t\t\t\toffset = [-X_OFFSET, 0];\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"right\":\r\n\t\t\t\toffset = [X_OFFSET, 0];\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"auto\":\r\n\t\t\t\toffset = [Y_OFFSET, 0];\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\treturn {\r\n\t\t\tclassName : \"location-label\",\r\n\t\t\tpermanent: true,\r\n\t\t\tdirection: LABEL_POSITIONS[this.labelPos],\r\n\t\t\tinteractive: true,\r\n\t\t\toffset: offset,\r\n\t\t\triseOnHover: true,\r\n\t\t}\r\n\t}", "function getButtonTextPosition(){\n var circleWidth = config.arcMin*0.85 * 2\n var bbox = this.getBBox();\n var textwidth = bbox.width;\n var dif = circleWidth - textwidth;\n var offset = dif/2;\n var position = (config.width/2 - config.arcMin*0.85) + offset;\n return position;\n }", "function pieLabelHelper(width, height, outerMargin, labelMargin, colorPalette, data, valueColName, labelColName) {\n var size = Math.min(width, height);\n var radius = size / 2 - outerMargin;\n var center = { cx: width / 2, cy: height / 2 };\n\n var dataSum = data.sum(function (record, index) {\n var value = (valueColName) ? record[valueColName] : record;\n return Math.abs(value);\n });\n\n var startAngle = 0;\n var infoRecords = [];\n\n for (var i = 0; i < data.length; i++) {\n var record = data[i];\n\n var value = Math.abs((valueColName) ? record[valueColName] : record);\n var label = (labelColName) ? record[labelColName] : record;\n\n var angle = value / dataSum * 360;\n var endAngle = startAngle + angle;\n var midAngle = startAngle + angle / 2;\n\n var cr = (colorPalette) ? vp.color.colorFromPalette(colorPalette, i) : null;\n var radians = (midAngle - 90) * Math.PI / 180;\n\n var xMidArc = center.cx + radius * Math.sin(radians);\n var yMidArc = center.cy + radius * Math.cos(radians);\n\n var xText = center.cx + (radius + labelMargin) * Math.cos(radians);\n var yText = center.cy + (radius + labelMargin) * Math.sin(radians);\n\n var halign = (midAngle > 180) ? 1 : 0;\n\n var valign = .5;\n if (midAngle > 315 || midAngle < 45) {\n valign = 1;\n } else if (midAngle >= 135 && midAngle <= 225) {\n valign = 0;\n }\n\n var info = {\n center: center, radius: radius, startAngle: startAngle, endAngle: endAngle,\n color: cr, midArc: { x: xMidArc, y: yMidArc }, xText: xText, yText: yText,\n hTextAlign: halign, vTextAlign: valign, label: label\n };\n\n infoRecords.push(info);\n\n startAngle = endAngle;\n }\n\n return infoRecords;\n }", "getXoffset() {\n return labelWidth + this.getFullwidth() + barHeight * 2 + 19\n }", "getLabelPosition() {\n return this._labelPosition;\n }", "function positionLabels() {\n // select all the labels and transform them\n d3.selectAll('.label')\n .attr('text-anchor', (d) => {\n const x = projection(d.coordinates)[0];\n return x < width / 2 - 20 ? 'end' :\n x < width / 2 + 20 ? 'middle' :\n 'start';\n })\n .attr('transform', (d) => {\n const loc = projection(d.coordinates);\n const x = loc[0];\n const y = loc[1];\n const offset = x < width / 2 ? -5 : 5;\n return `translate(${x + offset},${y - 2})`;\n })\n // make the city label disappear if the city point is on the back side of the globe\n .style('display', (d) => {\n if (d3.select(`.city-${d.city}`).node() && d3.select(`.city-${d.city}`).attr('d') !== null) {\n return 'inline';\n }\n return 'none';\n });\n}", "get labelPosition() {\n return this.getLabelPosition();\n }", "function updateLabels() {\n labelr = radius + 40 // radius for label anchor\n d3.selectAll(\"#pie text\")\n .data(pie(getData()))\n .transition()\n .duration(0)\n .attr(\"transform\", function(d) {\n var c = arc.centroid(d),\n x = c[0],\n y = c[1],\n // pythagorean theorem for hypotenuse\n h = Math.sqrt(x * x + y * y);\n return \"translate(\" + (x / h * labelr) + ',' + (y / h * labelr) + \")\";\n })\n .attr(\"dy\", \".35em\")\n .attr(\"text-anchor\", function(d) {\n return (d.endAngle + d.startAngle) / 2 > Math.PI ?\n \"end\" : \"start\";\n })\n\n .text(function(d, i) {\n if (getData()[i].value > 0) return getData()[i].label + \" (\" + getData()[i].value + \"%)\";\n else return null;\n });\n }", "function getChartTranslation() {\n var translation = [\n OUTER_RADIUS + GRAPH_PADDING,\n OUTER_RADIUS + GRAPH_PADDING\n ];\n return 'translate(' + translation + ')';\n }", "function startBarLabelPosition(d) {\n return viewButtonWidth + yAxisLabelWidth + xScale(d) + textPadding;\n }", "function labelX() {\n const l = d3.select(this.parentNode).select('line');\n // grabbing the values of the x1, x2, and y1 attributes\n const labelX1 = parseInt(l.attr('x1'));\n const labelX2 = parseInt(l.attr('x2'));\n // calculating and returing the x value for the message's label\n return (labelX1 + labelX2) / 2.0;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A triangulation is collinear if all its triangles have a nonnull area
function collinear(d) { const { triangles , coords } = d; for(let i = 0; i < triangles.length; i += 3){ const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2], cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]); if (cross > 0.0000000001) return false; } return true; }
[ "function collinear$1(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])\n - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n }", "function collinear(p1,p2,p3) {\n\t // from http://mathworld.wolfram.com/Collinear.html\n\t var area = p1.x*(p2.y - p3.y) + p2.x*(p3.y - p1.y) + p3.x*(p1.y - p2.y);\n\t return area == 0;\n\t}", "function collinear(p1, p2, p3) {\n // from http://mathworld.wolfram.com/Collinear.html\n var area = p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y);\n return area === 0;\n }", "function delaunay_collinear(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])\n - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n}", "function collinear(a, b, c) {\n /** area2 is doubled signed area of the triangle abc. */\n var area2 =\n (b.x - a.x) * (c.y - a.y) -\n (c.x - a.x) * (b.y - a.y);\n return Math.abs(area2) < EPS;\n }", "function collinear(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2], cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n }", "function Collinear(a,b,c) {\n\treturn( Area2(a,b,c) == 0 );\n}", "delaunay() {\n if (this.verts.length < 3) {\n throw new Error('Delaunay Triangulation needs at least three vertices')\n }\n\n let is_success = false\n for (let tries = 0; !is_success && tries < 10; tries++) {\n this.tris = []\n sort2d(this.verts, 0, 0, this.verts.length - 1)\n is_success = this.solve(0, 0, this.verts.length - 1)\n }\n\n if (!is_success) {\n throw new Error('Collinear vertices could not be resolved')\n }\n }", "function collinear(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])\n - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n}", "triangulate ( bound, isReal ) {\n\n if(bound.length < 2) {\n Log(\"BREAK ! the hole has less than 2 edges\");\n return;\n // if the hole is a 2 edges polygon, we have a big problem\n } else if(bound.length === 2) {\n Log(\"BREAK ! the hole has only 2 edges\");\n // DDLS.Debug.trace(\" - edge0: \" + bound[0].originVertex.id + \" -> \" + bound[0].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1404, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n // DDLS.Debug.trace(\" - edge1: \" + bound[1].originVertex.id + \" -> \" + bound[1].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1405, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n return;\n // if the hole is a 3 edges polygon:\n } else if(bound.length === 3) {\n\n let f = new Face();\n f.setDatas(bound[0], isReal);\n this._faces.push(f);\n bound[0].leftFace = f;\n bound[1].leftFace = f;\n bound[2].leftFace = f;\n bound[0].nextLeftEdge = bound[1];\n bound[1].nextLeftEdge = bound[2];\n bound[2].nextLeftEdge = bound[0];\n // if more than 3 edges, we process recursively:\n } else {\n let baseEdge = bound[0];\n let vertexA = baseEdge.originVertex;\n let vertexB = baseEdge.destinationVertex;\n let vertexC;\n let vertexCheck;\n let circumcenter = new Point();\n let radiusSquared = 0;\n let distanceSquared = 0;\n let isDelaunay = false;\n let index = 0;\n let i;\n let _g1 = 2;\n let _g = bound.length;\n while(_g1 < _g) {\n let i1 = _g1++;\n vertexC = bound[i1].originVertex;\n if(Geom2D.getRelativePosition2(vertexC.pos,baseEdge) == 1) {\n index = i1;\n isDelaunay = true;\n //DDLS.Geom2D.getCircumcenter(vertexA.pos.x,vertexA.pos.y,vertexB.pos.x,vertexB.pos.y,vertexC.pos.x,vertexC.pos.y,circumcenter);\n Geom2D.getCircumcenter(vertexA.pos, vertexB.pos, vertexC.pos, circumcenter);\n radiusSquared = Squared(vertexA.pos.x - circumcenter.x, vertexA.pos.y - circumcenter.y);\n // for perfect regular n-sides polygons, checking strict delaunay circumcircle condition is not possible, so we substract EPSILON to circumcircle radius:\n radiusSquared -= EPSILON_SQUARED;\n let _g3 = 2;\n let _g2 = bound.length;\n while(_g3 < _g2) {\n let j = _g3++;\n if(j != i1) {\n vertexCheck = bound[j].originVertex;\n distanceSquared = Squared(vertexCheck.pos.x - circumcenter.x, vertexCheck.pos.y - circumcenter.y);\n if(distanceSquared < radiusSquared) {\n isDelaunay = false;\n break;\n }\n }\n }\n if(isDelaunay) break;\n }\n }\n \n if(!isDelaunay) {\n // for perfect regular n-sides polygons, checking delaunay circumcircle condition is not possible\n Log(\"NO DELAUNAY FOUND\");\n /*let s = \"\";\n let _g11 = 0;\n let _g4 = bound.length;\n while(_g11 < _g4) {\n let i2 = _g11++;\n s += bound[i2].originVertex.pos.x + \" , \";\n s += bound[i2].originVertex.pos.y + \" , \";\n s += bound[i2].destinationVertex.pos.x + \" , \";\n s += bound[i2].destinationVertex.pos.y + \" , \";\n }*/\n index = 2;\n }\n\n let edgeA, edgeAopp, edgeB, edgeBopp, boundA, boundB, boundM = [];\n\n if(index < (bound.length - 1)) {\n edgeA = new Edge();\n edgeAopp = new Edge();\n this._edges.push( edgeA, edgeAopp );\n //this._edges.push(edgeAopp);\n edgeA.setDatas(vertexA,edgeAopp,null,null,isReal,false);\n edgeAopp.setDatas(bound[index].originVertex,edgeA,null,null,isReal,false);\n boundA = bound.slice(index);\n boundA.push(edgeA);\n this.triangulate(boundA,isReal);\n }\n if(index > 2) {\n edgeB = new Edge();\n edgeBopp = new Edge();\n this._edges.push(edgeB, edgeBopp);\n //this._edges.push(edgeBopp);\n edgeB.setDatas(bound[1].originVertex,edgeBopp,null,null,isReal,false);\n edgeBopp.setDatas(bound[index].originVertex,edgeB,null,null,isReal,false);\n boundB = bound.slice(1,index);\n boundB.push(edgeBopp);\n this.triangulate(boundB,isReal);\n }\n \n if( index === 2 ) boundM.push( baseEdge, bound[1], edgeAopp ); \n else if( index === (bound.length - 1) ) boundM.push(baseEdge, edgeB, bound[index]); \n else boundM.push(baseEdge, edgeB, edgeAopp );\n \n this.triangulate( boundM, isReal );\n\n }\n\n // test\n //this.deDuplicEdge();\n\n }", "triangulate ( bound, isReal ) {\n\n if(bound.length < 2) {\n Log(\"BREAK ! the hole has less than 2 edges\");\n return;\n // if the hole is a 2 edges polygon, we have a big problem\n } else if(bound.length === 2) {\n Log(\"BREAK ! the hole has only 2 edges\");\n // DDLS.Debug.trace(\" - edge0: \" + bound[0].originVertex.id + \" -> \" + bound[0].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1404, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n // DDLS.Debug.trace(\" - edge1: \" + bound[1].originVertex.id + \" -> \" + bound[1].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1405, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n return;\n // if the hole is a 3 edges polygon:\n } else if(bound.length === 3) {\n\n let f = new Face();\n f.setDatas(bound[0], isReal);\n this._faces.push(f);\n bound[0].leftFace = f;\n bound[1].leftFace = f;\n bound[2].leftFace = f;\n bound[0].nextLeftEdge = bound[1];\n bound[1].nextLeftEdge = bound[2];\n bound[2].nextLeftEdge = bound[0];\n // if more than 3 edges, we process recursively:\n } else {\n let baseEdge = bound[0];\n let vertexA = baseEdge.originVertex;\n let vertexB = baseEdge.destinationVertex;\n let vertexC;\n let vertexCheck;\n let circumcenter = new Point();\n let radiusSquared = 0;\n let distanceSquared = 0;\n let isDelaunay = false;\n let index = 0;\n let _g1 = 2;\n let _g = bound.length;\n while(_g1 < _g) {\n let i1 = _g1++;\n vertexC = bound[i1].originVertex;\n if(Geom2D.getRelativePosition2(vertexC.pos,baseEdge) == 1) {\n index = i1;\n isDelaunay = true;\n //DDLS.Geom2D.getCircumcenter(vertexA.pos.x,vertexA.pos.y,vertexB.pos.x,vertexB.pos.y,vertexC.pos.x,vertexC.pos.y,circumcenter);\n Geom2D.getCircumcenter(vertexA.pos, vertexB.pos, vertexC.pos, circumcenter);\n radiusSquared = Squared(vertexA.pos.x - circumcenter.x, vertexA.pos.y - circumcenter.y);\n // for perfect regular n-sides polygons, checking strict delaunay circumcircle condition is not possible, so we substract EPSILON to circumcircle radius:\n radiusSquared -= EPSILON_SQUARED;\n let _g3 = 2;\n let _g2 = bound.length;\n while(_g3 < _g2) {\n let j = _g3++;\n if(j != i1) {\n vertexCheck = bound[j].originVertex;\n distanceSquared = Squared(vertexCheck.pos.x - circumcenter.x, vertexCheck.pos.y - circumcenter.y);\n if(distanceSquared < radiusSquared) {\n isDelaunay = false;\n break;\n }\n }\n }\n if(isDelaunay) break;\n }\n }\n \n if(!isDelaunay) {\n // for perfect regular n-sides polygons, checking delaunay circumcircle condition is not possible\n Log(\"NO DELAUNAY FOUND\");\n /*let s = \"\";\n let _g11 = 0;\n let _g4 = bound.length;\n while(_g11 < _g4) {\n let i2 = _g11++;\n s += bound[i2].originVertex.pos.x + \" , \";\n s += bound[i2].originVertex.pos.y + \" , \";\n s += bound[i2].destinationVertex.pos.x + \" , \";\n s += bound[i2].destinationVertex.pos.y + \" , \";\n }*/\n index = 2;\n }\n\n let edgeA, edgeAopp, edgeB, edgeBopp, boundA, boundB, boundM = [];\n\n if(index < (bound.length - 1)) {\n edgeA = new Edge();\n edgeAopp = new Edge();\n this._edges.push( edgeA, edgeAopp );\n //this._edges.push(edgeAopp);\n edgeA.setDatas(vertexA,edgeAopp,null,null,isReal,false);\n edgeAopp.setDatas(bound[index].originVertex,edgeA,null,null,isReal,false);\n boundA = bound.slice(index);\n boundA.push(edgeA);\n this.triangulate(boundA,isReal);\n }\n if(index > 2) {\n edgeB = new Edge();\n edgeBopp = new Edge();\n this._edges.push(edgeB, edgeBopp);\n //this._edges.push(edgeBopp);\n edgeB.setDatas(bound[1].originVertex,edgeBopp,null,null,isReal,false);\n edgeBopp.setDatas(bound[index].originVertex,edgeB,null,null,isReal,false);\n boundB = bound.slice(1,index);\n boundB.push(edgeBopp);\n this.triangulate(boundB,isReal);\n }\n \n if( index === 2 ) boundM.push( baseEdge, bound[1], edgeAopp ); \n else if( index === (bound.length - 1) ) boundM.push(baseEdge, edgeB, bound[index]); \n else boundM.push(baseEdge, edgeB, edgeAopp );\n \n this.triangulate( boundM, isReal );\n\n }\n\n // test\n //this.deDuplicEdge();\n\n }", "FindAllTriangles() {\n if (this.fAllTri) return;\n\n this.fAllTri = true;\n\n let xcntr, ycntr, xm, ym, xx, yy,\n sx, sy, nx, ny, mx, my, mdotn, nn, a,\n t1, t2, pa, na, ma, pb, nb, mb, p1=0, p2=0, m, n, p3=0;\n const s = [false, false, false],\n alittlebit = 0.0001;\n\n this.Initialize();\n\n // start with a point that is guaranteed to be inside the hull (the\n // centre of the hull). The starting point is shifted \"a little bit\"\n // otherwise, in case of triangles aligned on a regular grid, we may\n // found none of them.\n xcntr = 0;\n ycntr = 0;\n for (n = 1; n <= this.fNhull; n++) {\n xcntr += this.fXN[this.fHullPoints[n-1]];\n ycntr += this.fYN[this.fHullPoints[n-1]];\n }\n xcntr = xcntr/this.fNhull+alittlebit;\n ycntr = ycntr/this.fNhull+alittlebit;\n // and calculate it's triangle\n this.Interpolate(xcntr, ycntr);\n\n // loop over all Delaunay triangles (including those constantly being\n // produced within the loop) and check to see if their 3 sides also\n // correspond to the sides of other Delaunay triangles, i.e. that they\n // have all their neighbours.\n t1 = 1;\n while (t1 <= this.fNdt) {\n // get the three points that make up this triangle\n pa = this.fPTried[t1-1];\n na = this.fNTried[t1-1];\n ma = this.fMTried[t1-1];\n\n // produce three integers which will represent the three sides\n s[0] = false;\n s[1] = false;\n s[2] = false;\n // loop over all other Delaunay triangles\n for (t2=1; t2<=this.fNdt; t2++) {\n if (t2 !== t1) {\n // get the points that make up this triangle\n pb = this.fPTried[t2-1];\n nb = this.fNTried[t2-1];\n mb = this.fMTried[t2-1];\n // do triangles t1 and t2 share a side?\n if ((pa === pb && na === nb) || (pa === pb && na === mb) || (pa === nb && na === mb)) {\n // they share side 1\n s[0] = true;\n } else if ((pa === pb && ma === nb) || (pa === pb && ma === mb) || (pa === nb && ma === mb)) {\n // they share side 2\n s[1] = true;\n } else if ((na === pb && ma === nb) || (na === pb && ma === mb) || (na === nb && ma === mb)) {\n // they share side 3\n s[2] = true;\n }\n }\n // if t1 shares all its sides with other Delaunay triangles then\n // forget about it\n if (s[0] && s[1] && s[2]) continue;\n }\n // Looks like t1 is missing a neighbour on at least one side.\n // For each side, take a point a little bit beyond it and calculate\n // the Delaunay triangle for that point, this should be the triangle\n // which shares the side.\n for (m=1; m<=3; m++) {\n if (!s[m-1]) {\n // get the two points that make up this side\n if (m === 1) {\n p1 = pa;\n p2 = na;\n p3 = ma;\n } else if (m === 2) {\n p1 = pa;\n p2 = ma;\n p3 = na;\n } else if (m === 3) {\n p1 = na;\n p2 = ma;\n p3 = pa;\n }\n // get the coordinates of the centre of this side\n xm = (this.fXN[p1]+this.fXN[p2])/2.0;\n ym = (this.fYN[p1]+this.fYN[p2])/2.0;\n // we want to add a little to these coordinates to get a point just\n // outside the triangle; (sx,sy) will be the vector that represents\n // the side\n sx = this.fXN[p1]-this.fXN[p2];\n sy = this.fYN[p1]-this.fYN[p2];\n // (nx,ny) will be the normal to the side, but don't know if it's\n // pointing in or out yet\n nx = sy;\n ny = -sx;\n nn = Math.sqrt(nx*nx+ny*ny);\n nx = nx/nn;\n ny = ny/nn;\n mx = this.fXN[p3]-xm;\n my = this.fYN[p3]-ym;\n mdotn = mx*nx+my*ny;\n if (mdotn > 0) {\n // (nx,ny) is pointing in, we want it pointing out\n nx = -nx;\n ny = -ny;\n }\n // increase/decrease xm and ym a little to produce a point\n // just outside the triangle (ensuring that the amount added will\n // be large enough such that it won't be lost in rounding errors)\n a = Math.abs(Math.max(alittlebit*xm, alittlebit*ym));\n xx = xm+nx*a;\n yy = ym+ny*a;\n // try and find a new Delaunay triangle for this point\n this.Interpolate(xx, yy);\n\n // this side of t1 should now, hopefully, if it's not part of the\n // hull, be shared with a new Delaunay triangle just calculated by Interpolate\n }\n }\n t1++;\n }\n }", "isControlPolygonLinear (_v, _degree) {\n // Given array of control points, _v, find the distance from each interior control point to line connecting v[0] and v[degree]\n\n // implicit equation for line connecting first and last control points\n let a = _v[0].y - _v[_degree].y\n let b = _v[_degree].x - _v[0].x\n let c = _v[0].x * _v[_degree].y - _v[_degree].x * _v[0].y\n\n let abSquared = a * a + b * b\n let distance = [] // Distances from control points to line\n\n for (let i = 1; i < _degree; ++i) {\n // Compute distance from each of the points to that line\n distance[i] = a * _v[i].x + b * _v[i].y + c\n if (distance[i] > 0.0) {\n distance[i] = (distance[i] * distance[i]) / abSquared\n }\n if (distance[i] < 0.0) {\n distance[i] = -((distance[i] * distance[i]) / abSquared)\n }\n }\n\n // Find the largest distance\n let maxDistanceAbove = 0.0\n let maxDistanceBelow = 0.0\n for (let i = 1; i < _degree; ++i) {\n if (distance[i] < 0.0) {\n maxDistanceBelow = Math.min(maxDistanceBelow, distance[i])\n }\n if (distance[i] > 0.0) {\n maxDistanceAbove = Math.max(maxDistanceAbove, distance[i])\n }\n }\n\n // Implicit equation for zero line\n let a1 = 0.0\n let b1 = 1.0\n let c1 = 0.0\n\n // Implicit equation for \"above\" line\n let a2 = a\n let b2 = b\n let c2 = c + maxDistanceAbove\n\n let det = a1 * b2 - a2 * b1\n let dInv = 1.0 / det\n\n let intercept1 = (b1 * c2 - b2 * c1) * dInv\n\n // Implicit equation for \"below\" line\n a2 = a\n b2 = b\n c2 = c + maxDistanceBelow\n\n let intercept2 = (b1 * c2 - b2 * c1) * dInv\n\n // Compute intercepts of bounding box\n let leftIntercept = Math.min(intercept1, intercept2)\n let rightIntercept = Math.max(intercept1, intercept2)\n\n let error = 0.5 * (rightIntercept - leftIntercept)\n\n return error < this.EPSILON\n }", "static cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev, b = p.next.next;\n if (!GraphicsGeometry.equals(a, b) && GraphicsGeometry.intersects(a, p, p.next, b) && GraphicsGeometry.locallyInside(a, b) && GraphicsGeometry.locallyInside(b, a)) {\n triangles.push(a.i / dim);\n triangles.push(p.i / dim);\n triangles.push(b.i / dim);\n // remove two nodes involved\n GraphicsGeometry.removeNode(p);\n GraphicsGeometry.removeNode(p.next);\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n return p;\n }", "function cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i / dim | 0);\n triangles.push(p.i / dim | 0);\n triangles.push(b.i / dim | 0);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n }", "function cureLocalIntersections(start, triangles, dim) {\n\t var p = start;\n\t do {\n\t var a = p.prev,\n\t b = p.next.next;\n\t\n\t if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\t\n\t triangles.push(a.i / dim);\n\t triangles.push(p.i / dim);\n\t triangles.push(b.i / dim);\n\t\n\t // remove two nodes involved\n\t removeNode(p);\n\t removeNode(p.next);\n\t\n\t p = start = b;\n\t }\n\t p = p.next;\n\t } while (p !== start);\n\t\n\t return filterPoints(p);\n\t}", "function cureLocalIntersections(start, triangles, dim) {\n\t var p = start;\n\t do {\n\t var a = p.prev,\n\t b = p.next.next;\n\n\t if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n\t triangles.push(a.i / dim);\n\t triangles.push(p.i / dim);\n\t triangles.push(b.i / dim);\n\n\t // remove two nodes involved\n\t removeNode(p);\n\t removeNode(p.next);\n\n\t p = start = b;\n\t }\n\t p = p.next;\n\t } while (p !== start);\n\n\t return filterPoints(p);\n\t}", "function cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i / dim);\n triangles.push(p.i / dim);\n triangles.push(b.i / dim);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n }", "function cureLocalIntersections(start, triangles, dim) {\n let p = start;\n do {\n const a = p.prev, b = p.next.next;\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n triangles.push(a.i / dim | 0);\n triangles.push(p.i / dim | 0);\n triangles.push(b.i / dim | 0);\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n p = start = b;\n }\n p = p.next;\n }while (p !== start);\n return filterPoints(p);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
6. Creating pairs example input: [a,b,c,d] 4 example output: 'a, b', 'b, c', 'c, d' input of size n n n or n^2 O(n^2) > polynomial complexity
function createPairs(arr) { for (let i = 0; i < arr.length; i++) { // O(n) for (let j = i + 1; j < arr.length; j++) { // O(n^2) console.log(arr[i] + ", " + arr[j]); } } }
[ "function createPairs(arr) {\n for (let i = 0; i < arr.length; i++) { // O(n)\n for(let j = i + 1; j < arr.length; j++) { // O(n)\n console.log(arr[i] + ', ' + arr[j] ); // O(1)\n }\n }\n}", "function createPairs(arr) {\n for (let i = 0; i < arr.length; i++) { // --> polynomial O(n^2) quadratic\n for (let j = i + 1; j < arr.length; j++) { // --> polynomial 0(n^2) quadratic\n console.log(arr[i] + ', ' + arr[j]); //--> constant\n }\n }\n}", "function createPairs(arr) {\n for (let i = 0; i < arr.length; i++) {\n /* O(n) --> directly proportional relation*/\n for (let j = i + 1; j < arr.length; j++) {\n /* O(n^2 --> for each time the outer loop \n runs n times, the inner loop also needs to run n times) */\n console.log(\n arr[i] + \", \" + arr[j]\n ); /* O(1) --> all the operations inside of the \n console log take a a constant time to run */\n }\n }\n}", "function splitPairs(input) {\n\n //for even lengths:\n //split into pairs of characters\n if (input.length % 2 === 0) {\n input = input.split('')\n }\n\n let newStrEven = [];\n if (input.length % 2 === 0) {\n for (let i = 0; i < input.length; i++) {\n newStrEven.push(input[i] + input[i + 1]) //ok\n input = input.slice(1) //[a, y]\n }\n return newStrEven\n }\n// newStrEven = newStrEven.toString()\nlet newStrOdd = [];\n if (input.length % 2 !== 0) {\n for (let j = 0; j < input.length; j++) {\n if (input.length >= 2) {\n if (input[j] === input[input.length - 1] && input[j] !== input[0]) {\n newStrOdd.push(input[j] + \"_\")\n } else {\n newStrOdd.push(input[j] + input[j + 1])\n input = input.slice(1)\n // console.log(input)\n }\n }\n }\n return newStrOdd\n }\n}", "function allPairs(array){ // O(n^2)\n const length = array.length;\n for (let i = 0; i < length; i++) {\n for (let j = 0; j < length; j++) \n console.log(array[i] + array[j])\n }\n}", "function pair(str) {\r\n\tvar pair1 = [\"A\", \"T\"];\r\n\tvar pair2 = [\"C\", \"G\"];\r\n\tvar toPair = str.split(\"\");\r\n\tvar result = [];\r\n\tfor(var i = 0; i < toPair.length; i++) {\r\n\t\tvar arr = [];\r\n\t\tarr.push(toPair[i]);\r\n\t\tif(pair1[0] === toPair[i]) {\r\n\t\t\tarr.push(pair1[1]);\r\n\t\t}\r\n\t\telse if(pair1[1] === toPair[i]) {\r\n\t\t\tarr.push(pair1[0]);\r\n\t\t}\r\n\r\n\t\telse if(pair2[0] === toPair[i]) {\r\n\t\t\tarr.push(pair2[1]);\r\n\t\t}\r\n\t\telse if(pair2[1] === toPair[i]) {\r\n\t\t\tarr.push(pair2[0]);\r\n\t\t}\r\n\t\tresult.push(arr);\r\n\r\n\t}\t\r\n\tconsole.log(result);\r\n return result;\r\n}", "function pairElement(str) {\n\n/*** a.traditional method ***/\n var rlt=[];\n let i;\n\n for(i=0; i<str.length; i++){\n switch(str.charAt(i)){\n case 'A':\n rlt.push(['A','T']);\n break;\n case 'T':\n rlt.push(['T','A']);\n break;\n case 'C':\n rlt.push(['C','G']);\n break;\n case 'G':\n rlt.push(['G','C']);\n break;\n default: break;\n }\n }\n\n return rlt;\n \n /*** b.map datastructure method ***/\n //define a map object with all pair possibilities \n var map = {T:'A', A:'T', G:'C', C:'G'};\n strArr = str.split('');\n\t \n //replace each Array item with a 2d Array using map\n for (var i=0;i<strArr.length;i++){\n strArr[i]=[strArr[i], map[strArr[i]]];\n }\n return strArr; \n\n /*** c. lookup table + map ***/\n var map = {T:'A', A:'T', G:'C', C:'G'};\n return str.split(\"\").map(function(arr){\n return arr = [arr[0],(map[arr[0]])];\n })\n\t \n}", "function getAllPair(input) {\n\t\t\tlet allPairs = []; \n\t\t\tfor(let i = 0; i < input.length - 1; i++) {\n\t\t\t\tfor(j = i + 1; j < input.length; j++) {\n\t\t\t\t\tallPairs.push(...getAllInput([input[i], input[j]]));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn allPairs;\n\t\t}", "static makeCouples(arr){\n return arr.reduce((ful,e,i) =>\n ful.concat(arr.slice(i+1)\n\t.map(e2=>e+','+e2)),[]);\n }", "function pairUp(str) {\n var result = []\n var students = \"\"\n for(i = 0; i < str.length; i+=2) {\n if(str[i+1] !== undefined) {\n students = str[i] + ' dan ' + str[i+1]\n } else {\n students = str[i] + ' dan Instruktur'\n }\n result.push(students)\n }\n return result\n}", "function printAllPairs(n) {\n // O(n)\n for (let i = 0; i < n; i++) {\n // O(n)\n for (let j = 0; j < n; j++) {\n console.log(i, j)\n }\n }\n}", "function getAllPairs(skill_array) {\n var pair_array = [];\n for (var i=0;i<skill_array.length;i++){\n for (var j=0;j<skill_array.length;j++){\n if(i > j){\n if(j%2){\n pair_array.push({\"label\":skill_array[i] + \" or \" +skill_array[j], \"param1\":skill_array[i], \"param2\":skill_array[j]});\n }\n else {\n pair_array.push({\"label\":skill_array[j] + \" or \" +skill_array[i], \"param1\":skill_array[j], \"param2\":skill_array[i]});\n }\n }\n }\n }\n return pair_array;\n}", "function dogPairs(dogs) {\n const pairs = [];\n for (let i = 0; i < dogs.length; i++) {\n const dog1 = dogs[i];\n for (let j = 0; j < dogs.length; j++) {\n const dog2 = dogs[j];\n console.log(dog1, dog2);\n if (j >= i + 1) {\n const pair = [dog1, dog2];\n pairs.push(pair);\n }\n }\n }\n return pairs;\n}", "static makeTriplets(arr){\n return arr.reduce((ful,e,i)=>\n ful.concat(arr.slice(i+1)\n .map((e2,i2)=>arr.slice(i+i2+2)\n .map(e3=>e+\",\"+e2+\",\"+e3))),[])\n .reduce((a,b)=>a.concat(b),[])\n }", "function unorderedPairs(s) {\n let a = [];\n for (let i = 0;i < s.length; i=(i+1)|0) {\n for (let j = (i+1)|0;j < s.length; j=(j+1)|0) {\n a.push([s[i],s[j]])\n }\n };\n return a;\n}", "function generateWordPairs(words){\n let wordPairs = {};\n for (let j = 0; j<words.length-1; j++){\n wordPairs[words[j]]=[];\n }\n for (let i = 0; i<words.length-1; i++){\n wordPairs[words[i]].push(words[i+1]);\n if(words[i+2]!== undefined){\n wordPairs[words[i]].push(words[i+2]);\n }\n }\nreturn wordPairs;\n}", "function arrayPairs(arr){\n\n}", "function pairToString(arr)\n{\n\tvar string = \"\";\n\n\tfor(var i = 0; i <= arr.length - 1; i++)\n\t{\n\t\tvar pair = arr[i];\n\t\tvar char = pair[0];\n\t\tvar value = pair[1];\n\t\tfor(var j = 0; j <= value - 1; j++)\n\t\t{\n\t\t\tstring += char;\n\t\t}\n\t}\n\treturn string;\n}", "function stringPairs(str) {\n // Array with the solution\n var returnArray = []\n\n // Test if the string has odd or even length\n if (str.length%2 == 0) {\n // If it has even length, we simply push pairs of\n // characters to the array by looping through the string,\n // two characters at a time\n for (var i=0; i<str.length; i+=2) {\n returnArray.push(str[i]+str[i+1])\n }\n } else {\n // If it has odd length, we loop through the string two\n // characters at a time, until the second last character.\n // We push the pairs of characters to the array and then\n // push the last character of the string separately with \n // an underscore as the second character of the pair\n for (var i=0; i<(str.length-1); i+=2) {\n returnArray.push(str[i]+str[i+1])\n }\n returnArray.push(str[str.length-1]+'_')\n }\n\n // Finally, return the resulting array\n return returnArray\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Special handling for hue switch commands
function handleHueSwitch(msg, lightNames) { switch (msg.payload.button) { case 1000: case 1001: case 1002: msg.payload = { on: true, red: 255, green: 255, blue: 255, bri: 100 }; node.status({ fill: 'green', shape: 'dot', text: 'Hue: On' }); break; case 2000: case 2001: case 2002: msg.payload = { bri_add: 10, duration: 1000 }; node.status({ fill: 'blue', shape: 'dot', text: 'Hue: Brighten' }); break; case 3000: case 3001: case 3002: msg.payload = { bri_add: -10, duration: 1000 }; node.status({ fill: 'blue', shape: 'dot', text: 'Hue: Dim' }); break; case 4000: case 4001: case 4002: msg.payload = { on: false }; node.status({ fill: 'blue', shape: 'dot', text: 'Hue: Off' }); break; case 1003: case 2003: case 3003: case 4003: // ignore switch release break; default: node.status({ fill: 'grey', shape: 'dot', text: 'Unrecognized Hue Switch command' }); node.error('Unrecognized Hue Switch command', msg); return; } delete msg.info; node._lights.api(msg, lightNames, function(err, lights) { node.log(err); node.log(lights); }); }
[ "set enableHue(value) {}", "get enableHue() {}", "function swatchHueClickHandler(e) {\n var swatchList = document.getElementsByClassName('swatch');\n [].forEach.call(swatchList, function(el) {\n el.classList.remove('active');\n });\n e.target.classList.add('active');\n \n hsl = [\n parseInt(e.target.getAttribute('data-h')),\n 100,\n 50\n ];\n [].slice.call(sliders).forEach(function (slider, index) {\n slider.noUiSlider.setHandle(0, hsl[index], true);\n });\n saveColor.style.display = 'none';\n}", "_initHueSelector() {\n const bounds = this._$hue.getBoundingClientRect();\n this._hueCtx.canvas.width = bounds.width;\n this._hueCtx.canvas.height = bounds.height;\n const gradientH = this._hueCtx.createLinearGradient(0, 0, 0, bounds.height);\n gradientH.addColorStop(0, 'rgb(255, 0, 0)'); // red\n gradientH.addColorStop(1 / 6, 'rgb(255, 255, 0)'); // yellow\n gradientH.addColorStop(2 / 6, 'rgb(0, 255, 0)'); // green\n gradientH.addColorStop(3 / 6, 'rgb(0, 255, 255)');\n gradientH.addColorStop(4 / 6, 'rgb(0, 0, 255)'); // blue\n gradientH.addColorStop(5 / 6, 'rgb(255, 0, 255)');\n gradientH.addColorStop(1, 'rgb(255, 0, 0)'); // red\n this._hueCtx.fillStyle = gradientH;\n this._hueCtx.fillRect(0, 0, bounds.width * 3, bounds.height);\n let isHueDown = false;\n this._$hue.addEventListener('pointerdown', (e) => {\n isHueDown = true;\n this._isHueInInteraction = true;\n this.requestUpdate();\n this._$hue.setPointerCapture(e.pointerId);\n this._setHueFromEvent(e, false);\n this._updateInput('pointerdown');\n });\n this._$hue.addEventListener('pointermove', (e) => {\n e.preventDefault();\n if (!isHueDown)\n return;\n this._setHueFromEvent(e);\n this._updateInput('pointermove', false);\n });\n this._$hue.addEventListener('pointerup', (e) => {\n isHueDown = false;\n this._isHueInInteraction = false;\n this.requestUpdate();\n this._$hue.releasePointerCapture(e.pointerId);\n this._setHueFromEvent(e, true);\n this._updateInput('pointerup', true);\n });\n // prevent viewport movements\n // __preventViewportMovement(this._$hue);\n }", "onSwitch() {}", "colourSwitch(colour){\n if (colour === \"red\"){\n return \"black\"\n }\n if (colour === \"black\"){\n return \"red\"\n }\n }", "set hueVariation(value) {}", "function updateHSL(){ \n let redVal=document.getElementById(\"redVal\").value;\n let greenVal=document.getElementById(\"greenVal\").value;\n let blueVal=document.getElementById(\"blueVal\").value;\n webSocketRGB(redVal,greenVal,blueVal);\n let [hueVal, satVal, lightVal] = rgbToHsl(redVal, greenVal, blueVal);\n sysl(\"hueVal\", hueVal);\n sysl(\"satVal\", satVal);\n sysl(\"lightVal\", lightVal);\n sysl(\"hueSlider\", hueVal);\n sysl(\"satSlider\", satVal);\n sysl(\"lightSlider\", lightVal);\n HueWheel.setHue(hueVal);\n HueWheel.setSaturation(satVal);\n HueWheel.setLightness(lightVal);\n setHueButton();\n HueWheel.drawColor();\n cssSetSaturationTrack(hueVal, lightVal); \n cssSetLightnessTrack(hueVal, satVal);\n}", "get hue() {\n\t\treturn this.data.hue;\n\t}", "get hue() { return this.hsl[0]; }", "clickHue() {\n this.getHueInput().click();\n }", "function swatchHSLClickHandler(e) {\n var swatchList = document.getElementsByClassName('swatch');\n [].forEach.call(swatchList, function(el) {\n el.classList.remove('active');\n });\n e.target.classList.add('active');\n \n hsl = [\n parseInt(e.target.getAttribute('data-h')),\n parseInt(e.target.getAttribute('data-s')),\n parseInt(e.target.getAttribute('data-l'))\n ];\n var update = false;\n [].slice.call(sliders).forEach(function (slider, index) {\n if ( 2 == index ) {\n update = true;\n }\n slider.noUiSlider.setHandle(0, hsl[index], update);\n });\n saveColor.style.display = 'none';\n}", "function _initHue() {\n hue = new Hue(Keys.hueBridge.key);\n hue.on('config_changed', (config) => {\n _fbSet('state/hue', config);\n });\n hue.on('lights_changed', (lights) => {\n _fbSet('state/hue/lights', lights);\n });\n hue.on('groups_changed', (groups) => {\n _fbSet('state/hue/groups', groups);\n });\n hue.on('sensor_unreachable', (sensor) => {\n const msg = {\n message: 'Hue sensor unreachable',\n level: 5,\n date: Date.now(),\n extra: sensor,\n };\n _fbPush('logs/messages', msg);\n });\n hue.on('sensor_low_battery', (sensor) => {\n const msg = {\n message: 'Hue sensor low battery',\n level: 5,\n date: Date.now(),\n extra: sensor,\n };\n _fbPush('logs/messages', msg);\n });\n }", "function isHueAdjuster(node) {\n\t// [ h() | hue() ]\n\treturn Object(node).type === 'func' && hueMatch.test(node.value);\n}", "function Hue() {\n var hue = {};\n \n // Public variables. \n hue.changedLights = [];\n hue.lights = {};\n\n // Private variables.\n var handleRegisterUser;\n var ipAddress = \"\";\n var maxRetries = 5;\n var registerInterval = 2000;\n var registerTimeout = 20000;\n var registerAttempts = 0;\n var retryCount = 0;\n var retryTimeout = 1000;\n var timeout = 3000;\n var url = \"\";\n var userName = \"\";\n var authenticated = false;\n \n // Use self in contained functions so the caller does not have to bind \"this\"\n // on each function call.\n var self = this;\n \n // Public functions. \n // Available to be used for e.g. inputHandlers.\n \n /** Contact the bridge and register the user, if needed. Add an input \n * handler to the trigger input to submit commands to the bridge.\n */\n hue.connect = function() {\n ipAddress = self.getParameter('bridgeIP');\n userName = self.getParameter('userName');\n\t\n if (userName.length < 11) {\n throw \"Username too short. Hue only accepts usernames that contain at least 11 characters.\";\n }\n\n if (ipAddress === null || ipAddress.trim() === \"\") {\n throw \"No IP Address is given for the Hue Bridge.\";\n }\n\n url = \"http://\" + ipAddress + \"/api\";\n \n contactBridge();\n };\n \n /** Get light settings from input and issue a command to the bridge. */\t\n hue.issueCommand = function() {\n \tvar commands = self.get('commands');\n\t//console.log(\"Issuing command.\");\n\n\t// (Re)connect with the bridge\n \tif (ipAddress !== self.getParameter('bridgeIP') || userName !== self.getParameter('userName')) {\n \t console.log(\"New bridge parameters detected.\");\n \t hue.connect();\n \t}\n\n \t// No connection to the bridge, ignore request.\n \tif (!authenticated) {\n \t console.log(\"Not authenticated, ignoring command.\");\n \t return;\n \t}\n \t\n \t// FIXME: Type check input\n\t//console.log(JSON.stringify(commands));\n\n\t// FIXME: If only one record, also accept input!!!\n\n \t// Iterate over commands (assuming input is an array of commands)\n\tfor (var i = 0; i < commands.length; i++) {\n \t var command = {};\n \t var lightID = commands[i].id;\n \t \n \t // Check whether input is valid\n \t if (typeof lightID === 'undefined') {\n \t\tself.error(\"Invalid command (\" + i + \"): please specify light id.\");\n \t } else {\n\n\t \t// Keep track of changed lights to turn off during wrap up.\n\t \tif (hue.changedLights.indexOf(lightID) == -1) {\n\t hue.changedLights.push(lightID);\n\t \t}\n\t \n\t \t// Pack properties into object\n\t \tif (typeof commands[i].on !== 'undefined') {\n\t \t command.on = commands[i].on;\n\t \t}\n\t \tif (typeof commands[i].bri !== 'undefined') {\n\t \t command.bri = limit(commands[i].bri, 0, 255);\n\t \t}\n\t \tif (typeof commands[i].hue !== 'undefined') {\n\t \t command.hue = limit(commands[i].hue, 0, 65280);\n\t \t}\n\t \tif (typeof commands[i].sat !== 'undefined') {\n\t \t command.sat = limit(commands[i].sat, 0, 255);\n\t \t}\n\t \tif (typeof commands[i].transitiontime !== 'undefined') {\n\t \t command.transitiontime = commands[i].transitiontime;\n\t \t}\n \t }\n\n \t if (Object.keys(command).length < 1) {\n \t\t//console.log(\"ERROR\");\n \t\tself.error(\"Invalid command (\" + i + \"): please specify at least one property.\");\n \t }\n \t else {\n \t\t//console.log(\"Command: \" + JSON.stringify(command));\n \t\tvar options = {\n\t \t body : JSON.stringify(command),\n\t \t timeout : 10000,\n\t \t url : url + \"/\" + userName + \"/lights/\" + lightID + \"/state/\"\n\t \t};\n\t \t//console.log(\"PUT request:\" + JSON.stringify(options));\n\t \thttp.put(options, function(response) {\n\t \t //console.log(JSON.stringify(response));\n\t if (isNonEmptyArray(response) && response[0].error) {\n\t \tself.error(\"Server responds with error: \" + \n\t \t\t response[0].error.description);\n\t }\n\t \t});\n \t }\n \t}\n };\n\n // Private functions.\n \n /** Handle an error. This will report it on the console and then retry a \n * fixed number of times before giving up. A retry is a re-invocation of \n * registerUser().\n */\n function bridgeRequestErrorHandler(err) {\n\t\n\t// FIXME: We should do a UPnP discovery here and find a bridge.\n\t// Could not connect to the bridge\n\tconsole.log('Error connecting to Hue basestation.');\n\tconsole.error(err);\n\tif (retryCount < maxRetries) {\n\t console.log('Will retry');\n\t retryCount++;\n\t setTimeout(function() {\n\t contactBridge;\n\t }, retryTimeout);\n\t} else {\n\t self.error('Could not reach the Hue basestation at ' + url +\n\t ' after ' + retryCount + ' attempts.');\n\t}\n }\n \n /** Contact the bridge to ensure it is operating. Register the user, if\n * needed.\n */\n function contactBridge() {\n\tauthenticated = false;\n\tconsole.log(\"Attempting to connecting to: \" + url + \"/\" + userName + \"/lights/\");\n var bridgeRequest = http.get(url + \"/\" + userName + \"/lights/\", function (response) {\n if (response !== null) {\n \tif (response.statusCode != 200) {\n \t // Response is other than OK.\n \t bridgeRequestErrorHandler(response.statusMessage);\n \t } else {\n \t console.log(\"Got a response from the bridge...\");\n \t \n \t\t var lights = JSON.parse(response.body);\n \t\t console.log(\"Reponse: \" + response.body);\n\n \t\t if (isNonEmptyArray(lights) && lights[0].error) {\n \t\t var description = lights[0].error.description;\n \t\t \n \t\t if (description.match(\"unauthorized user\")) {\n \t\t // Add this user.\n \t\t alert(userName + \" is not a registered user.\\n\" +\n \t\t \t \"Push the link button on the Hue bridge to register.\");\n \t\t //self.error(userName + \" is not a registered user.\\n\" +\n \t\t //\" Push the link button on the Hue bridge to register.\");\n \t\t handleRegisterUser = setTimeout(registerUser, registerInterval);\n \t\t } else {\n \t\t console.error('Error occurred when trying to get Hue light status.');\n \t\t self.error(description);\n \t\t }\n \t\t } else if (lights) {\n \t\t console.log(\"Authenticated!\");\n \t\t authenticated = true;\n \t\t hue.lights = lights;\n \t\t }\n \t\t}\n \t } else {\n \t\tself.error(\"Unable to connect to bridge.\");\n \t }\n \t}).on('error', bridgeRequestErrorHandler);\n bridgeRequest.on('error', bridgeRequestErrorHandler);\n }\n \n /** Utility function to check that an object is a nonempty array.\n * @param obj The object.\n */\n function isNonEmptyArray(obj) {\n\treturn (obj instanceof Array && obj.length > 0);\n }\n\n /** Utility function to limit the range of a number\n * and to force it to be an integer. If the value argument\n * is a string, then it will be converted to a Number.\n * @param value The value to limit.\n * @param low The low value.\n * @param high The high value.\n */\n function limit(value, low, high) {\n\tvar parsed = parseInt(value);\n\tif (typeof parsed === 'undefined') {\n\t parsed = parseFloat(value);\n\t if (typeof parsed === 'undefined') {\n\t self.error(\"Expected a number between \" + low + \" and \" + high + \", but got \" + value);\n\t return 0;\n\t } else {\n\t parsed = Math.floor(parsed);\n\t }\n\t}\n\tif (parsed < low) {\n\t return low;\n\t} else if (parsed > high) {\n\t return high;\n\t} else {\n\t return parsed;\n\t}\n }\n \n /** Register a new user.\n * This function repeats at registerInterval until registration is\n * successful, or until registerTimeout.\n * It does so because it needs to wait until the user clicks\n * the button on the Hue bridge.\n */\n function registerUser() {\n\n\tvar registerData = {\n\t devicetype : userName,\n\t username : userName\n\t};\n\tvar options = {\n\t body : JSON.stringify(registerData),\n\t timeout: 10000,\n\t url : url\n\t};\n\t\n\thttp.post(options, function(response) {\n\t var rsp = JSON.parse(response.body);\n\t //console.log(\"Response \" + JSON.stringify(response));\n\t if (isNonEmptyArray(rsp) && rsp[0].error) {\n\t \n\t var description = rsp[0].error.description;\n\n\t if (description.match(\"link button not pressed\")) {\n\t //repeat registration attempt unless registerTimeout has been reached.\n\t console.log(\"Please push the link button on the Hue bridge.\");\n\t registerAttempts++;\n\t if ((registerAttempts * registerInterval) > registerTimeout) {\n\t throw \"Failed to create user after \" + registerTimeout/1000 +\n\t \"s.\";\n\t }\n\t handleRegisterUser = setTimeout(registerUser, registerInterval);\n\t return;\n\t } else {\n\t throw description;\n\t }\n\t } else if ((isNonEmptyArray(rsp) && rsp[0].success)) {\n\t if (handleRegisterUser !== null) {\n\t clearTimeout(handleRegisterUser);\n\t }\n\t\t// contact the bridge and find the available lights\n\t\tcontactBridge();\n\t } else {\n\t //console.log(\"Response \" + JSON.stringify(response));\n\t console.log(JSON.stringify(JSON.parse(response.body)[0].success));\n\t throw \"Unknown error registering new user\";\n\t }\n\t});\n }\n \n return hue;\n}", "function isHueAdjuster(node) {\n // [ h() | hue() ]\n return Object(node).type === \"func\" && hueMatch.test(node.name);\n}", "get hueVariation() {}", "function apply_hue_on_three(){\n\t//console.log(`home_app> apply_hue_on_three()`);\n\tfor (const [light_id,light] of Object.entries(hue_light_list)) {\n\t\tif(light.name in hue_mesh_name){\n\t\t\tonHueLightState({detail:light});\n\t\t}\n\t\telse{\n\t\t\tconsole.warn(`home_app> no Object has hue property = '${light.name}'`);\n\t\t}\n\t}\n}", "_setCapabilityLightHue(value, opts){\n\n return new Promise(function(resolve, reject){\n\n advancedSettings = this.getSettings();\n\n // check that the advancedSettings of this controller are for 'RGB'\n if (advancedSettings.hasOwnProperty('controls') == -1){ return reject(new Error('malformed advancedSettings object in _setCapabilityLightHue')) };\n if (advancedSettings.controls !== 'RGB'){ return resolve() };\n\n // ensure that hsv is a valid array\n if (Array.isArray(hsv) === false || hsv.length !== 3){\n return reject(new Error('hsv is invalid'))\n }; // if\n\n // calculate the correct array for the new HSV values\n value = Math.round(parseFloat(value) * 360); // convert the decimal number 0-1 to a whole integer 0-360\n value = value.toString(); // convert the number to a string\n hsv[0] = value; // update the first value of the array to this new H value\n let hsvString = hsv.join(','); // convert the array to a string which is what Espurna expects\n\n if (writeLogs){ this.log('_setCapabilityLightHue called in /lib/device.js, setting hue to '+hsvString+' for topic '+advancedSettings.MQTTtopic) };\n\n client.publish(advancedSettings.MQTTtopic+'/hsv/set', hsvString, function(err){\n if (err){\n return reject(err)\n }; // if\n return resolve(null)\n }); // client.publish\n\n }.bind(this)); // return new Promise\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current score
function getScore() { return parseInt(currentScore); }
[ "function getScore() {\n return currentScore;\n}", "function getScore() {\n return score;\n }", "function getScore() {\n\treturn 0;\n}", "function getScore() {\n\t\treturn 0.0; //dummy\n\t}", "getScore() {\n\t\treturn this.score;\n\t}", "function getScore(){\n return score\n}", "function getScore() {\n return \"Your score: \" + _playerScore.toString();\n }", "function getCurrentScore() {\n let activePlayerKey = getActivePlayerKey();\n let currentScoreValue = playersData[activePlayerKey].score\n return currentScoreValue\n}", "getScore() {\n return this._score;\n }", "function getScore() {\n return state.score;\n}", "function currentScore () {\n\tscoreNumber++;\n}", "function get_current_clue_score(){\n\tif(is_current_clue_saved().clueScore!=undefined){\n\t\treturn is_current_clue_saved().clueScore;\n\t}else{\n\t\treturn 0;\n\t}\n}", "function firstScore () {\n return scores[0];\n }", "getScore() {\n if (!this.score) {\n // \tif (config.callGraph.dynamicallyInitializeCallGraph) {\n // \t\t// We get here if we can't set 'funcname.caller' because of stupid 'strict mode' \n // \t\t// or such\n // \t\tlet distancesInGraph = this.project.callGraph.distances;\n // \t\tthis.score = this.visitedNodes.min(curNodeUid => {\n // \t\t\tlet allDstNodes = distancesInGraph[curNodeUid];\n // \t\t\treturn Object.keys(allDstNodes).min(dstNodeId =>\n // \t\t\t\tallDstNodes[dstNodeId].isTarget ?\n // \t\t\t\tallDstNodes[dstNodeId].distance :\n // \t\t\t\tInfinity\n // \t\t\t)\n // \t\t});\n // \t\tthis.score = 1 / this.score;\n // } else {\n this.score = this.getCoveragePercentage();\n }\n // }\n\n return this.score;\n }", "function GetScore()\r\n{\r\n\tvar score\t\t= 0;\r\n\tvar learnerId\t= LMSGetValue(\"cmi.learner_id\");\r\n\tvar launchData\t= new ParameterParser(LMSGetValue(\"cmi.launch_data\"));\r\n\r\n\tif (launchData.Get(\"cheat\") == \"yes\" && learnerId == \"gweinfurther\")\r\n\t{\r\n\t\tscore = 100;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvar urlParameters\t= new ParameterParser(document.location.search);\r\n\t\tvar scoreString\t\t= urlParameters.Get(\"SCORE\");\r\n\t\tvar parsedScore\t\t= parseInt(scoreString, 10);\r\n\r\n\t\tif (!isNaN(parsedScore))\r\n\t\t\tscore = parsedScore;\r\n\t}\r\n\r\n\treturn score;\r\n}", "function getPlayerScore(){\n return playerScore;\n }", "function overallScore() {\n user.score = extrTotal - intrTotal;\n return extrTotal - intrTotal;\n }", "trackScore() {\r\n if (this.checkWord())\r\n score += 1;\r\n return score;\r\n }", "getScore(){\n\t\tlet s = 0;\n\t\tfor (let stat in this.stats) {\n\t\t\tif (typeof this.stats[stat] !== 'number') {continue}\n\t\t\ts += this.stats[stat];\n\t\t}\n\t\treturn s;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function gets array of images from artist's gallery
async function getImages() { var gallery = await getGallery(); var featured = []; for (var i = 0; i < 5; i++) { featured.push(gallery.results[i].thumbs[1].src); } return featured; }
[ "function genImagesFromGallery() {\n fullImageUrls = []\n var allImages = myJQ(\".tm-gallery-view__thumbnail\");\n if (allImages) {\n allImages.each(function(index,value) {\n var imageUrl = value.src.replace(\"64x64m\",\"plus\");\n console.log(\"img imageUrl=\" + imageUrl);\n fullImageUrls.push(imageUrl);\n });\n }\n}", "async getImages(gallery) {\n if (typeof kiss !== 'undefined' && gallery == null) gallery = kiss.PARAMS.gallery_id;\n if (gallery == null) throw new Error('Cannot get gallery images without an id. Either pass an ID or visit a gallery page');\n const gallery_id = gallery.id || gallery;\n const images = await this.fetch('GET', `/gallery/${gallery_id}/images`);\n if (images == null) return [];\n return images.map(i => new Image(this, i));\n }", "function getAllPhotos() {\n var result = [];\n var uploadedPics = [];\n // Store the image data to the array\n for (var i = 0; i < 40; i++) {\n if (document.getElementById('MaintenanceImage' + i)) {\n result.push(document.getElementById('MaintenanceImage' + i).src);\n }\n }\n // Extract real pics and store it/them to the new array\n for (var i = 0; i < result.length; i++) {\n if (result[i].charAt(0) == 'd') {\n uploadedPics.push(result[i]);\n }\n }\n return uploadedPics;\n}", "function getAllImages()\n{\n\n for (var i = 0; i < g_imageList.length; i++)\n {\n var img = new Image();\n img.src = \"img/companyPhotos/\" + g_imageList[i];\n g_images.push(img);\n \n }\n}", "function fetchImages() {\n const numPhotos = 18;\n const graphicPromises = [];\n const baseUrl =\n \"https://arcgis.github.io/arcgis-samples-javascript/sample-data/featurelayer-collection/photo-\";\n\n for (let i = 1; i <= numPhotos; i++) {\n const url = baseUrl + i.toString() + \".jpg\";\n const graphicPromise = exifToGraphic(url, i);\n graphicPromises.push(graphicPromise);\n }\n\n return promiseUtils.eachAlways(graphicPromises);\n}", "function loadImages(artType, gallery){\r\n var artDir = artType.toString();\r\n //Default location the images will be found to be added to the gallery:\r\n var image = '';\r\n var imageStart = (\"<img src='images/\"+artDir+\"/\");\r\n var imageEnd = \"'></img>\";\r\n //add the images to the gallery\r\n var imagesToLoad = findAppropriateImages(artDir);\r\n for(i=0; i < imagesToLoad.length; i++){\r\n image = imagesToLoad[i];\r\n gallery.innerHTML += (imageStart+image+imageEnd);\r\n }\r\n}", "grabImages(imgArr) {\n\t\tvar\timgGal = ''\n\t\tfor (var i = 0; i < imgArr.length; i++ ) {\n\t\t\timgGal += '<img src=\"' + imgArr[i].url_570xN + '\">'\n\t\t}\n\t\treturn imgGal\n\t}", "function getImages() {\n $.get(\"/api/artwork\", function(data) {\n console.log(\"Images\", data);\n images = data;\n if (!images || !images.length) {\n displayEmpty();\n } else {\n initializeRows(doGallery);\n }\n initializeRows(doGallery);\n });\n }", "function returnimages($dirname=\".\") {\n$pattern=\"(\\.jpg$)|(\\.png$)|(\\.jpeg$)|(\\.gif$)\"; //valid image extensions\n$files = array();\n$curimage=0;\nif($handle = opendir($dirname)) {\nwhile(false !== ($file = readdir($handle))){\nif(eregi($pattern, $file)){ //if this file is a valid image\n//Output it as a JavaScript array element\necho 'galleryarray['.$curimage.']=\"'.$file .'\";';\n$curimage++;\n}\n\n\n}\n\nclosedir($handle);\n}\nreturn($files);\n}", "function createAristArray (artistName, lastName) {\n\n var artistArray = [];//return different arrays for each artist?\n //only load first 6 now. how to pick 6 of 6-10 paintings in the folder?\n for( i=1; i<=6;i++){\n artistArray.push('img/' + artistName + '/' + lastName + i +'.jpg');\n }\n return artistArray\n}", "function createImages(photoArray) {\n const imageGallery = document.getElementById('gallery');\n imageGallery.innerHTML = \"\";\n const FARM = \"https://farm\";\n const DOMAIN = \".staticflickr.com/\";\n photoArray.forEach(function(PHOTO) {\n let newImg = document.createElement(\"img\");\n newImg.classList.add('gallery-image');\n let src = `${FARM}${PHOTO.farm}${DOMAIN}${PHOTO.server}/${PHOTO.id}_${PHOTO.secret}`;\n newImg.setAttribute('src', src + \"_m.jpg\")\n newImg.addEventListener('click', function() {\n showImageOriginal(src)\n });\n imageGallery.append(newImg);\n });\n}", "function getImages(){\n return images;\n }", "function getImageFiles(elem) {\n\tvar pic_set = [];\t\n\tfor (var j = 1; j <= NUM_PICS; j++) {\n\t\tpic_set.push('final-images/' + elem.noun + '_' + elem.order[j-1] + '.png');\n\t\t\t}\n\t\n\n return pic_set;\n}", "function makeGallery(imageArray){\n\n\t}", "async getImages () {\n // route parameters\n const response = await this.api('/gallery', 'GET', null, false, null);\n\n // validate the response API\n if (response.status === 200) {\n return response.json();\n } else {\n throw new Error(\"There was an issue when attempting to retrieve the Images\");\n }\n }", "function populateFigures() {\n var filename;\n var currentFig;\n /*loop through the jpgs in the images folder and assign to a corresponding img element in the\n photoOrder array */\n for (var i = 1; i < 4; i++)\t{\t\n filename = \"https://cdn.glitch.com/60727fd5-6722-4373-b04f-8543cf0cb884%2FIMG_0\" + photoOrder[i] + \"sm.jpg\";\n currentFig = document.getElementsByTagName(\"img\")[i-1]; //subtract 1 from the counter to match the array value \n currentFig.src = filename;\n }\n}", "function showImagesEventHandler(e) {\n var app = UiApp.getActiveApplication();\n var panel = app.getElementById('panelForImages').clear();\n var info = Utilities.jsonParse(ScriptProperties.getProperty('info'));\n for (i in info) {\n if (info[i][0] == e.parameter.albumListBox) {\n var data = UrlFetchApp.fetch(URL + '/albumid/' + info[i][1], googleOAuth_()).getContentText();\n var xmlOutput = Xml.parse(data, false);\n var photos = xmlOutput.getElement().getElements('entry');\n for (j in photos) {\n panel.add(app.createImage(photos[j].getElement('content').getAttribute('src').getValue()));\n }\n }\n }\n return app;\n}", "function getImages(jsonEvent) {\n\n var images = [];\n if (jsonEvent.mediaObject) {\n for (var i = 0; i < jsonEvent.mediaObject.length; i++) {\n if (jsonEvent.mediaObject[i]['@type'] === 'ImageObject') {\n images.push(jsonEvent.mediaObject[i]);\n }\n }\n }\n\n return images;\n\n }", "function getCarImgs() {\n var carImages = [];\n\n for (var i = 1; i <= 3; i++) {\n var carImage = [];\n carImage.push(new Image());\n carImage[0].src = './public/assets/cars/car' + i + '.png';\n carImage.push(new Image());\n carImage[1].src = './public/assets/cars/car' + i + '_shadow.png';\n carImages.push(carImage);\n }\n\n return carImages;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If user edits one of the TinyMCE fields, call formStateChanged for that tab.
setTinyListener(){ var form = this $(document).bind('laevigata:tinymce:change', null, (e) => form.formStateChanged('.about-my-etd')); }
[ "function setChanged (){\n\tformModified = true;\n}", "formChanged() {}", "function textareaChange() {\n // Mark flag if edit operation is made\n $('#right-code').bind('input propertychange', function() {\n modal_edit = 1;\n })\n $('#left-code').bind('input propertychange', function() {\n modal_edit = 1;\n })\n }", "function onFormValueChanged( /* element */ ) {\n\n function onResetToStoredData() {\n template.render( Y.dcforms.nullCallback );\n Y.log( 'Form reset to state before edit.', 'debug', NAME );\n }\n\n function onUpdatedFormData() {\n Y.log( 'Saved form state has been updated.', 'debug', NAME );\n }\n\n if( currentActivity._isEditable() ) {\n\n context.attachments.updateFormDoc( context, template, onUpdatedFormData );\n\n } else {\n\n if (formDoc && formDoc.type) {\n try {\n template.fromDict( Y.doccirrus.api.document.formDocToDict(formDoc), onResetToStoredData );\n } catch( parseErr ) {\n Y.log( 'Could not parse saved form state.', 'warn', NAME );\n }\n }\n\n return;\n }\n }", "function inputChanged(e) {\n formChanged = true;\n }", "function formEdited($form, isEdited) {\n \tif (isEdited) {\n \t\t$form.find(':submit,:reset').removeAttr('disabled')\n \t\t\t.removeClass('ui-state-disabled');\n \t} else if ($form.data('inform').undoEdit) {\n \t\t$form.find(':submit,:reset').attr('disabled', true)\n \t\t\t.addClass('ui-state-disabled');\n \t}\n }", "function updateEditorContent() {\n\t\t\tform.find(':tinymce').each(function() {\n\t\t\t\ttinyMCE.get(this.id).save();\n\t\t\t});\n\t\t}", "function formChanged(didTextBoxChange) {\n\tif(didTextBoxChange) {\n\t\t// do nothing\n\t}\n\telse {\n\t\tsetFormContents();\n\t}\n\tvar requestString = generateRequestString();\n\tajax(requestString)\n}", "function onFieldChanged() {\n if (!currentUser) return;\n\n handleFields(hiddenFields(), 'hide');\n handleFields(readOnlyFields(), 'disable');\n}", "function formChanged() {\r\n\tdisableWidget('newButton');\r\n\tenableWidget('saveButton');\r\n\tdisableWidget('printButton');\r\n\tdisableWidget('copyButton');\r\n\tenableWidget('undoButton');\r\n\tdisableWidget('deleteButton');\r\n\tdisableWidget('refreshButton');\r\n\tformChangeInProgress=true;\r\n\tgrid=dijit.byId(\"objectGrid\");\r\n\tif (grid) {\r\n\t\t// TODO : lock grid selection\r\n\t\t//saveSelection=grid.selection;\r\n\t\tgrid.selectionMode=\"none\";\r\n\t\t\r\n\t}\r\n}", "function callback_tinymce_init(editor) {\n editor.on('change', function () {\n $(editor.targetElm).trigger('change');\n });\n}", "function Form_TEMA__Modificar(){\n\tForm_TEMA__ActivarFormulario();\n\tForm_TEMA__ActivarBotonGuardar();\n\tForm_TEMA__DesactivarBotonModificar();\n\tForm_TEMA__TabPane.setSelectedIndex(0);\n\t}", "function setChange(form) \n{\n\tif (form.madechange)\n\t{\n\t\tform.madechange.value = \"yes\";\n\t}\n}", "function acritExpSettingsChangeTab(tab){\n\tif($('#acrit_exp_form #field_IBLOCK').attr('data-loaded')=='Y' && !window.acritExpInitialSettingsTabClick) {\n\t\tvar selectedTab = $('#field_IBLOCK_content [data-role=\"iblock-structure-settings-tabs\"] .adm-detail-subtab-active'),\n\t\t\ttab = $('#field_IBLOCK_content [data-role=\"iblock-structure-settings-tabs\"] .adm-detail-subtab-active').attr('ID'),\n\t\t\tiblock_id = $('input[data-role=\"profile-iblock-id\"]').val();\n\t\ttab = tab.replace(/^view_tab_/, '');\n\t\tif(tab == 'subtab_console') {\n\t\t\treturn;\n\t\t}\n\t\tacritExpAjax('save_last_settings_tab', 'iblock_id='+iblock_id+'&tab='+tab, null, null, false, true);\n\t}\n}", "function tabChanged(e){\n // var node = e.selectedValueTab;\n // gTrans.showDialogCorp = true;\n // if (node.id == 'tab1') {\n //\n // }\n // if (node.id == 'tab2'){\n // gTrans.dialog.activeDataOnTab('tab2');\n // gTrans.dialog.USERID = gCustomerNo;\n // gTrans.dialog.PAYNENAME = \"3\";\n // gTrans.dialog.TYPETEMPLATE = \"1\";\n // gTrans.dialog.requestData(node.id);\n // }\n }", "function afterEmChange(fieldName, selectedValue, previousValue)\n{\n\tif (fieldName == \"em.em_id\" && selectedValue != previousValue) {\n\t\tinfoTabController.my_info_form.refresh(\"em_id='\"+selectedValue.replace(\"'\", \"''\")+\"'\");\n\t}\n\t// return false so no fields are actually updated.\n\treturn false;\n}", "function onChange() {\n\n /**\n * text area value\n * @type {string}\n */\n var value = this.value;\n\n // has logger instance? => log change event\n if ( self.logger ) self.logger.log( 'change', value );\n\n // has individual change callback? => perform it\n if ( self.onchange ) self.onchange( self, value );\n\n }", "function onSettingsChange(){\r\n\t\t\r\n\t\tif(g_objInputUpdate)\r\n\t\t\tupdateValuesInput();\r\n\t}", "function handleTabChange() {\r\n\t// TODO tidy up selection history\r\n\t// save any changes to description\r\n\tif (currentObjectId) {\r\n\t\tonObjectTextChange();\r\n\t}\r\n\tif (currentFrameViewObjectId)\r\n\t\tcurrentFrameViewObjectId = undefined;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setNumber_blockBased Input: 1 <= i, j, i_block, j_block <= 3 1 <= n <= 9 Results: None Side Effects: change this.numbers, this.candidates
setNumber_blockBased(i_block, j_block, i, j, n){ this.setNumber((i_block-1)*3+i, (j_block-1)*3+j, n); }
[ "setCandidate_blockBased(i_block, j_block, i, j, n){\r\n this.setCandidate((i_block-1)*3+i, (j_block-1)*3+j, n);\r\n }", "setCandidate(i, j, n){\r\n const I = i-1;\r\n const J = j-1;\r\n const N = n-1;\r\n\r\n const n_bit = 1<<N;\r\n this.candidates[I*9 + J] |= n_bit;\r\n\r\n const i_bit = 1<<I;\r\n const j_bit = 1<<J;\r\n this.candidates_row[N*9 + I] |= j_bit;\r\n this.candidates_column[N*9 + J] |= i_bit;\r\n\r\n const block_I = Math.floor(I/3);\r\n const block_J = Math.floor(J/3);\r\n const U = I%3;\r\n const V = J%3;\r\n const block_bit = 1 << ((U*3) + V);\r\n this.candidates_block[N*9 + (block_I*3+block_J)] |= block_bit;\r\n }", "setNumber(i, j, n, depth=0){\r\n this.numbers[(i-1)*9 + (j-1)] = n;\r\n\r\n // i 行と j 列 の候補を削除\r\n for(let k=1; k<=9; k++){\r\n this.deleteCandidate(i, k, n);\r\n this.deleteCandidate(k, j, n);\r\n }\r\n\r\n // cell(i, j) のブロック内の候補を削除\r\n const i_block = Math.floor((i-1)/3) + 1;\r\n const j_block = Math.floor((j-1)/3) + 1;\r\n for(let u=1; u<=3; u++){\r\n for(let v=1; v<=3; v++){\r\n this.deleteCandidate_blockBased(i_block, j_block, u, v, n);\r\n }\r\n }\r\n\r\n // cell(i, j) の候補を削除\r\n for(let n=1; n<=9; n++){\r\n this.deleteCandidate(i, j, n);\r\n }\r\n\r\n // 最後に cell(i, j) に n の候補を台に優\r\n this.setCandidate(i, j, n);\r\n\r\n if(depth==0){\r\n this.shadow.setNumber(i, j, n, 1);\r\n }\r\n \r\n }", "getNumber_blockBased(i_block, j_block, i, j){\r\n return this.getNumber((i_block-1)*3+i, (j_block-1)*3+j);\r\n }", "deleteCandidate_blockBased(i_block, j_block, i, j, n){\r\n this.deleteCandidate((i_block-1)*3+i, (j_block-1)*3+j, n);\r\n }", "getCandidate_blockBased(i_block, j_block, i, j, n){\r\n return this.getCandidate((i_block-1)*3+i, (j_block-1)*3+j, n);\r\n }", "resetCandidate(){\r\n this.candidates.fill(0b111111111);\r\n this.candidates_row.fill(0b111111111);\r\n this.candidates_column.fill(0b111111111);\r\n this.candidates_block.fill(0b111111111);\r\n\r\n for(let i=1; i<=9; i++){\r\n for(let j=1; j<=9; j++){\r\n if(this.getNumber(i, j) > 0){\r\n this.setNumber(i, j, this.getNumber(i, j));\r\n }\r\n }\r\n }\r\n }", "getN_ListInBlock(i_block, j_block, n){\r\n let n_list = [];\r\n for(let i=1; i<=3; i++){\r\n for(let j=1; j<=3; j++){\r\n if(this.getCandidate_blockBased(i_block, j_block, i, j, n)==true){\r\n n_list.push([i, j]);\r\n }\r\n }\r\n }\r\n return n_list;\r\n }", "countCandidateInBlock(block_i, block_j, n){\r\n let result = this.candidates_block[(n-1)*9 + (block_i-1)*3 + (block_j-1)];\r\n result = (result & 0b0101010101) + ((result>>1) & 0b0101010101);\r\n result = (result & 0b1100110011) + ((result>>2) & 0b1100110011);\r\n result = (result & 0b1100001111) + ((result>>4) & 0b1100001111);\r\n result = (result & 0b0011111111) + ((result>>8) & 0b0011111111);\r\n return result;\r\n }", "createCandidateArray(n){\r\n \r\n const result = [];\r\n for(let i=0; i<10; i++){\r\n const subarray = new Array(10);\r\n subarray.fill(1);\r\n result.push(subarray);\r\n }\r\n\r\n for(let i=1; i<=9; i++){\r\n for(let j=1; j<=9; j++){\r\n if(this.getNumber(i, j)==n){\r\n // delete column, row\r\n for(let k=1; k<=9; k++){\r\n result[i][k] = 0;\r\n result[k][j] = 0;\r\n }\r\n\r\n // delete block\r\n const block_i_offset = Math.floor((i-1)/3)*3;\r\n const block_j_offset = Math.floor((j-1)/3)*3;\r\n for(let u=1; u<=3; u++){\r\n for(let v=1; v<=3; v++){\r\n result[block_i_offset+u][block_j_offset+v] = 0;\r\n }\r\n }\r\n }\r\n\r\n if(this.getNumber(i, j)>0){\r\n result[i][j] = 0;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }", "function setNumber(i,j){\n\n var rowLimit = i-1;\n var columnLimit = j-1;\n \n for(var x =0; x <= rowLimit; x++) {\n for(var y = 0; y <= columnLimit; y++) {\n let ele = document.getElementById(\"f\" + x + \"_c\" + y);\n var n = 0;\n\n var leftN = x - 1;\n var rightN = x + 1;\n\n var topN = y - 1;\n var bottomN = y + 1;\n\n var northwest = \"f\" + (x - 1)+\"_c\"+(y-1); \n var northeast = \"f\" + (x - 1)+\"_c\"+(y+1); \n var southwest = \"f\" + (x + 1)+\"_c\"+(y-1); \n var southeast = \"f\" + (x + 1)+\"_c\"+(y+1); \n\n\n var leftNele = document.getElementById(\"f\" + leftN + \"_c\" + y);\n var rightNele = document.getElementById(\"f\" + rightN + \"_c\" + y);\n\n var topNele = document.getElementById(\"f\" + x + \"_c\" + topN);\n var bottomNele = document.getElementById(\"f\" + x + \"_c\" + bottomN);\n\n var leftTopCorner = document.getElementById(northwest);\n var rightTopCorner = document.getElementById(northeast);\n\n var leftBottomCorner = document.getElementById(southwest);\n var rightBottomCorner = document.getElementById(southeast);\n\n if(typeof(leftNele) != 'undefined' && leftNele != null){\n if(leftNele.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(rightNele) != 'undefined' && rightNele != null){\n if(rightNele.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(topNele) != 'undefined' && topNele != null){\n if(topNele.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(bottomNele) != 'undefined' && bottomNele != null){\n if(bottomNele.dataset.bomb == 'true'){\n n++;\n }\n }\n //@#CORNERS\n if(typeof(leftTopCorner) != 'undefined' && leftTopCorner != null){\n if(leftTopCorner.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(rightTopCorner) != 'undefined' && rightTopCorner != null){\n if(rightTopCorner.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(leftBottomCorner) != 'undefined' && leftBottomCorner != null){\n if(leftBottomCorner.dataset.bomb == 'true'){\n n++;\n }\n }\n if(typeof(rightBottomCorner) != 'undefined' && rightBottomCorner != null){\n if(rightBottomCorner.dataset.bomb == 'true'){\n n++;\n }\n }\n\n\n\n if(ele.dataset.bomb == 'false'){\n ele.dataset.number = n;\n ele.innerHTML = '';\n }\n }\n }\n\n /*matrix.forEach(element => {\n //console.log('NUMBER ID '+element[0]); \n ele = document.getElementById(element[0]);\n let endSetAt = Math.floor(Math.random() * max) + 1;\n if(ele.dataset.bomb == 'false'){\n //ele.innerHTML = endSetAt;\n ele.dataset.number = endSetAt;\n ele.innerHTML = \"\";\n }else{\n // ele.innerHTML= \"\";\n } \n \n });*/\n}", "deleteCandidate(i, j, n){\r\n const I = i-1;\r\n const J = j-1;\r\n const N = n-1;\r\n\r\n const n_bit_mask = 0b111111111 ^ (1<<N);\r\n this.candidates[I*9 + J] &= n_bit_mask;\r\n\r\n const i_bit_mask = 0b111111111 ^ (1<<I);\r\n const j_bit_mask = 0b111111111 ^ (1<<J);\r\n this.candidates_row[N*9 + I] &= j_bit_mask;\r\n this.candidates_column[N*9 + J] &= i_bit_mask;\r\n\r\n const block_I = Math.floor(I/3);\r\n const block_J = Math.floor(J/3);\r\n const U = I%3;\r\n const V = J%3;\r\n const block_bit_mask = 0b111111111 ^ (1<<((U*3) + V));\r\n this.candidates_block[N*9 + (block_I*3+block_J)] &= block_bit_mask;\r\n }", "resetCandidate(){\r\n this.candidates.fill(0b111111111);\r\n this.candidates_row.fill(0b111111111);\r\n this.candidates_column.fill(0b111111111);\r\n this.candidates_block.fill(0b111111111);\r\n\r\n this.shadow.candidates.fill(0b111111111);\r\n this.shadow.candidates_row.fill(0b111111111);\r\n this.shadow.candidates_column.fill(0b111111111);\r\n this.shadow.candidates_block.fill(0b111111111);\r\n\r\n for(let i=1; i<=9; i++){\r\n for(let j=1; j<=9; j++){\r\n if(this.getNumber(i, j) > 0){\r\n this.setNumber(i, j, this.getNumber(i, j));\r\n }\r\n }\r\n }\r\n }", "function processNumberBlocks() {\n return true;\n }", "countNumbersInBlock(i_block, j_block){\r\n let count = 0;\r\n for(let i=1; i<=3; i++){\r\n for(let j=1; j<=3; j++){\r\n if(this.getNumber_blockBased(i_block, j_block, i, j)>0){\r\n count ++;\r\n }\r\n }\r\n }\r\n return count;\r\n }", "insertBlocks() {\n for (let i = 1; i <= this.numberOfBlocks; i++) {\n const blockCoordinates = this.generateCoordinatesFree();\n this.grid[blockCoordinates[0]][blockCoordinates[1]] = 1;\n }\n }", "function blockInfoSet(n, i, id) {\n\tblockInfo[currBlock[4]][i] = n;\n\tif (id == \"densitySl\" || id == \"viscositySl\") {\n\t\tblockInfo[currBlock[4]][0] = 0.1+0.9*(parseFloat(blockInfo[currBlock[4]][5])+5)*(blockInfo[currBlock[4]][6])/10;\n\t}\n\tblockSet(currBlock[4]);\n}", "async set_nth_blocknum_of_inode(inode, n, block_num) {\n if (n < inode.num_direct) {\n inode.direct[n] = block_num;\n } else {\n var indirect_index = n - inode.num_direct;\n var indirect_view = this.get_disk_block_view_from_block_num(inode.indirect[0]);\n indirect_view[indirect_index] = block_num;\n\n if (this.animations)\n await this.animations.read_block(inode.indirect[0], true);\n }\n\n return block_num;\n }", "function calculateConstraints(puzzle,puzzid) {\n\n //console.log(\"Calculating constraints\")\n\n // Grab a list of all the blocks\n var blockList = $('.block.puzzle-'+puzzid)\n\n // Loop through all the blocks \n blockList.each(function(){\n\n // Get the number of the block\n var n = $(this).attr(\"data-num\")\n\n // Get the origin row and column of the block\n var ori_left = $(this).css(\"left\")\n var ori_top = $(this).css(\"top\")\n ori_top2 = parseInt(ori_top.slice(0,-2))\n ori_left2 = parseInt(ori_left.slice(0,-2))\n ori_row = Math.round((ori_top2-5)/40)\n ori_col = Math.round((ori_left2-5)/40)\n\n // For horizontal blocks (vertical blocks have a different method)\n if ($(this).hasClass(\"block-hor\")) {\n\n // Loop through the columns moving left, until you find a blocked one\n var left_point_found = 0\n var left_point = ori_col\n while (left_point_found == 0) {\n if (left_point - 1 >= 0) {\n if (puzzle.gridState[puzzid-1][ori_row][left_point-1] == 1 || left_point == 0) {\n left_point_found = 1\n } else {\n left_point = left_point - 1\n }\n } else {\n left_point = 0\n left_point_found = 1\n }\n }\n // Loop through moving right, then add 1 to get the right edge\n var right_point_found = 0\n var right_point = ori_col + 1\n if ($(this).hasClass(\"block-size-3\")) {right_point = right_point+1}\n while (right_point_found == 0) {\n if (right_point + 1 <= 5) {\n if (puzzle.gridState[puzzid-1][ori_row][right_point+1] == 1 || right_point == 5) {\n right_point_found = 1\n } else {\n right_point = right_point + 1\n }\n } else {\n right_point = 5\n right_point_found = 1\n }\n }\n right_point = Math.min(right_point + 1,6) \n // If the block is the key block and the right point includes the edge, extend it\n if (n == 0 && right_point == 6) {\n right_point = 8\n }\n var divWidth = (right_point - left_point)*40\n\n // Create an element the shape of the left and right points\n var wrapDiv = $('<div class=\"wrap-constraint wrap-constraint-'+n+' puzzle-'+puzzid+'\"></div>')\n .css({\"width\":divWidth})\n .css({\"height\":\"40px\"})\n .css({\"top\":(ori_top2-5)+\"px\"})\n .css({\"left\":(left_point*40)+\"px\"})\n\n } else {\n\n // Loop through the rows moving up, until you find a blocked one\n var top_point_found = 0\n var top_point = ori_row\n while (top_point_found == 0) {\n if (top_point - 1 >= 0) {\n if (puzzle.gridState[puzzid-1][top_point-1][ori_col] == 1 || top_point == 0) {\n top_point_found = 1\n } else {\n top_point = top_point - 1\n }\n } else {\n top_point = 0\n top_point_found = 1\n }\n }\n // Loop through moving down, then add 1 to get the bottom edge\n var low_point_found = 0\n var low_point = ori_row + 1\n if ($(this).hasClass(\"block-size-3\")) {low_point = low_point+1}\n while (low_point_found == 0) {\n if (low_point + 1 <= 5) {\n if (puzzle.gridState[puzzid-1][low_point+1][ori_col] == 1 || low_point == 5) {\n low_point_found = 1\n } else {\n low_point = low_point + 1\n }\n } else {\n low_point = 5\n low_point_found = 1\n }\n }\n low_point = Math.min(low_point + 1,6)\n var divHeight = (low_point - top_point)*40\n\n // Create an element the shape of the left and right points\n var wrapDiv = $('<div class=\"wrap-constraint wrap-constraint-'+n+' puzzle-'+puzzid+'\"></div>')\n .css({\"width\":\"40px\"})\n .css({\"height\":divHeight})\n .css({\"top\":(top_point*40)+\"px\"})\n .css({\"left\":(ori_left2-5)+\"px\"})\n\n }\n\n // Append the div to the grid\n $('.wrap-constraint-'+n+'.puzzle-'+puzzid).remove()\n $('.ob-grid-body.puzzle-'+puzzid).append(wrapDiv)\n\n // Apply draggable\n applyDraggable(puzzid)\n\n })\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize a seneca entity to a structure accepted by dynamo and removes seneca attributes via .data$.
function serializeEntity(entity) { return attributes.wrap(entity.data$(false)); }
[ "function makeRawEntity(entity) {\n if (entity.entityAspect != null) {\n delete entity.entityAspect;\n }\n}", "function scrubEntity(entity) {\n\tentity = JSON.parse(JSON.stringify(entity));\n\n\tif (_.isFunction(entity.data$)) {\n\t\tentity = entity.data$();\n\t}\n\n\t/*eslint-disable */\n\tif (entity['entity$']) {\n\t\tdelete entity['entity$'];\n\t}\n\t/*eslint-enable */\n\n\treturn entity;\n}", "function deserializeEntity(entity) {\n\t\treturn attributes.unwrap(entity);\n\t}", "function putpost(si,args,done) {\n var ent_type = parse_ent(args)\n\n var ent = si.make(ent_type.zone,ent_type.base,ent_type.name)\n\n var data = args.data || {}\n\n var good = _.filter(_.keys(data),function(k){return !~k.indexOf('$')})\n //console.log(good)\n\n var fields = _.pick(data,good)\n //console.dir(fields)\n ent.data$(fields)\n\n if( ent_type.entid ) {\n ent.id = ent_type.entid\n }\n\n //console.dir(ent)\n\n save_aspect(si,{args:args,ent:ent},done,function(ctxt,done){\n //console.dir(ctxt.ent)\n ctxt.ent.save$(function(err,ent){\n var data = ent ? ent.data$() : null\n done(err, data)\n })\n })\n }", "function dynamoClean (entry) {\n ret = {\n FIRST_NAME: entry.FIRST_NAME.S,\n LAST_NAME: entry.LAST_NAME.S,\n EMAIL: entry.EMAIL.S,\n POSITION: entry.POSITION.S\n }\n return ret\n}", "function prepareForSerialization(entity) {\n var clone = entity.cloneNode(false);\n var children = entity.childNodes;\n for (var i = 0, l = children.length; i < l; i++) {\n var child = children[i];\n if (child.nodeType !== Node.ELEMENT_NODE || !child.hasAttribute('aframe-injected') && !child.hasAttribute('data-aframe-inspector') && !child.hasAttribute('data-aframe-canvas')) {\n clone.appendChild(prepareForSerialization(children[i]));\n }\n }\n optimizeComponents(clone, entity);\n return clone;\n}", "function DS_fromDatastore (obj, kind) {\n obj.data.id = obj.key.id; // every table makes it's unique entry ID known to web app\n if(typeof kind !== 'string') kind = obj.key.kind;\n //log(\"[\"+kind+\"]\"+JSON.stringify(obj));\n //log(\"GETTING SCHEMA FOR \"+kind);\n if(schema[kind].id == t_STR) {\n obj.data.id = obj.data.id.toString();\n }\n var membersToJsonParse = membersToJsonStringifyFilters[kind];\n if(membersToJsonParse) { // if some data members must be parsed to JSON, do it before the app gets the data\n for(var i=0;i<membersToJsonParse.length;++i){\n var k = membersToJsonParse[i];\n obj.data[k] = saferParse(obj.data[k]);\n }\n }\n return obj.data;\n}", "to_object(entity)\n\t{\n\t\tif (!entity)\n\t\t{\n\t\t\treturn\n\t\t}\n\n\t\tconst object = entity //.toObject()\n\t\tobject.id = object._id.toString()\n\t\tdelete object._id\n\n\t\treturn object\n\t}", "function action_putpost (si, args, done) {\n var ent_type = parse_ent(args)\n\n var ent = si.make(ent_type.zone, ent_type.base, ent_type.name)\n\n var data = args.data || {}\n\n var good = _.filter(_.keys(data), function (k) { return !~k.indexOf('$') })\n\n var fields = _.pick(data, good)\n ent.data$(fields)\n\n if (ent_type.entid != null) {\n ent.id = ent_type.entid\n } else if (data.id$ != null && options.allow_id) {\n ent.id$ = data.id$\n }\n\n save_aspect(si, {args: args, ent: ent}, done, function (ctxt, done) {\n ctxt.ent.save$(function (err, ent) {\n var data = ent ? ent.data$(true, 'string') : null\n done(err, data)\n })\n })\n }", "function updateEntityStore() {\n var storageString = JSON.stringify(entities)\n database.put('entities',storageString)\n }", "unserialize(data) {\n if (data && this._serializableProperties) {\n Object.getOwnPropertyNames(data).forEach((propertyName) => {\n let localPropertyName = propertyName;\n if (this._serializableProperties.has(propertyName) === false)\n localPropertyName = \"_\" + propertyName;\n if (this._serializableProperties.has(localPropertyName)) {\n const { type, options } = this._serializableProperties.get(localPropertyName);\n const isArray = options?.list ?? false;\n if (isArray) {\n this[localPropertyName] = data[propertyName].map((item) => {\n if (type) {\n let object = new type();\n if (object instanceof Serialize) {\n object.unserialize(item);\n return object;\n }\n }\n else\n return item;\n });\n }\n else if (type && new type() instanceof Serialize) {\n if (this[localPropertyName] !== undefined)\n this[localPropertyName].unserialize(data[propertyName]);\n else {\n this[localPropertyName] = new type();\n this[localPropertyName].unserialize(data[propertyName]);\n }\n }\n else\n this[localPropertyName] = data[propertyName];\n }\n });\n }\n }", "function saveNewEntity(entity, table, done) {\n\t\tentity.id = uuid();\n\t\tvar leanEntity = serializeEntity(entity);\n\t\t\n\t\tvar params = {\n\t\t\tTableName: table,\n\t\t\tItem: leanEntity\n\t\t};\n\t\t\n\t\tdynamoContext.putItem(params, function(err, data) {\n\t\t\tif(err) {\n\t\t\t\tdone(err);\n\t\t\t} else {\n\t\t\t\tdone(null, entity); \n\t\t\t}\n\t\t})\n\t}", "function EntityCopy(entity) {\n var copy_entity= {};\n copy_entity.eid = entity.eid;\n copy_entity.lat = entity.lat;\n copy_entity.lng = entity.lng;\n copy_entity.selected = entity.selected;\n copy_entity.title = entity.title;\n copy_entity.size = entity.size;\n copy_entity.level = entity.level;\n copy_entity.visible = entity.visible;\n copy_entity.ds = entity.ds.slice();\n return copy_entity;\n}", "function fromDatastore (obj) {\n obj.data.id = obj.key.id;\n return obj.data;\n}", "function aa_deser_sealObj(cmd, procLog) {\n\t\t\tvar objOrArr = nodesByKey[cmd.key];\n\t\t\t\n\t\t\tObject.seal(objOrArr);\n\t\t\taa_deser_log(cmd, procLog);\n\t\t}", "asJSON() {\r\n let root = super.asJSON();\r\n\r\n let initialObject = {};\r\n\r\n // Set selector based on type of nbt data\r\n initialObject[this._type] = this._selector\r\n if (this._type == \"entity\") {\r\n initialObject[this._type] = this._selector + this._tags;\r\n }\r\n\r\n initialObject[\"nbt\"] = this._nbt;\r\n\r\n let object = {...initialObject, ...root};\r\n\r\n return object;\r\n }", "static saveDataAsJson() {\n // Clone the game data\n let saveData = JSON.parse(JSON.stringify(novelData.novel));\n delete saveData.scenes;\n delete saveData.tagPresets;\n delete saveData.sounds;\n delete saveData.externalText;\n delete saveData.externalJson;\n let save = btoa(JSON.stringify(saveData));\n return save;\n }", "serialize() {\n const params = {};\n let obj = {\n score: params,\n staves: [],\n scoreText: [],\n textGroups: [],\n systemGroups: []\n };\n smoSerialize.serializedMerge(SmoScore.defaultAttributes, this, params);\n this.staves.forEach((staff) => {\n obj.staves.push(staff.serialize());\n });\n // Score text is not part of text group, so don't save separately.\n this.textGroups.forEach((tg) => {\n if (tg.isTextVisible()) {\n obj.textGroups.push(tg.serialize());\n }\n });\n this.systemGroups.forEach((gg) => {\n obj.systemGroups.push(gg.serialize());\n });\n obj.columnAttributeMap = this.serializeColumnMapped();\n smoSerialize.jsonTokens(obj);\n obj = smoSerialize.detokenize(obj, smoSerialize.tokenValues);\n obj.dictionary = smoSerialize.tokenMap;\n return obj;\n }", "function normalizeDataOnly(object) {\n if (object.dataOnly) {\n delete object.dataOnly;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using cast() saves having to type Vec.of so many times:
static cast(...args) { return args.map(x => Vec.from(x)); }
[ "function castToArray(val) {\n val = val || [];\n val = Array.isArray(val) ? val : (val == null ? [] : [val]);\n return val;\n}", "function FieldTypes_getCastValues() {\r\n\tvar retArray = new Array();\r\n\tvar temp;\r\n\r\n\tfor (var i in FieldTypes.castingHash) {\r\n\t\ttemp = FieldTypes.castDBType(FieldTypes.castingHash[i]); //parseInt(FieldTypes.castingHash[i]);\r\n\t\tif ((FieldTypes.castingHash[i] != -1) && (dwscripts.findInArray(retArray, temp) == -1)) {\r\n\t\t\tretArray.push(temp);\r\n\t\t}\r\n\t}\r\n\r\n\treturn retArray;\r\n}", "function castAsArray(arg) {\n if (!Array.isArray(arg)) {\n arg = [arg];\n }\n\n return arg;\n}", "CastData(g=[],s=[]){\n //set current cast\n this.Cast(g,s);\n return DSC.applyCast(this.o);\n }", "convertCppVectorToArray(vector) {\n if (vector == null) return [];\n \n const result = [];\n for (let i = 0; i < vector.size(); i++) {\n const item = vector.get(i);\n result.push(item);\n }\n return result;\n }", "function mapToValues(v){\n function mapRec(e){\n if(!isAVector(e)) return e;\n return mapRec(e.get(0));\n }\n return v.map(mapRec);\n }", "function safeCastArray(value) {\n if (value) {\n return castArray(value);\n } else {\n return [];\n }\n}", "function castArray(a) {\n if (isArray(a)) return a;\n if (arguments.length === 0) return [];\n\n return [a];\n}", "function as_list(i) { return i instanceof Array ? i : [i]; }", "function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n}", "toValue() {\n return this.content.map(value => value.map(element => element.toValue()));\n }", "function cast (){\n return arguments;\n}", "function cast(x, dtype) {\n return x.asType(dtype);\n}", "function convertArrayLikeObject(obj){\n return Array.from(obj);\n}", "static of(...items) {\n const Constructor = this;\n\n if (!Reflect.has(Constructor, brand)) {\n throw TypeError(\"This constructor is not a subclass of Float16Array\");\n }\n\n const length = items.length;\n\n // for optimization\n if (Constructor === Float16Array) {\n const proxy = new Float16Array(length);\n const float16bitsArray = getFloat16BitsArrayFromFloat16Array(proxy);\n\n for (let i = 0; i < length; ++i) {\n float16bitsArray[i] = roundToFloat16Bits(items[i]);\n }\n\n return proxy;\n }\n\n const array = new Constructor(length);\n\n for (let i = 0; i < length; ++i) {\n array[i] = items[i];\n }\n\n return array;\n }", "_columnCast(field, name, data, options) {\n var column = this._columns.get(name);\n if (typeof column.setter === 'function') {\n data = column.setter(options.parent, data, name);\n }\n if (column.array && field) {\n return this._castArray(name, data, options);\n }\n return this.convert('cast', column.type, data, column/*, {}*/);\n }", "visitCastExpression(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function convertToArray(val) {\n if (val instanceof Map) {\n return Array.from(val.values());\n }\n return Array.isArray(val) ? val : Array.from(val);\n }", "function castImmutable(value) {\n return value;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of LicenseConfiguration. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LicenseConfiguration.__pulumiType; }
[ "function _isObject(configurationObject) {\n\n // init\n var valid, validProperties, configurationProperties;\n\n // Check if configuration object\n valid = typeof configurationObject === 'object';\n configurationProperties = ['info', 'information', 'warn', 'warning', 'scs', 'success', 'includeLogs', 'includeTime'];\n\n validProperties = false;\n configurationProperties.forEach(function(_prop) {\n validProperties = validProperties || configurationObject.hasOwnProperty(_prop);\n });\n\n valid = valid && validProperties;\n\n\n ////////\n return valid;\n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RemediationConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === InfrastructureConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CertificateAuthorityCertificate.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EndpointConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Configuration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CertificateAuthority.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServerCertificate.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === GatewayAssociationProposal.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === SecurityConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ReplicationConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Certificate.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ExpressRouteCircuitConnection.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Organization.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === P2sVpnServerConfiguration.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === VpcIpv4CidrBlockAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ConfigurationTemplate.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DefaultVpcDhcpOptions.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === OrganizationCustomRule.__pulumiType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when clicking on a given $linkClicked the modal $modalToOpen is shown
function modalAlerts ($linkClicked, $modalToOpen) { $($linkClicked).on('click', function (e) { $($modalToOpen).modal('show') $(this).tooltip('hide') }) }
[ "function showModals($linkClicked , $modalToShow)\n {\n //Check if there's a checked checkbox and preserve state\n /*var boxes = $(linkClicked).parent().find('input')\n if( boxes.length > 0 )\n {\n for (var i = 0; i < boxes.length; i++) \n {\n if($(boxes[i])[0].checked)\n {\n $(boxes[i])[0].checked = true;\n }\n };\n }*/\n $($linkClicked).on('click',function(e){\n $($modalToShow).modal(\"show\");\n });\n }", "function modalAlerts($linkClicked, $modalToOpen)\n {\n $($linkClicked).on('click',function(e)\n {\n \n $($modalToOpen).modal(\"show\");\n $(this).tooltip('hide');\n });\n \n }", "function showModals ($linkClicked , $modalToShow) {\n // Check if there's a checked checkbox and preserve state\n /*var boxes = $(linkClicked).parent().find('input')\n if( boxes.length > 0 )\n {\n for (var i = 0; i < boxes.length; i++) \n {\n if($(boxes[i])[0].checked)\n {\n $(boxes[i])[0].checked = true\n }\n }\n }*/\n $($linkClicked).on('click', function (e) {\n $($modalToShow).modal('show')\n })\n }", "function showLinkModal () {\n var linkDialog = $(\"#link-dialog\");\n var linkInput = $(\"#link-input\");\n var goButton = $(\"#go-to-button\");\n\n // Go to URL when \"Go to! button is pressed\"\n goButton.on('click',function() {\n window.location.href = linkInput.val();\n });\n\n // Focus on input field after dialog is shown \n // and select its contents for quick copy & paste\n linkDialog.on('shown.bs.modal', function (e) {\n linkInput.focus().select();\n\n });\n // Clear input field after any type of dialog close\n linkDialog.on('hidden.bs.modal', function (e) {\n linkInput.val(\"\");\n });\n\n linkDialog.modal();\n }", "open(href, params) {\n if (typeof href === 'object')\n params = href;\n else {\n params = params || {};\n params.href = href;\n }\n eventBus.$emit('modal::open', params);\n }", "handleToggleLinkModal() {\n const { modalComponent } = this.state;\n\n if (modalComponent) {\n this.handleCloseModal();\n } else {\n const { editorState } = this.state;\n const contentState = editorState.getCurrentContent();\n const entityKey = getSelectionEntity(editorState);\n const entity = entityKey ? contentState.getEntity(entityKey) : null;\n this.handleOpenModal(() => (\n <LinkModal\n isOpen\n onAddLink={this.handleAddLink}\n onRemoveLink={this.handleRemoveLink}\n openInNewTab={entity ? entity.getData().target === '_blank' : false}\n toggle={this.handleCloseModal}\n url={entity ? entity.getData().url : null}\n />\n ));\n }\n }", "function handleCrmLinkModal(event){\n \n setCurrentCrmOppType(event.currentTarget.id);\n crmModalToggle();\n setCurrentCrmSelectedOpp(null);\n setCurrentCrmSelectedOppText(\"Type-in and Select the CRM Opportunity to link !\");\n }", "function openAndCloseModalAnyhow(specific_link, specific_modal){\n for (i = 0; i < specific_link.length; i++){\n\n specific_link[i].onclick = function(){\n specific_modal.className = \"is-hidden\";\n specific_modal.className = \"Modal\";\n app_container.parentElement.className = \"ModalOpen\";\n\n for (i = 0; i < close_button.length; i++){\n close_button[i].onclick = function(){\n hideModal(specific_modal);\n }\n }\n\n document.onclick = function(event){\n if (event.target === specific_modal){\n hideModal(specific_modal)\n }\n }\n }\n }\n}", "function displayModal() {\n const clickedLink = $(this).text();\n if (clickedLink === \"JOIN US\" || clickedLink === \"Join Us Now\") {\n $(\".joinUs\").modal(\"show\");\n } else if (clickedLink === \"Product Information\") {\n $(\"#product-information\").modal(\"show\");\n } else if (clickedLink === \"Customer Service\") {\n $(\"#customer-service\").modal(\"show\");\n } else if (clickedLink === \"Privacy Policy and GDPR\") {\n $(\"#privacy-policy\").modal(\"show\");\n } else if (clickedLink === \"Testimonials\") {\n $(\"#testimonials\").modal(\"show\");\n }\n}", "openModal() {\n // to open modal set isModalOpen tarck value as true\n this.isModalOpen = true;\n }", "function linkAreaClick(e)\n{\n let item = e.target.id;\n currentLinkId = item.substring(1);\n // console.log(e.target.id[0], \" CLICKED\");\n\n if( item[0] === 'd' )\n showModal(modalDelEl);\n if( item[0] === 'e' )\n { \n //console.log(\"EDIT LINK ID == \", currentLinkId);\n let target = getElemById(currentLinkId);\n linkTitleEl.value = target.innerText;\n linkUrlEl.value = target.getAttribute(\"href\");\n modalResult = \"update\";\n showModal(modalEditEl);\n }\n}", "function exportAsLink() {\n var trigger = document.getElementById('export-as-link-trigger');\n\n trigger.addEventListener('click', function() {\n $('#export-as-link').modal('show');\n });\n }", "function showModal(){\n\t\t$('.js_newPortal').on('click', function(){\n\t\t\t$('.modal.modal__addNewPortal').addClass('modalOpen');\n\t\t});\n\t}", "function openDialogselectLinkType(){\n //console.log(\"openDialogselectLinkType\");\n activateLinkCSS(false);\n $('#link_types_dialog').modal({\n show: true\n });\n }", "function onSummaryEntryLinkClick(){\n\t// Close the summary dialog\n\n\t$(\"#entryDetailsModal\").modal(\"show\");\n\n\n\t// Emulate the effects of a closed details dialog\n\tonDetailsModalHidden();\n\n\t// Get the ID of the entry link\n\tvar id = $(this).data(\"id\");\n\n\t// Trigger the usual handler\n\tdisplayModalEntryDetails(id);\n\n\t// Return false to prevent the default handler for hyperlinks\n\treturn false;\n}", "function headerLinkClicks(e){\n \n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n //JQueryfying the event object so that I can easily get the href attr\n var url = $(e.target).attr(\"href\");\n\n $.ajax(url,{dataType:\"text\"}).then(function(data){\n $modal.html(data).show();\n });\n }", "function openModal(ruleOrder, ruleName, ruleType, isNew) {\n console.log(\"ruleType : \" + ruleType + \" icin ruleOrder : \" + ruleOrder)\n resetModal();\n if (isNew) {\n console.log(\"Modal yeni olusturulacak\")\n } else {\n if (isEqual(ruleType, RULE_TYPE.FORMNAME.name)) {\n console.log(\"FormNameRule Modal duzenlenecek\")\n var editedRule = formNameRuleList[ruleOrder];\n editModal(editedRule);\n } else if (isEqual(ruleType, RULE_TYPE.VERSION.name)) {\n console.log(\"VersionRule Modal duzenlenecek\")\n var editedRule = versionRuleList[ruleOrder];\n editModal(editedRule);\n } else {\n console.log(\"Rule Modal duzenlenecek\")\n var editedRule = ruleList[ruleOrder];\n editModal(editedRule);\n }\n }\n $('#defineRuleModal').modal({\n backdrop: \"static\",\n keyboard: false\n });\n\n $(\"#ruleOrder\").text(ruleOrder);\n $(\"#ruleType\").text(ruleType);\n $(\"#ruleName\").text(ruleName);\n $('#linkStep1').click();\n}", "function __BRE__show_modal(modal_id){$('#'+modal_id).modal('show');}", "function shown_bs_modal( /*event*/ ) {\n //Focus on focus-element\n var $focusElement = $(this).find('.init_focus').last();\n if ($focusElement.length){\n document.activeElement.blur();\n $focusElement.focus();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change Select All Close Time
function selectAllCloseingTime(){ var closetimehrs = $("#restaurant_delivery_mon_close_hr").val(); var closetimemins = $("#restaurant_delivery_mon_close_min").val(); var closetimesess = $("#restaurant_delivery_mon_close_sess").val(); if( (closetimehrs == "") || (closetimemins == "") ){ $("#resSelectAllCloseErr").html(err_lang_arr['resmycc_plz_sel_mon_close_time']).show(); $("#selectclose").attr('checked',false); return false; }else{ $("#resSelectAllCloseErr").hide(); //Tues $('#restaurant_delivery_tue_close_hr').val(closetimehrs); $('#restaurant_delivery_tue_close_min').val(closetimemins); $('#restaurant_delivery_tue_close_sess').val(closetimesess); //wed $('#restaurant_delivery_wed_close_hr').val(closetimehrs); $('#restaurant_delivery_wed_close_min').val(closetimemins); $('#restaurant_delivery_wed_close_sess').val(closetimesess); //thu $('#restaurant_delivery_thu_close_hr').val(closetimehrs); $('#restaurant_delivery_thu_close_min').val(closetimemins); $('#restaurant_delivery_thu_close_sess').val(closetimesess); //fri $('#restaurant_delivery_fri_close_hr').val(closetimehrs); $('#restaurant_delivery_fri_close_min').val(closetimemins); $('#restaurant_delivery_fri_close_sess').val(closetimesess); //sat $('#restaurant_delivery_sat_close_hr').val(closetimehrs); $('#restaurant_delivery_sat_close_min').val(closetimemins); $('#restaurant_delivery_sat_close_sess').val(closetimesess); //sun $('#restaurant_delivery_sun_close_hr').val(closetimehrs); $('#restaurant_delivery_sun_close_min').val(closetimemins); $('#restaurant_delivery_sun_close_sess').val(closetimesess); } }
[ "function selectAllCloseingTime(){\n\t\t\n\t\tvar closetimehrs = $(\"#restaurant_delivery_mon_close_hr\").val();\n\t\tvar closetimemins = $(\"#restaurant_delivery_mon_close_min\").val();\n\t\tvar closetimesess = $(\"#restaurant_delivery_mon_close_sess\").val();\n\t\t\n\t\tif( closetimehrs == \"\" || closetimemins == \"\" ){\n\t\t\t$(\"#resSelectAllCloseErr\").addclass(\"errormsg\").html(\"Please select monday closeing time\").show();\n\t\t\t$(\"#selectclose\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{\n\t\t\t$(\"#resSelectAllCloseErr\").hide();\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_tue_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_tue_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_wed_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_wed_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_thu_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_thu_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_fri_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_fri_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_sat_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_sat_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_close_hr.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_sun_close_min.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_sun_close_sess.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t}\n\t}", "function selectAllSecondCloseingTime(){\n\t\t\n\t\tvar closetimehrs = $(\"#restaurant_delivery_mon_close_hr_second\").val();\n\t\tvar closetimemins = $(\"#restaurant_delivery_mon_close_min_second\").val();\n\t\tvar closetimesess = $(\"#restaurant_delivery_mon_close_sess_second\").val();\n\t\t\n\t\t/** if( closetimehrs == \"\" || closetimemins == \"\" ){\n\t\t\t$(\"#resSelectAllSecondCloseErr\").html(\"Please select monday Second closing time\").show();\n\t\t\t$(\"#selectsecondclose\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{\n\t\t\t$(\"#resSelectAllSecondCloseErr\").hide(); **/\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_tue_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_tue_close_sess_second').val(closetimesess);\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_wed_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_wed_close_sess_second').val(closetimesess);\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_thu_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_thu_close_sess_second').val(closetimesess);\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_fri_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_fri_close_sess_second').val(closetimesess);\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_sat_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_sat_close_sess_second').val(closetimesess);\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_close_hr_second').val(closetimehrs);\n\t\t\t$('#restaurant_delivery_sun_close_min_second').val(closetimemins);\n\t\t\t$('#restaurant_delivery_sun_close_sess_second').val(closetimesess);\n\t\t}", "function selectAllSecondCloseingTime(){\n\t\t\n\t\tvar closetimehrs = $(\"#restaurant_delivery_mon_close_hr_second\").val();\n\t\tvar closetimemins = $(\"#restaurant_delivery_mon_close_min_second\").val();\n\t\tvar closetimesess = $(\"#restaurant_delivery_mon_close_sess_second\").val();\n\t\t\n\t\t/*if( closetimehrs == \"\" || closetimemins == \"\" ){\n\t\t\t$(\"#resSelectAllSecondCloseErr\").addclass(\"errormsg\").html(\"Please select monday Second closing time\").show();\n\t\t\t$(\"#selectsecondclose\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{*/\n\t\t\t$(\"#resSelectAllSecondCloseErr\").hide();\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_tue_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_tue_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_wed_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_wed_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_thu_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_thu_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_fri_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_fri_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_sat_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_sat_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\t\t\t\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_close_hr_second.selectpicker').selectpicker('val', closetimehrs);\n\t\t\t$('#restaurant_delivery_sun_close_min_second.selectpicker').selectpicker('val', closetimemins);\n\t\t\t$('#restaurant_delivery_sun_close_sess_second.selectpicker').selectpicker('val', closetimesess);\n\t\t//}\n\t}", "function selectAllOpeningTime(){\n\t\t\n\t\tvar opentimehrs = $(\"#restaurant_delivery_mon_open_hr\").val();\n\t\tvar opentimemins = $(\"#restaurant_delivery_mon_open_min\").val();\n\t\tvar opentimesess = $(\"#restaurant_delivery_mon_open_sess\").val();\n\t\t\n\t\tif( (opentimehrs == \"\") || (opentimemins == \"\") ){\n\t\t\t$(\"#resSelectAllOpenErr\").html(err_lang_arr['resmycc_plz_sel_mon_open_time']).show();\n\t\t\t$(\"#selectopen\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{\n\t\t\t$(\"#resSelectAllOpenErr\").hide();\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_tue_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_tue_open_sess').val(opentimesess);\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_wed_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_wed_open_sess').val(opentimesess);\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_thu_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_thu_open_sess').val(opentimesess);\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_fri_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_fri_open_sess').val(opentimesess);\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_sat_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_sat_open_sess').val(opentimesess);\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_open_hr').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_sun_open_min').val(opentimemins);\n\t\t\t$('#restaurant_delivery_sun_open_sess').val(opentimesess);\n\t\t}\n\t}", "_onSelectTime() {\n store.setTimeSelectedFlag(true);\n this._setYmdHis();\n }", "function selectAllSecondOpeningTime(){\n\t\t\n\t\tvar opentimehrs = $(\"#restaurant_delivery_mon_open_hr_second\").val();\n\t\tvar opentimemins = $(\"#restaurant_delivery_mon_open_min_second\").val();\n\t\tvar opentimesess = $(\"#restaurant_delivery_mon_open_sess_second\").val();\n\t\t\n\t\t/*if( opentimehrs == \"\" || opentimemins == \"\" ){\n\t\t\t$(\"#resSelectAllOpenErr\").addclass(\"errormsg\").html(\"Please select monday second opening time\").show();\n\t\t\t$(\"#selectsecondopen\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{*/\n\t\t\t$(\"#resSelectAllSecondOpenErr\").hide();\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_tue_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_tue_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_wed_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_wed_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_thu_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_thu_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_fri_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_fri_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_sat_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_sat_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_open_hr_second.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_sun_open_min_second.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_sun_open_sess_second.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t//}\n\t}", "function selectAllSecondOpeningTime(){\n\t\t\n\t\tvar opentimehrs = $(\"#restaurant_delivery_mon_open_hr_second\").val();\n\t\tvar opentimemins = $(\"#restaurant_delivery_mon_open_min_second\").val();\n\t\tvar opentimesess = $(\"#restaurant_delivery_mon_open_sess_second\").val();\n\t\t\n\t\t/** if( opentimehrs == \"\" || opentimemins == \"\" ){\n\t\t\t$(\"#resSelectAllOpenErr\").html(\"Please select monday second opening time\").show();\n\t\t\t$(\"#selectsecondopen\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{\n\t\t\t$(\"#resSelectAllSecondOpenErr\").hide(); **/\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_tue_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_tue_open_sess_second').val(opentimesess);\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_wed_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_wed_open_sess_second').val(opentimesess);\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_thu_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_thu_open_sess_second').val(opentimesess);\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_fri_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_fri_open_sess_second').val(opentimesess);\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_sat_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_sat_open_sess_second').val(opentimesess);\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_open_hr_second').val(opentimehrs);\n\t\t\t$('#restaurant_delivery_sun_open_min_second').val(opentimemins);\n\t\t\t$('#restaurant_delivery_sun_open_sess_second').val(opentimesess);\n\t\t}", "function selectAllOpeningTime(){\n\t\t\n\t\tvar opentimehrs = $(\"#restaurant_delivery_mon_open_hr\").val();\n\t\tvar opentimemins = $(\"#restaurant_delivery_mon_open_min\").val();\n\t\tvar opentimesess = $(\"#restaurant_delivery_mon_open_sess\").val();\n\t\t\n\t\tif( opentimehrs == \"\" || opentimemins == \"\" ){\n\t\t\t$(\"#resSelectAllOpenErr\").addClass(\"errormsg\").html(\"Please select monday opening time\").show();\n\t\t\t$(\"#selectopen\").attr('checked',false);\n\t\t\treturn false;\n\t\t}else{\n\t\t\t$(\"#resSelectAllOpenErr\").hide();\n\t\t\t\n\t\t\t//Tues\n\t\t\t$('#restaurant_delivery_tue_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_tue_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_tue_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\n\t\t\t//wed\n\t\t\t$('#restaurant_delivery_wed_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_wed_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_wed_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//thu\n\t\t\t$('#restaurant_delivery_thu_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_thu_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_thu_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//fri\n\t\t\t$('#restaurant_delivery_fri_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_fri_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_fri_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//sat\n\t\t\t$('#restaurant_delivery_sat_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_sat_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_sat_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t\t//sun\n\t\t\t$('#restaurant_delivery_sun_open_hr.selectpicker').selectpicker('val', opentimehrs);\n\t\t\t$('#restaurant_delivery_sun_open_min.selectpicker').selectpicker('val', opentimemins);\n\t\t\t$('#restaurant_delivery_sun_open_sess.selectpicker').selectpicker('val', opentimesess);\n\t\t\t\n\t\t}\n\t}", "function time(select){\n var option = document.createElement('option');\n option.value = 'closed';\n option.innerText = 'Closed';\n select.appendChild(option);\n for(let i = 0; i < 1440; i += 30){\n option = document.createElement('option');\n var hour = Math.floor(i/60);\n var min = i % 60;\n if(min === 0){\n min = min.toString();\n min = '0' + min;\n }else{\n min = min.toString();\n }\n if(hour < 10){\n hour = hour.toString();\n hour = '0' + hour;\n }else{\n hour = hour.toString();\n }\n option.value = hour + ':' + min;\n option.innerText = hour + ':' + min;\n select.appendChild(option);\n }\n }", "selectToday() {\n const today = new Date();\n today.setHours(0);\n today.setMinutes(0);\n today.setSeconds(0);\n today.setMilliseconds(0);\n this.select(today);\n this.close();\n }", "function selectNow() {\n resetView();\n select(new Date());\n }", "function reselect_exit_time() {\n if (chart && exit_time) {\n chart.series[0].zones[1].value = parseInt(exit_time)*1000;\n // force to redraw:\n chart.isDirty = true;\n chart.redraw();\n }\n return;\n }", "function stopTimeSelect() {\n context.on(\"mousemove\", null);\n context.on(\"mouseup\", null);\n filterByDate(MONTHS[TRANGE[0]], MONTHS[TRANGE[1]], _(KIVA['loans']).clone());\n}", "function resetTimeOptions() {\n while (timeSelect.childElementCount > 1) {\n timeSelect.removeChild(timeSelect.lastChild);\n }\n}", "function onHourTickSelect(event) {\n headline.innerHTML = 'Select Minutes';\n var parent = this.parentElement;\n currentDateTime.setHours(parseInt(this.innerHTML));\n updateInputValue();\n\n addClass(parent, 'datipi-circle-hidden');\n\n removeClass(minutes, 'datipi-circle-hidden');\n addClass(minutes, 'datipi-circle-selector');\n window.setTimeout(function () {\n parent.style.display = 'none';\n minutes.style.visibility = 'visible';\n }, 350);\n\n // The outside click event should not occur\n event.stopPropagation();\n }", "function updateCloseDate() {\n\tjQuery('.form-item-close-date').css( 'display', jQuery('#edit-use-close-date-0')[0].checked ? 'none' : 'block' );\n}", "closeTimePicker() {\n this._closeTimePicker();\n }", "_changeToMinuteSelection() {\n const that = this,\n svgCanvas = that._centralCircle.parentElement || that._centralCircle.parentNode;\n\n that._inInnerCircle = false;\n\n cancelAnimationFrame(that._animationFrameId);\n that.interval = that.minuteInterval;\n\n that.$hourContainer.removeClass('jqx-selected');\n that.$minuteContainer.addClass('jqx-selected');\n\n svgCanvas.removeChild(that._centralCircle);\n svgCanvas.removeChild(that._arrow);\n svgCanvas.removeChild(that._head);\n\n that._getMeasurements();\n that._numericProcessor.getAngleRangeCoefficient();\n that._draw.clear();\n\n svgCanvas.appendChild(that._centralCircle);\n svgCanvas.appendChild(that._arrow);\n svgCanvas.appendChild(that._head);\n\n that._renderMinutes();\n\n that._drawArrow(true, undefined, true);\n }", "function setTimes()\n{\n\tvar dateJan = new Date(2012, 0, 1);\n\tvar dateNow = new Date();\n\n var fid = document.getElementById(\"Day\").selectedIndex;\n \n dateNow.setTime(forecasts[fid].date)\n\n\tif(dateNow.getTimezoneOffset() == dateJan.getTimezoneOffset())\n\t\ttimes = tzArray[\"STD\"];\n\telse\n\t\ttimes = tzArray[\"DST\"];\n\n // Keep the same time selected\n\tTindex = document.getElementById(\"Time\").selectedIndex;\n\n\tfor(var i = 0; i < times.length; i++) {\n\t\tdocument.getElementById(\"Time\").options[i] = new Option(times[i], times[i]);\n\t\tif(Tindex == i || (Tindex == -1 && times[i] == forecasts[fid].default_t))\n\t\t\tdocument.getElementById(\"Time\").options[i].selected = true;\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UHelpUNIFACE : proc statement help
function UHelpUNIFACE(which) { w = window.open(which, "UnifaceHelpWindow", "scrollbars=yes,resizable=yes,width=300,height=150"); if (uTestBrowserNS()) { w.focus(); } }
[ "function uciCmd(cmd){\n console.log(\"[INPUT] UCI: \" + cmd);\n engine.postMessage(cmd);\n }", "function ShowUsage( )\r\n{\r\n EnterFunction( arguments );\r\n\r\n /*\r\n * see if we were asked for help\r\n */\r\n if( g_oMessages.szCmdOpts.indexOf( \"?\" ) == -1 )\r\n {\r\n WScript.Echo( g_oMessages.L_BadCommand_txt );\r\n }\r\n WScript.Echo( g_oMessages.L_Usage_txt );\r\n}", "function sayHI(){w.pM({'cmd': 'start', 'msg': 'Hi'});}", "function auxcommand(parm, state) {\n switch (parm) {\n case '0': // Simulation Mode\n simmode = state;\n break;\n case '2': // Layout Mode\n commsonline = state;\n if (!state) {\n statustext('red', 'Layout Offline');\n }\n break;\n }\n setobject('a', parm, state);\n}", "function ConnectionStoredProcMenu_analyzeServerBehavior(sbObj, allRecs)\r\n{\r\n // nothing needed here\r\n}", "function C009_Library_Jennifer_Untie() {\n\tActorUntie();\n\tC009_Library_Jennifer_CalcParams();\n}", "function ETO_InvertibleCmd() { }", "function cmd_Help() {\n\t\t\n\t}", "function displayHelp() {\n ICEUtils.displayHelp(helpID);\n}", "function userinfo_dispatcher_routines() {\n\n\n}", "function clickedHelp() {\n ICEUtils.displayHelp(args.helpID);\n}", "function uzun() {console.log (\"Ben uzun js dosyasıyım!..\");}", "function il03DisplayNotificationDetails(param){ \r\n\tset(\"V[z_il03_notifnumber]\",param.notif);\r\n\tz_il03_return_flag = true;\r\n\t\t\r\n\tonscreen 'SAPLSMTR_NAVIGATION.0100'\r\n\t\tenter('/nil03');\r\n\r\n\t// Display Functional Location: Initial screen\r\n\tonscreen 'SAPMILO0.1110'\r\n\t\tset('F[Functional loc.]', '&V[z_il03_fnlocno]');\r\n\t\tenter();\r\n\t\tonerror\r\n\t\t\tz_il03_return_flag = false;\r\n\t\t\tmessage(_message);\r\n\t\t\tenter(\"/n\");\r\n\r\n\tonscreen 'SAPMILO0.2100'\r\n\t\tenter('/34');\r\n\r\n\tonscreen 'SAPLIWO1.2100'\r\n\t\tenter('=R_ME');\r\n\r\n\tonscreen 'RIQMEL20.1000'\r\n\t\tset('F[Notification date]', '');\r\n\t\tset('F[QMNUM-LOW]', '&V[z_il03_notifnumber]');\r\n\t\tenter('/8');\r\n\t\tonerror\r\n\t\t\tz_il03_return_flag = false;\r\n\t\t\tmessage(_message);\r\n\t\t\tenter(\"/n\");\r\n}", "function getProcedures(){}", "function SBDatabaseCall_analyzeDatabaseCall()\n{\n}", "function UHelpNATIVE(topic,mode,logicalname)\n{\n w = window.open(\"help?topic=\"+topic+\"&mode=\"+mode+\"&logicalname=\"+logicalname, \"UnifaceHelpNative\",\n \"scrollbars=yes,resizable=yes,width=400,height=200\");\n if (uTestBrowserNS()) {\n w.focus();\n }\n}", "function evtRoutine1( sender, parms )\n {\n var ref = this.REF, rtn = Lansa.evtRoutine( this, COM_OWNER, \"#com_owner.Initialize\", 23 );\n\n //\n // EVTROUTINE Handling(#com_owner.Initialize)\n //\n rtn.Line( 23 );\n {\n\n //\n // #com_owner.ProcessSearch( #MySession.pProductSearch )\n //\n rtn.Line( 25 );\n COM_OWNER.mthPROCESSSEARCH.call( this, ref.MYSESSION.ref.getPPRODUCTSEARCH() );\n\n }\n\n //\n // ENDROUTINE\n //\n rtn.Line( 27 );\n rtn.end();\n }", "function showCommandHelpFucntion(){\n console.log('\"show\" command is used to show the list of clients, servers or both ');\n console.log('that are created by the user during the wrt-c session');\n console.log('The syntax of the command is the follows:');\n console.log('');\n console.log('show [client/server/all]');\n console.log('');\n}", "function xqserver_msghello_upperboundsdescription_v2(){\r\n\tsetup();\r\n\tengine.MsgHello(0,++l_dwSequence,g_dwVersion,\"01234567890123456789012345678901234567890123456789012345678901234567890123456789\",80);\r\n\tExpectedState(engine,CONNECTED);\r\n}//endmethod" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the general comment
function saveGeneralComment(sync, successCallback, errorCallback) { var gradeable = getGradeable(); if ($('#extra-general')[0].style.display === "none") { //Nothing to save so we are fine if (typeof(successCallback) === "function") { successCallback(); } return; } var comment_row = $('#comment-id-general'); var gradeable_comment = comment_row.val(); var current_question_text = $('#rubric-textarea-custom'); var overwrite = $('#overwrite-id').is(":checked"); $(current_question_text[0]).text(gradeable_comment); ajaxSaveGeneralComment(gradeable.id, gradeable.user_id, gradeable_comment, sync, successCallback, errorCallback); }
[ "saveComment() {\n let comment = get(this, 'comment');\n\n this.sendAction('saveComment', comment);\n }", "function saveGeneralComment(sync, successCallback, errorCallback) {\n var gradeable = getGradeable();\n\n if ($('#extra-general')[0].style.display === \"none\") {\n //Nothing to save so we are fine\n if (typeof(successCallback) === \"function\") {\n successCallback();\n }\n return;\n }\n \n var comment_row = $('#comment-id-general');\n var gradeable_comment = comment_row.val();\n var current_question_text = $('#rubric-textarea-custom');\n var overwrite = $('#overwrite-id').is(\":checked\");\n $(current_question_text[0]).text(gradeable_comment);\n \n ajaxSaveGeneralComment(gradeable.id, gradeable.user_id, gradeable.active_version, gradeable_comment, sync, successCallback, errorCallback);\n}", "save(options={}, context=undefined) {\n console.assert(this.get('canSave'),\n 'save() called when canSave is false.');\n\n const extraData = _.clone(this.get('extraData'));\n extraData.require_verification = this.get('requireVerification');\n\n const comment = this.get('comment');\n comment.set({\n text: this.get('text'),\n issueOpened: this.get('openIssue'),\n extraData: extraData,\n richText: this.get('richText'),\n includeTextTypes: 'html,raw,markdown',\n });\n\n comment.save({\n success: () => {\n this.set('dirty', false);\n this.trigger('saved');\n\n if (_.isFunction(options.success)) {\n options.success.call(context);\n }\n },\n\n error: _.isFunction(options.error)\n ? options.error.bind(context)\n : undefined,\n });\n }", "async function _saveNewComment() {\n document.getElementById('saveButton').disabled = true;\n \n page.notice.setNotice('saving comment...', true);\n\n var postParams = {\n sourcefileid: settings.spreadsheetid,\n tags: document.getElementById('tagInput').value,\n comment: document.getElementById('commentInput').value,\n hovertext: document.getElementById('hovertextInput').value\n }\n\n var requestResult = await googleSheetWebAPI.webAppPost(apiInfo, 'newcomment', postParams, page.notice);\n if (requestResult.success) {\n page.notice.setNotice('copy succeeded', false);\n }\n\n document.getElementById('saveButton').disabled = false;\n }", "function newComment() {\n const newComment = {\n name: nameInput.val(),\n title: titleInput.val(),\n content: commentInput.val()\n };\n console.log(newComment);\n comment = newComment;\n submitComment(comment);\n }", "function saveComment(comment) {\n var def = $q.defer();\n var req = {\n method: comment.id ? 'PUT' : 'POST',\n url: \"comments\",\n data: comment}\n $http(req)\n\t .success(function (data) {\n\t def.resolve(data);\n\t })\n .error(function () {\n def.reject(\"Failed\");\n });\n return def.promise;\n }", "_saveCommon(severity) {\n if (this.commentEditor.get('canSave')) {\n this.commentEditor.setExtraData('severity', severity);\n this.commentDialog.save();\n }\n }", "function savecomment(name, email, number, comment){\n var newcommentRef = commentsRef.push();\n newcommentRef.set({\n name: name,\n email:email,\n number:number,\n comment:comment\n });\n}", "function saveComments(div_comments, sls_id, ref_type_id, comment_text){\n\tpars = 'type=38&action=save_comments&sls_id='+sls_id+'&ref_type_id='+ref_type_id+'&comment='+comment_text;\n\n\t// AJAX > Go get all comments associated to this story/link\n\tvar myAjax = new Ajax.Updater(\n\t\t\t\t\t div_comments,\n\t\t\t\t\t base_url, {\n\t\t\t\t\t \tmethod: 'get',\n\t\t\t\t\t \tparameters: pars,\n\t\t\t\t\t \tonComplete:function(){\n\t\t\t\t\t \t\t$(div_comments).style.display = 'inline';\n\t\t\t\t\t \t}\n\t\t\t\t\t });\n}", "function saveCommentPopup(e) {\n const popup = $(e.currentTarget).closest('.comment-popup');\n const ids = JSON.parse($(popup).data('ids'));\n let statusData = {};\n if ($(popup).data('status')) {\n statusData.status = $(popup).data('status');\n }\n if ($(popup).data('query')) {\n statusData.query = $(popup).data('query');\n }\n saveVerifyComment(ids, statusData, $(popup).find('textarea').val());\n $.fancybox.close();\n }", "async function saveComment(commentText) {\n // Add a new comment entry to the Firebase database.\n try {\n await addDoc(collection(db, 'resources', String(getResourceId()), 'comments'), {\n name: getUserName(),\n text: commentText,\n profilePicUrl: getProfilePicUrl(),\n timestamp: serverTimestamp()\n });\n }\n catch (error) {\n console.error('Error writing new comment to Firebase Database', error);\n }\n}", "function saveCommentObject() {\n\torderItems[commentItemPos].notes = $('#commentBox').val();\n\tconsole.log(orderItems);\n\t$('#commentBox').val(''); //Clear comment box\n\t$('#commentModal').modal('toggle');\n}", "function addcomment() {\r\n}", "function postMessageToSave() {\n saveComment().then(() => {\n navKakao.style.display = \"block\";\n resetTextMessage();\n setNavScreen();\n });\n}", "static save_relation(win, ename, cname){\n const comment= {};\n //\n //Get the value of the start \n comment[\"start\"]=win.document.getElementById(\"start\").value;\n //\n //Get the end of the comment\n comment[\"end\"]= win.document.getElementById(\"end\").innerText;\n //\n //Get the is_a selection option inorder to test if selected\n const is_a=win.document.getElementById(\"is_a\").checked;\n //\n //if the is_a is selected save the type of the relation as an is_a \n if(is_a){\n comment[\"type\"]={\"type\":\"is_a\"}; \n }\n //\n //GEt the option for the has_a relation to test if it is selected \n const has_a =win.document.getElementById(\"has_a\").checked;\n //\n //If selected save the type of the relaation as a has a and also include the\n //title of the relation \n if(has_a){\n comment[\"type\"]={\"type\":{\"has_a\":win.document.getElementById(\"title\").value}};\n }\n //\n //update the database \n databases[page_graph.dbname].entities[ename].columns[cname].alter(comment);\n }", "static async saveComment(token, username, id, user_id) {\n let res = await this.request(`comments/${username}/${id}/save`, token, { user_id }, 'post');\n return { comment: res.comment };\n }", "function editComment(tree, id, content) {\n\n}", "put (comment) { return Api().put('comment/' + commentId, comment)}", "function saveComments() {\n\n localStorage.setItem('comments', JSON.stringify(sectionComments));\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A wrapper object around a Leaflet layer object that is used for defining layer control behavior. layer: The layer object to be controlled (REQUIRED). name: The caption that should be used to display the layer in the layer control (REQUIRED). groupName: If more than one LayerControlItem is given the same groupName, they will combined in a select (dropdown) control which appears as a single entry in the layer control. The groupName will be used as a caption. (DEFAULT = name argument). base: boolean true if this is a base layer, false if this is an overlay layer (DEFAULT = false). labelable: boolean true if this layer can be labelled (DEFAULT = false).
function LayerControlItem(layer, name, groupName, base, labelable) { this.layer = layer; this.name = name; this.groupName = groupName || name; this.base = !!base; this.labelable = !!labelable; }
[ "function addBasicLayer(layer) {\r\n var thisLayer = null;\r\n if (layer.objects)\r\n thisLayer = L.geoJson(layer.objects.features);\r\n else if (layer.tiles)\r\n thisLayer = L.tileLayer(layer.tiles, { id: layer.name });\r\n // else.. add other types of layers\r\n if (thisLayer != null) {\r\n thisLayer.basicLayer = true;\r\n if (layer.basicID)\r\n thisLayer.basicID = layer.basicID;\r\n layerControl.addOverlay(thisLayer, layer.name);\r\n if (layer.default && layer.default == 1) {\r\n thisLayer.addTo(map);\r\n layerControl._update();\r\n }\r\n }\r\n}", "function LayerControlGroup(layerControlItems, name, base) {\n this.layerControlItems = layerControlItems;\n this.name = name;\n this.base = !!base;\n\n this._anyLayerVisible = function (map) {\n for (var i in this.layerControlItems) {\n if (map.hasLayer(this.layerControlItems[i].layer)) return true;\n }\n return false;\n };\n\n this.anyLabelable = function () {\n for (var i in this.layerControlItems) {\n if (this.layerControlItems[i].labelable) return true;\n }\n return false;\n };\n\n // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)\n this.createVisibleInputElement = function (map) {\n var checked = this._anyLayerVisible(map);\n if (this.base) {\n var radioHtml = '<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"leaflet-base-layers\"';\n //var radioHtml = '<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"leaflet-exclusive-group-layer-' + this.group + '\"';\n if (checked) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n var radioFragment = document.createElement('div');\n radioFragment.innerHTML = radioHtml;\n radioFragment.firstChild.layerControlElementType = LayerControlElementType.VisibilityRadio;\n radioFragment.firstChild.groupName = this.name;\n return radioFragment.firstChild;\n } else {\n var input = document.createElement('input');\n input.type = 'checkbox';\n input.className = 'leaflet-control-layers-selector';\n input.defaultChecked = checked;\n input.layerControlElementType = LayerControlElementType.VisibilityCheckbox;\n input.groupName = this.name;\n return input;\n }\n };\n\n this.createLabelInputElement = function () {\n var input = document.createElement('input');\n input.type = 'checkbox';\n input.className = 'leaflet-control-layers-selector';\n input.defaultChecked = false;\n input.layerControlType = \"label\";\n input.layerControlElementType = LayerControlElementType.LabelCheckbox;\n input.groupName = this.name;\n return input;\n };\n\n this.createNameSpanElement = function () {\n var span = document.createElement('span');\n span.innerHTML = ' ' + this.name;\n span.groupName = name;\n return span;\n };\n\n // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)\n this.createSelectElement = function (map) {\n // NOTE: Opening the select element and displaying the options list fires the select.onmouseout event which \n // propagates to the div container and collapses the layer control. The onmouseout handler below will\n // stop this event from propagating. It has an if-else clause because IE handles this differently than other browsers.\n var selectHtml = '<select class=\"leaflet-control-layers-selector\" onmouseout=\"if (arguments[0]) {arguments[0].stopPropagation();} else {window.event.cancelBubble();}\">';\n\n for (var i = 0; i < this.layerControlItems.length; i++) {\n selectHtml += '<option value=\"' + this.layerControlItems[i].name + '\"';\n if (map.hasLayer(this.layerControlItems[i].layer)) {\n selectHtml += \" selected='selected'\";\n }\n selectHtml += '>' + this.layerControlItems[i].name + \"</option>\";\n }\n selectHtml += '</select>';\n\n var selectFragment = document.createElement('div');\n selectFragment.innerHTML = selectHtml;\n selectFragment.firstChild.layerControlElementType = LayerControlElementType.LayerSelect;\n selectFragment.firstChild.groupName = this.name;\n return selectFragment.firstChild;\n };\n}", "function createLayer(layer){\n\t\t\t\tvar id = layer.getAttribute(\"label\");\n\t\t\t\tvar myLayer;\n\t\t\t\ttries[id]++;\n\t\t\t\t// Set layer properties on startup if specified on url\n\t\t\t\tif (queryObj.layer && queryObj.layer != \"\") {\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1) {\n\t\t\t\t\t\tif (layerObj[id]){\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": layerObj[id].opacity,\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\": layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t// not found on url, not visible\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// FeatureServer tlb 10/19/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layerObj[id]) \n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\" : layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\" : layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t// Set layer properties from config.xml file\n\t\t\t\t} else {\n\t\t\t\t\t// MapServer\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t} \n\t\t\t\t\t// FeatureServer tlb 9/28/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// 3-21-22 check if loaded\n\t\t\t\tmyLayer.on(\"load\", layerLoadedHandler);\n\t\t\t\tmyLayer.on(\"error\", layerLoadFailedHandler);\n\t\t\t}", "function LayerGroup( p_name, p_layers, p_visible ) {\n this.name = p_name;\n this.visible = p_visible || true;\n this.layers = p_layers || [];\n\n var _this = this;\n\n // Adds a layer to the group and sets the visibility to the group's.\n this.addLayer = function( layer ) {\n layer.setVisible( this.visible );\n this.layers.push( layer );\n }\n\n // Removes a layer from the group\n this.removeLayer = function( layer ) {\n var index = this.layers.indexOf( layer );\n if ( index > -1 ) {\n return this.layers.splice( index, 1 );\n }\n }\n \n // Toggles whether or not contained markers are visible on map.\n this.setVisible = function( p_visible ) {\n this.visible = p_visible;\n this.layers.forEach( function( layer, index, array ) {\n layer.setVisible( _this.visible );\n });\n if ( checkbox ) { // Update the linked checkbox to relfect change if linked\n checkbox.prop(\"checked\", this.visible);\n }\n }\n\n // Links a checkbox to toggle this layer\n var checkbox;\n this.linkCheckbox = function( p_checkbox ) {\n checkbox = p_checkbox;\n // Update the checkbox to reflect the layer's state\n checkbox.prop(\"checked\", true);\n checkbox.change( function() {\n _this.setVisible( $(this).is(':checked') );\n });\n }\n}", "function create_map_base_layer(tile_layer_name) {\n let layer;\n switch (tile_layer_name) {\n case 'osm':\n layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: 'Map data © <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors'\n });\n break;\n case 'googleSat':\n layer = new L.TileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {\n subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],\n attribution: 'Map data © <a href=\"https://www.google.com/maps/\">Google Maps</a>'\n });\n break;\n default: // default to the Google Satellite view.\n layer = new L.TileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {\n subdomains: ['mt0', 'mt1', 'mt2', 'mt3']\n });\n break;\n }\n return layer;\n}", "function LayerBase(title, id) {\n this.id = \"layer-\" + id;\n this.title = title;\n this.handle_id = \"layerhandle_\" + id;\n\n this.timeline = new Timeline(this);\n}", "function setLayer(layerName, object) {\n\t\tcore.layers[layerName] = object;\n\t}", "function tileLayerFromName(name) {\n var all = _mapUxService.getAllBaseLayerConfigs();\n var opt = all[name] || all.osm || all.dark2 || all.ogWorld || all.googleTerrain || all.googleHybrid || all.googleRoadmap || all.googleSatellite;\n if (opt.type === 'xyz') {\n var tilelayer = new L.TileLayer(opt.url, opt.options || opt.layerParams);\n return tilelayer;\n }\n throw 'not implemented tilelayer creation from ' + JSON.stringify(opt);\n }", "addLayer(name) {\n this.layers[name] = new layer_1.Layer();\n }", "function initLayerControl() {\n // set layer control options if it does not already exist\n /* if (!self.layerControlOptions) {\n self.layerControlOptions = self.getScopeDefaults().layerControlOptions;\n }*/\n \n /*self._layerControl = new L.Control.Layers({\n \"Basemap\": self._baseLayer\n }, {}, self.layerControlOptions).addTo(self._map);*/\n }", "getLayer(name) {\n if (this.layers.has(name)) {\n return this.layers.get(name);\n }\n else if (this.parallaxLayers.has(name)) {\n return this.parallaxLayers.get(name);\n }\n else if (this.uiLayers.has(name)) {\n return this.uiLayers.get(name);\n }\n else {\n throw `Requested layer ${name} does not exist.`;\n }\n }", "setLayer(layer) {\n this.layer = layer;\n }", "function addLayerToControlLayer(featureCollection, layer) {\n var layer_display_name, display_name, name\n if (featureCollection.type == \"FeatureCollection\") {\n var type = \"Devices\"\n if (featureCollection.features.length > 0) {\n type = (featureCollection.features[0].geometry.type == \"Point\") ? \"Devices\" : \"Zones\"\n }\n layer_display_name = Util.isSet(featureCollection.properties) && Util.isSet(featureCollection.properties.layer_display_name) ? featureCollection.properties.layer_display_name : type\n display_name = featureCollection.properties.display_name\n name = featureCollection.properties.name\n } else if (Array.isArray(featureCollection) && featureCollection.length > 0) { // collections of features gets the name of the type of the first element\n layer_display_name = (featureCollection[0].geometry.type == \"Point\") ? \"Devices\" : \"Zones\"\n display_name = Util.isSet(featureCollection[0].properties.display_type) ? featureCollection[0].properties.display_type : featureCollection[0].properties.type\n name = Util.isSet(featureCollection[0].properties.layer_name) ? featureCollection[0].properties.layer_name : null\n } else { // layers from one element gets the name from that element\n layer_display_name = (featureCollection.geometry.type == \"Point\") ? \"Devices\" : \"Zones\"\n display_name = featureCollection.properties.display_name\n name = featureCollection.properties.name\n }\n if (_layerControl) {\n _layerControl.addGipOverlay(layer, display_name, layer_display_name)\n if (name) {\n // console.log('Map::addLayerToControlLayer: Info - Adding', name)\n _gipLayers[name] = layer\n } else {\n console.log('Map::addLayerToControlLayer: featureCollection has no layer name', featureCollection)\n }\n } else {\n console.log('Map::addLayerToControlLayer: _layerControl not set', featureCollection)\n }\n}", "guiLayer(name, opts){\n\n let layer = new GUILayer(this.scene, opts);\n this.scene.layers.set(name, layer);\n return layer;\n\n }", "function createLayer(_name) {\n\tvar _prev = getLayerByName(_name);\n\n\tif (_prev != null) {\n\n\t} else {\n\t\treturn new Layer(_name);\n\t}\n}", "function Layer(projection, proxy) {\n 'use strict';\n /**\n * interact stock a reference of the current interact of the map\n * @type {Interaction}\n */\n var interact = null;\n /**\n * ListLayers contains all Layers of the map\n * @type {Array}\n */\n this.ListLayers = [];\n /**\n * selectableLayers contains all selectable Layers of the map\n * @type {Array}\n */\n this.selectableLayers = [];\n\n /**\n * defaultWMTSResolutions store the resolution array if defaultbackground is a WMTS layer\n\t * @type {Array}\n */\t \n\tthis.defaultWMTSResolutions = [];\n\t\n /**\n * defaultBackground layer name \n\t * @type {string}\n */\t \n\tthis.defaultBackground = '';\n\t\n\tthis.setDefaultBackGround = function(layerName){\n\t\tthis.defaultBackground = layerName;\n\t};\t\n\t\n /**\n * featureLayerGis is the Feature Layer object\n * @type {Feature}\n */\t \n this.featureLayerGis = new Feature(projection, proxy);\n /**\n * rasterLayerGis is the Raster Layer object\n * @type {LayerRaster}\n */\n this.rasterLayerGis = new LayerRaster(projection, proxy);\n /**\n * Layer Method\n * getLayers is a getter to all Layers\n * @returns {Array} is an array with all data layers of the map\n */\n this.getLayers = function(){\n return this.ListLayers;\n };\n\n /**\n * Layer Method\n * getVisibleLayers is a getter to all layers and his visible value\n * @returns {Array} is an array with all layers and his visible value of the map\n */\n this.getVisibleLayers = function(){\n var ListVisibleLayers = [];\n var RasterLayer = this.getLayersRasterMap();\n var FeatureLayer = this.getLayersFeatureMap();\n for(var i = 0; i < RasterLayer.length; i++){\n ListVisibleLayers.push(\"'\"+RasterLayer[i].get('title')+\"'\");\n ListVisibleLayers.push(RasterLayer[i].getVisible());\n }\n for(var j = 0; j < FeatureLayer.length; j++){\n ListVisibleLayers.push(\"'\"+FeatureLayer[j].get('title')+\"'\");\n ListVisibleLayers.push(FeatureLayer[j].getVisible());\n }\n return ListVisibleLayers;\n };\n\n /**\n * Layer Method\n * getSelectedLayers is a getter to all selectable Layers\n * @returns {Array} is an array with all selectable layers of the map\n */\n this.getSelectableLayers = function(){\n return this.selectableLayers;\n };\n\n /**\n * Layer Method\n * getFeatureLayers is a getter to Feature Layer Object\n * @returns {Feature|*}\n */\n this.getFeatureLayers = function(){\n return this.featureLayerGis;\n };\n\n /**\n * Layer Method\n * getRasterLayers is a getter to Raster Layer Object\n * @returns {LayerRaster|*}\n */\n this.getRasterLayers = function(){\n return this.rasterLayerGis;\n };\n\n /**\n * Layer Method\n * setInteract is a setter to define the interact reference\n * @param newInteract\n */\n this.setInteract = function(newInteract){\n interact = newInteract;\n };\n\n /**\n * Layer Method\n * addLayerRaster add a background map at the ListLayer\n * @param backGround is an array with all parameters to define a background\n */\n this.addLayerRaster = function(backGround){\n var name = this.rasterLayerGis.createRasterLayer(backGround);\n this.ListLayers.push(name);\n };\n\n /**\n * Layer Method\n * addWMSLayerRaster add a background map at the ListLayer to a WMS\n * @param wms is an array with all parameters to define a wms layer\n */\n this.addWMSLayerRaster = function(wms){\n var wmsLibelle = wms[0];\n var wmsServer = wms[1];\n var wmsUrl = wms[2];\n var wmsLayer = wms[3];\n var wmsAttribution = wms[4];\n this.rasterLayerGis.createWMSLayer(wmsLibelle, wmsServer, wmsUrl, wmsLayer, wmsAttribution);\n this.ListLayers.push(wmsLibelle);\n };\n\n /**\n * Layer Method\n * addWMTSLayerRaster add a background map at the ListLayer to a WMTS\n * @param wmts is an array with all parameters to define a wmts layer\n */\n this.addWMTSLayerRaster = function(wmts){\n var wmtsLibelle = wmts[0];\n var wmtsServer = wmts[1];\n var wmtsUrl = wmts[2];\n var wmtsProj = wmts[3];\n var wmtsReso = wmts[4];\n var wmtsOrigin = wmts[5];\n var wmtsAttribution = wmts[6];\n\t\tvar isDefault = this.isDefaultBackGround(wmtsLibelle);\n\t\tvar wmtsResolutions = this.rasterLayerGis.createWMTSLayer(wmtsLibelle, wmtsServer, wmtsUrl, wmtsProj, wmtsReso, wmtsOrigin, wmtsAttribution, isDefault);\n\t\t//If DefaultBackground then get the resolutions to apply it to the view\n\t\tif(wmtsResolutions !== undefined && wmtsResolutions !== '' && isDefault){\n\t\t\tthis.setDefaultWMTSResolutions(wmtsResolutions);\n\t\t}\n\t\tthis.ListLayers.push(wmtsLibelle);\n };\n\n /**\n * Layer Method\n * addWMSQueryLayerRaster add a background map at the ListLayer to a WMS\n * @param wms is an array with all parameters to define a wms layer\n */\n this.addWMSQueryLayerRaster = function(wms){\n var wmsOrder = wms[0];\n var wmsName = wms[1];\n var wmsServer = wms[2];\n var wmsUrl = wms[3];\n var wmsLayer = wms[4];\n var wmsVisbility = wms[5];\n var wmsAttribution = wms[6];\n var wmsResoMin = wms[7];\n var wmsResoMax = wms[8];\n this.featureLayerGis.createWMSQueryLayer(wmsName, wmsServer, wmsUrl, wmsLayer, wmsVisbility, wmsAttribution, wmsResoMin, wmsResoMax);\n this.ListLayers.push(wmsOrder +'-'+ wmsName);\n };\n\n /**\n * Layer Method\n * addWFSLayer add a layer map at the ListLayer to a WFS\n * @param wfs is an array with all parameters to define a wfs layer\n * @param heatmap define the heatmap parameters\n * @param thematic define the thematic parameters\n * @param cluster define the cluster parameters\n * @param thematicComplex define the thematic complex parameters\n */\n this.addWFSLayer = function(wfs, heatmap, thematic, cluster, thematicComplex){\n var wfsIdLayer = wfs[0];\n var wfsServer = wfs[1];\n var wfsUrl = wfs[2];\n var wfsProj = wfs[3];\n var wfsQuery = wfs[4];\n var wfsAttribution = wfs[5];\n var wfsLayers = this.featureLayerGis.createWFSLayer(wfsIdLayer, wfsServer, wfsUrl, wfsProj, wfsQuery, wfsAttribution, heatmap, thematic, cluster, thematicComplex);\n for(var i = 0; i < wfsLayers.length; i++) {\n this.ListLayers.push(wfsLayers[i]);\n }\n };\n\n /**\n * Layer Method\n * addLayerVector add a layer map at the ListLayer\n * @param data is an array with all parameters to define a specific layer\n * @param format is the type of data\n * @param heatmap define the heatmap parameters\n * @param thematic define the thematic parameters\n * @param cluster define the cluster parameters\n * @param thematicComplex define the thematic complex parameters\n */\n this.addLayerVector = function(data, format, heatmap, thematic, cluster, thematicComplex){\n var names = this.featureLayerGis.addLayerFeature(data, format, heatmap, thematic, cluster, thematicComplex);\n for(var i = 0; i < names.length; i++) {\n this.ListLayers.push(names[i]);\n this.selectableLayers.push(names[i].split('-')[1]);\n }\n };\n\t\n\t/**\n * Layer Method\n * returns true if the given layerName is the defaultbackground\n * @param layerName is the name of a layer\n */\n\tthis.isDefaultBackGround = function(layerName){\n\t\treturn(layerName === this.defaultBackground);\n };\n\n\t/**\n\t* activateDefaultBackGround activates the default background to initiate the map\n\t*/\n\tthis.activateDefaultBackGround = function(){\n\t\tfor (var layerMap = 0; layerMap < this.ListLayers.length; layerMap++){\n if(this.ListLayers[layerMap] === this.defaultBackground) {\n if (this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap]) !== undefined){\n\t\t\t\t\tthis.rasterLayerGis.setRasterVisibility(this.ListLayers[layerMap], true);\n\t\t\t\t}\n }\n }\n\t};\n\t\n\t\n /**\n * Layer Method\n * getLayersRasterMap is a getter to all Rasters Layers\n * @returns {Array} is an array with all raster layers of the map\n */\n this.getLayersRasterMap = function(){\n var ListLayersRasterMap = [];\n for (var layerMap = 0; layerMap < this.ListLayers.length; layerMap++){\n if(this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap])!== undefined) {\n ListLayersRasterMap.push(this.rasterLayerGis.getRasterByName(this.ListLayers[layerMap]));\n }\n }\n return ListLayersRasterMap;\n };\n\n /**\n * Layer Method\n * getLayersFeatureMap is a getter to all Features Layers\n * @returns {Array} is an array with all feature layers of the map\n */\n this.getLayersFeatureMap = function(){\n var ListLayersFeatureMap = [];\n for (var layerMap = this.ListLayers.length-1; layerMap >= 0; layerMap--){\n var layerMapName = this.ListLayers[layerMap].split('-')[1];\n if(this.featureLayerGis.getFeatureByName(layerMapName)!== undefined) {\n ListLayersFeatureMap.push(this.featureLayerGis.getFeatureByName(layerMapName));\n }\n }\n return ListLayersFeatureMap;\n };\n\n /**\n * Layer Method\n * getLayersMap is a getter to all Layers in groups\n * @returns {Array} is an array with all data layers in groups\n */\n this.getLayersMap = function(){\n var ListLayersMap = [];\n this.ListLayers.sort();\n ListLayersMap.push(new ol.layer.Group({\n title:'Fonds de plan',\n layers: this.getLayersRasterMap()\n }));\n ListLayersMap.push(new ol.layer.Group({\n title:'Couches',\n layers: this.getLayersFeatureMap()\n }));\n ListLayersMap.push(interact.getDraw().getDrawLayer());\n ListLayersMap.push(interact.getMeasure().getMeasureLayer());\n if(interact.getEditor() !== null){\n ListLayersMap.push(interact.getEditor().getEditLayer());\n }\n return ListLayersMap;\n };\n\n /**\n * Layer Method\n * showLayer enable or disable a visibility of a layer\n * @param layerName the name of the layer\n * @param visible the indicator of visibility\n */\n this.showLayer = function(layerName, visible){\n if(this.rasterLayerGis.getRasterByName(layerName)!== undefined) {\n this.rasterLayerGis.getRasterByName(layerName).setVisible(visible);\n }\n if(this.featureLayerGis.getFeatureByName(layerName)!== undefined) {\n this.featureLayerGis.getFeatureByName(layerName).setVisible(visible);\n }\n };\n\t\n\tthis.setDefaultWMTSResolutions = function(WMTSResolutions) {\n\t\tthis.defaultWMTSResolutions = WMTSResolutions;\n\t};\n\t\n\tthis.getDefaultWMTSResolutions = function() {\n\t\treturn this.defaultWMTSResolutions;\n\t};\n}", "setLayer({layer}) {\n this.layer = layer\n }", "addLayer(layer) {\n if (typeof layer.onSelect !== 'function') {\n layer.onSelect = null;\n };\n\n this.layers.push({ \n tree: rbush(), \n alpha: layer.alpha, \n visible: layer.visible,\n visibleCaption: layer.visibleCaption,\n caption: layer.caption,\n selectable: layer.selectable, \n selectChangeStoke: layer.selectChangeStoke,\n selectStrokeWidth: layer.selectStrokeWidth,\n selectStrokeColor: layer.selectStrokeColor,\n selectChangeFill: layer.selectChangeFill,\n selectFillColor: layer.selectFillColor,\n onSelect: layer.onSelect });\n return this.layers.length-1;\n }", "function Layer () {\n this._components = [];\n this._componentIsDirty = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function clears the memory of the calculator
function clearMemory(){ $values.innerText=0; numberIsClicked=false; operatorIsClicked=false; equalsToIsClicked=false; myoperator=""; numberOfOperand=0; }
[ "function clearCalculator() {\n calculator.displayNumber = '0';\n calculator.operator = null;\n calculator.firstNumber = null;\n calculator.waitingForSecondNumber = false;\n}", "function clearCalculator() {\n calculator.displayNumber = \"0\";\n calculator.operator = null;\n calculator.firstNumber = null;\n calculator.waitingForSecondNumber = false;\n}", "function clearScreen(){\n calculator.displayValue='0';\n calculator.firstOperand=null;\n calculator.waitingForSecondOperand=true;\n calculator.operator=null;\n \n}", "function clearClicked(){\n console.log(\"clearClicked\");\n $(\"#result\").empty();\n $(\"#operator\").empty();\n $(\"#firstNumber\").empty();\n $(\"#secondNumber\").empty();\n calc.init(); // reset state of calc object\n}", "function allClear() {\n chosenOperator = '';\n firstOperand = '';\n chosenNumber = '';\n operatorCalc = false; \n equalsCalc = false; \n calcResult = '';\n resultDisplay.style.fontSize = '2.5em';\n}", "clear() {\n // creates the previousOperand, currentOperand, and operation properties that will be manipulated by calculator functionality\n this.previousOperand = \"\";\n this.currentOperand = \"\";\n this.operation = undefined;\n }", "function clear() {\n calc.calculation = []\n calc.screens.value = ''\n calc.screens.placeholder = '01134'\n}", "function Clear(){\n console.log(\"Clearing\");\n ResetOperators();\n output.innerHTML = 0;\n operatorToggle= false;\n decimal = false;\n lastOperator = \"\";\n numberStorage = 0;\n}", "function resetCalculator(){\n calculator.screenValue ='0';\n calculator.firstOperand = null; \n calculator.waitingForSecondOperand = false;\n calculator.operator = null;\n}", "function clearData() {\n clearScreen();\n firstOperand, secondOperand = \"\";\n operator = null;\n}", "function clear(display) {\n // reset values\n Calc.num1 = \"0\";\n Calc.num2 = \"0\";\n Calc.result = \"0\";\n Calc.operator = \"\";\n\n // reset display\n updateDisplay(display);\n} // end clear", "function resetCalculator() {\n calculator.outputValue = \"0\";\n calculator.firstValue = null;\n calculator.secondOperand = false;\n calculator.operator = null;\n}", "function resetCalculator() {\n calculator.displayValue = '0';\n calculator.firstOperand = null;\n calculator.waitingForSecondOperand = false;\n calculator.operator = null;\n console.log(calculator);\n }", "function clear(){\n //clear view\n setView([]);\n //clear numbers\n setNumbers([]);\n //clear operators\n setOperator([]);\n //clear numAux\n setAux([]);\n }", "clear() {\n this.lastOperand = \"\";\n this.currOperand = \"\";\n this.operator = undefined;\n }", "function clearCalculatorObject(){\n calculatorObject = {\n inputOne: '',\n operationInput: '',\n inputTwo: '',\n }\n}", "function clear() {\n state = {\n operandOne: \"0\",\n operandTwo: undefined,\n operation: undefined,\n result: undefined\n };\n }", "function clearAll() {\n\texpression.value = \"\";\n\toperatorMode = true;\n\tdecimalMode = true;\n\tnegativeSign = false;\n}", "_resetAll() {\n this._firstValue = 0;\n this._operatorValue = '';\n this._awaitingNextValue = false;\n this._calculatorDisplay.textContent = '0';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add api version header to endpoint operation
function addApiVersionHeader(endpointRequest) { var api = endpointRequest.service.api; var apiVersion = api.apiVersion; if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) { endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion; } }
[ "function addApiVersionHeader(endpointRequest) {\n\t var api = endpointRequest.service.api;\n\t var apiVersion = api.apiVersion;\n\t if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {\n\t endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;\n\t }\n\t}", "function addApiVersionHeader(endpointRequest) {\n var api = endpointRequest.service.api;\n var apiVersion = api.apiVersion;\n\n if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {\n endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;\n }\n }", "setApiVersion(version: string) {\n this.apiVersion = version;\n }", "function setGitHubApiVersionHeader(config) {\n if (gitHubApiUtils.isGitHubApiUrl(config.url)) {\n config.headers['Accept'] = gitHubApiVersionHeader;\n }\n return config;\n }", "function setGitHubApiVersionHeader(config) {\n if (gitHubApiUtils.isGitHubApiUrl(config.url)) {\n config.headers['Accept'] = gitHubApiVersionHeader;\n }\n return config;\n }", "function handleVersion(req, res, next) {\n\tvar version = req.params.version;\n\tif (validator.isValid(version, 'ApiVersion')) {\n\t\treq.api_version = version;\n\t\tnext();\n\t} else {\n\t\tvar error = {};\n\t\terror.msg = \"Bad ApiVersion: \" + req.originalUrl;\n\t\tnext(new ClientError(error));\n\t}\n}", "function detectApiVersionMiddleware(req, res, next) {\n const version = parseInt(req.headers[\"n-api-version\"], 10) || parseInt(req.params.apiVersion, 10) || 0;\n req.apiVersion = res.apiVersion = version;\n\n next();\n}", "function logComponentVersion(response, version, lambdaId) {\n prefixResponseHeader(response, constants_1.HTTP_HEADERS.x0Components, `w=${version},wi=${lambdaId}`);\n}", "static defaultEndpoint(req : $Request, res : $Response) {\n res.json({\n version: '1.0',\n });\n }", "function versionApi(enable, ver, baseUrl = '/', endpoint = '') {\n let url = '';\n\n if (!ver)\n enable = false;\n\n if (enable && endpoint)\n url = urljoin(`/v${version(ver).major}`, baseUrl, endpoint);\n else if (enable && !endpoint)\n url = urljoin(`/v${version(ver).major}`, baseUrl);\n else if (!enable && endpoint)\n if (baseUrl === '/')\n url = urljoin(endpoint);\n else\n url = urljoin(baseUrl, endpoint);\n else if (!enable && !endpoint)\n url = urljoin(baseUrl);\n\n if (!_.startsWith(url, '/'))\n url = `/${url}`;\n\n return url;\n}", "function versionResponse() {\n console.log('Reporting version', version);\n return new Response(JSON.stringify({ version : version }), {\n headers : new Headers({ 'Content-Type' : 'application/json' })\n });\n }", "static custom(version) {\n return new PayloadFormatVersion(version);\n }", "get apiHeader() {\n const token = this.apiKey ? 'Bearer ' + this.apiKey : '';\n const apiHeader = new HttpHeaders({\n Authorization: token,\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-cache',\n Pragma: 'no-cache',\n Expires: 'Sat, 01 Jan 2000 00:00:00 GMT'\n });\n return apiHeader;\n }", "static getApiAuthHeader() {\n return {'authorization': `bearer ${Auth.getToken()}`};\n }", "async useLatestApiVersion() {\n try {\n this.setApiVersion(await this.retrieveMaxApiVersion());\n }\n catch (err) {\n // Don't fail if we can't use the latest, just use the default\n this.logger.warn('Failed to set the latest API version:', err);\n }\n }", "_attachToApi(restApi) {\n if (this.restApiId && this.restApiId !== restApi.restApiId) {\n throw new Error('Cannot attach authorizer to two different rest APIs');\n }\n this.restApiId = restApi.restApiId;\n const deployment = restApi.latestDeployment;\n const addToLogicalId = core_1.FeatureFlags.of(this).isEnabled(cx_api_1.APIGATEWAY_AUTHORIZER_CHANGE_DEPLOYMENT_LOGICAL_ID);\n if (deployment && addToLogicalId) {\n let functionName;\n if (this.handler instanceof lambda.Function) {\n // if not imported, attempt to get the function name, which\n // may be a token\n functionName = this.handler.node.defaultChild.functionName;\n }\n else {\n // if imported, the function name will be a token\n functionName = this.handler.functionName;\n }\n deployment.node.addDependency(this);\n deployment.addToLogicalId({\n authorizer: this.authorizerProps,\n authorizerToken: functionName,\n });\n }\n }", "getClientVersion() {\n const query_params = {\n key: this.apiKey\n }\n\n return fetch(BASE_URL + DOTA_VERSION + 'GetClientVersion/v1/?' + handleQueryParams(query_params))\n .then(response => responseHandler(response))\n .catch(e => e)\n }", "getVersion(api_url, options) {\n return this.request(api_url, 'apiinfo.version', [], options);\n }", "static addApiServiceSpec(servicename,spec){Env.api.services[servicename]=spec}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a Movement into the Movement List
addMovement(e) { e.preventDefault(); let movement = { id: new Date(), description: this.state.description, amount: this.state.amount }; this.setState({ movements: [...this.state.movements, movement] }); this.setState({ description: '', amount: 0 }); }
[ "function addMove(){\n return data.push(newMove());\n }", "function Add(unit : GameObject){\n\tunit.GetComponent(UnitControl).hasMoved = true;\n\tunits[TotalUnitCount] = unit;\n\tTotalUnitCount++;\n\tUnitsMoved++;\n}", "addMove() {\n\t\tif (Math.ceil(this.allMoves / this.players.length) == 1) {\n\t\t\tthis.moves++;\n\t\t}\n\t\tthis.allMoves = 0;\n\t}", "addMove(tile){\n let moveOccupant = tile.getOccupant();\n if (!moveOccupant){\n this.moves.push(tile);\n }\n }", "pushMove (move) {\n // const origPoint = this._currPoint\n this._moves.push(move)\n this._currPoint = this._currPoint.pointAfterMove(move)\n this._currPoint.occupied = true\n // console.log(`push move from ${origPoint} to ${this._currPoint}`)\n }", "addItem (data) {\n var item = { name: data.item, x: data.x, y: data.y };\n this.currentRoom.items.push(item);\n this.spawnItem(item);\n\n this.evalEvent(data.item);\n }", "customMovement(){}", "addMove(type, options) {\n this.moves.push(new type(this, options));\n return this;\n }", "function addMove() {\n moves++;\n movesSpan.textContent = moves;\n if (moves === 1) {\n movesPlural.textContent = 'Move';\n } else {\n movesPlural.textContent = 'Moves';\n }\n}", "addShot(shot, ordinance) {\n this.shots.push(shot);\n }", "move(movement) {\n\t\tconst firstID = movement[0];\n\t\tconst secondID = movement[1];\n\t\tconst firstHexagon = this.hexagonList.get(IDToKey(firstID));\n\t\tconst secondHexagon = this.hexagonList.get(IDToKey(secondID));\n\t\tconst unit = firstHexagon.getUnit();\n\t\tfirstHexagon.setUnit(null);\n\t\tsecondHexagon.setUnit(unit);\n\t\tunit.setPosition(secondID);\n\t}", "updateMovement() {\n this.movement = this.generate(this[this.moveAlong]);\n }", "function getMovements() {\n for (var j = 0; j < listElevators.length; j++) {\n movList.push(listElevators[j].movement);\n }\n}", "function giveSword() {\n target.items.push(items.sword);\n\n}", "function addMovement(req, res) {\n\tvar query = req.body;\n\tvar type = parseInt(query.type) + 1;\n\tvar type0 = query.type;\n\tvar date = query.date;\n\tvar name = query.name;\n\tvar amount = query.amount;\n\tif (isValidType(type) && isValidDate(date) && isValidName(name)) {\n\t\tconsole.log(\"Adding movement: \" + name);\n\t\tvar sql = \"INSERT INTO movements(typeID, name, movementDate, amount) VALUES ($1, $2, $3, $4) returning movementID\";\n\t\tvar params = [type, name, date, amount];\n\n\t\tdbTransaction(sql, params, function(error, result) {\n\t\t\tif (error || result == null) {\n\t\t\t\tres.writeHead(500).json({success: false, data: error});\n\t\t\t} else {\n\t\t\t\tres.writeHead(200, {'Content-Type': 'application/json'});\n\t\t\t\tres.end(JSON.stringify({success: true, type: type0, movementID: result[0].movementid}));\n\t\t\t}\n\t\t})\n\t}\n\telse\n\t{\n\t\tres.status(500).json({success: false, data: \"Invalid input.\"});\n\t}\n}", "pushMove(move){\n\n this.moveQueue.push(move);\n this.checkIfGameover(move);\n move.piece.setHasMoved();\n this.moveCount++;\n }", "add( bullet ){\r\n\r\n this.bullets[this.bullets.length] = bullet;\r\n }", "function add(movementShape) {\n\t\tvar div = getRandomDiv();\n\t\tif (movementShape == \"circle\") {\n\t\t\tdiv.style.borderRadius = '50px';\n\t\t\tdocument.getElementById('circle').appendChild(div);\n\t\t\tmoveInCircle(div);\n\t\t}\n\t\tif (movementShape == \"rectangular\") {\n\t\t\tdocument.getElementById('rectangular').appendChild(div);\n\t\t\tmoveInRectangular(div);\n\t\t}\n\t\tif (movementShape == \"ellipse\") {\n\t\t\tdiv.style.borderRadius = '50px';\n\t\t\tdiv.style.width = '70px';\n\t\t\tdocument.getElementById('ellipse').appendChild(div);\n\t\t\tmoveInEllipse(div);\n\t\t}\n\t}", "static addMovement(tween, direction) {\n let evnt = AnimationHandler.getNextEvent()\n if (evnt === null) {\n evnt = new SynchronousAnimations(tween, direction);\n AnimationHandler.eventQueue.push(evnt);\n } else {\n evnt.addMovement(tween, direction);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function Reveal cell if there no bomb around
function reveal(_index) { if (!$cell[_index].classList.contains('cell-bomb')) { $cell[_index].classList.add('secure'); _index = parseInt($cell[_index].getAttribute('data-index')) - 1; if (!$cell[_index + 1].classList.contains('cell-bomb')) { $cell[_index + 1].classList.add('secure'); if (bombArounds[_index + 1] > 0) $cell[_index + 1].innerHTML = bombArounds[_index + 1]; } if (!$cell[_index - 1].classList.contains('cell-bomb')) { $cell[_index - 1].classList.add('secure'); if (bombArounds[_index - 1] > 0) $cell[_index - 1].innerHTML = bombArounds[_index - 1]; } if (!$cell[(_index - cols)].classList.contains('cell-bomb')) { $cell[_index - cols].classList.add('secure'); if (bombArounds[_index - cols] > 0) $cell[_index - cols].innerHTML = bombArounds[_index - cols]; } if (!$cell[(_index - cols) + 1].classList.contains('cell-bomb')) { $cell[(_index - cols) + 1].classList.add('secure'); if (bombArounds[(_index - cols) + 1] > 0) $cell[(_index - cols) + 1].innerHTML = bombArounds[_index - cols + 1]; } if (!$cell[(_index - cols) - 1].classList.contains('cell-bomb')) { $cell[(_index - cols) - 1].classList.add('secure'); if (bombArounds[(_index - cols) - 1] > 0) $cell[(_index - cols) - 1].innerHTML = bombArounds[_index - cols + 1]; } if (!$cell[(_index + cols)].classList.contains('cell-bomb')) { $cell[(_index + cols)].classList.add('secure'); if (bombArounds[(_index + cols)] > 0) $cell[(_index + cols)].innerHTML = bombArounds[_index + cols]; } if (!$cell[(_index + cols) + 1].classList.contains('cell-bomb')) { $cell[(_index + cols) + 1].classList.add('secure'); if (bombArounds[(_index + cols) + 1] > 0) $cell[(_index + cols) + 1].innerHTML = bombArounds[_index + cols + 1]; } if (!$cell[(_index + cols) - 1].classList.contains('cell-bomb')) { $cell[(_index + cols) - 1].classList.add('secure'); if (bombArounds[(_index + cols) - 1] > 0) $cell[(_index + cols) - 1].innerHTML = bombArounds[_index + cols - 1]; } } }
[ "function expandShown(elCell, i, j) {\n var cell = gBoard[i][j];\n // CR: if (cell.isMarked || cel.isShown) rutern Will be better\n if (cell.isMarked === true) return;\n if (cell.isShown === true) return;\n if (cell.isBomb === true) {\n gameOver();\n // CR: there is no need to return, \"else if\" is better then return\n return;\n }\n if (cell.bombsAroundCount !== 0) {\n document.querySelector('.' + elCell.className).innerHTML = cell.bombsAroundCount;\n cell.isShown = true;\n return;\n }\n document.querySelector('.' + elCell.className).style.backgroundColor = '#D4CDCD';\n cell.isShown = true; \n revealNeighbors(i, j);\n}", "revealCell() {\n\t\tGameController.currentCellsCount--;\n\t\tif (GameController.currentCellsCount == GameController.mines) {\n\t\t\tGameController.winGame();\n\t\t}\n\t\tthis.visited = true;\n\t\tthis.view.interactive = false;\n\t\tvar img = '';\n\t\tif (this.isMine) {\n\t\t\timg = \"assets/RevealedMineCell.png\";\n\t\t} else {\n\t\t\timg = \"assets/EmptyCell.png\";\n\t\t\tif (this.danger > 0) {\n\t\t\t\tthis.dangerTxt = new PIXI.Text(this.danger +'',{fontFamily : 'Arial', fontSize: GameController.cellSize*.8, fill : this.getDangerColor(), align : 'center'});\n\t\t\t\tthis.dangerTxt.anchor.set(0.5);\n\t\t\t\tthis.dangerTxt.position.set(this.position.x, this.position.y);\n\t\t\t\tgridContainer.addChild(this.dangerTxt);\n\t\t\t}\n\t\t}\n\t\tthis.view.texture = PIXI.loader.resources[img].texture;\n\t}", "function autoReveal(cell) {\n var cellCoord = getCellCoord(cell.id);\n var cellI = cellCoord.i;\n var cellJ = cellCoord.j;\n recReveal(cellI,cellJ);\n\n function recReveal(i,j) {\n if(isOutOfBounds(i, j) || isFilled(i, j)){\n return;\n }\n var tdCell = document.querySelector('#cell-' + i + '-' +j);\n revealCell(tdCell);\n if (gBoard[i][j].contain === 'empty') {\n recReveal(i - 1,j);\n recReveal(i,j + 1);\n recReveal(i + 1,j);\n recReveal(i,j - 1);\n }\n }\n}", "function revealSafeCells(cell) {\n\tvar x = $(cell).data(\"x\")*1;\n\tvar y = $(cell).data(\"y\")*1;\n\tvar neighbourhood = [ \n\t\t[x-1,y-1],\n\t\t[x,y-1],\n\t\t[x+1,y-1],\n\t\t[x-1,y],\n\t\t[x+1,y],\n\t\t[x-1,y+1],\n\t\t[x,y+1],\n\t\t[x+1,y+1]\n\t]; // coordinates of neighbouring cells\n\t\n\tfor (nCell in neighbourhood ) {\n\t\tvar x = neighbourhood[nCell][0] // overrides previous variable\n\t\tvar y = neighbourhood[nCell][1] // overrides previous variable\n\n\t\t/* check if x and y are within existing range\n\t\t * check if cell is not already revealed\n\t\t * check if cell is not flagged\n\t\t * than reveal it\n\t\t */\n\t\tif ( x >= 0 && x < settings.cols && y >= 0 && y < settings.rows && ( $(matrix[y][x]).hasClass(\"revealed\") == false) && ( $(matrix[y][x]).hasClass(\"flag\") == false) ){\n\t\t\t$(matrix[y][x]).addClass(\"revealed\");\n\t\t\t$(matrix[y][x]).unbind(\"click\");\n\t\t\t\n\t\t\tvar mines = mineCheck(matrix[y][x]);\n\t\t\t\n\t\t\tif ( mines == 0 ) {\n\t\t\t\trevealSafeCells( matrix[y][x] );\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$(matrix[y][x]).addClass(\"mines\"+mines);\n\t\t\t\t$(matrix[y][x]).html(mines);\n\t\t\t}\n\t\t}\n\t}\n}", "revealCell(index, value) {\n const grid = this.container.querySelector('.minesweeper-grid');\n const cell = Array.from(grid.children)[index];\n\n cell.classList.remove('flag');\n cell.classList.remove('minesweeper-cell-unrevealed');\n cell.classList.add('minesweeper-cell-revealed');\n\n if (value === 0) {\n cell.innerHTML = '';\n } else if (value > 0) {\n cell.innerHTML = value;\n cell.classList.add(`value${value}`);\n } else {\n this.addBomb(cell);\n cell.classList.add('valuebomb');\n }\n }", "function deathShowBombs() {\n for(let i = 0; i <= maxX; i++) {\n for(let j = 0; j <= maxY; j++) {\n with(cellArray[arrayIndexOf(i, j)]) {\n if(!isExposed) {\n if((isBomb) && (!isFlagged)) {\n boardImages[imageIndexOf(i, j)].src = bombRevealed.src;\n } else if((!isBomb) && (isFlagged)) {\n boardImages[imageIndexOf(i, j)].src = bombMisFlagged.src;\n }\n }\n }\n }\n }\n}", "reveal(cell) {\n cell.isOpen = true;\n if (cell.value === '*') {\n this.isOver = true;\n return;\n }\n if (cell.value) return;\n\n cell.neighbors.forEach(neighbor => {\n if (!neighbor.isOpen && neighbor.value !== '*' && !neighbor.hasFlag) {\n this.reveal(neighbor);\n }\n });\n }", "revealCells() {\n this.isRevealed = true;\n if (this.neighbourAmount === 0) {\n this.floodFillAlgorithm();\n }\n }", "reveal_cell(cell) {\n let cell_id = Config.CELL_ID(cell.row, cell.column)\n , dom_cell = document.getElementById(cell_id);\n\n if(cell.state === Config.CELL_MINE) {\n this.add_class(cell_id, 'exploded');\n dom_cell.innerHTML = this.mine_html;\n }\n else {\n this.add_class(cell_id, 'revealed');\n if(cell.mines > 0) {\n dom_cell.innerHTML = this.color_cell(cell.mines);\n }\n }\n }", "function youDied(x, y) {\r\n var cell = grid[y][x];\r\n\r\n // give the cell we died on a red background, and make it a bit visible\r\n cell.image.style = 'background: red; padding: 4px';\r\n\r\n revealCell(x, y);\r\n\r\n // reveal all other mines\r\n passGrid(function(x, y, cell) {\r\n if(cell.value == -1)\r\n revealCell(x, y);\r\n });\r\n}", "revealEmpty(x, y) {\n let neighbouringCells = [];\n for (let i = x - 1; i < x + 2; i++) {\n for (let j = y - 1; j < y + 2; j++) {\n\n //check whether coordinates are valid\n if (this.state.boardSize > i && i > -1 &&\n this.state.boardSize > j && j > -1 && !this.state.board[i][j].isRevealed) {\n this.revealCell(i, j);\n neighbouringCells.push(this.state.board[i][j]);\n } else { continue }\n }\n }\n\n //reveal cells untill neighbour cell value is not 0\n neighbouringCells.map(cell => {\n if (cell.value === 0) { this.revealEmpty(cell.x, cell.y) }\n })\n }", "revealMines() {\n for (let i=0; i<this.rows; i++) {\n for (let j=0; j<this.columns; j++) {\n let square = this.grid[i][j];\n if (square.getIsMine()) {\n square.open();\n }\n }\n }\n }", "function expandShown(idxI, idxJ) {\n for (var i = idxI - 2; i <= idxI + 2; i++) {\n for (var j = idxJ - 2; j <= idxJ + 2; j++) {\n if (i === idxI && j === idxJ) { continue; }\n if (i >= 0 && i <= gBoard.length - 1 && j >= 0 && j <= gBoard[0].length - 1) {\n var elCell = document.getElementById(' ' + i + '-' + j);\n if (!gBoard[i][j].isBomb && !gBoard[i][j].isMarked) {\n gBoard[i][j].isShown = true;\n if (elCell.classList.contains('unshown')) {\n gState.shownCount++;\n elCell.classList.remove('unshown');\n }\n var child = elCell.childNodes[0];\n if (child !== undefined) {\n child.style.display = 'block';\n }\n }\n }\n }\n }\n}", "function showMines() {\n\n for (var i = 0; i < gBoard.length; i++) {\n for (var j = 0; j < gBoard.length; j++) {\n if (gBoard[i][j].isMine) {\n gBoard[i][j].isShown = true\n renderCell(i, j)\n }\n }\n }\n}", "revealNeighbours() {\n if (this.isRevealed) {\n let aroundCs = this.neighbours;\n if (aroundCs.reduce((a, x) => a + (x.isFlag ? 1 : 0), 0) === this.number)\n for (let c of aroundCs)\n if (c.state === CellState.unrevealed) c.simulateClick(100);\n }\n }", "function onFirstClickMine(cell, modalCell) {\n modalCell.isMine = false\n setMinesOnBoard(gBoard, 1);\n setMinesNegsCount(gBoard);\n expandShown(gBoard, cell.i, cell.j)\n gGame.shownCount++;\n}", "function failShowMines() {\n for (let x = 0; x < gridSize; x++) {\n for (let y = 0; y < gridSize; y++) {\n if (arr[x][y].isBomb == 1) {\n //If it's a bomb, show it as 'exploded'\n let elemID = x + \" \" + y;\n document.getElementById(elemID).className = \"exploded-square\";\n }\n\n if (arr[x][y].isBomb == 0 && arr[x][y].isClicked == 0) {\n //If not a bomb, show it as 'clicked'\n userClick(x, y);\n arr[x][y].isClicked = 0; //'unclick', since user didn't actually click, just for show on end game\n }\n }\n }\n}", "function isAllCellExplored(){\n\tfor (var i=0; i<matrixSize; i++){\n\t\tfor (var j=0; j<matrixSize; j++){\n\t\t\tif((bombMatrix[i][j]==0)&&(b.cell([i,j]).get()===null)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\t\n\t}\n\treturn true;\n}", "function ExposeCellsAround(cell, cellRow, cellCol) {\r\n var neighCell;\r\n var neighCellId;\r\n var livesSection = document.querySelector(\".lives-left\");\r\n if ((gBoard[cellRow][cellCol]).isShown === false && (gBoard[cellRow][cellCol]).isMarked === false) {\r\n if ((gBoard[cellRow][cellCol]).isMine === true) {\r\n gGame.lives--;\r\n livesSection.innerHTML = `Total lives left ${gGame.lives}`;\r\n cell.innerHTML = `<img src=\"pics/mine.png\">`;\r\n var smiley = document.querySelector('.smiley');\r\n smiley.innerHTML = `<img src=\"pics/sadSmiley.png\">`;\r\n setTimeout(changeBackToHappy, 500);\r\n\r\n }\r\n if ((gBoard[cellRow][cellCol]).isMine === false && (gBoard[cellRow][cellCol]).isMarked === false) {\r\n if ((gBoard[cellRow][cellCol]).minesAroundCounter > 0) {\r\n (gBoard[cellRow][cellCol]).isShown = true;\r\n cell.innerHTML = (gBoard[cellRow][cellCol]).minesAroundCounter;\r\n cell.classList.add('uncovered');\r\n gGame.nonMineCells--;\r\n\r\n\r\n }\r\n if ((gBoard[cellRow][cellCol]).minesAroundCounter === 0 && (gBoard[cellRow][cellCol]).isMarked === false) {\r\n (gBoard[cellRow][cellCol]).isShown = true;\r\n cell.classList.add('uncovered');\r\n gGame.nonMineCells--;\r\n for (var i = cellRow - 1; i <= cellRow + 1; i++) {\r\n if (i < 0 || i >= gLevel.SIZE) continue;\r\n for (var j = cellCol - 1; j <= cellCol + 1; j++) {\r\n if (i === cellRow && j === cellCol) continue;\r\n if (j < 0 || j >= gLevel.SIZE) continue;\r\n if (!(gBoard[i][j].isMarked) && (!(gBoard[i][j].isShown))) {\r\n neighCellId = (i * (gLevel.SIZE) + j).toString();\r\n neighCell = document.getElementById(neighCellId);\r\n console.log(neighCellId);\r\n ExposeCellsAround(neighCell, i, j);\r\n }\r\n }\r\n }\r\n\r\n }\r\n }\r\n\r\n }\r\n\r\n\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Example: filterPalindromes([ "word", "Ana", "race car" ]) output: [ "Ana", "race car" ]
function filterPalindromes (words) { // Write your code here, and // return your final answer. let output = [] for (let i = 0; i < words.length; i++){ let word = words[i].length - 1 if (words[i][0].toLowerCase() === words[i][word].toLowerCase()){ output.push(words[i]) } } return output }
[ "function filterPalindromes (words) {\n let palindromesArr = [];\n for ( let i = 0; i < words.length; i++ ) {\n let flip = words[i].split('').reverse().join('');\n flip = flip.toLowerCase().split(' ').join('');\n console.log(flip);\n if ( flip === words[i].toLowerCase().split(' ').join('') ) {\n palindromesArr.push(words[i]);\n }\n }\n return palindromesArr;\n}", "function filterPalindromes (words) {\n // Write your code here, and\n // return your final answer.\n var allPali=[];\n for(var i=0; i < words.length; i++) {\n\t words[i] = words[i].toLowerCase().split(' ').join('');\n\t flage = true;\n\t for(var j = 0; j < words[i].length; j++) {\n\t\t flage = (words[i][j] === words[i][words[i].length -(j+1)]) && flage ;\n\t }\n\t if(flage) {\n\t\tallPali.push(words[i])\n\t }\n }\n return allPali;\n}", "function palindromeFilter(array){\n return array.filter(function(ele){\n return isPalindromeHelper(ele); \n });\n}", "function palindromeFilter2(array) {\n return array.filter(function(string){\n return string === string.split('').reverse().join('');\n });\n}", "function palindromes(string) {\n return substrings(string).filter(isPalindrome);;\n}", "function get_palindromes(txt) {\r\n let words = uniques(splitwords(txt)),\r\n palin = [];\r\n for(let i=0;i<words.length;i++) {\r\n if(words[i].length<3)\r\n continue;\r\n let mid = Math.round(words[i].length/2),\r\n j = 0;\r\n while(j<mid) {\r\n if(words[i].charAt(j) !== words[i].charAt(words[i].length-j-1))\r\n break;\r\n j++;\r\n }\r\n if(j===mid) palin.push(words[i]);\r\n }\r\n return palin;\r\n}", "function nonPalindrome(sentence) {\n var str = sentence.split(\" \")\n var result = []\n var palStr = \"\"\n for (let i = 0; i < str.length; i++) {\n for (let j = str[i].length -1; j >= 0; j--) {\n palStr+=str[i][j]\n \n }\n\n if (palStr.toLowerCase() != str[i].toLowerCase()) {\n result.push(str[i])\n }\n\n palStr = \"\"\n \n }\n\n return result\n\n}", "function extractPalindromes(text){\n var textArray = text.split(\" \");\n var palindromes = [];\n var n = -1;\n for (var i = 0; i<textArray.length; i++)\n {\n if (textArray[i] == reverseString(textArray[i]))\n {\n palindromes.push(textArray[i]);\n }\n }\n return palindromes;\n \n function reverseString(string){\n var reverse = \"\";\n for (var i = string.length-1; i >= 0 ;i--)\n {\n reverse += string[i]; \n }\n return reverse;\n }\n}", "function palindromeChecker2 (word){\n let toLowerCase = word.split('').map(letter => letter.toLowerCase())\n return toLowerCase.join('') === toLowerCase.reverse().join('')\n}", "function findPalindromes(txt){\r\n txt = txt.toLowerCase();\r\n txt = txt.replace(/[.,'\"?+\\/!@#$%\\^&\\*;:{}=\\-_`~()]/gm,\" \"); // remove punctuation\r\n txt = txt.replace(/(\\r|\\n)/g,\"\"); // remove newline\r\n var oldTxt = txt.split(\" \");\r\n var array = [];\r\n var count = 0;\r\n for (var i = 0; i < oldTxt.length; i++){\r\n console.log(oldTxt[i]);\r\n console.log(oldTxt[i].split(\"\").reverse().join(\"\"));\r\n // check there is an alphanumerical palindrome that is >=2 characters long\r\n if (oldTxt[i] === oldTxt[i].split(\"\").reverse().join(\"\") && oldTxt[i].length >= 2){\r\n console.log(oldTxt[i].split(\"\").reverse().join(\"\"));\r\n array[count] = oldTxt[i];\r\n count++;\r\n }\r\n }\r\n return array;\r\n}", "function palindromes(str) {\n let arrWords = str.toLowerCase().split(' ');\n let counter = 0;\n let palindrome = []\n for (let j = 0; j < arrWords.length; j++) {\n let result = [];\n let arr = arrWords[j].split('')\n for (let i = arr.length; i >= 0; i--) {\n result.push(arr[i])\n }\n if (result.join('') === arrWords[j]) {\n counter++;\n palindrome.push(arrWords[j]);\n }\n }\n return `${palindrome.join(' ')}- palindromes: ${counter}`\n }", "function find_palindrome_words(text){\n let a = text.split(\" \");\n for(let i = 0; i < a.length; i++){\n let arr = a[i].split(\"\");\n arr.reverse();\n arr = arr.join(\"\");\n if(a[i] === arr){\n console.log(arr);\n }\n }\n}", "function palindrome(string){}", "function palindrome(string){\r\n\tstring = string.toLowerCase();\r\n\tstring = string.replace(/[^a-z0-9]/,'');\r\n\treturn string === string.split(\"\").reverse().join(\"\");\r\n}", "function isPalindrome(word)\n{\n \n}", "function palindromes(string) {\n var allSubstrings = substrings(string);\n allSubstrings = allSubstrings.filter(substr => substr.length > 1);\n\n return allSubstrings.filter(function(substr) {\n if (substr === substr.split('').reverse().join('')) {\n return true;\n }\n });\n}", "function polindromIs(word) {\n return word.split('').reverse().join('');\n}", "function find_palindrome_words(str) {\n let arr = str.split(\" \");\n let arrReturn = [];\n for(let i = 0; i < arr.length; i++) {\n if(i % 2 !== 0) {\n arrReturn.push(arr[i]);\n }\n }\n return arrReturn;\n}", "function isPalindrome(word) {\n word = word.toLowerCase();\n for (var i = 0, j = word.length-1; i < j; i++, j--) {\n if (word[i] !== word[j]) {\n return false;\n }\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that recusively compares newNode with curr to place in the BST O(logn) if balanced
_insertNode(curr, newNode){ if(newNode.data <= curr.data){ // if newNode <= curr then Go or Insert Left if(curr.left === null){ curr.left = newNode; this.nodeCount++; }else{ this._insertNode(curr.left,newNode); } }else{ // if newNode > curr then Go or Insert Right if(curr.right === null){ curr.right = newNode; this.nodeCount++; }else{ this._insertNode(curr.right,newNode); } } }
[ "insertRecursively(val, currNode = this.root) {\n const addingNode = new Node(val);\n if (!this.root) {\n this.root = addingNode;\n return this;\n }\n\n if (val < currNode.val) {\n if (!currNode.left) {\n currNode.left = addingNode;\n return this;\n }\n this.insertRecursively(val, currNode.left);\n }\n if (val > currNode.val) {\n if (!currNode.right) {\n currNode.right = addingNode;\n return this;\n }\n this.insertRecursively(val, currNode.right);\n }\n }", "insertRecursively(val, current = this.root) {\n // If the tree is empty insert at the root.\n if (this.root === null) {\n this.root = new Node(val);\n return this;\n }\n\n // If not we find the right spot for the new val\n // recursively\n\n if(val < current.val){\n if(current.left === null){\n current.left = new Node(val);\n return this;\n } else {\n this.insertRecursively(val, current = current.left);\n }\n } else if(current.val < val){\n if(current.right === null) {\n current.right = new Node(val);\n return this;\n } else {\n this.insertRecursively(val, current = current.right);\n }\n\n }\n\n }", "function isBalanced(tree) {\n\tvar current = tree;\n\tif(current.left != null) {\n\t\tif(current.right == null) {\n\t\t\tif(current.left.left || current.left.right) {\n\t\t\t\tconsole.log('not balanced');\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tisBalanced(current.left);\n\t\t}\n\t}\n\tif(current.right != null) {\n\t\tif(current.left == null) {\n\t\t\tif(current.right.left || current.right.right) {\n\t\t\t\tconsole.log('not balanced');\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tisBalanced(current.right);\n\t\t}\n\t}\n}", "insert(value) {\n const newNode = new BinarySearchTree(value);\n let currNode = this;\n while (currNode) {\n if (newNode.value < currNode.value) {\n if (!currNode.left) {\n currNode.left = newNode;\n break;\n }\n currNode = currNode.left;\n } else if (newNode.value > currNode.value) {\n if (!currNode.right) {\n currNode.right = newNode;\n break;\n }\n currNode = currNode.right;\n } else {\n break;\n }\n }\n }", "insertRecursively(val) {\n const newNode = new Node(val);\n function recursionHelper(currentNode){\n if (!currentNode){\n return;\n }\n if (currentNode.val < val){\n if (!currentNode.left){\n currentNode.left = newNode;\n return;\n }else{\n recursionHelper(currentNode.left);\n }\n }else{\n if (!currentNode.right){\n currentNode.right = newNode;\n return;\n }else{\n recursionHelper(currentNode.right);\n }\n }\n }\n recursionHelper(this.root);\n return this.root;\n }", "function isItBst(tree) {\n let currNode = tree\n if (currNode === null) {\n return false\n }\n if (currNode.right && currNode.right.key < currNode.key) {\n return false\n }\n if (currNode.left && currNode.left.key > currNode.key) {\n return false\n }\n if (currNode.left) {\n return isItBst(currNode.left)\n }\n if (currNode.right) {\n return isItBst(currNode.right)\n }\n return true\n}", "function insertHelper() {\n if (current.val === node.val) return this;\n\n if (node.val < current.val) {\n if (current.left === null) {\n current.left = node;\n } else {\n current = current.left;\n return insertHelper();\n }\n // node value is greater than current value\n } else {\n if (current.right === null) {\n current.right = node;\n } else {\n current = current.right;\n return insertHelper();\n }\n } \n }", "function balanced(bst) {\n let leftHeight = heightOfBST(bst.left);\n let rightHeight = heightOfBST(bst.right);\n\n if (Math.abs(rightHeight - leftHeight) <= 1) {\n return true;\n } else if (Math.abs(rightHeight - leftHeight) > 1) {\n return false;\n }\n}", "insertRecursively(val, node = this.root) {\n let newNode = new Node(val);\n if (this.root === null) {\n this.root = newNode;\n return this;\n }\n\n if (val < node.val) {\n if (!node.left) {\n node.left = newNode;\n return this;\n }\n else this.insertRecursively(val, node.left);\n } else if (val > node.val) {\n if (!node.right) {\n node.right = newNode;\n return this;\n }\n else this.insertRecursively(val, node.right);\n }\n\n }", "isBalanced() {\n let balanced = function (node) {\n if (node === null) { // Base case\n return true;\n }\n let heightDifference = Math.abs(this.findHeight(node.left) - this.findHeight(node.right));\n if (heightDifference > 1) {\n return false;\n } else {\n return balanced(node.left) && balanced(node.right);\n }\n }\n return balanced(this.root);\n }", "insertRecursively(val) {\n const newNode = new Node(val);\n if (!this.root) {\n this.root = newNode;\n return this;\n }\n\n const compareFn = this.compareFn;\n const f = function(node) {\n const cmpResult = compareFn(val, node.val);\n\n if (cmpResult < 0 && node.left) {\n f(node.left);\n } else if (cmpResult < 0) {\n node.left = newNode;\n newNode.parent = node;\n } else if (node.right) {\n f(node.right);\n } else {\n node.right = newNode;\n newNode.parent = node;\n }\n };\n\n f(this.root);\n return this;\n }", "insert(val) {\n const currentNode = this.root;\n const newNode = new Node(val);\n if (!currentNode){\n this.root = newNode;\n return this.root;\n }\n while (currentNode){\n if (val < currentNode.val){\n if (!currentNode.left){\n currentNode.left = newNode;\n return this.root;\n }else{\n currentNode = currentNode.left;\n }\n }else{\n if (!currentNode.right){\n currentNode.right = newNode;\n return this.root;\n }else{\n currentNode = currentNode.right;\n }\n }\n }\n }", "contains(target) {\n let currNode = this;\n while (currNode) {\n if (target === currNode.value) {\n return true;\n }\n if (target < currNode.target) {\n currNode = currNode.left;\n } else {\n currNode = currNode.right;\n }\n }\n return false;\n }", "function sameBST(arr1, arr2){\n if(arr1.length !== arr2.length){\n return false;\n } if(arr1[0] !== arr2[0]){\n return false;\n } if(arr1.length === 0){\n return true;\n }\n let big1 = [];\n let lil1 = [];\n let big2 = [];\n let lil2 = [];\n for(let i=0; i<arr1.length; i++){\n if(arr1[i] >= arr1[0]){\n big1.push(arr1[i]);\n } else {\n lil1.push(arr1[i]);\n }\n if(arr2[i] >= arr2[0]){\n big2.push(arr2[i]);\n } else {\n lil2.push(arr2[i]);\n }\n }\n let smaller = sameBST(lil1, lil2);\n if (!smaller){\n return false;\n }\n if(big1.length !== big2.length){\n return false;\n } \n for(let i=0; i<big1.length; i++){\n if(big1[i] !== big2[i]){\n return false;\n }\n }\n return true;\n}", "insertRecursively(val, node = this.root) {\n const newNode = new Node(val);\n\n if (!this.root) {\n this.root = newNode;\n return this;\n }\n if (node.val > val) {\n if (!node.left) {\n node.left = newNode;\n return this;\n }\n this.insertRecursively(val, node.left);\n } else {\n if (!node.right) {\n node.right = newNode;\n return this;\n }\n this.insertRecursively(val, node.right);\n }\n }", "find(val, current) {\n if (current === undefined) {\n current = this.root;\n if(this.isEmpty()){\n return false;\n }\n }\n if(current.val == val){\n return true;\n }else if(val < current.val){\n if(current.left == null){\n return false;\n }else{\n return this.find(val, current.left);\n }\n }else{\n if(current.right == null){\n return false;\n }else{\n return this.find(val, current.right);\n }\n }\n }", "function findOrAdd(rootNode, newNode) {\n if (newNode.data === rootNode.data || newNode.data === rootNode.left || newNode.data === rootNode.right) {\n return true\n } else if (newNode.data < rootNode.data) {\n return !rootNode.left ? rootNode.left = newNode : findOrAdd(rootNode.left, newNode)\n } else if (newNode.data > rootNode.data) {\n return !rootNode.right ? rootNode.right = newNode : findOrAdd(rootNode.right, newNode)\n }\n}", "insert(val, currentNode=this.root) {\n // [] Check if the root exists\n if (!this.root) { \n // [] if it does not, then set the root to be a new TreeNode with the value\n this.root = new TreeNode(val);\n return\n }\n // [] Check if the val greater the currentNode\n // [] If the value is less than the current node\n if (val < currentNode.val) {\n // [] Check if a left node exists\n if (!currentNode.left) {\n // [] if it doesn't exist then insert it\n currentNode.left = new TreeNode(val);\n } else {\n // [] otherwise then recurse and call pass in currentNode.left\n this.insert(val, currentNode.left);\n }\n } else {\n // [] If the value is greater or equal to the current node\n // [] Check if a right node exists\n if (!currentNode.right){\n // [] if it doesn't exist then insert it\n currentNode.right = new TreeNode(val);\n } else {\n // [] otherwise then recurse and call pass in currentNode.right\n this.insert(val, currentNode.right);\n }\n }\n\n }", "searchRecur(val, currentNode=this.root) {\n // [] Check if currentNode is true\n // [] if not return false\n if (!currentNode) return false;\n // [] Compare the value with the current node's value\n // [] If it is less than the current node's value\n if (val < currentNode.val) {\n // [] recurse left\n return this.searchRecur(val, currentNode.left);\n }\n // [] else if it is greater than the current node's value\n else if (val > currentNode.val) {\n // [] recurse right\n return this.searchRecur(val, currentNode.right);\n }\n // [] else\n else {\n // return true\n return true\n }\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns report rows based on query. Returns rowarray only contains keyvalues
function getReportRows(query) { var rows = []; var report = AdWordsApp.report(query); var rowsIterator = report.rows(); while ( rowsIterator.hasNext() ) { rows.push( rowsIterator.next() ); } return rows; }
[ "get keyRows() {\n return (this.rows || [])\n .map((row, index) => ({ [this.keyField]: index + '', ...row }))\n .map(row => ({ ...Table.BASIC_ROW_CONFIG, ...row, ...{ _identity: row[this.keyField] } }));\n }", "get rows(){\n //Bah, I hate declaring variables up here, but gotta do what ya gotta do.\n var rows = [];\n var record = null;\n var row = null;\n var column = null;\n var currentField = null;\n\n //Map the list view output to the lightning data table format output.\n if(!isEmpty(this.records) && !isEmpty(this.records.data)){\n //Iterate through the list view records and map them to a friendlier data table-esque format.\n for(record of this.records.data.records.records){\n row = {};\n for( column of this.columns){\n currentField = record.fields[column.fieldName];\n if(!isEmpty(currentField)){\n row[column.fieldName] = currentField.value;\n }\n }\n rows.push(row);\n }\n }\n return rows;\n }", "function _getRows(dataBaseQuerry) {\n var report = AdsApp.report(dataBaseQuerry);\n return report.rows();\n}", "_getRowsArray() {\n return this._rows instanceof QueryList ? this._rows.toArray() : this._rows;\n }", "function getQueryResultRows(chunk) {\r\n var data = JSON.parse(chunk);\r\n var resultRows = [];\r\n var varObjs = data.head.vars;\r\n // Loop through result rows\r\n for (var rowIndex in data.results.bindings) {\r\n var resultRowData = data.results.bindings[rowIndex];\r\n var bindings = [];\r\n // Loop through binded variables\r\n for (var varIndex in varObjs) {\r\n var varName = varObjs[varIndex];\r\n var varValueStr = String(resultRowData[varName].value);\r\n // Add Variable Binding Value\r\n bindings.push({\r\n varName: varName,\r\n varValue: new IRI(varValueStr)\r\n });\r\n }\r\n // Add Query Result Row\r\n resultRows.push({\r\n rowNr: Number(rowIndex),\r\n bindings: bindings\r\n });\r\n }\r\n return resultRows;\r\n}", "getAllRows() {\r\n\t\t// The table needs to be loaded before we attempt to access the rows.\r\n\t\t// We could just return an empty Map here, but throwing an error highlights the mistake.\r\n\t\tif (!this.isLoaded)\r\n\t\t\tthrow new Error('Attempted to read a data table rows before table was loaded.');\r\n\r\n\t\tconst rows = this.rows;\r\n\r\n\t\t// Inflate all copy table data before returning.\r\n\t\tif (!this.isInflated) {\r\n\t\t\tfor (const [destID, srcID] of this.copyTable)\r\n\t\t\t\trows.set(destID, rows.get(srcID));\r\n\r\n\t\t\tthis.isInflated = true;\r\n\t\t}\r\n\r\n\t\treturn rows;\r\n\t}", "async all() {\n const input = this.getInput();\n const outputs = [];\n let page;\n // if this is the first page, or if we have not hit the last page, continue loading records…\n while (page == null || page.lastEvaluatedKey != null) {\n if ((page === null || page === void 0 ? void 0 : page.lastEvaluatedKey) != null) {\n input.ExclusiveStartKey = page.lastEvaluatedKey;\n }\n page = await this.page(input);\n outputs.push(page);\n }\n return output_1.QueryOutput.fromSeveralOutputs(this.tableClass, outputs);\n }", "filterRows(keys) {\n this.DataTable().search(keys).draw();\n }", "getRows() {\n return this._rows.slice();\n }", "values() {\n //*Variable that will store all the values\n let valuesArr = [];\n //*Looping through the table and return all the values that are stored at index 1 [key, value]\n for (let i = 0; i < this.keyMap.length; i++) {\n if (this.keyMap[i]) {\n for (let j = 0; j < this.keyMap[i].length; j++) {\n //*Loop that will check and push only all the unique values\n if (!valuesArr.includes(this.keyMap[i][j][1])) {\n //*Pushing all the values into the empty array and returning them\n valuesArr.push(this.keyMap[i][j][1]);\n }\n }\n }\n }\n return valuesArr;\n }", "getRows() {\n const rows = []\n\n let [hasNext, iter] = this.listStore.getIterFirst()\n\n while(hasNext) {\n const rowText = this.listStore.getValue(iter, 0).getString()\n\n rows.push(rowText)\n\n hasNext = this.listStore.iterNext(iter)\n }\n\n return rows\n }", "static async getAllRows() {\n return (await sheet).sheetsByIndex[0].getRows();\n }", "collectResults() {\n // Collect groups\n let rows = Array.from(this.groups, ([_, group]) => {\n const { bindings: groupBindings, aggregators } = group;\n // Collect aggregator bindings\n // If the aggregate errorred, the result will be undefined\n const aggBindings = {};\n for (const variable in aggregators) {\n const value = aggregators[variable].result();\n if (value !== undefined) { // Filter undefined\n aggBindings[variable] = value;\n }\n }\n // Merge grouping bindings and aggregator bindings\n return groupBindings.merge(aggBindings);\n });\n // Case: No Input\n // Some aggregators still define an output on the empty input\n // Result is a single Bindings\n if (rows.length === 0) {\n const single = {};\n for (const i in this.pattern.aggregates) {\n const aggregate = this.pattern.aggregates[i];\n const key = rdf_string_1.termToString(aggregate.variable);\n const value = sparqlee_1.AggregateEvaluator.emptyValue(aggregate);\n if (value !== undefined) {\n single[key] = value;\n }\n }\n rows = [bus_query_operation_1.Bindings(single)];\n }\n return rows;\n }", "checkedRows(rows, indexKey) {\n // If there are no checked rows and an end indexKey is undefined, then check all rows.\n if (typeof indexKey === 'undefined' && !this.hasCheckedRows()) {\n return rows;\n }\n\n // If there are checked rows and an end index is provided, then remove all checked rows.\n if (typeof indexKey === 'undefined' && this.hasCheckedRows()) {\n return {};\n }\n\n // Uncheck a single row if it already exists in the items property.\n if (this.getCheckedRows().hasOwnProperty(indexKey)) {\n return this.removeCheckedRow(indexKey);\n }\n\n // Add row to the items list with the index as the key and resourceId as the value.\n return {\n ...this.getCheckedRows(),\n [indexKey]: rows[indexKey],\n };\n }", "function resultToArray(result){\n var rows = result.rows, row, arr = [];\n for(var i = 0, l = rows.length; i < l; i++) {\n arr.push(rows.item(i));\n }\n return arr;\n }", "getRecords(query, cb) {\n this._db.all(query, (err, rows) => {\n if (err) {\n cb(err, null);\n }\n cb(null, rows);\n });\n }", "function getRows() {\n var self = this;\n\n self._getRows.apply(self, arguments);\n}", "function getSelectedRows(){\n\n var tblData = table.rows({selected: true}).data();\n var tmpData;\n var strData = [];\n\n $.each(tblData, function (i) {\n tmpData = tblData[i]['key'];\n strData.push(tmpData);\n\n });\n\n return strData;\n}", "getRowByKey(key) {\n const rec = this.filteredSortedData ? this.primaryKey ?\n this.filteredSortedData.find(record => record[this.primaryKey] === key) :\n this.filteredSortedData.find(record => record === key) : undefined;\n const index = this.dataView.indexOf(rec);\n if (index < 0 || index > this.dataView.length) {\n return undefined;\n }\n return new IgxGridRow(this, index, rec);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method updates the angle between the angle between the mouse and the centre of the slider when a click is detected.
handleClick(e) { this.updateAngles(e); }
[ "updateAngles(e) {\n var currX = e.pageX;\n var currY = e.pageY;\n var angleInRadians = Math.atan2(currY - this.state.sliderCentreY, currX - this.state.sliderCentreX);\n var angleInDegrees = (Math.round((180 / Math.PI) * angleInRadians) + Constants.MAX_DEG - Constants.ANGLE_OFFSET_DEG) % 361;\n this.setState({\n cursor: 'grabbing',\n mouseX: currX,\n mouseY: currY,\n deg: angleInDegrees,\n rad: angleInRadians\n });\n this.handleAngleChanged(angleInRadians, angleInDegrees);\n }", "function mouseMoved() {\n mouseAngle = atan2(mouseY - height / 2, mouseX - width / 2)\n}", "function mouseDragged() {\n mouseAngle = atan2(mouseY - height / 2, mouseX - width / 2)\n}", "function OnInitAngleSliderChange ()\r\n {\r\n var angle = document.getElementById ('initAngleSlider').value;\r\n document.getElementById ('initAngleOutput').value = angle + '°';\r\n\r\n _dTheta = angle / 180 * Math.PI;\r\n\r\n _dCurrXPos = _dLength * Math.sin (_dTheta);\r\n _dCurrYPos = _dLength * Math.cos (_dTheta);\r\n\r\n var nPrevTrailState = _DrawTrail;\r\n _DrawTrail = false;\r\n _TrailPoints = [];\r\n\r\n drawScreen ();\r\n\r\n _DrawTrail = nPrevTrailState;\r\n }", "function changeAngle(){\n angle = PI / 24 * slider.value();\n turtle();\n}", "function OnInitAngle1SliderChange ()\r\n {\r\n var angle = document.getElementById ('initAngle1Slider').value;\r\n document.getElementById ('initAngle1Output').value = angle + '°';\r\n\r\n _dTheta1 = angle / 180 * Math.PI;\r\n\r\n var nPrevTrailState = _DrawTrail;\r\n _DrawTrail = false;\r\n _TrailPoints = [];\r\n\r\n drawScreen ();\r\n\r\n _DrawTrail = nPrevTrailState;\r\n }", "function OnInitAngle1SliderChange ()\r\n {\r\n var angle = document.getElementById ('initAngle1Slider').value;\r\n document.getElementById ('initAngle1TextBox').value = angle + '°';\r\n\r\n _dTheta1 = angle / 180 * Math.PI;\r\n\r\n var nPrevTrailState = _DrawTrail;\r\n _DrawTrail = false;\r\n _TrailPoints = [];\r\n\r\n drawScreen ();\r\n\r\n _DrawTrail = nPrevTrailState;\r\n }", "function calculateAngle() {\n\t\t\t\t\treturn Math.cos((event.touches[0].pageY - event.touches[1].pageY) / fidget.pinch.distance);\n\t\t\t\t}", "updateAngle() {\n this.angle = Math.atan2(this.destY - this.y, this.destX - this.x)\n * (180 / Math.PI) - 90;\n }", "function getAngle( v, mouse ){\n var angle,\n ox = v.x - mouse.x,\n oy = v.y - mouse.y;\n \n if( ox !== 0 ){\n angle = toDegrees( Math.atan( oy/ox ) );\n \n if( ox > 0 && oy > 0){\n angle += 180;\n }else if( ox < 0 && oy > 0 ) {\n angle += 360;\n }else if( ox < 0 && oy < 0 ) {\n angle = angle;\n }else if( ox > 0 && oy < 0 ) {\n angle += 180 ;\n }else{\n angle = ox > 0 ? 180 : 0; \n }\n \n } else {\n if(oy > 0){\n angle = 270;\n } else {\n angle = 90;\n }\n }\n \n return angle;\n }", "function mousePressed(){\n angle ++;\n if ( angle == 16 ){\n angle = 2;\n }\n}", "function OnInitAngle2SliderChange ()\r\n {\r\n var angle = document.getElementById ('initAngle2Slider').value;\r\n document.getElementById ('initAngle2TextBox').value = angle + '°';\r\n\r\n _dTheta2 = angle / 180 * Math.PI;\r\n\r\n var nPrevTrailState = _DrawTrail;\r\n _DrawTrail = false;\r\n _TrailPoints = [];\r\n\r\n drawScreen ();\r\n\r\n _DrawTrail = nPrevTrailState;\r\n }", "function onAngleChanged(event) {\n viewer.atom.changeNucletAngle(editNuclet, event.target.value);\n viewer.render();\n }", "function getCalcAngleCb(ref) {\n return (pos) => {\n //console.log('angle callback');\n if (ref.current == null) {\n console.error('Slider move callback null ref');\n return;\n }\n /*\n * Calculate position of mouse relative to the actual slider bar\n */\n let bbox = ref.current.getBoundingClientRect();\n let dx = pos.x - (bbox.left + bbox.width/2);\n let dy = pos.y - (bbox.top + bbox.height/2);\n let theta = -1*Math.atan2(dy,dx);\n theta = theta > 0 ? theta : theta + 2*Math.PI\n return(clamp(0,theta,Math.PI*2));\n };\n}", "getMouseAngle() {\n let r = distance(mouse.x, mouse.y, this.center, this.center);\n let relativeMouseX = (mouse.x - this.center) / r;\n let relativeMouseY = (-mouse.y + this.center) / r;\n let mouseAngle = Math.atan2(relativeMouseY, relativeMouseX);\n if (mouseAngle < 0) mouseAngle += tau;\n // round to nearest percent\n mouseAngle = (tau / 100) * Math.round(mouseAngle / (tau / 100));\n return (mouseAngle);\n }", "function reCalculateAngleMove() {\n console.log(currentMouseLocX + \" \" + currentMouseLocY);\n myTankO.calculateAngle(currentMouseLocX,currentMouseLocY);\t\n}", "function angle_OnClick()\n{\n\ntry {\n\tnAngles = DVD.AnglesAvailable;\n\n // return if there is only 1 viewing angle\n\tif (nAngles <= 1) return;\n\n\tnCurrentAngle = DVD.CurrentAngle + 1;\n\tif (nCurrentAngle > nAngles)\n\t\tnCurrentAngle = 1;\n\tDVD.CurrentAngle = nCurrentAngle;\n\n\tangle_ToolTip();\n}\n\ncatch(e) {\n e.description = L_ERRORUnexpectedError_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}", "function angleOfProjectionChange(scope) {\n var bullet_case_tween = createjs.Tween.get(getChild(\"bullet_case\")).to({\n rotation: (-(scope.angle_of_projection))\n }, 500); /** Tween rotation of bullet case, with respect to the slider angle value */\n\tvar bullet_case_tween = createjs.Tween.get(getChild(\"case_separate\")).to({\n rotation: (-(scope.angle_of_projection))\n }, 500); /** Tween rotation of bullet case, with respect to the slider angle value */\n bullet_moving_theta = scope.angle_of_projection + 10; /** Bullet moving angle */\n calculation(scope); /** Value calculation function */\n scope.erase_disable = true; /** Disable the erase button */\n}", "function lambdaListener() {\n const angle = boundNumberToInterval(this.value, -180, 180); // makes number cut off at -180 and 180\n const rotation = projection.rotate();\n projection.rotate([angle, rotation[1], rotation[2]]);\n render(land50, broker_data, broker_data_type, path);\n document.getElementById(\"lambda\").value = angle;\n document.getElementById(\"lambda-val\").value = angle;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store JSON object into the current context with a given id
set(id, object){ localStorage.setItem(`${this.state.context}-${id}`, JSON.stringify(object)); }
[ "function modJson(id, newEntry) {\n json.id = newEntry\n}", "function saveTaskData(id, obj)\n{\n const data = $(\"body\").data();\n const activeTasks = data.tasks.active;\n activeTasks[id] = obj;\n}", "function addToJSON(obj) {\n jsonInput[obj.id] = obj.value;\n}", "function setContext(id) {\n\n if (typeof(id) === 'number') {\n\n // Initialize global categories.\n var categories = CategoryList.query();\n categories.$promise.then(function (data) {\n Data.categories = data;\n Data.currentCategoryIndex = data[0].id;\n });\n\n // Initialize global tags.\n var tags = TagList.query();\n tags.$promise.then(function (data) {\n if (data.length > 0) {\n\n Data.tags = data;\n Data.currentTagIndex = data[0].id;\n }\n });\n\n // Initialize global content types\n var types = ContentTypeList.query();\n types.$promise.then(function (data) {\n if (data.length > 0) {\n Data.contentTypes = data;\n Data.currentContentIndex = data[0].id;\n }\n\n });\n\n updateAreaContext(id);\n\n }\n\n }", "_set (context, id) {\n this.special.set(context, id)\n }", "function storeInLocalStorage(json_obj, storage_key){\n localStorage.setItem(storage_key, JSON.stringify(json_obj));\n}", "function saveObjectID(object_id) {\n localStorage.setItem('object_id', object_id)\n console.log(object_id)\n }", "function createData(localJson){\n\tlocalStorage.setItem(userID.toString(), localJson);\n}", "addLocation(id) {\n // Add location to saved based on it's id\n this.saved.push(id);\n // Save to Local Storage\n this.persistData();\n }", "function addToJSON(obj, id, color) {\n item = {};\n item.id = id;\n item[\"color\"] = color;\n\n obj.push(item);\n }", "function saveFn(obj){ \n if(obj.hasOwnProperty('id')){\n var itemKey = this.saveKey(obj.id);\n this.storage.setItem(itemKey, JSON.stringify(obj));\n return true;\n }else{\n return false;\n }\n }", "function addHobbyAsJson() {\n var hobby = {};\n //hobby. = id;\n hobby.name = document.getElementById('add-hoby-name');\n hobby.description = document.getElementById('add-hoby-desc');\n\n addHobbyContainer.innerHTML = null;\n $('#add-hobby').removeClass('hidden');\n $('#save-hobby').addClass('hidden');\n\n var data = JSON.stringify(hobby);\n //setData(data, \"hobby\");\n}", "static setId(id) {\n let idNumber = Store.getId();\n idNumber = id;\n localStorage.setItem(\"id\", JSON.stringify(idNumber));\n }", "save() {\n\t\tvar json = JSON.stringify(this);\n\t\tlocalStorage.setItem(this.keyname, json);\n\t}", "function storeAliasObject(string, obj) {\n var key = string;\n var value = obj;\n var jsonfile = {};\n jsonfile[key] = value;\n chrome.storage.local.set(jsonfile, function () {\n\n });\n\n}", "async put(id, obj) {\n if (id === undefined) throw new Error('No ID provided');\n const options = this.copyOptions();\n options.url = appendIdIfExists(options.url, id);\n options.body = obj;\n const response = await request.put(options);\n return response.body;\n }", "function saveTransaction(id) {\n if (typeof id == \"string\") {\n localStorage.optly_transactions = (typeof localStorage.optly_transactions == 'undefined' ? \"/\" + id + \"/\" : localStorage.optly_transactions + id + \"/\");\n }    \n }", "saveState() {\n const that = this;\n\n if (!that.id) {\n that.warn(that.localize('noId'));\n return;\n }\n\n //Save to LocalStorage\n window.localStorage.setItem('jqxDockingLayout' + that.id, JSON.stringify(that.getJSONStructure()));\n }", "function setDataRest(jsonObj) {\n var url = getUrl(jsonObj.module, 'set');\n\n if (jsonObj.param) {\n url += jsonObj.param;\n }\n\n return requestHandle({\n method: \"post\",\n url: url,\n params: {\n action: \"add\"\n },\n data: jsonObj.data,\n headers: getHeaders()\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for selected seats
function updateSelectedSeats() { if(ticketPrice == 800) { showCoachType.innerText = "AC Normal" } else if(ticketPrice == 1200) { showCoachType.innerText = "AC Business" } else if(ticketPrice == 400) { showCoachType.innerText = "Non AC" } const selectedSeats = document.querySelectorAll(".row .seat.selected") const SelectedSeatsIndex = [...selectedSeats].map(seat => [...seats].indexOf(seat)) const selectedSeatsLength = selectedSeats.length showTotalSeats.innerText = selectedSeatsLength let selectedSeatsText = [] SelectedSeatsIndex.forEach(function(seat) { selectedSeatsText.push(seats[seat].innerText) }) showTotalPrice.innerText = ticketPrice * selectedSeatsLength showSeats.innerText = selectedSeatsText.join(", ") }
[ "function selectSeat (event) {\n // Check if a free seat was clicked\n if (event.target.classList.contains('seat') &&\n !event.target.classList.contains('occupied')) {\n \n // Remove if exists a class or add it if it doesnt exists\n event.target.classList.toggle('selected');\n\n // Update total seats selected and its price\n updatedSelectedCount();\n\n updateMovieAndPrice();\n }\n}", "function updateSelectedSeats(e) {\n\tif(nb_seats==5 && (!e.target.classList.contains(\"selected\"))){\n\t\ttoastr[\"error\"](\"Vous ne poivez pas réserver plus de 5 places.\");\n\t\treturn;\n\t}\n\tif (e.target.classList.contains(\"seat\") && !e.target.classList.contains(\"occupied\"))\te.target.classList.toggle(\"selected\");\n}", "function selectSeat(e){\n\t\te = event.target;\n\t\tseats.forEach(function(seat) {\n\t\t\tif (e.innerText == seat.number && seat.status==='a') {\n\t\t\t\tseat.status = 's';\n\t\t\t} else if (e.innerText == seat.number && seat.status==='s') {\n\t\t\t\tseat.status = 'a';\n\t\t\t}\n\t\t})\n\t\tif ($(this).hasClass('availible')) {\n\t\t\t$(this).removeClass('availible').addClass('selected');\n\t\t\t$(this).css('background-color', '#646362');\n\t\t} else if ($(this).hasClass('selected')) { \n\t\t\t$(this).removeClass('selected').addClass('availible');\n\t\t\t$(this).css('background-color', '#E5E7E6')\n\t\t}\n\t\tconsole.log(this);\n\t}", "function _seatsSelected() {\n console.log();\n if (seatingsController.tickets.length === 1) {\n _buildInputForm();\n _buildBookingButton();\n _disableBookingButton();\n _listenToInputForm();\n _listenToBookingButton();\n } else if (seatingsController.tickets.length === 0) {\n _clearBookingButton();\n _clearInputForm();\n }\n _buildSeatNumberCounter();\n _buildPriceCounter();\n}", "function chooseSeat() {\n if(ticketPack.additionalTicketID <= 0){\n chooseSeat_single();\n }\n else{\n if(dualSeatCheckShortcut(chooseSeat_SECTIONTransformer(SECTION)) == true){\n chooseSeat_dualOne();\n }\n else{\n chooseSeat_dualSingle();\n }\n }\n}", "function selectSeat() {\r\n\r\n try {\r\n //helper.searchFlight(fileName);\r\n seatPreference = ['Window', 'Middle', 'Aisle'],\r\n index = readlineSync.keyInSelect(seatPreference, 'Which seat do you want?');\r\n selectedSeat = helper.seatSelection(index + 1, seatPreference[index]);\r\n }\r\n catch (e) {\r\n throw e;\r\n }\r\n}", "function getSelectedSeats() {\n var seatsArr = [];\n $('.selected').each(function(index, value) {\n var seatNum = this.getAttribute('data-seat');\n seatsArr.push(seatNum);\n })\n return seatsArr;\n }", "function createseating(){\r\n \r\n var seatingValue = [];\r\n for ( var i = 0; i < 10; i++){\r\n \r\n for (var j = 1; j < 10; j++){\r\n\r\n var seatingStyle = \"<div class='seat available'></div>\";\r\n seatingValue.push(seatingStyle);\r\n\r\n if ( j === 9){\r\n var seatingStyle = \"<div class='clearfix'></div>\";\r\n seatingValue.push(seatingStyle);\r\n } \r\n } \r\n }\r\n\r\n /**\r\n * It handles all the seat selection with button click, hover and seat selection etc events.\r\n */\r\n $('#messagePanel').html(seatingValue);\r\n \r\n $(function(){\r\n $('.seat').on('click',function(){\r\n \r\n if($(this).hasClass( \"selected\" )){\r\n $( this ).removeClass( \"selected\" ); \r\n if(count !== 0) {\r\n count--;\r\n }\r\n }else{ \r\n $( this ).addClass( \"selected\" );\r\n bookBtn = true;\r\n count++;\r\n }\r\n\r\n if(bookBtn && count !== 0) {\r\n $(\"#proceedBtn\").show();\r\n }else if(count === 0){\r\n $(\"#proceedBtn\").hide();\r\n }\r\n console.log(\"selected seats: \", count)\r\n });\r\n \r\n $('.seat').mouseenter(function(){ \r\n $( this ).addClass( \"hovering\" );\r\n \r\n $('.seat').mouseleave(function(){ \r\n $( this ).removeClass( \"hovering\" );\r\n \r\n });\r\n }); \r\n });\r\n \r\n }", "function seatCount(e){\n if(e.target.classList.contains('selected')){\n e.target.classList.remove('selected');\n totalSeat.pop(e.target.id);\n calculateValue(totalSeat, ticketPrice);\n }\n else{\n if (e.target.classList.contains('seat') && !e.target.classList.contains('occupied')) {\n e.target.classList.add('selected');\n totalSeat.push(e.target.id);\n calculateValue(totalSeat, ticketPrice);\n }\n }\n}", "function clickSeat() {\n console.log(\"Clicked \" + props.seat.seatName);\n // alert(\"Clicked \" + props.seat.seatName);\n setSelected({ seat: props.seat.id, level:selected.level });\n }", "showSeats(movieIndex) {\n this.seats.forEach(seat => {\n seat.classList.remove('selected')\n seat.classList.remove('occupied')\n })\n this.movies[movieIndex].seats.forEach(spot => {\n this.seats[spot].classList.add('selected')\n })\n this.movies[movieIndex].occupiedSeats.forEach(spot => {\n this.seats[spot].className = 'seat occupied'\n })\n this.updateSelection(this.movies[movieIndex].price)\n }", "function addSeatToSelectedList(seat) {\n var seatSelectionObject = { \"RowIndex\": seat.RowIndex, \"ColumnIndex\": seat.ColumnIndex, \"AreaNumber\": seat.area.AreaNumber },\n i = 0;\n\n for (i = 0; i < m_selectedSeats.length; i++) {\n if (m_selectedSeats[i].AreaCategoryCode === seat.area.AreaCategoryCode) {\n m_selectedSeats[i].Seats.unshift(seatSelectionObject); // Push to front\n return;\n }\n }\n}", "function deselectSofa(seat) {\n\n var i, sofaSeat;\n\n for (i = 0; i < seat.SeatsInGroup.length; i++) {\n sofaSeat = getSeat(seat.area.AreaNumber, seat.SeatsInGroup[i].RowIndex, seat.SeatsInGroup[i].ColumnIndex);\n\n if (sofaSeat.Status === SELECTED) { // Seat is reserved\n deselectSeat(seat.area.AreaNumber, sofaSeat.RowIndex, sofaSeat.ColumnIndex);\n }\n }\n}", "function selectTempSeats(tempSeatData) {\n var seatsArr = [];\n var tempArr = tempSeatData.split('|');\n tempArr.splice(0, 2);\n tempArr.pop();\n var i;\n for (i = 0; i < tempArr.length; i+=4) {\n seatsArr.push({\n area: tempArr[i+1] - 0,\n row: tempArr[i+2] - 1,\n col: tempArr[i+3] - 1\n });\n }\n\n var areaCode = tempArr[0];\n\n SeatingControl.deselectAllSeats(areaCode);\n\n for (var s = 0; s < seatsArr.length; s++) {\n SeatingControl.selectSeat(seatsArr[s].area, seatsArr[s].row, seatsArr[s].col);\n }\n\n syncState();\n }", "function selectSeat(e) {\n //find the selected movie\n if (e.target.className === \"seat\") {\n e.target.classList.add(\"selected\")\n addUI()\n } else if (e.target.className === \"seat selected\") {\n e.target.classList.remove(\"selected\")\n removeUI()\n }\n}", "function createSeats(reservedSeat)\r\n{\r\n\tvar seatList=[],seatNumber,seatClass;\r\n\tvar k=0;\r\n\tvar selected_movie=$('.movies-toggle span').text();\r\n\tno_of_seats=$('.quantity-toggle span').text();\r\n\tfor(var i=0;i<settings.rows;i++,k++)\r\n\t{\r\n\t\tfor(var j=0;j<settings.column;j++)\r\n\t\t{\r\n\r\n\t\t\tseatNumber=(j+i*settings.column+1);\r\n\t\t\t\r\n\r\n\t\t\tif(seatNumber==51)\r\n\t\t\t\t{\r\n\r\n\t\t\t\t\tseatList.push(\"</ul></div>\"+\"<div class='silver_tickets_map col-md-12'><p class='category'>SILVER (Rs \"+settings.price.Silver+\")\"+\"</p>\"+\"<ul id='tickets_map' class='Silver'>\");\r\n\t\t\t\t\tk=0;\r\n\t\t\t\t}\r\n\t\t\t\telse if(seatNumber==151)\r\n\t\t\t\t{\r\n\t\t\t\t\tseatList.push(\"</ul></div>\"+\"<div class='bronze_tickets_map col-md-12'><p class='category'>BRONZE (Rs \"+settings.price.Bronze+\")\"+\"</p>\"+\"<ul id='tickets_map' class='Bronze'>\");\r\n\t\t\t\t\tk=0;\r\n\t\t\t\t}\r\n\t\t\t\telse if(seatNumber==1)\r\n\t\t\t\tseatList.push(\"<div class='gold_tickets_map col-md-12'><p class='category'>GOLD (Rs \"+settings.price.Gold+\")\"+\"</p>\"+\"<ul id='tickets_map' class='Gold'>\");\r\n\r\n\t\t\tseatClass=settings.seatCss+' '+settings.rowCssPrefix+i.toString()+' '+settings.colCssPrefix+j.toString();\r\n\t\t\t\r\n\t\t\tif ($.isArray(reservedSeat) && $.inArray(seatNumber+'', reservedSeat) != -1) \r\n\t\t\t{\r\n seatClass += ' ' + settings.selectedSeatCss;\r\n }\r\n\t\t\t//seatList.push(\"<li class='\"+seatClass+\"'\"+\" style='top:\"+(i*settings.height).toString()+\"px;left:\"+(j*settings.width).toString()+\"px;'>\"+\"<a title='\"+seatNumber+\"'></a>\"+\"</li>\");\r\n\t\t\tif(seatNumber%25==4||seatNumber%25==21)\r\n\t\t\t{\r\n\t\t\t\t\r\n\t\t\t\tseatClass += ' '+'invisible';\r\n\t\t\t\tinvisibleSeats.push(seatNumber);\r\n\t\t\t\tseatList.push(\"<li class='\"+seatClass+\"'\"+\" style='top:\"+(k*settings.height+5).toString()+\"px;left:\"+(j*settings.width).toString()+\"px;'>\"+\"</li>\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tseatList.push(\"<li id='\"+selected_movie+\"' class='\"+seatClass+\"'\"+\" style='top:\"+(k*settings.height+5).toString()+\"px;left:\"+(j*settings.width).toString()+\"px;'>\"+\"<a title='\"+seatNumber+\"'></a>\"+\"</li>\");\r\n\t\t}\r\n\t}\r\n\tdocument.getElementById(\"container\").innerHTML=seatList.join('');\r\n\tsetUpClickBinding();\r\n}", "function selectSeat(planseat) {\n if (classie.has(planseat, \"row__seat--reserved\")) {\n return false;\n }\n if (classie.has(planseat, \"row__seat--selected\")) {\n classie.remove(planseat, \"row__seat--selected\");\n return false;\n }\n // add selected class\n classie.add(planseat, \"row__seat--selected\");\n\n // the real seat\n const seat = seats[planseats.indexOf(planseat)];\n // show the seat´s perspective\n previewSeat(seat);\n}", "changeSeat() {}", "function addSeatToSelectedList(seat, priceAreaNumber) {\n // var seatSelectionObject = { \"RowIndex\": seat.RowIndex, \"ColumnIndex\": seat.ColumnIndex, \"AreaNumber\": seat.area.AreaNumber },\n // i = 0;\n var seatSelectionObject = { \"RowIndex\": seat.RowIndex, \"ColumnIndex\": seat.ColumnIndex, \"AreaNumber\": priceAreaNumber },\n i = 0;\n for (i = 0; i < m_selectedSeats.length; i++) {\n if (m_selectedSeats[i].AreaCategoryCode === seat.area.AreaCategoryCode) {\n m_selectedSeats[i].SelectedSeats.unshift(seatSelectionObject); // Push to front\n return;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task 5: As corporate wants to add more and more flavors to their lineup, they've realized that they need to remove flavors based on flavor name, as opposed to just arbitrarily removing the first or last flavor. Your task is to get an index by flavor name, and remove that flavor from the array. Your function should accept: (1) an array (2) a string (flavor) For example, removeFlavorByName(originalFlavors, "Vanilla") would return an array with the length 30 including all of the flavors except Vanilla. Hint: You can use .splice() for this Done!
function removeFlavorByName(array, string) { string = array.indexOf(string); array.splice(string, 1); return array; }
[ "function removeFlavorByName(originalFlavors, flavor){\n // for-in loop to check for specified flavor only for indices in the array\n for(let index in originalFlavors) {\n // If we find the specified flavor, use the corresponding index to splice it out of the array\n if(originalFlavors[index] == flavor) {\n // splice method will remove the elelment with the given index\n // we are not replacing it with any other flavor\n originalFlavors.splice(index, 1);\n // return the updated array\n return originalFlavors; \n }\n }\n}", "function removeFlavorByName(arr, flavor) {\n if (!Array.isArray(arr)) {\n console.log(\"arr is not an array!\");\n return null;\n } else if (typeof flavor !== \"string\") {\n console.log(\"flavor must be a string\");\n return null;\n }\n\n if (arr.includes(flavor)) {\n const indexToDelete = arr.indexOf(flavor);\n\n arr.splice(arr.indexOf(flavor), 1);\n return arr;\n } else {\n console.log(\"The provided flavor is not in the array!\");\n return null;\n }\n}", "function removeLastFlavor(originalFlavors){\n // use .pop() array method to remove last array element at index = length - 1\n originalFlavors.pop();\n // display the result\n console.log(originalFlavors);\n}", "function getFlavorByIndex(originalFlavors, index){\n // return the array element with the given index\n return originalFlavors[index];\n}", "function remove(animals, name){\n // create a for loop to look through the array of animals \n for (let i = 0; i < animals.length; i++){\n //check if animal name using strick comparison is in the animals index\n if(name === animals[i].name){\n \n return animals.shift(i,1);\n }\n \n}\n}", "_handleFlavourDelete(i) {\n const { newJuice } = this.state\n\n // updates state with flavour tag i removed\n this.setState({\n newJuice: {\n ...newJuice,\n flavours: [\n ...newJuice.flavours.slice(0, i),\n ...newJuice.flavours.slice(i + 1),\n ]\n }\n })\n\n return\n }", "function arrayItemRemove(favorites, index) {\n let removed = favorites.splice(index, 1);\n}", "function removeFruits(fruits, fruitsToRemove) {\n if(fruitsToRemove === undefined || fruitsToRemove.length === 0) return fruits;\n\n for(var i=0; i<fruits.length; i++){\n if(typeof fruits[i] !== \"string\")\n return;\n\n if(fruitsToRemove.indexOf(fruits[i]) !== -1){\n fruits.splice(i, 1);\n }\n\n }\n return fruits\n }", "function remove(animals, name) {\n //loop over animal array\n for (var i = 0; i < animals.length; i++) {\n //if name in animals array matches name\n if (animals[i].name === name) {\n //remove the animal from animals array using splice\n return animals.splice(name, 1);\n }\n } \n}", "function remove_nutrition(input_array) {\r\n var nutrition = ['nutrition'];\r\n var ingredients = ['ingredient', 'substance'];\r\n var stage = 1;\r\n for (var i = 0; i < input_array.length; i++) {\r\n if (stage == 1) {\r\n for (var j = 0; j < nutrition.length; j++) {\r\n if (input_array[i].toLowerCase().includes(nutrition[j].toLowerCase())) {\r\n stage = 2;\r\n input_array.splice(i, 1);\r\n i--;\r\n break;\r\n }\r\n }\r\n } else if (stage == 2) {\r\n for (var j = 0; j < ingredients.length; j++) {\r\n if (input_array[i].toLowerCase().includes(ingredients[j].toLowerCase())) {\r\n stage = 3;\r\n break;\r\n } else {\r\n input_array.splice(i, 1);\r\n i--;\r\n break;\r\n }\r\n }\r\n } else {\r\n break;\r\n }\r\n }\r\n return input_array;\r\n}", "function removeFruits(fruits, fruitsToRemove) {\n // FILL THIS IN\n var newFruitsArray = [];\n \n for(var i = 0; i < fruits.length; i++){\n var newFruits = fruits[i];\n if(fruitsToRemove.indexOf(newFruits) === -1){\n newFruitsArray.push(newFruits);\n }\n }\n \n return newFruitsArray;\n }", "function removeFruits(fruits, fruitsToRemove) {\n for (var i = 0; i < fruitsToRemove.length; i++) {\n for (var x = 0; x < fruits.length; x++) {\n if (fruitsToRemove[i]==fruits[x]) {\n fruits.splice(x, 1);\n };\n };\n }\n // FILL THIS IN\n }", "function remove(animals, name){\n// use for loop to look through array to see if name matches a name in the animals array of objects \n for(var i = 0; i < animals.length; i++){\n if(name === animals[i].name){\n// use .splice to then delete that item if found \n animals.splice(i,1);\n }\n }\n}", "function remove(animals, name) {\n// declare a for loop that loops through the indices of the animals array\n for (let i = 0; i < animals.length - 1; i++) {\n//declare a conditional that checks if the name parameter is in the array\n if (animals[i][\"name\"] === name) {\n//if true remove the name object from the array\n animals.splice(animals[i], 1);\n }\n }\n}", "function removeFruits(fruits, fruitsToRemove) {\n for (var i = 0; i < fruits.length; i++) { \n \t\tfor (var j = 0; j < fruitsToRemove.length; j++) { \n \t\t\tif (fruits[i] == fruitsToRemove[j]) { \n \t\t\t\tfruits.splice(i,1); \n \t\t\t\t\n \t\t\t}\n \t\t} \n \t}\n\t console.log(fruits);\n\t return fruits; \n }", "function remove(animals, name){\n \n \n for(var i = 0; i< animals.length; i++){\n//Check if name exist in animals array \n if(name === animals[i].name){\n//if name exist remove it \n animals.splice(i, 1);\n }\n }\n \n}", "function removeFruits(fruits, fruitsToRemove) {\n // FILL THIS IN\n for ( var i = 0; i < fruitsToRemove.length; i++ ) {\n for ( var j = fruits.length; j > -1; j-- ) {\n if ( fruits[j] == fruitsToRemove[i] ) { fruits.splice(j, 1); }\n }\n }\n return fruits;\n }", "function remove(arr, valueToRemove) {\n let index = arr.indexOf(valueToRemove);\n return arr = arr.slice(0, index).concat(arr.slice(index + 1)); // complete this statement\n}", "function remove(animals, name){\n //var loweranimals = animals.map(names => names.toLowerCase());\n //console.log(\"lowercase\" + animals);\n for (var i = 0; i < animals.length; i++ ){\n if( animals[i].name.toLowerCase() === name.toLowerCase() )\n {\n console.log('before splice ' + animals);\n animals.splice(i);\n console.log('after splice ' + animals);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests the NetworkHealthState and updates the page.
requestNetworkHealth_() { this.networkHealth_.getHealthSnapshot().then(result => { this.networkHealthState_ = result.state; }); }
[ "function updateHealthDisplay(){\n healthDisplay.html(userHealth);\n}", "function getStatusAndUpdate() {\n console.info('Fetching status');\n var errorMsg = 'Error fetching status from monitor app';\n app.xhr.open('get', app.urls.api + '/status/', true);\n app.xhr.onreadystatechange = function () {\n if (app.xhr.readyState !== 4) return;\n if (app.xhr.status === 200) {\n app.container.innerHTML = app.xhr.responseText;\n return;\n }\n app.container.innerHTML = errorMsg;\n return;\n };\n app.xhr.send();\n}", "updateStatus() {\n\t\tthis.setState( { loading: true } );\n\t\tthis.browserCachingStatus( 'refresh' );\n\t}", "function getClusterHealth() {\n\t\tvar options = {callbackParameter: 'callback'};\n\t\treqManager.sendMultiGetJsonP(\"clusterHealth\", urls, null, HealthinfoHandler, errorHandler, options);\n\t\tsetTimeout(function(){ \n\t\t\tgetClusterHealth();\n\t\t}, pollInterval);\n\t}", "function updateNetworkStatus() {\n if (navigator.onLine) { \n headerElement.classList.remove('bg-error');\n headerElement.classList.add('bg-gray');\n } else {\n console.log('App is offline'); \n headerElement.classList.add('bg-error')\n headerElement.classList.remove('bg-gray');\n }\n }", "function _updatePage() {\n $('main').removeClass('loaded loading');\n $('main').html(page_cache[encodeURIComponent(State.url)]);\n\n _showPage();\n _updateTitle();\n }", "updateNetworkState() {\n if (navigator.onLine) {\n if (this._isOffline === true) {\n this.showMsg(this._config.msgOnline);\n this.bgSyncPolyfill();\n }\n this._isOffline = false;\n } else {\n this.showMsg(this._config.msgOffline);\n this._isOffline = true;\n }\n }", "function onStatusRequest() {\n var request = new XMLHttpRequest();\n request.open(\"GET\", `${urlGuestAPI}?cmd=status&name=${username}`, true);\n request.timeout = 2000;\n request.onload = onStatusResponse;\n request.send();\n}", "function updateNetworkStatus() {\n if (navigator.onLine) {\n headerElement.classList.remove('app__offline');\n }\n else {\n headerElement.classList.add('app__offline');\n }\n }", "handleState() {\n return this.checkHealth();\n }", "function updateNetworkStatus() {\n if (navigator.onLine) {\n self.setState({ isAppOnline: true });\n }\n else {\n self.setState({ isAppOnline: false });\n }\n }", "async checkInfuraNetworkStatus() {\n const response = await fetch('https://api.infura.io/v1/status/metamask');\n const parsedResponse = await response.json();\n this.store.updateState({\n infuraNetworkStatus: parsedResponse\n });\n return parsedResponse;\n }", "function onHealthUpdate() {\n\ttry {\n\t\tTi.API.info('healthDataRefresh');\n\t\thealthDatas = [];\n\t\tif (OS_IOS) {\n\t\t\tcommonFunctions.openActivityIndicator(commonFunctions.L('activityLoading', LangCode));\n\t\t\thealthKitAuthorization();\n\t\t\tgetValuesFromHealthKit();\n\t\t} else {\n\t\t\tgoogleFitDataAndroid();\n\t\t}\n\t} catch(ex) {\n\t\tcommonFunctions.handleException(\"healthdatas\", \"onHealthUpdate\", ex);\n\t}\n}", "function updateUI()\n{\n\tvar stateSend = getDifferent(homeStateNew, homeState);\n\tif (stateSend !== undefined) {\n\t\tawsClient.send(stateSend);\n\t\twebSocket.send(stateSend);\n\t}\t\n}", "function doGetNodeStatus() {\n\n // Asynch version\n web3.net.getListening(function(error, result){\n if(error) setData('get_peer_count',error,true);\n else {\n // Since connected lets get the count\n web3.net.getPeerCount( function( error, result ) {\n if(error){\n setData('get_peer_count',error,true);\n } else {\n setData('get_peer_count','Peer Count: '+result,(result == 0));\n }\n });\n }\n });\n}", "function SimplifiedStatusIndicator() {\n var that = this;\n var DEBUG = false;\n\n // #region HEARTBEAT\n\n // Send heartbeat with updates to database\n // When this stops, the database will set status to offline\n var HEARTBEAT_TIMEOUT_MS = 5000,\n heartbeat;\n function startHeartbeatTimer() {\n if (heartbeat) {\n Script.clearTimeout(heartbeat);\n heartbeat = false;\n }\n\n heartbeat = Script.setTimeout(function() {\n heartbeat = false;\n getStatus(setStatus);\n }, HEARTBEAT_TIMEOUT_MS);\n }\n\n // #endregion HEARTBEAT\n\n\n // #region SEND/GET STATUS REQUEST\n\n function setStatusExternally(newStatus) {\n if (!newStatus) {\n return;\n }\n\n setStatus(newStatus);\n }\n\n\n var request = Script.require('request').request,\n REQUEST_URL = \"https://highfidelity.co/api/statusIndicator/\";\n function setStatus(newStatus) {\n if (heartbeat) {\n Script.clearTimeout(heartbeat);\n heartbeat = false;\n }\n\n if (newStatus && currentStatus !== newStatus) {\n currentStatus = newStatus;\n that.statusChanged();\n }\n\n var queryParamString = \"type=heartbeat\";\n queryParamString += \"&username=\" + AccountServices.username;\n\n var displayNameToSend = MyAvatar.displayName;\n \n queryParamString += \"&displayName=\" + displayNameToSend;\n queryParamString += \"&status=\" + currentStatus;\n var domainID = location.domainID;\n domainID = domainID.substring(1, domainID.length - 1);\n queryParamString += \"&organization=\" + domainID;\n\n var uri = REQUEST_URL + \"?\" + queryParamString;\n\n if (DEBUG) {\n console.log(\"simplifiedStatusIndicator: setStatus: \" + uri);\n }\n\n request({\n uri: uri\n }, function (error, response) {\n startHeartbeatTimer();\n\n if (error || !response || response.status !== \"success\") {\n console.error(\"Error with setStatus: \" + JSON.stringify(response));\n return;\n }\n });\n }\n\n\n // Get status from database\n function getStatus(callback) {\n var queryParamString = \"type=getStatus\";\n queryParamString += \"&username=\" + AccountServices.username;\n\n var uri = REQUEST_URL + \"?\" + queryParamString;\n\n if (DEBUG) {\n console.log(\"simplifiedStatusIndicator: getStatus: \" + uri);\n }\n\n request({\n uri: uri\n }, function (error, response) {\n if (error || !response || response.status !== \"success\") {\n console.error(\"Error with getStatus: \" + JSON.stringify(response));\n } else if (response.data.userStatus.toLowerCase() !== \"offline\") {\n if (response.data.userStatus !== currentStatus) {\n currentStatus = response.data.userStatus;\n that.statusChanged();\n }\n }\n \n if (callback) {\n callback();\n }\n });\n }\n\n\n function getLocalStatus() {\n return currentStatus;\n }\n\n // #endregion SEND/GET STATUS REQUEST\n\n\n // #region SIGNALS\n\n function updateProperties(properties) {\n // Overwrite with the given properties\n var overwriteableKeys = [\"statusChanged\"];\n Object.keys(properties).forEach(function (key) {\n if (overwriteableKeys.indexOf(key) > -1) {\n that[key] = properties[key];\n }\n });\n }\n\n \n var currentStatus = \"available\"; // Default is available\n function toggleStatus() {\n if (currentStatus === \"busy\") {\n currentStatus = \"available\";\n // Else if current status is \"available\" OR anything else (custom)\n } else {\n currentStatus = \"busy\";\n }\n\n that.statusChanged();\n\n setStatus();\n }\n\n\n // When avatar becomes active from being away\n // Set status back to previousStatus\n function onWentActive() {\n if (currentStatus !== previousStatus) {\n currentStatus = previousStatus;\n that.statusChanged();\n }\n setStatus();\n }\n\n\n // When avatar goes away, set status to busy\n var previousStatus = \"available\";\n function onWentAway() {\n previousStatus = currentStatus;\n if (currentStatus !== \"busy\") {\n currentStatus = \"busy\";\n that.statusChanged();\n }\n setStatus();\n }\n\n\n // Domain changed update avatar location\n function onDomainChanged() {\n var queryParamString = \"type=updateEmployee\";\n queryParamString += \"&username=\" + AccountServices.username;\n queryParamString += \"&location=unknown\";\n\n var uri = REQUEST_URL + \"?\" + queryParamString;\n\n if (DEBUG) {\n console.log(\"simplifiedStatusIndicator: onDomainChanged: \" + uri);\n }\n\n request({\n uri: uri\n }, function (error, response) {\n if (error || !response || response.status !== \"success\") {\n console.error(\"Error with onDomainChanged: \" + JSON.stringify(response));\n } else {\n // successfully sent updateLocation\n if (DEBUG) {\n console.log(\"simplifiedStatusIndicator: Successfully updated location after domain change.\");\n }\n }\n });\n }\n\n\n function statusChanged() {\n\n }\n\n // #endregion SIGNALS\n\n\n // #region APP LIFETIME\n\n // Creates the app button and sets up signals and hearbeat\n function startup() {\n MyAvatar.wentAway.connect(onWentAway);\n MyAvatar.wentActive.connect(onWentActive);\n MyAvatar.displayNameChanged.connect(setStatus);\n Window.domainChanged.connect(onDomainChanged);\n\n getStatus(setStatus);\n\n Script.scriptEnding.connect(unload);\n }\n\n\n // Cleans up timeouts, signals, and overlays\n function unload() {\n MyAvatar.wentAway.disconnect(onWentAway);\n MyAvatar.wentActive.disconnect(onWentActive);\n MyAvatar.displayNameChanged.disconnect(setStatus);\n Window.domainChanged.disconnect(onDomainChanged);\n if (heartbeat) {\n Script.clearTimeout(heartbeat);\n heartbeat = false;\n }\n }\n\n // #endregion APP LIFETIME\n\n that.toggleStatus = toggleStatus;\n that.setStatus = setStatus;\n that.getLocalStatus = getLocalStatus;\n that.statusChanged = statusChanged;\n that.updateProperties = updateProperties;\n\n startup();\n}", "function sendStatusUpdate() {\n var queryParamString = \"type=heartbeat\";\n queryParamString += \"&username=\" + AccountServices.username;\n queryParamString += \"&displayName=\" + MyAvatar.displayName;\n queryParamString += \"&status=\";\n queryParamString += currentStatus;\n\n var uri = REQUEST_URL + \"?\" + queryParamString;\n\n if (DEBUG) {\n console.log(\"sendStatusUpdate: \" + uri);\n }\n\n request({\n uri: uri\n }, function (error, response) {\n startHeartbeatTimer();\n\n if (error || !response || response.status !== \"success\") {\n console.error(\"Error with updateStatus: \" + JSON.stringify(response));\n return;\n }\n });\n }", "function checkNetworkStatus() { \n if (online) {\n displayOnline()\n } else {\n displayOffline()\n }\n}", "function displayNetworkStatus () {\n\tchrome.storage.sync.get(['newPlannedEvents', 'networkIsOkay'], function(storage){\n\t\tvar plannedEventsExist = storage.newPlannedEvents != null && storage.newPlannedEvents.length > 0;\n\t\tvar networkHasProblems = storage.networkIsOkay != null && storage.networkIsOkay == false;\n\t\tif (plannedEventsExist || networkHasProblems) {\n\t\t\tvar networkStatusHtml = '<tr id=\"plannedEventsContainerRow\"><td id=\"networkStatus\" colspan=\"2\"><div>\\n';\n\t\t\tif (networkHasProblems) {\n\t\t\t\tnetworkStatusHtml += '<div class=\"networkStatusTitle\"><a href=\"http://www.snap.net.nz/support/network-status\" target=\"_blank\">Snap\\'s network is not OK &ndash; click here for details</a></div>\\n';\n\t\t\t} else if (plannedEventsExist) {\n\t\t\t\tnetworkStatusHtml += '<img id=\"dismiss\" src=\"/img/stop.png\" title=\"Dismiss\" />\\n';\n\t\t\t\tnetworkStatusHtml += '<div class=\"networkStatusTitle\"><a href=\"http://www.snap.net.nz/support/network-status\" target=\"_blank\">Upcoming network events:</a></div>\\n';\n\t\t\t\tnetworkStatusHtml += '<div id=\"plannedEvents\">';\n\t\t\t\tfor (var x in storage.newPlannedEvents) {\n\t\t\t\t\tvar newPlannedEvent = storage.newPlannedEvents[x];\n\t\t\t\t\tnetworkStatusHtml += '<a href=\"http://www.snap.net.nz'+newPlannedEvent.href+'\" target=\"_blank\">'+newPlannedEvent.text+'</a><br />\\n';\n\t\t\t\t}\n\t\t\t\tnetworkStatusHtml += '</div>\\n';\n\t\t\t}\n\t\t\tnetworkStatusHtml += '</div></td></tr>\\n';\n\t\t\t$('tr#plannedEventsContainerRow').remove();\n\t\t\t$('tr#mainRow').after(networkStatusHtml);\n\t\t\tif (networkHasProblems) {\n\t\t\t\t$('td#networkStatus').addClass('networkIsNotOkay');\n\t\t\t}\n\t\t\t$('td#lastUpdated').parent('tr').addClass('addWhiteSpaceBelow');\n\t\t\t\n\t\t\t// When user clicks the Network Status #dismiss icon, mark newPlannedEvents as old so they don't get shown again, then shrink popup window\n\t\t\tif (plannedEventsExist && !networkHasProblems) {\n\t\t\t\t$('img#dismiss').on('click', function(){\n\t\t\t\t\tchrome.storage.sync.get(['oldPlannedEvents', 'newPlannedEvents'], function(storage) {\n\t\t\t\t\t\tvar oldPlannedEvents = [];\n\t\t\t\t\t\tfor (var x in storage.newPlannedEvents) {\n\t\t\t\t\t\t\tvar newPlannedEvent = storage.newPlannedEvents[x];\n\t\t\t\t\t\t\toldPlannedEvents.push(newPlannedEvent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchrome.storage.sync.set({ oldPlannedEvents: oldPlannedEvents }, function(){\n\t\t\t\t\t\t\tchrome.storage.sync.remove('newPlannedEvents', function(){\n\t\t\t\t\t\t\t\tvar bodyHeight = $('body').height();\n\t\t\t\t\t\t\t\tvar containerHeight = $('tr#plannedEventsContainerRow').height();\n\t\t\t\t\t\t\t\t$('tr#plannedEventsContainerRow').remove();\n\t\t\t\t\t\t\t\t$('html, body').css('height', (bodyHeight - containerHeight) + 'px');\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a button to confirm note changes
function createBtnConfirm() { let btnConfirm = document.createElement("button"); btnConfirm.className = "note-button note-button-bottom"; btnConfirm.addEventListener("click", function () { saveNotesToLocalStorage(); }); btnConfirm.appendChild(createImgConfirm()); return btnConfirm; }
[ "function closeNewNote() {\n \n const addNotebtn = document.createElement('button')\n addNotebtn.id = 'add-note-btn'\n addNotebtn.name = 'add-note'\n addNotebtn.innerText = '+ create a new note'\n\n const newNote = document.querySelector('div.new_note')\n newNote.parentElement.replaceChild(addNotebtn, newNote)\n \n document.querySelector('#add-note-btn').addEventListener('click', addNoteEditor) \n}", "function handleNoteButtonEvent(thisObj) {\n _changed = true;\n if ($(thisObj.getHtmlIds().noteContainer).visible()) {\n if (thisObj.getStandardValue() == thisObj.getMeta().seeNoteCui) {\n thisObj.clearNote();\n }\n else {\n thisObj.hideNote();\n }\n }\n else {\n thisObj.showNote();\n }\n }", "click_blackBookConfirmation_AddNoteButton(){\n this.blackBookConfirmation_AddNoteButton.waitForExist();\n this.blackBookConfirmation_AddNoteButton.click();\n }", "click_blackBookNote_SaveNoteButton(){\n this.blackBookNote_SaveNoteButton.waitForExist();\n this.blackBookNote_SaveNoteButton.click();\n }", "function DeleteClick() {\n notyConfirm('Are you sure to delete?', 'DeleteSupplierCreditNote()');\n}", "function addNoteButton(note) {\n var li = $(\"<div />\", slide.contentDocument);\n li.addClass(\"noteButton\");\n var time = $(\"<div />\", slide.contentDocument);\n time.addClass(\"noteButtonTime\");\n time.text(new Date(note.time).toLocaleString());\n li.append(time);\n var summary = $(\"<div />\", slide.contentDocument);\n summary.addClass(\"noteButtonSummary\");\n summary.text(noteSummary(note));\n li.append(summary);\n li.click(function () showNote(note, li));\n $(\"#noteList\", slide.contentDocument).append(li);\n return li;\n }", "function createButton(note) {\n const noteButton = document.createElement('button');\n noteButton.innerHTML = note.note;\n noteButton.addEventListener('click', function () {\n new Audio('/sounds/' + note.sound).play().then(r => console.log(r));\n });\n\n noteButton.classList.add('note-button');\n noteButton.style.backgroundColor = note.color;\n noteButton.style.height = noteButton.style.width = imageHeight / 6 + 'px';\n noteButton.style.left = 130 + note.topX + 'px';\n noteButton.style.top = fretboardDiv.getBoundingClientRect().top + note.topY + 'px';\n\n return noteButton;\n}", "setConfirmButtonText(t){this.confirmButtonText=t}", "toggleConfirmChangesButton() {\n\t\tif ( ! this.props.isEditing ) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet settingsMapping = {\n\t\t\tselectedContainer: 'containerID',\n\t\t\tselectedContainerAMP: 'ampContainerID',\n\t\t\tselectedAccount: 'accountID',\n\t\t\tuseSnippet: 'useSnippet',\n\t\t};\n\n\t\t// Disable the confirmation button if necessary conditions are not met.\n\t\tif ( ! this.canSaveSettings() ) {\n\t\t\tsettingsMapping = {};\n\t\t}\n\n\t\ttoggleConfirmModuleSettings( 'tagmanager', settingsMapping, this.state );\n\t}", "function toggleNotes() {\n if (notes) {\n notesButton.style.backgroundColor = \"var(--bg)\";\n notes = false;\n } else {\n notesButton.style.backgroundColor = \"var(--btn-out)\";\n notes = true;\n }\n update();\n}", "function cancelEditNote(note) {\n let noteToBeUpdated=note.parentNode;\n let prevText=\"\";\n prevNotes = prevNotes.filter(function( obj ) {\n if(obj.id === noteToBeUpdated.id)\n {prevText=obj.text;return false;}\n return true;\n });\n noteToBeUpdated.removeChild(noteToBeUpdated.getElementsByTagName(\"textarea\")[0]);\n noteToBeUpdated.removeChild(noteToBeUpdated.getElementsByTagName(\"button\")[0]);\n noteToBeUpdated.removeChild(noteToBeUpdated.getElementsByTagName(\"button\")[0]);\n let para=document.createElement(\"p\");\n para.innerText=prevText;\n noteToBeUpdated.appendChild(para);\n}", "click_blackBookNote_DeleteButton(){\n this.blackBookNote_DeleteButton.waitForExist();\n this.blackBookNote_DeleteButton.click();\n }", "setConfirmButtonText(t) {\n this.confirmButtonText = t;\n }", "function createNewNote(noteId){\n\n var noteSelection = document.getElementById(\"note-selection\");\n\n // Iterate over all the children of the note selection. If found a note\n // with the same id, set the note to a new id and start searching\n // from the beginning with the new note id to find a match.\n var children = noteSelection.children;\n var count = 0;\n var tempNoteId = noteId;\n for (var i = 0; i < children.length; i++){\n if (String(children.item(i).id) == tempNoteId){\n tempNoteId = noteId + \"(\" + ++count + \")\";\n i = -1;\n }\n }\n // set the new note id\n noteId = tempNoteId;\n // If the NoteBook doesnt already contain the id, create a blank entry for\n // it in the notebook\n if(!myNotebook.notes.hasOwnProperty(noteId)){\n myNotebook.notes[noteId] = \"\";\n }\n\n // Create new note button in the note selection box with its noteId displayed\n var newNote = document.createElement(\"BUTTON\");\n newNote.id = noteId;\n var t = document.createTextNode(noteId);\n newNote.appendChild(t);\n\n // Add an Event listener that when the user click on the note, save the\n // currently open note, replace the text area with the new notes content,\n // update the currentNoteId and highlight the new note button.\n newNote.addEventListener(\"click\", function () {\n saveCurrentNote();\n currentNoteId = this.id;\n document.getElementById(\"my-text-area\").value = myNotebook.notes[currentNoteId];\n var buttons = document.getElementsByClassName(\"btn-highlight\");\n for (var i = 0; i < buttons.length; i++){\n buttons[i].className = \"\";\n }\n this.className = \"btn-highlight\";\n });\n\n // Insert the new note at the end of the list, before the newNote button\n var newNoteBtn = document.getElementById(\"new-note-btn\");\n noteSelection.insertBefore(newNote, newNoteBtn);\n // Activate newly added note\n newNote.click();\n}", "function createNoteButton(text, noteNumber, element){\n\n\tvar button = function() {\n\t\tthis.button = document.createElement(\"BUTTON\");\n\t\tthis.listener = function(){\n\n\t\tplayTone(thequiz.get_question(current_question)[\"note\" + noteNumber]);\n\n\t\t};\n\n\t}\n\n\tbuttonName = new button();\n\n\tvar t = document.createTextNode(text);\n\tbuttonName.button.appendChild(t);\n\tdocument.getElementById(element).appendChild(buttonName.button);\n\n\t//$(\"<button></button\").text(text);\n\t//$(element).append()\n\n\tbuttonName.button.addEventListener('click', buttonName.listener);\n\n\treturn buttonName\n\n}", "function noteFinished() {\n\t\t\t\t\t\tlet txt;\n\t\t\t\t\t\tlet r = confirm(\"Are you sure the task is finished?\");\n\t\t\t\t\t\tif (r == true) {\n\t\t\t\t\t\t\ttxt = \"You closed the note\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttxt = \"You pressed Cancel\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdocument.getElementById(\"closing\").innerHTML = txt;\n\t\t\t\t\t}", "function generateBackendButton(filename, callback, cssClass, text, title, version = \"\", refreshCallback) {\n const button = document.createElement(\"button\")\n button.setAttribute(\"class\", cssClass)\n button.textContent = text\n button.title = title\n button.value = version\n button.onclick = () => {\n if (version === \"\") {\n createConfirmWindow(\"Do you really wish to delete this photo?\", () =>{\n callback(filename, refreshCallback)\n })\n } else {\n callback(filename, version)\n }\n\n }\n return button\n}", "function createUpdateButton() {\n // Get prestashop original update button\n var btn = document.getElementById('desc-module-update');\n var label = btn.querySelector('div');\n var icon = btn.querySelector('i');\n\n // If plugin has not updates, hide button and return\n if (typeof mbbx == 'undefined' || typeof mbbx.updateVersion == 'undefined')\n return btn.style.display = 'none';\n\n // Set mobbex update url\n var currentUrl = new URL(window.location.href);\n currentUrl.searchParams.set('run_update', 1);\n btn.setAttribute('href', currentUrl.href);\n\n // Show new version label\n label.innerHTML = `Actualizar a ${mbbx.updateVersion}`;\n label.style.color = '#2eacce';\n\n // Change icon\n icon.classList = 'material-icons';\n icon.innerHTML = 'get_app';\n icon.style.fontSize = '32px';\n }", "function confirmClose() {\n //console.log(styleWhenNoteWasOpened, editingField.classList)\n if (clickedNote === \"\") {\n if (textWasEdited) {\n saveNewNote();\n } else closeEditor();\n } else if (clickedNote.innerHTML != editingField.innerHTML || textWasEdited) {\n saveNote();\n } else closeEditor();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }