query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
The endQuiz() function clears the timer and brings the user to the High Scores Page
function endQuiz() { // clear interval clearInterval(intervalId); // Show the user the quiz is over setTimeout(showHighScore, 2000); }
[ "function endQuiz(){\n clearInterval(timerId)\n questionZoneEl.style.display = 'none';\n finalZoneEl.style.display = 'block';\n finalScoreEl.append(timeRemaining);\n\n}", "function allQuestionsAnswered() {\n clearTimeout(countdown);\n}", "function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}", "function startQuiz() {\n arrScore = []; // sets the score array to empty if not already done so\n // document.getElementsByName(\"question1\").defaultChecked = false;\n qz0Div.classList.add(\"hidden\"); // hide the quiz start div\n qz1Div.classList.remove(\"hidden\"); // show the 1st question\n scoreTimer(); // kick off the timer\n}", "function clearScreen(event) {\n pageTitleEl.textContent = '';\n instructionEl.textContent = '';\n startButtonEl.textContent = '';\n quizStarter();\n}", "function scoreTimer() {\n secondsLeft = originalTimerValue; // set the secondsLeft var the independently set global var for the timer value\n spanTime.textContent = Math.floor(secondsLeft); // display the initial time state on-screen as 60\n var timerInterval = setInterval(function () {\n // create a setInterval loop to a var called timerInterval\n secondsLeft = secondsLeft - timePenalty - 1; // on each interval, decrease secondsLeft by 1 and subtract answer penalty;\n timePenalty = \"\"; // Reset timePenalty so only applied once per wrong answer\n spanTime.textContent = Math.floor(secondsLeft); // update time readout in the header to the current sec.s remaining\n // If the current screen/div being viewed is NOT a question (in other words, the user isn't in mid-quiz)\n if (\n !qz0Div.classList.contains(\"hidden\") ||\n !qz11Div.classList.contains(\"hidden\") ||\n !scoresDiv.classList.contains(\"hidden\")\n ) {\n clearInterval(timerInterval); // stop the timer\n // else, if questions are currently being answered/quiz is in progress, AND if the seconds run out...\n } else if (secondsLeft < 1) {\n secondsLeft = 0; // reset the secondsLeft variable\n clearInterval(timerInterval); // stop the timer\n // alert(\"Time's up!\"); // alert the user that time is up\n // startingPoint(); // reset the time and div visibilities to the starting point...\n qz0Div.classList.add(\"hidden\"); // ...then hide the quiz question divs...\n qz1Div.classList.add(\"hidden\");\n qz2Div.classList.add(\"hidden\");\n qz3Div.classList.add(\"hidden\");\n qz3Div.classList.add(\"hidden\");\n qz4Div.classList.add(\"hidden\");\n qz5Div.classList.add(\"hidden\");\n qz6Div.classList.add(\"hidden\");\n qz7Div.classList.add(\"hidden\");\n qz8Div.classList.add(\"hidden\");\n qz9Div.classList.add(\"hidden\");\n qz10Div.classList.add(\"hidden\");\n qz11Div.classList.remove(\"hidden\"); // ...then show the tally page...\n scoreTitle.textContent = \"You have run out of time.\"; // ...and then change scoring div title to note time ran out\n }\n finalTimeRemaining = secondsLeft; // sets the finalTimeRemaining global variable on the clock to however many seconds are left\n spanTime.textContent = finalTimeRemaining; // set the countdown timer readout to be the remaining time on the clock.\n }, 1000); // interval timer loops every 1000 milliseconds aka every second\n}", "function finishGame() {\n clearBoard();\n score += timePassed > score ? timePassed % score : score % timePassed;\n scoreText.innerText = `${score}`;\n showStats();\n updateScoreTable();\n saveGameData();\n setTimer(STOP_TIMER);\n document.getElementsByClassName('details')[0].style.display = 'none';\n getById('player-name').style.pointerEvents = 'all';\n}", "function highScores() {\n if (\n !qz1Div.classList.contains(\"hidden\") ||\n !qz2Div.classList.contains(\"hidden\") ||\n !qz3Div.classList.contains(\"hidden\") ||\n !qz4Div.classList.contains(\"hidden\") ||\n !qz5Div.classList.contains(\"hidden\") ||\n !qz6Div.classList.contains(\"hidden\") ||\n !qz7Div.classList.contains(\"hidden\") ||\n !qz8Div.classList.contains(\"hidden\") ||\n !qz9Div.classList.contains(\"hidden\") ||\n !qz10Div.classList.contains(\"hidden\")\n ) {\n // if the quiz has started and any question is currently displayed...\n alert(\n \"You are in the middle of a timed quiz. Please complete the quiz before view High Scores.\"\n ); // show user alert that must complete quiz before viewing High Scores\n } else if (!qz11Div.classList.contains(\"hidden\")) {\n // else if score tally div is displayed (and the score hasn't been submitted)...\n alert(\"Please submit your score before viewing High Scores.\"); // show user alert that must submit score before viewing High Scores\n } else {\n // else if the quiz start or the score board is displayed...\n qz0Div.classList.add(\"hidden\"); // ...hide the quiz start div...\n scoresDiv.classList.remove(\"hidden\"); // ...and show the scoreboard div.\n submitScores();\n }\n}", "function reset() {\n\t\t// go to next question\n\t\tgame.qIndex++;\n\n\t\tif (game.qIndex < game.qArray.length) {\n\t\t\t//remove classes for styling answers\n\t\t\t$(\".answerArea\").find(\".correct\").toggleClass(\"correct\");\n\t\t\t$(\".answerArea\").find(\".selected\").toggleClass(\"selected\");\n\t\t\t//reset time\n\t\t\tgame.timeLeft = 8;\n\t\t\t//reset answer\n\t\t\tgame.currentAnswer = \"\";\n\t\t\t//go to next question\n\t\t\t// game.qIndex++;\n\t\t\t//toggle clock back onto page\n\t\t\t$(\".top-middle\").toggleClass(\"hide\")\n\t\t\t//hide right and wrong divs\n\t\t\t$(\".right\").addClass(\"hide\");\n\t\t\t$(\".wrong\").addClass(\"hide\");\n\t\t\tnewQ();\n\t\t} else {\n\t\t\tgameOver()\n\t\t}\n\t}", "function retrogameEnd() {\n questionContainerElement.classList.add('hide')\n userInfo.classList.add('hide')\n \n var retroHighScore = endScore;\n document.getElementById(\"id_high_score\").value = endScore+1;\n //Variable for leaderboard \n document.getElementById(\"scoreform\").style.display = \"block\";\n document.getElementById(\"id_high_score\").value = retroHighScore;\n submitButton.classList.remove('hide')\n roundNum.classList.add('hide')\n logoutButton.classList.add('hide')\n}", "function goToQuiz() {\n toQuiz(funcGuess)\n funcGuess = \"\"\n }", "function easygameEnd() {\n questionContainerElement.classList.add('hide')\n userInfo.classList.add('hide')\n var easyHighScore = endScore;\n document.getElementById(\"id_high_score\").value = endScore+1;\n //Variable for leaderboard \n document.getElementById(\"scoreform\").style.display = \"block\";\n document.getElementById(\"id_high_score\").value = easyHighScore;\n submitButton.classList.remove('hide')\n roundNum.classList.add('hide')\n logoutButton.classList.add('hide')\n\n}", "function gameEnd() {\n startingTime = 0;\n formatTime(startingTime);\n clearInterval(timer);\n let currentCards = qsa(\".card\");\n let i;\n for (i = 0; i < currentCards.length; i++) {\n currentCards[i].removeEventListener(\"click\", cardSelect, false);\n }\n $(\"refresh\").onclick = function() {\n return false;\n };\n deselectAll();\n\n }", "function decrement(){\n\ttimeNumber--;\n\n\t//Show time in time span\n\t$(\".time\").html(timeNumber);\n\n\t//if time runs out, set question to unanswered. \n\tif(timeNumber === 0){\n\t\tsetQuestionUnanswered();\n\t}\n}", "function getNextQn() {\n setTimeout(function() {\n // Clear the UI to prepare for next question.\n $(\"#stopwatch\").empty();\n $(\"#survey-says\").empty();\n $(\"#wonder-woman\").empty();\n\n if (wonderWomenTrivia.getNumQnsAsked() < numQns) {\n // ASSERT: Game is not over.\n wonderWoman = wonderWomenTrivia.getUniqueRandomQnA(); \n correctAns = displayQnASet(wonderWoman);\n }\n else {\n // ASSERT: Game is over.\n displayGameStats();\n }\n }, ((timeout / 3) * 1000));\n }", "function displayGobackAndClearScore() {\n goBack = document.createElement('input');\n clearHighScoresbtn = document.createElement('input');\n listener.appendChild(clearHighScoresbtn);\n listener.appendChild(goBack);\n goBack.setAttribute(\"type\", \"submit\");\n clearHighScoresbtn.setAttribute(\"type\", \"submit\");\n clearHighScoresbtn.setAttribute(\"class\", \"clear\");\n goBack.setAttribute(\"value\", \"GoBack\");\n goBack.setAttribute(\"class\", \"goBack\");\n goBack.setAttribute(\"style\", \"margin-left:50px;margin-top:50px;color:rgb(56, 10, 10); font-size:20px; cursor: pointer;background:rgb(158, 62, 62)\")\n clearHighScoresbtn.setAttribute(\"style\", \"margin-left:30px;color:rgb(56, 10, 10); font-size:20px;margin-top:50px; cursor: pointer;background:rgb(158, 62, 62)\")\n clearHighScoresbtn.setAttribute(\"value\", \"ClearHighScores\");\n goback = document.querySelector(\".clear\");\n clearHighScoresbuton = document.querySelector(\".clear\");\n goBack = document.querySelector(\".goBack\");\n // Restarting the game\n goBack.addEventListener(\"click\", function (e) {\n e.preventDefault();\n window.location.href = \"https://hhutku.github.io/code-quiz/\";\n });\n // Clearing the result scores\n clearHighScoresbuton.addEventListener(\"click\", function (e) {\n e.preventDefault();\n localStorage.clear();\n containerHighScores.setAttribute(\"style\", \"display:none\");\n });\n}", "function scoreTally() {\n getQ10Answers(); // Call the corresponding getQ#Answers function\n arrScore.push(q10FinalAnswer); // Push the final submitted answer to a array to hold all answers selected\n let timeDelay = 2; // Set a 2 sec. delay to show the answer validation message\n if (q10Answers.value == \"true\") {\n // If the answer selected is correct...\n q10CorrectMsg.classList.remove(\"hidden\"); // ...Show the \"Correct\" validation message\n } else {\n // If it's incorrect...\n q10IncorrectMsg.classList.remove(\"hidden\"); // ...Show the \"Incorrect\" validation message\n }\n let timeDelayInterval = setInterval(function () {\n // Create the timer interval\n timeDelay--; // Decrement the previously set time delay for showing messaging by once per loop\n if (timeDelay === 0) {\n // Once the interval loop hits 0...\n clearInterval(timeDelayInterval); // ...Clear the timer interval\n q10CorrectMsg.classList.add(\"hidden\"); // ...Hide the correct answer validation message again\n q10IncorrectMsg.classList.add(\"hidden\"); // ...Hide the wrong answer validation message again\n qz10Div.classList.add(\"hidden\"); // ...Hide the current question\n qz11Div.classList.remove(\"hidden\"); // ...Show the next question\n }\n }, 1000); // ...Set the interval looping at 1000 milliseconds (aka 1 sec. per interval loop)\n scoreTitle.textContent = \"You have completed this quiz.\"; // Updates the div title with a \"completed\" notice.\n spanTime.textContent = finalTimeRemaining; // sets a var to the final time displayed on quiz completion\n finalTimeRemaining = parseInt(finalTimeRemaining); // parses that displayed time string into an integer resets the timeRemaining value to it\n correctCount = 0; // set the correct count var to 0\n for (i = 0; i < arrScore.length; i++) {\n // for loop to loop through the answers array\n if (arrScore[i] == \"true\") {\n // if the current index position has a value of \"true\" (our value for \"correct\")\n correctCount++; // increment the correct counter global variable by 1\n } else {\n // if it's false or empty, make some space in the console and do nothing\n console.log(\"---\");\n }\n }\n spanNumCorrect.textContent = correctCount; // set the text in the page that relays the # correct\n let percentTimeMultiplier = \"\"; // create a var to hold a calculated multiplier to use for a weighted score\n if (finalTimeRemaining < 1) {\n // if the time has run out (or possible been driven below zero due to penalties)\n percentTimeMultiplier = 0; // set the multiplier to 0\n } else {\n // if the quiz was completed in time\n percentTimeMultiplier =\n 1 - (originalTimerValue - finalTimeRemaining) / originalTimerValue; // calculate a % change in time for adjusting the score\n }\n weightedScore = Math.ceil(\n correctCount * percentTimeMultiplier + correctCount\n ); // set a weighted score var to be the rounded up sum of the correct responses and the correct responses * the % change in time multipier\n spanFinalScore.textContent = weightedScore; // set the text relaing the final weighted score to the calculated variable\n}", "function startQuizz() {\n setPreviousTime(currentDate.getTime())\n addTimers();\n setQuestionNumber(0);\n }", "function handleRestartQuiz() {\n $('main').on('click', '#restart-quiz-btn', event => {\n console.log(\"Restarting Quiz\");\n\n STORE.quizStarted = false;\n STORE.currentQuestion = 0;\n STORE.score = 0;\n STORE.submittingAnswer = false;\n renderQuiz();\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
validateTheEnteredName(): validates the entered name as per current item name Updates the teddy dialogue box with text stating whether the answer is correct or wrong and also makes the item image draggable if the name is correct
function validateTheEnteredName(){ //Scrolls to the question element.Useful in portrait mode. scrollRightPanelContainer(); //Fetch the user entered name var enteredName = document.getElementById('answerInputElement').value; //Check if the user entered an item name and the name is equal to current item if(enteredName != "undefined" && (currentItem.itemName.toLowerCase() === enteredName.toLowerCase())){ //Make the image draggable document.getElementById('item_'+currentItem.itemId).setAttribute('draggable' ,'true'); //Change the dialogue box to tell the answer is correct and text displayed //id chosen based on portrait or landscape mode if(window.innerWidth > window.innerHeight){ document.getElementsByClassName('tdialogue-box-text')[0].innerHTML = teddyDialogues.gameCorrectItem; } else { document.getElementsByClassName('tdialogue-box-text')[0].innerHTML = teddyDialogues.gameCorrectItemPotrait; } //Recreate the rooms on left side for the next question resetLeftPanel(); } else { //Change the dialogue box to tell that answer is wrong document.getElementsByClassName('tdialogue-box-text')[0].innerHTML = teddyDialogues.gameIncorrectItem; } }
[ "function validate_name(name_id, item)\n{\n\tvar name = document.getElementById( name_id );\n\tif( ! name || (name.value.length === 0) )\n\t{\n\t\talert( 'Please enter a name for the \"' + item + '\"' );\n\t\treturn null;\n\t}\n\treturn name.value;\n}", "function validateName()\n{\n\t//variable name is set by element id contactName from the form\n\tvar name = document.getElementById(\"contactName\").value; \n\t\n\t//validation for name\n\tif(name.length == 0)\n\t{\n\t\tproducePrompt(\"Name is Required\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!name.match(/^[A-Za-z]*\\s{1}[A-Za-z]*$/))\n\t{\n\t\tproducePrompt(\"First and Last name Please\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Welcome \" + name, \"namePrompt\", \"green\"); \n\t\treturn true; \n\t\n}", "function nameValidate(name) {\r\n var nameValue = document.getElementById('contact-name').value;\r\n var nameRegex = /^[a-zA-Z \\-\\']+(?:\\s[a-zA-Z]+)*$/.test(nameValue);\r\n var inputErr = document.getElementsByTagName('input')[1];\r\n\r\n if (nameValue == null || nameValue == \"\") {\r\n document.getElementById('name-err').innerHTML = \"This field is required.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (!nameRegex) {\r\n document.getElementById('name-err').innerHTML = \"Alphabet characters only.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (nameRegex) {\r\n var inputValid = document.getElementsByTagName('input')[1];\r\n inputValid.setAttribute('class', 'input-valid');\r\n document.getElementById('name-err').style.display = 'none';\r\n return true;\r\n }\r\n }", "function validateUpdateOwnerName(firstname,e) {\n if (!isValidName(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει τουλάχιστον δύο χαρακτήρες)');\n e.preventDefault();\n } else if (!isOnlyLetters(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει μόνο γράμματα)');\n e.preventDefault();\n } else {\n $(\".nameOwnerUpdateErr\").text(\"\");\n }\n } //end function ", "function validatePlayerName() {\n const name = getGameForm()['player-name'].value;\n if (!name.trim()) {\n getById('play-button').style.visibility = 'hidden';\n } else {\n playerName = name;\n getById('play-button').style.visibility = 'visible';\n }\n}", "function name_check() {\r\n name_warn();\r\n final_validate();\r\n}", "function validateNameField(reporting = true) {\n var nameField = $(\"#name\");\n if (!hasText(nameField)) {\n console.log(\"name error\");\n setError(nameField, true);\n if (reporting) {\n displayError(\"You need to tell me your name!\");\n }\n return false;\n } else {\n setError(nameField, false);\n displayError(\"\");\n return true;\n }\n}", "function check_gardening_botanical_name() \n\t\t{ \n\t\t\tvar boname_length = $(\"#update_gardening_botanical_name\").val().length;\n\n\t\t\tif(boname_length == \"\" || boname_length == null)\n\t\t\t\t{\n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Please fill in data into the field\"); \n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t\t}\n\t\t\t\n\t\t\telse if(boname_length <2 || boname_length > 20) {\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Should be between 2-20 characters\");\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t}\n\t\t\t\n\t\t\telse \n\t\t\t{\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").hide();\n\t\t\t}\n\t\t}", "function renameElement() {\n var id = $(this).parent().attr(\"data-id\");\n var item = fileSystem.findElementById(id);\n var editedItemName = prompt(\"Please enter the new name\", item.name);\n if (editedItemName == undefined) {\n return;\n }\n try {\n fileSystem.renameElement(id, editedItemName);\n } catch (err) {\n alert(err.message);\n }\n updateUI();\n }", "function LocationNameValidation(e) {\n\tvar ret\n\tvar keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;\n\tif (document.getElementById('locNameText').value.length == 0) {\n\t\tret = ((keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t} else if ((preLocVal == 32 || preLocVal == 46) && (keyCode == 32 || keyCode == 46)) {\n\t\tret = false;\n\t} else {\n\t\tret = ((keyCode == 32) || (keyCode == 46)\n\t\t\t\t|| (keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (keyCode >= 48 && keyCode <= 57)|| (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t\tpreLocVal = keyCode\n\n\t}\n\tdocument.getElementById(\"error\").style.display = ret ? \"none\" : \"inline\";\n\treturn ret;\n}", "function city_name_dialog(suggested_name, unit_id) {\n // reset dialog page.\n $(\"#city_name_dialog\").remove();\n $(\"<div id='city_name_dialog'></div>\").appendTo(\"div#game_page\");\n\n $(\"#city_name_dialog\").html($(\"<div>What should we call our new city?</div>\"\n\t\t \t + \"<input id='city_name_req' type='text' value='\" \n\t\t\t + suggested_name + \"'>\"));\n $(\"#city_name_dialog\").attr(\"title\", \"Build New City\");\n $(\"#city_name_dialog\").dialog({\n\t\t\tbgiframe: true,\n\t\t\tmodal: true,\n\t\t\twidth: \"300\",\n\t\t\tclose: function() {\n\t\t\t\tkeyboard_input=true;\n\t\t\t},\n\t\t\tbuttons: [\t{\n\t\t\t\t\ttext: \"Cancel\",\n\t\t\t\t click: function() {\n\t\t\t\t\t\t$(\"#city_name_dialog\").remove();\n \t\t\t\t\tkeyboard_input=true;\n\t\t\t\t\t}\n\t\t\t\t},{\n\t\t\t\t\ttext: \"Ok\",\n\t\t\t\t click: function() {\n\t\t\t\t\t\tvar name = $(\"#city_name_req\").val();\n\t\t\t\t\t\tif (name.length == 0 || name.length >= MAX_LEN_NAME - 4 \n\t\t\t\t\t\t || encodeURIComponent(name).length >= MAX_LEN_NAME - 4) {\n\t\t\t\t\t\t swal(\"City name is invalid\");\n\t\t\t\t\t\t return;\n\t\t\t\t\t\t}\n\n var actor_unit = game_find_unit_by_number(unit_id);\n\n var packet = {\"pid\" : packet_unit_do_action,\n \"actor_id\" : unit_id,\n \"target_id\": actor_unit['tile'],\n \"value\" : 0,\n \"name\" : encodeURIComponent(name),\n \"action_type\": ACTION_FOUND_CITY};\n\t\t\t\t\t\tsend_request(JSON.stringify(packet));\n\t\t\t\t\t\t$(\"#city_name_dialog\").remove();\n\t\t\t\t\t\tkeyboard_input=true;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t});\n\n $(\"#city_name_req\").attr('maxlength', MAX_LEN_NAME);\n\t\n $(\"#city_name_dialog\").dialog('open');\t\t\n\n $('#city_name_dialog').keyup(function(e) {\n if (e.keyCode == 13) {\n \tvar name = $(\"#city_name_req\").val();\n\n var actor_unit = game_find_unit_by_number(unit_id);\n\n var packet = {\"pid\" : packet_unit_do_action,\n \"actor_id\" : unit_id,\n \"target_id\": actor_unit['tile'],\n \"value\" : 0,\n \"name\" : encodeURIComponent(name),\n \"action_type\": ACTION_FOUND_CITY};\n\tsend_request(JSON.stringify(packet));\n\t$(\"#city_name_dialog\").remove();\n keyboard_input=true;\n }\n });\n keyboard_input=false;\n}", "function queueNames(name) {\n\n // Make sure name is in lower case \n name = name.toLowerCase();\n\n //Take first letter of name\n firstLetter = name.charCodeAt(0);\n\n if (firstLetter > 108 && firstLetter < 123) {\n\n // Displays 'Back to the line!' alert pop-up, if the first letter of the name is between the letter L and is letter Z.\n alert('Back to the line!');\n\n } else if (firstLetter > 122 || firstLetter < 97) {\n\n // Display 'Invalid Name!' alert pop-up, if the first letter is not a chracter from the alphabet.\n alert('Invalid Name!');\n\n\n } else {\n //Display 'Next' alert pop-up, if the first letters is before letter M. \n alert('Next!')\n }\n}", "function uomShortNameValidation(e) {\n\tvar ret\n\tvar keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;\n\tif (document.getElementById('uomShortNameText').value.length == 0) {\n\t\tret = ((keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t} else if ((test == 32) && (keyCode == 32 )) {\n\t\tret = false;\n\t} else {\n\t\tret = ((keyCode == 32)\n\t\t\t\t|| (keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t\ttest = keyCode\n\n\t}\n\tdocument.getElementById(\"error1\").style.display = ret ? \"none\" : \"inline\";\n\treturn ret;\n}", "function submetTheGameResults() {\n\n\tsetDisplayVisible(\"nameSubmet\");\n\n\tif (element(\"userName\").value !== \"\") {\n\t\tapp.userName = element(\"userName\").value;\n\n\t\tsendTheNumberOfGuessesToDataBase();\n\t\t\n\t} else {\n\n\t\t\n\t\tsetTheElementInnerTextWithNewColor(\"checked-number-worning\",\"Error Enter your Name ...!!!\",\"#df2920\");\n\n\t}\n\n}", "function isNameOK(field) {\r\n\t\r\n\tvar name = field.value.trim();\r\n\tconsole.log(name); // TEST CODE\r\n\t\r\n\tif (emptyString(name)) {\r\n\t\talert('Le nom du groupe doit être renseigné.');\r\n\t\treturn false;\r\n\t}\r\n\telse if (fiftyChar(name)) {\r\n\t\talert('Le nom du groupe ne peut pas dépasser cinquante caractères.');\r\n\t\treturn false;\r\n\t}\r\n\telse {\r\n\t\treturn true;\r\n\t}\r\n}", "function blurName() {\n if(name === '') {\n toast.error(`Preencha o campo nome corretamente!`, {\n\t\t\t\tposition: \"top-right\",\n\t\t\t\tautoClose: false,\n\t\t\t\thideProgressBar: true,\n\t\t\t\tccorretamenteloseOnClick: true,\n\t\t\t\tpauseOnHover: false,\n\t\t\t\tdraggable: true,\n\t\t\t\tprogress: undefined,\n\t\t\t});\n }\n }", "function checkDialog(name, expectedNameText, expectedNameHtml) {\n var expectedText = expectedNameText || name;\n var expectedHtml = expectedNameHtml || expectedText;\n\n // Configure the test profile and show the confirmation dialog.\n var testProfile = self.testProfileInfo_(true);\n testProfile.name = name;\n CreateProfileOverlay.onSuccess(testProfile);\n assertEquals('managedUserCreateConfirm',\n OptionsPage.getTopmostVisiblePage().name);\n\n // Check for the presence of the name and email in the UI, without depending\n // on the details of the messsages.\n assertNotEquals(-1,\n $('managed-user-created-title').textContent.indexOf(expectedText));\n assertNotEquals(-1,\n $('managed-user-created-switch').textContent.indexOf(expectedText));\n var message = $('managed-user-created-text');\n assertNotEquals(-1, message.textContent.indexOf(expectedText));\n assertNotEquals(-1, message.textContent.indexOf(custodianEmail));\n\n // The name should be properly HTML-escaped.\n assertNotEquals(-1, message.innerHTML.indexOf(expectedHtml));\n\n OptionsPage.closeOverlay();\n assertEquals('settings', OptionsPage.getTopmostVisiblePage().name, name);\n }", "function askForName() {\n var name = \"\";\n\n // Ensure name is valid\n while(name === \"\" || name === null) {\n name = window.prompt(\"Please enter a display name.\", \"\");\n }\n\n console.log(\"Player name set to \" +name+ \".\");\n return name;\n }", "function formValidateParticipant() {\n var inputNames = document.querySelectorAll(\"input#name\");\n \n // validates each participant name\n for(var i = 0; i < inputNames.length; i++) {\n var name = inputNames[i].value;\n // checks whether name is invalid or null\n if(!nameValidate(name) || name == null || name == \"\") {\n alert(\"Invalid participant name. Participant name should always begin with a capital letter.\");\n return false;\n }\n }\n return true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if the URL anchor destiny is the starting section (the one using 'active' class before initialization)
function isDestinyTheStartingSection(){ var anchors = window.location.hash.replace('#', '').split('/'); var destinationSection = getSectionByAnchor(decodeURIComponent(anchors[0])); return !destinationSection.length || destinationSection.length && destinationSection.index() === startingSection.index(); }
[ "onCurrent(element) {\n\t\tvar slide = _.getSlide(element);\n\n\t\tif (slide) {\n\t\t\treturn \"#\" + slide.id === location.hash;\n\t\t}\n\n\t\treturn false;\n\t}", "function atBeginning() {\n\treturn currentSceneIndex === 0;\n}", "function activeRoute(routeName) {\n return window.location.href.indexOf(routeName) > -1 ? true : false\n }", "function loadAnchor() {\n\tvar anchor = \"\" + window.location;\n\t\n\tvar index = anchor.indexOf('?');\n\tif (index != -1) { anchor = anchor.substring(0,index); }\n\t\n\tindex = anchor.indexOf('#');\n\tif (index == -1 || index == anchor.length-1) {\n\t\treturn false;\n\t}\n\t\n\tanchor = decodeURIComponent(anchor.substring(index+1));\n\tfor (var roleIndex = 0; roleIndex < roles.length; roleIndex++) {\n\t\tvar role = roles[roleIndex];\n\t\tif (role.title == anchor) {\n\t\t\tshowLessons(getRole(roleIndex));\n\t\t\treturn true;\n\t\t}\n\t\tfor (var lessonIndex = 0; lessonIndex < role.lessons.length; lessonIndex++) {\n\t\t\tvar lesson = role.lessons[lessonIndex];\n\t\t\tif (lesson.title == anchor) {\n\t\t\t\tshowLesson(getLesson(roleIndex, lessonIndex));\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}", "function SetActiveLink(){\r\n var path = window.location.pathname;\r\n var pathSplit = path.split(\"/\");\r\n var urlEnd = pathSplit[pathSplit.length - 1];\r\n\r\n var activeLinkID = url_navlink_dict[urlEnd];\r\n $(\"#\" + activeLinkID).addClass(\"active\");\r\n}", "function contains_hash(){\n var hash = document.location.hash;\n return hash && (section[0].id == hash.substr(1) ||\n section.find(hash.replace(\".\",\"\\\\.\")).length>0);\n }", "function activeNavigation() {\n var locationUrl = window.location.href;\n var handlerAndAction = locationUrl\n .replace(/(.*\\/\\/vacation.+?\\/)(index.cfm\\/)?/i, '')\n .replace(/\\?.+/, '')\n .split('/');\n var currentHandler = handlerAndAction[0].toLowerCase();\n var currentAction = handlerAndAction[1] || 'index';\n var currentObjectId = handlerAndAction[2];\n\n $('[data-handler=\"' + currentHandler + '\"]').addClass('active');\n\n // breadcrumbs\n buildBradcrumbs(currentHandler, currentAction, currentObjectId);\n}", "function isStartOfSlide(elt)\n{\n if (elt.nodeType != 1) return false;\t\t// Not an element\n if (elt.classList.contains(\"slide\")) return true;\n if (window.getComputedStyle(elt).getPropertyValue('page-break-before') ==\n 'always') return true;\n if (elt.nodeName != \"H1\") return false;\n\n /* The element is an H1. It starts a slide unless it is inside class=slide */\n while (true) {\n elt = elt.parentNode;\n if (!elt || elt.nodeType != 1) return true;\n if (elt.classList.contains(\"slide\")) return false;\n }\n}", "function currentMenuItem() {\n\n\tvar cur_url = window.location.href;\n\tvar firstChar = cur_url.indexOf(\"/\", 7);\n\tvar lastChar = cur_url.indexOf(\"/\", firstChar + 1);\n\n\tif (lastChar > -1) {\n\t\tvar cur_word = cur_url.substring(firstChar + 1, lastChar);\n\t} else {\n\t\tvar cur_word = 'home';\n\t}\n\n\t$('.menu li').each(function(){\n\n\t\tif ( $(this).hasClass(cur_word) ) {\n\n\t\t\t$(this).addClass('active');\n\n\t\t} else if ( $(this).hasClass('active') ) {\n\n\t\t\t$(this).removeClass('active');\n\n\t\t}\n\t});\n}", "function isHome() {\n return \"home\" == gadgets.views.getCurrentView().name_;\n}", "function crawlStarted() {\n return ($localStorage.currentCrawl !== undefined);\n }", "function setActiveSubsection(activeHref) {\n var tocLinkToActivate = document.querySelector(\".toc a[href$='\" + activeHref + \"']\");\n var currentActiveTOCLink = document.querySelector(\".toc a.active\");\n if (tocLinkToActivate != null) {\n if (currentActiveTOCLink != null && currentActiveTOCLink !== tocLinkToActivate) {\n currentActiveTOCLink.classList.remove(\"active\");\n }\n tocLinkToActivate.classList.add(\"active\");\n }\n}", "function checkURL()\n{\n if (/\\bfull\\b/.test(location.search)) toggleMode();\n if (/\\bstatic\\b/.test(location.search)) interactive = false;\n}", "isStart(editor, point, at) {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false;\n }\n\n var start = Editor.start(editor, at);\n return Point.equals(point, start);\n }", "function onScroll(event){\n var scrollPos = $(document).scrollTop();\n $('a.activeOnScroll').each(function () {\n var currLink = $(this);\n var refElement_id = $(this).attr(\"href\");\n var refElement = $(refElement_id);\n if ( (refElement.offset().top <= scrollPos ) && ( refElement.offset().top + refElement.height() > scrollPos ) ) {\n $('a.activeOnScroll').parent().removeClass(\"active\");\n currLink.parent().addClass(\"active\");\n }\n });\n}", "function showTabsBasedOnAnchor() {\n if (BootstrapTabHistory.options.showTabsBasedOnAnchor) {\n var anchor = window.location && window.location.hash;\n\n if (anchor) {\n var $tabElement = showTabForSelector(anchor);\n\n if ($tabElement && window.addEventListener && window.removeEventListener) {\n var anchorYOffset = function ($tabElement) {\n var elementSetting = $tabElement.data('tab-history-anchor-y-offset');\n\n if (elementSetting === undefined) {\n return BootstrapTabHistory.options.defaultAnchorYOffset;\n } else {\n return elementSetting;\n }\n }($tabElement); // HACK: This prevents scrolling to the tab on page load. This relies on the fact that we should never get\n // here on `history.forward`, `history.back`, or `location.reload`, since in all those situations the\n // `history.state` object should have been used (unless the browser did not support the modern History API).\n\n\n if (anchorYOffset || anchorYOffset === 0) {\n var scrollListener = function resetAnchorScroll() {\n window.removeEventListener('scroll', scrollListener);\n window.scrollTo(0, anchorYOffset);\n };\n\n window.addEventListener('scroll', scrollListener);\n }\n }\n } else {\n $(\"ul.nav:not('.exclude-from-tab-history')\").each(function () {\n if (!jQuery(this).find('li a .active').length) jQuery(this).find('li a').first().tab('show');\n });\n }\n }\n }", "function CheckUrlEnd(checkUrl){\r\n var path = window.location.pathname;\r\n var pathSplit = path.split(\"/\");\r\n var urlEnd = pathSplit[pathSplit.length - 1];\r\n\r\n if(urlEnd == checkUrl){\r\n return true;\r\n }\r\n\r\n return false;\r\n}", "async isCorrectPageOpened() {\n let currentURL = await PageUtils.getURL()\n return currentURL.indexOf(this.pageUrl)!== -1\n }", "function sectionOn() { }", "function getPage() {\n\tvar sPath = window.location.pathname;\n\tvar sPage = sPath.substring(sPath.lastIndexOf('/') + 1);\n\tif (sPage == \"scheduled.jsf\") {\n\t\tdocument.getElementById(\"scheduledLink\").setAttribute(\"class\",\"active\");\n\t} else if (sPage == \"reports.jsf\") {\n\t\tdocument.getElementById(\"reportsLink\").setAttribute(\"class\",\"active\");\n\t} else {\n\t\tdocument.getElementById(\"homeLink\").setAttribute(\"class\",\"active\");\n\t}\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMGUI_API void GetTexDataAsRGBA32(unsigned char out_pixels, int out_width, int out_height, int out_bytes_per_pixel = NULL); // 4 bytesperpixel
GetTexDataAsRGBA32() { return this.native.GetTexDataAsRGBA32(); }
[ "GetTexDataAsAlpha8() {\r\n return this.native.GetTexDataAsAlpha8();\r\n }", "function modifyImgRGBA(data, indexes, typeOfJoint) {\n var len = indexes.length; /// length of buffer\n var i = 0; /// cursor for RGBA buffer\n var t = 0; /// cursor for RGB buffer\n\n var color = jointColor(typeOfJoint);\n\n // Modify img RGB\n for(; i < len; i += 1) {\n idx = indexes[i] * 4;\n\n data[idx] = color[0]; /// copy RGB data to canvas from custom array\n data[idx + 1] = color[1];\n data[idx + 2] = color[2];\n data[idx + 3] = 255; /// remember this one with createImageBuffer \n }\n\n return data;\n}", "function createDataTexture(gl, floatArray) {\n var width = floatArray.length / 4, // R,G,B,A\n height = 1,\n texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D,\n 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, floatArray);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n return texture;\n }", "function readPixels(texture, face) {\n var rt = new pc.RenderTarget({ colorBuffer: texture, depth: false, face: face });\n var data = new Uint8ClampedArray(texture.width * texture.height * 4);\n var device = texture.device;\n device.setFramebuffer(rt._glFrameBuffer);\n device.initRenderTarget(rt);\n device.gl.readPixels(0, 0, texture.width, texture.height, device.gl.RGBA, device.gl.UNSIGNED_BYTE, data);\n return data;\n}", "function getPixel(imageData, x, y) {\n var index = (y * 4) * imageData.width + (x * 4),\n data = imageData.data;\n\n return {\n index: {\n r: index,\n g: index + 1,\n b: index + 2,\n a: index + 3\n },\n\n 'byte': {\n r: data[index],\n g: data[index + 1],\n b: data[index + 2],\n a: data[index + 3]\n },\n\n 'float': {\n r: toFloat(data[index]),\n g: toFloat(data[index + 1]),\n b: toFloat(data[index + 2]),\n a: toFloat(data[index + 3])\n }\n };\n}", "map (tu, tv) {\n if (this.internalBuffer) { \n // using a % operator to cycle/repeat the texture if needed\n let u = Math.abs(((tu * this.width) % this.width)) >> 0;\n let v = Math.abs(((tv * this.height) % this.height)) >> 0;\n\n let pos = (u + v * this.width) * 4;\n\n let r = this.internalBuffer.data[pos];\n let g = this.internalBuffer.data[pos + 1];\n let b = this.internalBuffer.data[pos + 2];\n let a = this.internalBuffer.data[pos + 3];\n\n return new BABYLON.Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n }\n // Image is not loaded yet\n else {\n return new BABYLON.Color4(1, 1, 1, 1);\n }\n }", "imageToBytes (img, flipY = false, imgFormat = 'RGBA') {\n // Create the gl context using the image width and height\n const {width, height} = img\n const gl = this.createCtx(width, height, 'webgl', {\n premultipliedAlpha: false\n })\n const fmt = gl[imgFormat]\n\n // Create and initialize the texture.\n const texture = gl.createTexture()\n gl.bindTexture(gl.TEXTURE_2D, texture)\n if (flipY) // Mainly used for pictures rather than data\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)\n // Insure [no color profile applied](https://goo.gl/BzBVJ9):\n gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE)\n // Insure no [alpha premultiply](http://goo.gl/mejNCK).\n // False is the default, but lets make sure!\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n\n // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)\n gl.texImage2D(gl.TEXTURE_2D, 0, fmt, fmt, gl.UNSIGNED_BYTE, img)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)\n\n // Create the framebuffer used for the texture\n const framebuffer = gl.createFramebuffer()\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0)\n\n // See if it all worked. Apparently not async.\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)\n if (status !== gl.FRAMEBUFFER_COMPLETE)\n this.error(`imageToBytes: status not FRAMEBUFFER_COMPLETE: ${status}`)\n\n // If all OK, create the pixels buffer and read data.\n const pixSize = imgFormat === 'RGB' ? 3 : 4\n const pixels = new Uint8Array(pixSize * width * height)\n // gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)\n gl.readPixels(0, 0, width, height, fmt, gl.UNSIGNED_BYTE, pixels)\n\n // Unbind the framebuffer and return pixels\n gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n return pixels\n }", "getFramePaletteUint32(frameIndex, paletteBuffer = new Uint32Array(16)) {\r\n assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index');\r\n const colors = this.getFramePalette(frameIndex);\r\n paletteBuffer.fill(0);\r\n colors.forEach(([r, g, b, a], i) => paletteBuffer[i] = (a << 24) | (b << 16) | (g << 8) | r);\r\n return paletteBuffer;\r\n }", "tgaParse(use_rle, use_pal, header, offset, data) {\n let pixel_data, pixel_size, pixel_total, palettes;\n pixel_size = header.pixel_size >> 3;\n pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n if (use_pal) {\n palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));\n }\n // Read RLE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n let c, count, i;\n let shift = 0;\n let pixels = new Uint8Array(pixel_size);\n while (shift < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels.\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, shift + i * pixel_size);\n }\n shift += pixel_size * count;\n }\n else {\n // Raw pixels.\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[shift + i] = data[offset++];\n }\n shift += count;\n }\n }\n }\n else {\n // RAW Pixels\n pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));\n }\n return {\n pixel_data: pixel_data,\n palettes: palettes\n };\n }", "function createTextureArray(gl, array) {\n var dtype = array.dtype\n var shape = array.shape.slice()\n var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)\n if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {\n throw new Error('gl-texture2d: Invalid texture size')\n }\n var packed = isPacked(shape, array.stride.slice())\n var type = 0\n if(dtype === 'float32') {\n type = gl.FLOAT\n } else if(dtype === 'float64') {\n type = gl.FLOAT\n packed = false\n dtype = 'float32'\n } else if(dtype === 'uint8') {\n type = gl.UNSIGNED_BYTE\n } else {\n type = gl.UNSIGNED_BYTE\n packed = false\n dtype = 'uint8'\n }\n var format = 0\n if(shape.length === 2) {\n format = gl.LUMINANCE\n shape = [shape[0], shape[1], 1]\n array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)\n } else if(shape.length === 3) {\n if(shape[2] === 1) {\n format = gl.ALPHA\n } else if(shape[2] === 2) {\n format = gl.LUMINANCE_ALPHA\n } else if(shape[2] === 3) {\n format = gl.RGB\n } else if(shape[2] === 4) {\n format = gl.RGBA\n } else {\n throw new Error('gl-texture2d: Invalid shape for pixel coords')\n }\n } else {\n throw new Error('gl-texture2d: Invalid shape for texture')\n }\n if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {\n type = gl.UNSIGNED_BYTE\n packed = false\n }\n var buffer, buf_store\n var size = array.size\n if(!packed) {\n var stride = [shape[2], shape[2]*shape[0], 1]\n buf_store = pool.malloc(size, dtype)\n var buf_array = ndarray(buf_store, shape, stride, 0)\n if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {\n convertFloatToUint8(buf_array, array)\n } else {\n ops.assign(buf_array, array)\n }\n buffer = buf_store.subarray(0, size)\n } else if (array.offset === 0 && array.data.length === size) {\n buffer = array.data\n } else {\n buffer = array.data.subarray(array.offset, array.offset + size)\n }\n var tex = initTexture(gl)\n gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)\n if(!packed) {\n pool.free(buf_store)\n }\n return new Texture2D(gl, tex, shape[0], shape[1], format, type)\n }", "function canvasToUint8Array(context) {\n var canvas = context.canvas;\n var arrayBuffer = new ArrayBuffer(canvas.width * canvas.height);\n var pixelData = new Uint8Array(arrayBuffer);\n\n var imageData = context.getImageData(0, 0, canvas.width, canvas.height);\n var pixels = imageData.data;\n for(var i= 0, j=0; i < pixels.length; i+=4, j++) {\n var luminance = ((pixels[i] + pixels[i+1] + pixels[i+2]) / 3) * pixels[i+3] / 256;\n pixelData[j] = luminance;\n }\n\n return pixelData;\n }", "static arrayBufferToImage(data)\n\t{\n\t\tvar byteStr = '';\n\t\tvar bytes = new Uint8Array(data);\n\t\tvar len = bytes.byteLength;\n\t\tfor (var i = 0; i < len; i++)\n\t\t\tbyteStr += String.fromCharCode(bytes[i]);\n\t\tvar base64Image = window.btoa(byteStr);\n\t\tvar str = 'data:image/png;base64,' + base64Image;\n\t\tvar img = new Image();\n\t\timg.src = str;\n\t\treturn img;\n\t}", "function tgaParse( use_rle, use_pal, header, offset, data ) \n{\n var pixel_data,\n pixel_size,\n pixel_total,\n palettes;\n\n pixel_size = header.pixel_size >> 3;\n pixel_total = header.width * header.height * pixel_size;\n\n // Read palettes\n if ( use_pal ) \n {\n palettes = data.subarray( offset, offset += header.colormap_length * ( header.colormap_size >> 3 ) );\n }\n\n // Read RLE\n if ( use_rle ) \n {\n pixel_data = new Uint8Array(pixel_total);\n\n var c, count, i;\n var shift = 0;\n var pixels = new Uint8Array(pixel_size);\n\n while (shift < pixel_total) \n {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n\n // RLE pixels.\n if (c & 0x80) \n {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) \n {\n pixels[i] = data[offset++];\n }\n\n // Copy pixel array\n for (i = 0; i < count; ++i) \n {\n pixel_data.set(pixels, shift + i * pixel_size);\n }\n\n shift += pixel_size * count;\n } \n else \n {\n // Raw pixels.\n count *= pixel_size;\n for (i = 0; i < count; ++i) \n {\n pixel_data[shift + i] = data[offset++];\n }\n shift += count;\n }\n }\n } \n else \n {\n // RAW Pixels\n pixel_data = data.subarray(\n offset, offset += (use_pal ? header.width * header.height : pixel_total)\n );\n }\n\n return {\n pixel_data: pixel_data,\n palettes: palettes\n };\n}", "getTextureCoords() {\n return null;\n }", "function parseTexture(gl, textureJSON) {\n checkParameter(\"parseTexture\", gl, \"gl\");\n checkParameter(\"parseTexture\", textureJSON, \"textureJSON\");\n var width = textureJSON[\"width\"];\n checkParameter(\"parseTexture\", width, \"textureJSON[width]\");\n var height = textureJSON[\"height\"];\n checkParameter(\"parseTexture\", height, \"textureJSON[height]\");\n var data = textureJSON[\"data\"];\n checkParameter(\"parseTexture\", data, \"textureJSON[data]\");\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.activeTexture(gl.TEXTURE0);\n texture.image = new Image();\n texture.image.src = data;\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_R, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n}", "function paletteToImage() {\n var png = new PNG({\n width: getNextPowerOf2(PALETTE.length),\n height: 1\n });\n\n var i = 0;\n PALETTE.forEach(function(color) {\n for(var c = 0; c < 4; ++c) {\n png.data[i++] = (color[c] || 1)*255;\n }\n });\n\n console.log(`Palette (1 x ${png.width}) size is ${(png.data || []).length} bytes with ${PALETTE.length} colors`);\n var data = PNG.sync.write(png, {});\n return data;\n}", "function RawTexture(data,width,height,/**\n * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n */format,scene,generateMipMaps,invertY,samplingMode,type){if(generateMipMaps===void 0){generateMipMaps=true;}if(invertY===void 0){invertY=false;}if(samplingMode===void 0){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}var _this=_super.call(this,null,scene,!generateMipMaps,invertY)||this;_this.format=format;_this._engine=scene.getEngine();_this._texture=scene.getEngine().createRawTexture(data,width,height,format,generateMipMaps,invertY,samplingMode,null,type);_this.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;_this.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;return _this;}", "texImage3D(ctx, funcName, args) {\n let [target, level, internalFormat, width, height, depth, border, format, type] = args;\n const info = getTextureInfo(target);\n updateMipLevel(info, target, level, internalFormat, width, height, depth, type);\n }", "static get VERTEX_FLOAT_SIZE() { return 3 + 3 + 2; }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
produce an array of math problems with a top number, a bottom number, an operator, an answer
function makeProblems(digits, operator) { var p = []; for (var i=0; i<25; i+=1) { // get random numbers with the biggest one first // TODO: figure out "negative numbers" feature here and in controls var numbers = []; numbers.push(getRandomInt(getMax(digits))); numbers.push(getRandomInt(getMax(digits))); numbers = numbers.sort(getSorted).reverse(); // figure out the answer for each problem var topNum = numbers[0]; var bottomNum = numbers[1]; var answer = 0; switch(operator) { case "+": answer = topNum + bottomNum; break; case "-": answer = topNum - bottomNum; break; case "x": answer = topNum * bottomNum; break; case "÷": topNum = topNum || 1; bottomNum = bottomNum || 1; var remainder = topNum % bottomNum; answer = Math.floor(topNum / bottomNum) + (remainder ? " r" + remainder : ""); break; } p.push({topNum: topNum, bottomNum: bottomNum, operator: operator, answer: answer}) } return p; }
[ "function evaluate(numbers, op) {\n if(op === '+')\n return numbers.reduce(add);\n else if(op === '-')\n return numbers.reduce (subtract);\n else if(op === '*')\n return numbers.reduce(multiply);\n else if(op === '/')\n return numbers.reduce(divide);\n else if(op === '%')\n return numbers.reduce(modulo);\n }", "parseExpressionByOperator(expression, operator, index) {\n //startingIndex will be the index of where the expression slice will begin\n let startingIndex = index;\n //endingIndex will be the index of where expression slice ends.\n let endingIndex = index;\n const validOperators = ['-', '+', '/', '*']\n //if the next char is a -, we want to increment the ending index by 1 because we want to include the - as part of the number. \n if(expression[endingIndex + 1] === \"-\"){\n endingIndex += 1;\n }\n\n //increment endingIndex as long as the char at endingIndex + 1 is a number or equal to .\n while(!isNaN(expression[endingIndex + 1]) || expression[endingIndex + 1] === \".\"){\n endingIndex += 1;\n };\n //decrement startingIndex as long as the char at startingIndex - 1 is a number or equal to .\n while(!isNaN(expression[startingIndex - 1]) || expression[startingIndex - 1] === \".\"){\n startingIndex -= 1;\n };\n //will check if the startingIndex - 1 is a - and if startingIndex - 2 is a valid operator, or if the starting index is 1 because we also want to \n //include the - to denote the number as a negative.\n if(expression[startingIndex - 1] === \"-\" && (startingIndex === 1 || validOperators.includes(expression[startingIndex - 2]))){\n startingIndex -= 1;\n };\n //beginningExpression will be the string beginning expression up and not including the startingIndex\n let beginningExpression = expression.slice(0, startingIndex);\n //the expressionSlice will be the string starting at the startingIndex and including the endingIndex.\n let expressionSlice = expression.slice(startingIndex, endingIndex + 1);\n //the endingExpression string will be anything after the endingIndex + 1.\n let endingExpression = expression.slice(endingIndex + 1);\n\n //depending on what the operator is, we will send the expressionSlice to the respective function and make returned value equal to expressionSlice. 5*2 will return 10\n switch (operator) {\n case \"*\":\n expressionSlice = this.multiplicationCalculation(expressionSlice);\n break;\n case \"/\":\n expressionSlice = this.divisionCalculation(expressionSlice);\n break;\n case \"-\":\n expressionSlice = this.substractionCalculation(expressionSlice);\n break;\n case \"+\":\n expressionSlice = this.additionCalculation(expressionSlice);\n break;\n }\n //the function will return a new string with all the expressions concatenated.\n return beginningExpression.concat(expressionSlice, endingExpression);\n }", "calculateBrackets() {\n //this section is to handle multiplication bracket notation. Example \"5(10)\" should equal 50\n let sliceIndex = this.calculation.search(/[0-9]\\(/) //find instances of digit followed by open bracket\n if (sliceIndex > -1) {\n this.calculation = this.calculation.slice(0, sliceIndex+1) + \"*\" + this.calculation.slice(sliceIndex + 1); // add a \"*\" between them so function picks it up\n this.calculateBrackets(); //restart function to check for multiple instances\n };\n\n let openBracket = this.calculation.lastIndexOf(\"(\"); //this will target innermost parentheses and solve the expression within, removing 1 layer from the equation\n let closeBracket = this.calculation.indexOf(\")\", openBracket);\n if (openBracket !== -1 && closeBracket !== -1) { // in this case, there are brackets that need sorting\n let expressionSlice = this.calculation.slice(openBracket+1, closeBracket); //slice that contains the expression \n\n let arrayExpression = [...this.calculation] //convert to array for splice purposes\n arrayExpression.splice(openBracket, closeBracket - openBracket + 1, this.calculateAddition(expressionSlice)); // replace expression including brackets with the result\n this.calculation = arrayExpression.join(\"\") // convert back to string\n this.calculateBrackets(); //repeat to check for more parentheses\n }\n }", "function cookingByNumbers(arr) {\n\tlet num = arr.shift();\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tnum = perform(num, arr[i]);\n\t\tconsole.log(num);\n\t}\n\n\tfunction perform(num, operation) {\n\t\tswitch (operation) {\n\t\tcase 'chop':\n\t\t\treturn num / 2;\n\t\tcase 'dice':\n\t\t\treturn Math.sqrt(num);\n\t\tcase 'spice':\n\t\t\treturn ++num;\n\t\tcase 'bake':\n\t\t\treturn num * 3;\n\t\tcase 'fillet':\n\t\t\treturn num * 0.8;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}", "function equals(){\n $('.equals').on(\"click\", function(){\n arrNum = inputArray.join(\"\");\n joinedArray.push(arrNum);\n inputArray = [];\n switch(operator){\n case '+':\n answer = add(parseFloat(joinedArray[0]), parseFloat(joinedArray[1]));\n inputArray = [];\n displayAnswer();\n joinedArray=[];\n inputArray.push(answer);\n break;\n case '-':\n answer = subtract(parseFloat(joinedArray[0]), parseFloat(joinedArray[1]));\n inputArray = [];\n displayAnswer();\n joinedArray=[];\n inputArray.push(answer);\n break;\n case '/':\n answer = divide(parseFloat(joinedArray[0]), parseFloat(joinedArray[1]));\n inputArray = [];\n displayAnswer();\n joinedArray=[];\n inputArray.push(answer);\n break;\n case '*':\n answer = multiply(parseFloat(joinedArray[0]), parseFloat(joinedArray[1]));\n inputArray = [];\n displayAnswer();\n joinedArray=[];\n inputArray.push(answer);\n break;\n }\n });\n }", "function evaluate(expression) {\n var i = 1,\n temp = [];\n // Evaluate all the multiplication and division first.\n while (i < expression.length) {\n // The end of the context is reached.\n // Break out of the while loop.\n if (/\\)/.exec(expression[i])) {\n i = expression.length;\n continue;\n }\n // The first item of the triplet is an open parenthesis.\n // Open a new context.\n if (/\\(/.exec(expression[i - 1])) {\n expression.splice((i - 1), 1);\n // Create a new evaluation context.\n expression = evaluate(expression);\n }\n // Check for multiplication or division.\n if (/[\\*\\\\]/.exec(expression[i])) {\n // The last item of the triplet is an open parenthesis.\n if (/\\(/.exec(expression[i + 1])) {\n // Open a new context and evaluate it.\n temp = evaluate(expression.slice((i + 2)));\n // Slice the known expression up to the new context and concat it\n // with the evaluated new context array.\n expression = expression.slice(0, (i + 1)).concat(temp);\n }\n // We move through each triplet in the array and evaluate.\n expression.splice((i - 1), 3, operate(expression[i], expression[i - 1], expression[i + 1]));\n }\n // If the operator isn't multiplication or division, move to the next triplet.\n else {\n i += 2;\n }\n }\n // Evaluate the addition and subtraction.\n i = 1;\n while (i < expression.length) {\n // The end of the context is reached.\n // Break out of the while loop.\n if (/\\)/.exec(expression[i])) {\n expression.splice(i, 1);\n return expression;\n }\n // The first item of the triplet is an open parenthesis.\n // Open a new context.\n if (/\\(/.exec(expression[i - 1])) {\n expression.splice((i - 1), 1);\n // Create a new evaluation context.\n expression = evaluate(expression);\n }\n expression.splice((i - 1), 3, operate(expression[i], expression[i - 1], expression[i + 1]));\n }\n return expression;\n }", "function createPlusLevelSix() {\n var rangeAB = range(1, 11);\n var numberA = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n var numberB = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n\n var numberSum = numberA + numberB;\n \n var plusEquation = [numberA, numberB, numberSum];\n return plusEquation;\n}", "function getAnswersArray(Array){\n switch(Array){\n case grid1:\n return grid1ans;\n break;\n case grid2:\n return grid2ans;\n break;\n case grid3:\n return grid3ans;\n break;\n case grid4:\n return grid4ans;\n break;\n case grid5:\n return grid5ans;\n break;\n case grid6:\n return grid6ans;\n break;\n case grid7:\n return grid7ans;\n break;\n case grid8:\n return grid8ans;\n break;\n case grid9:\n return grid9ans;\n break;\n case grid10:\n return grid10ans;\n break;\n default:\n return 0;\n }\n}", "function evaluateExpression(equation, inputs) {\n //I'm pretty sure this removes all whitespace.\n equation = equation.replace(/\\s/g, \"\");\n //if equation is an input (like 't'), return the value for that input.\n if (equation in inputs) {\n return inputs[equation];\n }\n //make each variable x like (x) so that 5(x) can work\n //to avoid infinite recursion, make sure each substring like (((x))) is turned into (x)\n for (var variable in inputs) {\n var prevLength = 0;\n while (prevLength!=equation.length) {\n //it looks like this will only go through the loop once, but actually the length of equation might change before the end of the loop\n prevLength = equation.length;\n equation = equation.replace(\"(\"+variable+\")\", variable);//first remove parenthesis from ((x)), if they exist\n }\n \n equation = equation.replace(variable, \"(\"+variable+\")\");//then add parenthesis back\n }\n //if start with - or $ (my negative replacement), negate entire expression\n if (equation.indexOf(\"-\")==0 || equation.indexOf(\"$\")==0) {\n return -1*evaluateExpression(equation.slice(1), inputs);\n }\n for (var i=1; i<equation.length; i++) {//phantom multiplication (first char cannot have a phantom *)\n //5(3) should become 5*(3)\n //5cos(3) should become 5*cos(3)\n if (equation.charAt(i)==\"(\") {\n var insertionIndex = i;\n //size of unary operation\n for (var size=MAX_FUNCTION_LENGTH; size>=MIN_FUNCTION_LENGTH; size--) {\n if (i>=size) {\n var charsBefore = equation.slice(i-size,i);\n if (charsBefore in functions) {\n insertionIndex = i-size;\n break;\n }\n }\n }\n if (insertionIndex) {\n var prevChar = equation.charAt(insertionIndex-1);\n if (prevChar==\"*\" || prevChar==\"+\" || prevChar==\"/\" || prevChar==\"-\" || prevChar==\"^\" || prevChar==\"(\") {\n \n } else {\n equation=equation.slice(0,insertionIndex).concat(\"*\",equation.slice(insertionIndex));\n i++;\n }\n }\n }\n }\n //parenthesis\n //get rid of all parentheses\n while (equation.indexOf(\"(\")>=0) {\n //use for (a*(m+a)) and (a+m)*(a+a). thus you can't just take the first '(' and last ')' and you can't take the first '(' and first ')' parentheses. You have to make sure the nested parentheses match up\n //start at the first '('\n var startIndex = equation.indexOf(\"(\");\n var endIndex = startIndex+1;\n var nestedParens = 0;\n //find end index\n //stop when outside of nested parentheses and the character is a ')'\n while (equation.charAt(endIndex)!=\")\" || nestedParens) {\n if (equation.charAt(endIndex)==\")\") {\n nestedParens--;\n }\n if (equation.charAt(endIndex)==\"(\") {\n nestedParens++;\n }\n endIndex++;\n }\n //find what's in the parentheses and also include the parenthesis.\n var inParens = equation.slice(startIndex+1, endIndex);\n var includingParens = equation.slice(startIndex, endIndex+1);\n \n var value = evaluateExpression(inParens, inputs);\n //size of unary operation\n //in range. Must enumerate backwards so acos(x) does not get interpreted as a(cos(x))\n for (var size=4; size>=2; size--) {\n if (startIndex>=size) {\n var charsBefore = equation.slice(startIndex-size, startIndex);\n if (charsBefore in functions) {\n value = functions[charsBefore](value);\n includingParens=equation.slice(startIndex-size, endIndex+1);\n break;\n }\n }\n }\n \n if (includingParens==equation) {//like (5) or cos(3)\n return value;\n } else {\n //replace in equation.\n equation = equation.replace(includingParens, value);\n }\n }\n //done with parentheses\n \n //deal with negatives. replace with dollar sign\n //this is so 4/-7 doesn't get interpreted as (4/)-7, which could raise a divide by zero error\n equation = equation.replace(\"*-\", \"*$\");\n equation = equation.replace(\"--\", \"+\");//minus negative is plus\n equation = equation.replace(\"+-\", \"-\");//add negative is minus\n equation = equation.replace(\"/-\", \"/$\");\n equation = equation.replace(\"(-\", \"($\");\n \n //now the divide and conquer algorithm (or whatever this is)\n \n //check if equation contains any operations like \"+\", \"-\", \"/\", etc.\n\tif (equation.indexOf(\"+\")>=0) {\n //start at zero and add from there\n var sum = 0;\n var toAdd = equation.split(\"+\");//divide\n for (var operand in toAdd) {\n sum += evaluateExpression(toAdd[operand], inputs);//conquer\n }\n //everything has been taken care of.\n return sum;\n }\n if (equation.indexOf(\"-\")>=0) {\n var diff = 0;\n var toSub = equation.split(\"-\");\n var first = true; //if looking at the first operand, it's positive. Subtract all others.\n //this is much easier in Haskell\n //first:toSum = first - (sum toSub)\n for (var op in toSub) {\n if (first) diff = evaluateExpression(toSub[op], inputs);\n else diff -= evaluateExpression(toSub[op], inputs);\n first=false;\n }\n return diff;\n }\n\tif (equation.indexOf(\"*\")>=0) {\n\t\tvar multiple = 1;//start with one (multiplicative identity)\n\t\tvar toMultiply = equation.split(\"*\");\n\t\tfor (var factor in toMultiply) {\n\t\t\tmultiple *= evaluateExpression(toMultiply[factor], inputs);\n\t\t}\n\t\treturn multiple;\n\t}\n if (equation.indexOf(\"/\")>=0) {\n var quot = 0;\n var toDiv = equation.split(\"/\");\n var first = true;\n for (var op in toDiv) {\n if (first) quot = evaluateExpression(toDiv[op], inputs);\n else quot /= evaluateExpression(toDiv[op], inputs);\n first=false;\n }\n return quot;\n }\n if (equation.indexOf(\"^\")>=0) {\n var exp = 0;\n var toPow = equation.split(\"^\");\n var first = true;\n for (var op in toPow) {\n if (first) exp = evaluateExpression(toPow[op], inputs);\n else exp = Math.pow(exp, evaluateExpression(toPow[op], inputs));\n first=false;\n }\n return exp;\n }\n \n //no function. assume it's a number (base 10 of course)\n var value = parseFloat(equation, 10);\n if (equation.charAt(0)==\"$\") {//negative\n value = parseFloat(equation.slice(1), 10) * -1;\n }\n\treturn value;\n}", "function createPlusLevelFour() {\n var numberA;\n var numberB;\n\n var numberSum = 100; //initialize numberSum,and make it bigger than 10.\n if( answercount <= totalAnswerCount/2 ){\n if( level%2 == 1 ){\n \n numberA = Math.floor(Math.random() * 5) + 1;\n numberB = numberA;\n \n numberSum = numberA + numberB;\n\n }\n if( level%2 == 0 ){\n while ( numberSum > 20 || numberSum < 10 ) {\n numberA = Math.floor(Math.random() * 10) + 1;\n numberB = Math.floor(Math.random() * 5) + 1;\n\n numberSum = numberA + numberB;\n }\n \n }\n \n }else{\n if( level%2 == 1 ){\n while ( numberSum < 10 ) {\n numberA = Math.floor(Math.random() * 9) + 1;\n numberB = numberA;\n \n numberSum = numberA + numberB;\n\n }\n }\n if( level%2 == 0 ){\n while ( numberSum > 20 || numberSum < 10 ) {\n numberA = Math.floor(Math.random() * 10) + 1;\n numberB = Math.floor(Math.random() * 5) + 6;\n\n numberSum = numberA + numberB;\n }\n \n }\n }\n var plusEquation = [numberA, numberB, numberSum];\n return plusEquation; \n}", "function createPlusLevelFive() {\n var rangeAB = range(1, 11);\n var numberA = 0;\n var numberB = 0;\n\n var numberSum = 100; //initialize numberSum,and make it bigger than 10.\n\n while (numberSum > 21 || numberSum < 10) {\n numberA = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n numberB = rangeAB[Math.floor(Math.random() * rangeAB.length)];\n\n numberSum = numberA + numberB;\n }\n\n var plusEquation = [numberA, numberB, numberSum];\n return plusEquation;\n}", "function createMinusLevelFive() {\n var rangeA = range(11, 19);\n var rangeB = range(2, 10);\n var numberA = 0;\n var numberB = 0;\n\n var numberDiff = 100; //initialize numberDiff,and make it bigger than 9.\n\n while (numberDiff > 9) {\n numberA = rangeA[Math.floor(Math.random() * rangeA.length)];\n numberB = rangeB[Math.floor(Math.random() * rangeB.length)];\n\n numberDiff = numberA - numberB;\n }\n\n var plusEquation = [numberA, numberB, numberDiff];\n return plusEquation;\n}", "function operate(operator, a, b){\n switch(operator) {\n case '+':\n answer = sum(a, b);\n break;\n case 'x':\n answer = product(a, b);\n break;\n case '-':\n answer = difference(a, b);\n break; \n case '/':\n answer = quotient(a, b);\n console.log(`${a} ${b}`)\n break;\n case '√':\n answer = squareRoot(a);\n console.log(`${operator} ${a}`)\n break;\n default:\n answer = \"Syntax Error\";\n \n } \n checkDecimalPlaces(answer);\n firstValue = '';\n secondValue = '';\n operation = '';\n myValue = '';\n displayContent(answer);\n console.log(`%cThe answer ${answer}`, `background: tomato`);\n return answer;\n}", "function equationOne() {\n return (30 + 2) * 20;\n}", "function createMinusLevelSix() {\n var rangeA = range(2, 19);\n var rangeB = range(1, 10);\n\n var numberDiff = -100; //initialize numberDiff,and make it less than 1.\n\n while (numberDiff < 1) {\n numberA = rangeA[Math.floor(Math.random() * rangeA.length)];\n numberB = rangeB[Math.floor(Math.random() * rangeB.length)];\n\n numberDiff = numberA - numberB;\n }\n\n var plusEquation = [numberA, numberB, numberDiff];\n return plusEquation;\n}", "visitArith_expr(ctx) {\r\n console.log(\"visitArith_expr\");\r\n let length = ctx.getChildCount();\r\n let value = this.visit(ctx.term(0));\r\n for (var i = 1; i * 2 < length; i = i + 1) {\r\n if (ctx.getChild(i * 2 - 1).getText() === \"+\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"+\",\r\n left: value,\r\n right: this.visit(ctx.term(i)),\r\n };\r\n } else if (ctx.getChild(i * 2 - 1).getText() === \"-\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"-\",\r\n left: value,\r\n right: this.visit(ctx.term(i)),\r\n };\r\n }\r\n }\r\n return value;\r\n }", "get operators() {return []}", "function parse(stack) {\n var numStack = []; // Number stack\n var opStack = []; // Operator stack\n while (stack.length > 0) {\n var val = stack.pop();\n if (isOperator(val)) {\n opStack.push(val);\n } else if (typeof val == 'number') {\n numStack.push(val);\n } else if (val == ')') {\n var b = numStack.pop();\n var a = numStack.pop();\n var op = opStack.pop();\n numStack.push(performOp(a, b, op));\n }\n }\n console.log(numStack);\n}", "function createMinusLevelFour() {\n var rangeB = range(1, 10);\n var numberA = 10;\n var numberB = rangeB[Math.floor(Math.random() * rangeB.length)];\n\n var numberDiff = numberA - numberB;\n\n var plusEquation = [numberA, numberB, numberDiff];\n return plusEquation;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display guess history to user
function displayHistory (){ let list = "<ul class='list-group'>" for (let i = guesses.length - 1; i >= 0; i--){ list += "<li class='list-group-item'>" + "You guessed " + guesses[i] + "</li>" } list += '</ul>' document.getElementById('history').innerHTML = list }
[ "function saveGuessHistory(guess) {\n\tguesses.push(guess)\n}", "function updateGuess() {\n ch_push(state.guess)\n }", "function updateGuessedDisplay() {\n $('#guessed0').html(currentGuess[0]);\n $('#guessed1').html(currentGuess[1]);\n $('#guessed2').html(currentGuess[2]);\n $('#guessed3').html(currentGuess[3]);\n updateDisplay();\n }", "function showHistory() {\n\n\t}", "function handleGuess() {\n // Check if remaining guesses is -1 and setup a new game if so.\n\tif (remainingGuesses == -1) {\n\t\tsetupNewGame();\n\t}\n\n\tif (remainingGuesses == 1) {\n\t\tguessBtn.disabled = true;\n\t}\n\n // Retreive the user's newest guess.\n\tlet newestGuess = getGuessInput();\n\n // Check if the user has won. We should show a message, set remaining guesses to 0, and return from this function.\n \t// Check if the guess is higher or lower and show appropriate message.\n\t// The user has used a guess, decrement remainin guesses and show the new value.\n\n\tif (newestGuess == magicNumber) {\n\t\tshowMessage(\"win-message\");\n\t\tremainingGuesses = 0;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t} else if (newestGuess < magicNumber) {\n\t\tshowMessage(\"higher-message\");\n\t\tremainingGuesses--;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t} else if (newestGuess > magicNumber) {\n\t\tshowMessage(\"lower-message\");\n\t\tremainingGuesses--;\n\t\tshowRemainingGuesses(remainingGuesses);\n\t}\n\n // If the remaining guesses is 0, then the user has lost and that message should be shown.\n\tif ((remainingGuesses === 0) && (newestGuess != magicNumber)) {\n\t\tshowMessage(\"lose-message\");\n\t}\n}", "function suggestGuess(){\n\tif(guess<answer){\n\t\treturn \" guess higher.\";\n\t} else{\n\t\treturn \" guess lower.\";\n\t}\n}", "function guess() {\n\t\t// Capture the guess value:\n\t\tvar inputValue = document.getElementById(\"input\").value;\n\t\t\n\t\t// Verify the guess is a number using the previously defined function (isNumber()):\n\t\tvar isNum = isNumber(inputValue);\n\t\tif ( isNum === false) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"red\", true, \"You must enter a number!\");\n\t\t\tupdateGameGuesses(inputValue, \"Not a number\");\n\n\t\t// Was the guess too low?\n\t\t} else if ( inputValue < ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too low\");\n\t\t\tupdateGameGuesses(inputValue, \"Too low\");\n\n\t\t// Was the guess too high?\n\t\t} else if ( inputValue > ranNum ) {\n\t\t\tguesses += 1;\n\t\t\tdisplay(\"yellow\", true, \"Too high\");\n\t\t\tupdateGameGuesses(inputValue, \"Too high\");\n\n\t\t// Was the guess correct?\n\t\t} else if (ranNum == inputValue) { \n\t\t\tguesses += 1;\n\t\t\t// Display a message if the user guessed correctly on their first try:\n\t\t\tif(guesses === 1) {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It only took you one guess!\", \"Start again (it's ready).\");\n\t\t\t// Display a message if the user required 2 or more guesses:\n\t\t\t} else {\n\t\t\t\tdisplay(\"blue\", false, \"You got it! The number was \" + ranNum + \". It took you \" + guesses + \" guesses.\", \"Start again (it's ready).\")\n\t\t\t}\n\t\t\tupdateGameGuesses(inputValue, \"Correct\");\n\n\t\t\t// For this one game, that was guessed correctly, store the game stats:\n\t\t\tvar gameStat = [numRange, ranNum, guesses];\n\t\t\t// Add the game stat to an array that persists for the window session (is emptied after a page refresh):\n\t\t\tvar sessionScore = new Array();\n\t\t\tsessionScore[sessionScore.length] = gameStat;\n\n\t\t\t// Display the Session Scores in a table:\n\t\t\tfor( var i = 0; i < sessionScore.length; i++ ) {\n\t\t\t\tvar gameStat = sessionScore[i],\n\t\t\t\ttr = document.createElement(\"tr\"),\n\t\t\t\ttd0 = document.createElement(\"td\"),\n\t\t\t\ttd1 = document.createElement(\"td\"),\n\t\t\t\ttd2 = document.createElement(\"td\");\n\n\t\t\t\ttd0.appendChild(document.createTextNode(\"1 to \" + gameStat[0]));\n\t\t\t\ttd1.appendChild(document.createTextNode(gameStat[1]));\n\t\t\t\ttd2.appendChild(document.createTextNode(gameStat[2]));\n\t\t\t\ttr.appendChild(td0);\n\t\t\t\ttr.appendChild(td1);\n\t\t\t\ttr.appendChild(td2);\n\t\t\t\tsessionScoreTable.appendChild(tr);\n\t\t\t}\n\n\t\t\t// Reset the game:\n\t\t\tresetGameGuessesTable();\n\t\t\tgameGuesses.length = 0;\n\t\t\tgameStat = 0;\n\t\t\tguesses = 0;\n\t\t\tnewRanNum();\n\t\t}\n\t}", "function guessingGame(userInput) {\n \n \n \n if ((!userInput) || (!userInputRangeLowEl) || (!userInputRangeHighEl)){\n if (submitBtnEl.value === \"Start\") {\n submitBtnEl.value = \"Submit\"\n }\n msgDisplayEl.innerHTML = \"Please guess a number\"\n } else if (parseInt(userInput) === ranNumber) {\n document.body.innerHTML = '<nav><header>You guessed it right after <span>'+ numberOfGuesses +'</span> tirals ! Great job!\\n <INPUT TYPE=\"button\" onClick=\"history.go(0)\" VALUE=\"Play Again\"></header></nav> <style> nav { background-color: #2F4E81; color: #fff; font-weight: bolder; height: 5em; text-align: center; margin: 0px auto;} header { padding:1em; width: auto; margin: auto;} span{color: red;}<\\style>';\n \n clearInput();\n console.log(ranNumber);\n submitBtnEl.value = \"Start\";\n submitBtn2El.value = \"Pick\";\n \n \n \n \n \n } else if (userInput > ranNumber) {\n msgDisplayEl.innerHTML = \"Your number is greater than the secret number!\"\n clearInput();\n submitBtnEl.value = \"Guess Again!\";\n submitBtn2El.value = \"Already Picked!\";\n numberOfGuesses++;\n \n } else if (userInput < ranNumber) {\n msgDisplayEl.innerHTML = \"Your number is less than the secret number!\"\n clearInput();\n submitBtn2El.value = \"Already Picked!\";\n submitBtnEl.value = \"Guess Agina!!\";\n numberOfGuesses++;\n \n }\n\n\n}", "function relativeFeedback(secretNumber, oldGuess, newGuess) {\n var oldDiff = parseInt(Math.abs(secretNumber - oldGuess));\n var newDiff = parseInt(Math.abs(secretNumber - newGuess));\n if (newDiff > oldDiff) {\n $('#relative-feedback').text('You are colder than the last guess!');\n } else if (newDiff === oldDiff) {\n $('#relative-feedback').text('You are as far as your previous guess!');\n } else {\n $('#relative-feedback').text('You are hotter than the last guess!');\n }\n }", "function submitGuess() {\n if (!currentGuess.includes(0)) {\n guesses.push(currentGuess);\n\n $('#row' + guesses.length).find('.col1').html(currentGuess[0]);\n $('#row' + guesses.length).find('.col2').html(currentGuess[1]);\n $('#row' + guesses.length).find('.col3').html(currentGuess[2]);\n $('#row' + guesses.length).find('.col4').html(currentGuess[3]);\n\n result = guessResult();\n\n if (result[0] == 2 && result[1] == 2 && result[2] == 2 && result[3] == 2) {\n $('#result').html(\"YOU WIN\");\n } else {\n $('#row' + guesses.length).find('.result').html(result.toString());\n }\n\n currentGuess = [0, 0, 0, 0];\n updateGuessedDisplay();\n setSelected(0);\n updateDisplay();\n if (guesses.length >= 12) {\n $('#result').html(\"YOU LOSE!\");\n }\n\n }\n }", "function showHint() {\n clueToGuess = clue[Math.floor(Math.random() * clue.length)];\n for (var i = 0; i < clue; i++) {\n if (correctGuess === wordToGuess) {\n clue++;\n }\n clueToGuess.push(\" \");\n }\n document.getElementById(\"hint\").innerHTML = (\"Hint: \" + clueToGuess);\n}", "function guess() {\n\n // WRITE YOUR EXERCISE 4 CODE HERE\n let guess = 0;\n let number= 0;\n let attempt = 0;\nnumber = (Math.floor(Math.random()* 1000) + 1);\nguess = prompt (\"Please enter your guess. The range is a random integer between 1 to 1,000.\")\nattempt += 1\nwhile (guess != number){\n if (guess > 1000 || guess < 1 || guess%1 != 0)\n guess = prompt (\"Invalid guess. Try a valid number between 1 to 1,000.\")\nif (guess < number) {\n guess = prompt (\"Guess too small. Try another number between 1 to 1,000.\")\n attempt += 1\n}\nif (guess > number) {\n guess = prompt (\"Guess too big. Try another number between 1 to 1,000.\")\n attempt += 1\n}\n}\nif (guess == number) {\n var p = document.getElementById(\"guess-output\");\n p.innerHTML = \"You did it! The random integer was \" + number + \" and you took \" + attempt + \" tries or try (if you somehow got the random interger in your first guess) to figure out the random integer.\"\n}\n ////////////////// DO NOT MODIFY\n check('guess'); // DO NOT MODIFY\n ////////////////// DO NOT MODIFY\n}", "function guessNumber(){\n\n let guess = user.value;\n user.value = '';\n\n /* Random Math Function */\n let number = Math.floor(Math.random() * 5 + 1);\n\n /* Correct guess */\n if(guess == number){\n story.innerHTML = `Bra jobbat! Du gissade ${number} och det var rätt och nu har spöket försvunnit och ingen behöver vara rädd mer!`;\n btn.style.display = 'none';\n user.style.display = 'none';\n link.innerHTML = 'Gå ut ur rummet';\n\n /* Guesss was to high */\n }else if(guess > number){\n story.innerHTML = 'Fel! Det var för högt. Försök igen!';\n\n /* Guess was to low */\n } else if(guess < number){\n story.innerHTML = 'Fel! Det var för lågt. Försök igen!';\n }\n }", "function renderGoalHistory() {\n if (appbit.permissions.granted(\"access_activity\")) {\n\n // query all days history step data\n const dayRecords = dayHistory.query({\n limit: 10\n }); // versa 2 only has previous 6 days saved\n var week_cal_total = 0;\n var week_steps_total = 0;\n\n var flags = [];\n\n if ((global_done_calories)> (CAL_GOAL)) {\n flags.push('✅');\n } else {\n flags.push('❓');\n }\n dayRecords.forEach((day, index) => {\n var day_calories = day.calories;\n\n week_cal_total += reduce(day.calories) ;\n \n week_steps_total += day.steps;\n document.getElementById('average').text = prettyNumber(week_cal_total / index) +\n \" ... \" + prettyNumber(week_steps_total / index); \n\n\n\n if (reduce(day_calories) >= CAL_GOAL) {\n flags.push('✅'); // emoji that are not supported on clockface will break all emojis\n\n } else {\n flags.push('⚪️');\n }\n\n });\n\n document.getElementById('flags').text = (flags.reverse().join(''));\n }\n\n}", "getHistory () {\n return this.game.history({ verbose: true })\n }", "function correctGuess() {\n score += wrongAnswersLeft;\n if (score > hScore) {\n hScore = score;\n }\n setCorrectScreen(wrongAnswersLeft);\n }", "function yourGuessWasText() {\n document.querySelector('.your-guess-was-text').innerHTML =\n ('Your Last Guess Was:');\n}", "function addGuess(){\n userInputArray.push(\"userInput\");\n }", "function revealLetter() {\n\t\t\tuserGuessIndex = word.indexOf(userGuess);\n\t\t\tfor (i=0; i < word.length; i++) {\n\t\t\t\tif (word[i] === userGuess) {\n\t\t\t\t\thide = hide.split(\"\");\n\t\t\t\t\thide[i] = userGuess;\n\t\t\t\t\thide = hide.join(\"\");\n\t\t\t\t\ttargetA.innerHTML = hide;\n\n\t\t\t\t}\n\t\t\t}\t\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal function to obtain a nested property in `obj` along `path`.
function deepGet(obj, path) { var length = path.length; for (var i = 0; i < length; i++) { if (obj == null) return void 0; obj = obj[path[i]]; } return length ? obj : void 0; }
[ "function setGetObjPath(obj, path, value) {\n addLog('setGetObjPath was Triggered');\n if (typeof path == 'string') {\n path = path.split('.');\n obj = obj || scope[path.splice(0, 1)];\n\n if (!obj) {\n return false;\n }\n return setGetObjPath(obj, path, value);\n } else if (path.length === 1 && value !== undefined) {\n obj[path[0]] = value;\n\n return obj;\n } else if (path.length === 0) {\n return obj;\n } else {\n return setGetObjPath(obj[path[0]],path.slice(1), value);\n }\n }", "function getPropertyValuePath(path: NodePath, propertyName: string): ?NodePath {\n types.ObjectExpression.assert(path.node);\n\n return path.get('properties')\n .filter(propertyPath => getPropertyName(propertyPath) === propertyName)\n .map(propertyPath => propertyPath.get('value'))[0];\n}", "function field(obj, pathString) {\n if (!obj || typeof pathString !== 'string') return '';\n function fn(obj, path) {\n var prop = path.shift();\n if (!(prop in obj) || obj[prop] == null) return '';\n if (path.length) {\n return fn(obj[prop], path);\n }\n return String(obj[prop]);\n }\n return fn(obj, pathString.split('.'));\n}", "stringOrObject( obj, objPath/*, rez */) {\n if (_.isString(obj)) { return obj; } else { return LO.get(obj, objPath); }\n }", "function obj_find(obj, prop, val) {\n\tfor (let k in obj) {\n\t\tlet v = obj[k]\n\t\tif (v[prop] === val)\n\t\t\treturn v\n\t}\n\treturn null\n}", "function walkJSON (obj, func, options = {}) {\n const traverse = (obj, curDepth, path, key) => {\n if (curDepth && key && !options.finalPathsOnly) func.apply(this, [key, curDepth, path])\n if (!obj) {\n if (options.finalPathsOnly) func.apply(this, [key, curDepth, path])\n return // Bail on falsey obj ref\n }\n // If this entry is an array then loop over its contents\n if (_.isArray(obj)) {\n if (!obj.length && options.finalPathsOnly) func.apply(this, [key, curDepth, path])\n obj.forEach((val, index) => {\n if (_.isObject(val) || _.isArray(val)) {\n let newPath = path.length ? `${path}[${index}]` : `[${index}]`\n traverse(val, curDepth + 1, newPath)\n }\n })\n // If this entry is an object then loop over its keys\n } else if (_.isObject(obj)) {\n const keys = Object.keys(obj)\n if (!keys.length && options.finalPathsOnly) func.apply(this, [key, curDepth, path])\n keys.forEach(key => {\n if (obj[key] !== null) {\n let newPath = path.length ? `${path}.${key}` : key\n traverse(obj[key], curDepth + 1, newPath, key)\n } else {\n let newPath = path.length ? `${path}.${key}` : key\n func.apply(this, [key, curDepth + 1, newPath])\n }\n })\n } else {\n if (options.finalPathsOnly) func.apply(this, [key, curDepth, path])\n }\n }\n return traverse(obj, 0, '')\n}", "function result_result(obj, path, fallback) {\n path = _toPath_toPath(path);\n var length = path.length;\n if (!length) {\n return modules_isFunction(fallback) ? fallback.call(obj) : fallback;\n }\n for (var i = 0; i < length; i++) {\n var prop = obj == null ? void 0 : obj[path[i]];\n if (prop === void 0) {\n prop = fallback;\n i = length; // Ensure we don't continue iterating.\n }\n obj = modules_isFunction(prop) ? prop.call(obj) : prop;\n }\n return obj;\n}", "getProperty(exemplar, key) {\n\t\tlet original = exemplar;\n\t\tlet prop = exemplar.prop(key);\n\t\twhile (!prop && exemplar.parent[0]) {\n\t\t\tlet { parent } = exemplar;\n\t\t\tlet entry = this.find(parent);\n\t\t\tif (!entry) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\texemplar = entry.read();\n\t\t\tprop = exemplar.prop(key);\n\t\t}\n\t\treturn prop;\n\t}", "async getRecord(path, idProp = \"id\") {\n try {\n const snap = await this.getSnapshot(path);\n let object = snap.val();\n if (typeof object !== \"object\") {\n object = { value: snap.val() };\n }\n return Object.assign(Object.assign({}, object), { [idProp]: snap.key });\n }\n catch (e) {\n throw new AbstractedProxyError(e);\n }\n }", "function getArrayMemberProperty(aObj, aEnv, aProp) {\r\n // First get the array.\r\n let obj = aObj;\r\n let propWithoutIndices = aProp.substr(0, aProp.indexOf(\"[\"));\r\n\r\n if (aEnv) {\r\n obj = getVariableInEnvironment(aEnv, propWithoutIndices);\r\n } else {\r\n obj = DevToolsUtils.getProperty(obj, propWithoutIndices);\r\n }\r\n\r\n if (!isObjectUsable(obj)) {\r\n return null;\r\n }\r\n\r\n // Then traverse the list of indices to get the actual element.\r\n let result;\r\n let arrayIndicesRegex = /\\[[^\\]]*\\]/g;\r\n while ((result = arrayIndicesRegex.exec(aProp)) !== null) {\r\n let indexWithBrackets = result[0];\r\n let indexAsText = indexWithBrackets.substr(1, indexWithBrackets.length - 2);\r\n let index = parseInt(indexAsText);\r\n\r\n if (isNaN(index)) {\r\n return null;\r\n }\r\n\r\n obj = DevToolsUtils.getProperty(obj, index);\r\n\r\n if (!isObjectUsable(obj)) {\r\n return null;\r\n }\r\n }\r\n\r\n return obj;\r\n}", "function prop(name){\n return function(obj){\n return obj[name];\n };\n}", "function jptr(obj, prop, newValue) {\n if (typeof obj === 'undefined') return false;\n if (!prop || typeof prop !== 'string' || (prop === '#')) return (typeof newValue !== 'undefined' ? newValue : obj);\n\n if (prop.indexOf('#')>=0) {\n let parts = prop.split('#');\n let uri = parts[0];\n if (uri) return false; // we do internal resolution only\n prop = parts[1];\n prop = decodeURIComponent(prop.slice(1).split('+').join(' '));\n }\n if (prop.startsWith('/')) prop = prop.slice(1);\n\n let components = prop.split('/');\n for (let i=0;i<components.length;i++) {\n components[i] = jpunescape(components[i]);\n\n let setAndLast = (typeof newValue !== 'undefined') && (i == components.length-1);\n\n let index = parseInt(components[i],10);\n if (!Array.isArray(obj) || isNaN(index) || (index.toString() !== components[i])) {\n index = (Array.isArray(obj) && components[i] === '-') ? -2 : -1;\n }\n else {\n components[i] = (i > 0) ? components[i-1] : ''; // backtrack to indexed property name\n }\n\n if ((index != -1) || obj.hasOwnProperty(components[i])) {\n if (index >= 0) {\n if (setAndLast) {\n obj[index] = newValue;\n }\n obj = obj[index];\n }\n else if (index === -2) {\n if (setAndLast) {\n if (Array.isArray(obj)) {\n obj.push(newValue);\n }\n return newValue;\n }\n else return undefined;\n }\n else {\n if (setAndLast) {\n obj[components[i]] = newValue;\n }\n obj = obj[components[i]];\n }\n }\n else {\n if ((typeof newValue !== 'undefined') && (typeof obj === 'object') &&\n (!Array.isArray(obj))) {\n obj[components[i]] = (setAndLast ? newValue : ((components[i+1] === '0' || components[i+1] === '-') ? [] : {}));\n obj = obj[components[i]];\n }\n else return false;\n }\n }\n return obj;\n}", "function deepUpdate(obj, up, level) { //**should change this to use new objects with prototypes of object instead of copying all members... ****done, but not tested.\r\n\t\tif (level) {\r\n\t\t\t// <level> should start with a \"[\" or a \".\" -- if both missing prepend a \".\"\r\n\t\t\tif (level.search(/^\\.|^\\[/) === -1) {\r\n\t\t\t\tlevel = \".\" + level;\r\n\t\t\t}\r\n\t\t\tobj = eval(\"obj\" + level);\r\n\t\t}\r\n\t\tif (up) {\r\n\t\t\tfor (var i in up) {\r\n\t\t\t\tif (isObject(up[i])) {\r\n\t\t\t\t\tobj[i] = deepProto(up[i]);\t\t\t\r\n\t\t\t\t} else {\r\n\t\t\t\t\tobj[i] = up[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn obj;\r\n\t}", "function findFirstProp(objs, p) {\n for (let obj of objs) {\n if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }\n }\n}", "async expandProperty(property) {\n // JavaScript requires keys containing colons to be quoted,\n // so prefixed names would need to written as path['foaf:knows'].\n // We thus allow writing path.foaf_knows or path.foaf$knows instead.\n property = property.replace(/^([a-z][a-z0-9]*)[_$]/i, '$1:');\n\n // Expand the property to a full IRI\n const context = await this._context;\n const expandedProperty = context.expandTerm(property, true);\n if (!ContextUtil.isValidIri(expandedProperty))\n throw new Error(`The JSON-LD context cannot expand the '${property}' property`);\n return namedNode(expandedProperty);\n }", "function calcProp(ka, p) {\n var val = ka[p];\n if (isKeepAssigned(val)) {\n recalc(val);\n } else {\n val.val = findFirstProp(ka.objs, p);\n }\n}", "function shallowUpdate(obj, up, level) {\r\n\t\tif (level) {\r\n\t\t\t// <level> should start with a \"[\" or a \".\" -- if both missing prepend a \".\"\r\n\t\t\tif (level.search(/^\\.|^\\[/) === -1) {\r\n\t\t\t\tlevel = \".\" + level;\r\n\t\t\t}\r\n\t\t\tobj = eval(\"obj\" + level);\r\n\t\t}\r\n\t\tif (up) {\r\n\t\t\tfor (var i in up) {\r\n\t\t\t\tobj[i] = up[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn obj;\t\t\t\r\n\t}", "function isValidObjectPath(path) {\n return path.match(/^(\\/$)|(\\/[A-Za-z0-9_]+)+$/);\n}", "get nextPath() { return this.next && this.next.path }", "get pathPart() {\n return this.getStringAttribute('path_part');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Occurs after all windows have been closed.
onAllWindowsClosed() { // Stub }
[ "function onClosed() {\n\t// dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}", "function mainWindowCloseCallback() {\n logger.silly(\"Closing main window\");\n\n // Save the sizes of the window\n const size = mainWindow.getSize();\n store.set(\"main-width\", size[0]);\n store.set(\"main-height\", size[1]);\n\n // Check is the window is maximized\n store.set(\"main-maximized\", mainWindow.isMaximized());\n mainWindow = null;\n}", "_destroy() {\n\t\tthis.workspaces_settings.disconnect(this.workspaces_names_changed);\n\t\tWM.disconnect(this._ws_number_changed);\n\t\tglobal.display.disconnect(this._restacked);\n\t\tglobal.display.disconnect(this._window_left_monitor);\n\t\tthis.ws_bar.destroy();\n\t\tsuper.destroy();\n\t}", "closeAllWindows() {\n let windows = this.getInterestingWindows();\n for (let i = 0; i < windows.length; i++)\n windows[i].delete(global.get_current_time());\n }", "function closeAllInfoWindows() {\n\tfor (var i=0;i<infoWindows.length;i++) {\n\t\tinfoWindows[i].close();\n\t}\n}", "function closeAllInfoWindows() {\n for (var latLng in latLngDict) {\n latLngDict[latLng].infoWindow.close();\n }\n closeAllBusInfoWindows();\n }", "function closeAllBusInfoWindows() {\n for (var latLng in latLngToBusDict) {\n latLngToBusDict[latLng]['infoWindow'].close();\n }\n }", "closeAll() {\n this.openDialogs.forEach(ref => ref.close());\n }", "function CloseWindow ( w )\n {\n \tif ( w && !w.closed )\n \t{\n \t\tw.close();\n \t}\n }", "handleClose (evt) {\n if (this.focused() && !this.forceQuit) {\n this.contentWindows.forEach((w) => w.close())\n if (process.platform === 'darwin' || this.appSettings.hasTrayIcon) {\n this.mailboxesWindow.hide()\n evt.preventDefault()\n this.forceQuit = false\n }\n }\n }", "function closeWin()\r\n{\r\n var browserWin = getBrowserWindow();\r\n if (browserWin && browserWin.gStatusManager\r\n && browserWin.gStatusManager.closeMsgDetail)\r\n {\r\n browserWin.gStatusManager.closeMsgDetail();\r\n }\r\n else\r\n { \r\n self.close();\r\n }\r\n return;\r\n}", "function popupPVAsWindow_onunload(event)\n{\n\ttry\n\t{\n\t\tif (!window.close())\n\t\t{\n\t\t\tdt_pvClosePopUp(false);\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t}\n}", "async closeAllWindowProcesses() {\n\t\tconst windowProcesses = await this.getWindowProcessList();\n\t\tfor (const a in windowProcesses) {\n\t\t\tconst windowProcess = windowProcesses[a];\n\t\t\twindowProcess.close();\n\t\t}\n\t}", "close() {\n if(this.added) {\n this.added = false;\n this.getJQueryObject().remove();\n\n // Remove entry from global entries variable\n entries = _.omit(entries, this.id);\n\n GUI.onEntriesChange();\n GUI.updateWindowHeight();\n }\n }", "function cpsh_onClose(evt) {\n if (processed) {\n WapPushManager.close();\n return;\n }\n quitAppConfirmDialog.hidden = false;\n }", "quit () {\n this.forceQuit = true\n this.mailboxesWindow.close()\n }", "function messageBoxCloseCallback() {\n logger.silly(\"Closing messagebox\");\n}", "function closeReportWindow () {\n\tset_element_display_by_id_safe('ReportWindow', 'none');\n\tset_element_display_by_id_safe('report_error1', 'none');\n\tset_element_display_by_id_safe('report_error2', 'none');\n\tset_element_display_by_id_safe('error_div', 'none');\n}", "function jConfirmWindowClosed(callbackFunction)\n\t\t\t\t{\n\t\t\t\t\t//User can't click on buttons anymore\n\t\t\t\t\tconfirmWindow.find('input').attr('disabled','true');\n\t\t\t\t\tif(callbackFunction)\n\t\t\t\t\t{\n\t\t\t\t\t\tcallbackFunction(link);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(parameters.splash)\n\t\t\t\t\t{\n\t\t\t\t\t\tsplash.fadeOut('slow');\n\t\t\t\t\t}\n\t\t\t\t\tconfirmWindow.fadeOut('slow',function()\n\t\t\t\t\t{\n\t\t\t\t\t\tif(parameters.onclose)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparameters.onclose(link);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(this).remove();\n\t\t\t\t\t});\n\t\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createTable: method responsible for creating the table Arguments: x, y, z position of the table
createTable(x, y, z) { 'use strict'; var table = new Table(x, y, z); table.createTableLeg(-35, 30, -50); table.createTableLeg(-35, 30, 50); table.createTableLeg(35, 30, -50); table.createTableLeg(35, 30, 50); table.createTableTop(); this.scene.add(table); return table; }
[ "function createTable(table, columnX, columnY) {\n let counter = 0;\n\n for (let valueX of columnX) {\n let row = table.insertRow();\n let cell = row.insertCell();\n let text = document.createTextNode(valueX);\n cell.appendChild(text);\n\n let cellY = row.insertCell();\n let textY = document.createTextNode(columnY[counter]);\n cellY.appendChild(textY);\n counter++; \n }\n}", "function generateTable() {\n emptyTable();\n generateRows();\n generateHead();\n generateColumns();\n borderWidth();\n}", "function drawTable(){\n var wrapper = document.getElementById(\"table-wrapper\");\n var table = document.createElement(\"TABLE\");\n\n table.id = \"game-table\";\n wrapper.appendChild(table);\n\n var t = document.getElementById(\"game-table\");\n\n for(var x=0;x<colorArray.length;x++){\n var tr = document.createElement(\"TR\");\n tr.id = \"row\" + x;\n t.appendChild(tr);\n for(var y=0;y<colorArray.length;y++){\n var r = document.getElementById(\"row\" + x);\n var node = colorArray[x][y].print(\"cell\"+x+\"-\"+y);\n r.appendChild(node);\n }\n }\n }", "_create_table_template(self, cont_id, height_px)\r\n\t{\r\n\t\tconsole.log(\"_create_table_template/\");\r\n\t\t\r\n\t\tvar tableCont = document.getElementById(cont_id);\r\n\r\n\t\tvar dchartTableDivEl = document.createElement(\"div\"); \r\n\t\tdchartTableDivEl.style = \"max-height:\"+height_px.toString()\r\n\t\t\t\t\t\t\t\t\t\t\t +\"px; overflow-y: scroll;\";\r\n\t\t\r\n\t\tvar dchartTable = document.createElement(\"table\");\r\n\t\tdchartTable.className = \"table table-striped\";\r\n\r\n\t\tdchartTableDivEl.append(dchartTable);\r\n\t\t\r\n\t\tvar dchartTableHead = document.createElement(\"thead\");\r\n\t\tdchartTableHead.innerHTML = dchart_table_head;\r\n\t\tdchartTable.append(dchartTableHead);\r\n\t\t\r\n\t\tvar dchartTableBody = document.createElement(\"tbody\");\r\n\t\tdchartTableBody.id = self.__dchar_table_body_id;\r\n\t\t\r\n\t\tdchartTable.append(dchartTableBody);\r\n\t\t\r\n\t\ttableCont.append(dchartTableDivEl);\r\n\t\t\r\n\t\tconsole.log(\"/_create_table_template\");\r\n\t}", "function createTable() {\n var main = $('#region-main');\n var table = $('<table></table>');\n table.attr('id', 'local-barcode-table');\n table.addClass('generaltable');\n table.addClass('local-barcode-table');\n\n var thead = table.append('<thead></thead>');\n var header = thead.append('<tr></tr>');\n header.html('<th colspan=\"8\" class=\"local-barcode-th-left local-barcode-sm-hide\">' + strings[1] +\n ' - (<span id=\"local_barcode_id_count\">' +\n '0</span> ' + strings[6] + ')</th>' +\n '<th colspan=\"17\" class=\"local-barcode-th-center\">' + strings[0] + '</th>' +\n '<th colspan=\"5\" class=\"local-barcode-th-right\">' + strings[8] +\n '(<span id=\"local_barcode_id_submit_count\">0</span>)</th>');\n table.append('<tbody id=\"tbody\"></tbody>');\n\n main.append(table);\n }", "function createTable() {\n $(\"#main\").append(\"<table id='field'>\");\n for (var r = 0; r < dim_max; r++) {\n $(\"#field\").append(\"<tr id='r\" + r + \"'>\");\n for (var c = 0; c < dim_max; c++) {\n //row\n $(\"#r\" + r).append(\"<td id='\" + r + \"-\" + c + \"' align='center'>\");\n //4 images per row\n $(\"#\"+r+\"-\"+c).append(\"<img>\");\n $(\"#\"+r+\"-\"+c).children().attr(\"src\", \"images/\" + (r*dim_max+(c+1)) + \".jpg\");\n $(\"#\"+r+\"-\"+c).children().attr(\"ondragstart\", \"return false;\");\n }\n }\n}", "function createTable() {\n\tdocument.getElementById('output').innerHTML = \"Creating Table...\";\n\n\tlet keys = [\"Index\", \"SS58\", \"Owner\", \"Deposit\", \"Permanent?\"];\n\n\tlet table = document.getElementById('indices-table');\n\n\t// Clear table\n\twhile (table.firstChild) {\n\t\ttable.removeChild(table.firstChild);\n\t}\n\n\tlet thead = document.createElement('thead');\n\tlet tbody = document.createElement('tbody');\n\n\tlet tr = document.createElement('tr');\n\tfor (key of keys) {\n\t\tlet th = document.createElement('th');\n\t\tth.innerText = key;\n\t\ttr.appendChild(th);\n\t}\n\n\tfor (index of Object.keys(global.indices)) {\n\t\tlet tr2 = document.createElement('tr');\n\n\t\tfor (key in keys) {\n\t\t\tlet td = document.createElement('td');\n\t\t\ttd.innerText = global.indices[index][key];\n\t\t\ttr2.appendChild(td);\n\t\t}\n\t\ttbody.appendChild(tr2);\n\t}\n\n\tthead.appendChild(tr);\n\ttable.appendChild(thead);\n\ttable.appendChild(tbody);\n\n\tdocument.getElementById('output').innerHTML = \"Done.\";\n}", "function CreateTable(list,methodName)\n {\n var tb = document.createElement(\"table\");\n var recordStyle;\n \n for (var i=0;i<list.length;i++)\n {\n var row = document.createElement(\"tr\"); \n var cell = document.createElement(\"td\"); \n \n if(i%2 == 0)\n {\n recordStyle = 'ACA_TabRow_Single_Line font12px';\n }\n else\n {\n recordStyle = 'ACA_TabRow_Double_Line font12px';\n } \n \n cell.innerHTML = \"<a href='#' title=\\\"\"+list[i]+\"\\\" onclick='\" + methodName + \"(\\\"\"+list[i]+\"\\\")' class=\\\"\" + recordStyle +\"\\\"><span>\" + TruncateString(list[i]) + \"</span></a>\";\n \n row.appendChild(cell); \n tb.appendChild(row); \n } \n \n return tb;\n }", "function createHolidayTable(holidayDate,holidayWeek,holidayName,holidayPublic){\n\n let tr = document.createElement('tr')\n let th = document.createElement('th')\n th.setAttribute('scope',\"row\")\n let td2 = document.createElement('td') \n let td3 = document.createElement('td') \n let td4 = document.createElement('td')\n th.innerHTML=holidayDate\n td2.innerHTML=holidayWeek \n td3.innerHTML=holidayName\n td4.innerHTML=holidayPublic\n tr.append(th,td2,td3,td4)\n let tbodyList = document.getElementById('tbody-list')\n tbodyList.append(tr) \n\n }", "function CreateTblRow(tblName, field_setting, data_dict, col_hidden) {\n //console.log(\"========= CreateTblRow =========\", tblName);\n //console.log(\"data_dict\", data_dict);\n\n const field_names = field_setting.field_names;\n const field_tags = field_setting.field_tags;\n const field_align = field_setting.field_align;\n const field_width = field_setting.field_width;\n const column_count = field_names.length;\n\n //const col_left_border = (selected_btn === \"btn_overview\") ? cols_overview_left_border : cols_stud_left_border;\n const col_left_border = field_setting.cols_left_border;\n\n// --- lookup index where this row must be inserted\n const ob1 = (data_dict.lastname) ? data_dict.lastname.toLowerCase() : \"\";\n const ob2 = (data_dict.firstname) ? data_dict.firstname.toLowerCase() : \"\";\n // ordering of table overview is doe on server, put row at end\n const row_index = (selected_btn === \"btn_result\") ? b_recursive_tblRow_lookup(tblBody_datatable, setting_dict.user_lang, ob1, ob2) : -1;\n\n// --- insert tblRow into tblBody at row_index\n const tblRow = tblBody_datatable.insertRow(row_index);\n if (data_dict.mapid) {tblRow.id = data_dict.mapid};\n\n// --- add data attributes to tblRow\n tblRow.setAttribute(\"data-pk\", data_dict.id);\n\n// --- add data-sortby attribute to tblRow, for ordering new rows\n tblRow.setAttribute(\"data-ob1\", ob1);\n tblRow.setAttribute(\"data-ob2\", ob2);\n\n// --- add EventListener to tblRow\n tblRow.addEventListener(\"click\", function() {HandleTblRowClicked(tblRow)}, false);\n\n// +++ insert td's into tblRow\n for (let j = 0; j < column_count; j++) {\n const field_name = field_names[j];\n\n // skip columns if in columns_hidden\n if (!col_hidden.includes(field_name)){\n const field_tag = field_tags[j];\n const class_width = \"tw_\" + field_width[j];\n const class_align = \"ta_\" + field_align[j];\n\n // --- insert td element,\n const td = tblRow.insertCell(-1);\n\n // --- create element with tag from field_tags\n const el = document.createElement(field_tag);\n\n // --- add data-field attribute\n el.setAttribute(\"data-field\", field_name);\n\n // --- add text_align\n el.classList.add(class_width, class_align);\n\n // --- add left border before each group\n if(col_left_border.includes(j)){td.classList.add(\"border_left\")};\n\n // --- append element\n td.appendChild(el);\n\n// --- add EventListener to td\n if (field_name === \"withdrawn\") {\n if(permit_dict.permit_crud && permit_dict.requsr_same_school){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n // this is done in add_hover: td.classList.add(\"pointer_show\");\n };\n } else if (field_name === \"gl_status\") {\n if(permit_dict.permit_approve_result && permit_dict.requsr_role_insp){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n };\n //} else if ([\"diplomanumber\", \"gradelistnumber\"].includes(field_name)){\n // td.addEventListener(\"change\", function() {HandleInputChange(el)}, false)\n // el.classList.add(\"input_text\");\n };\n // --- put value in field\n UpdateField(el, data_dict)\n } // if (!columns_hidden[field_name])\n } // for (let j = 0; j < 8; j++)\n return tblRow\n }", "function _tableElement(nbLignes,nbColonnes,image) {\n \n var table = \"<table>\";\n \n // extraire la hauteur et la largeur de l'image\n var hauteur = image.naturalHeight;\n var largeur = image.naturalWidth;\n \n // générer les attributs \"height\" et \"width\" des canvas\n var attributeHeight = _heightAttribute(hauteur,nbLignes);\n var attributeWidth = _widthAttribute(largeur,nbColonnes);\n \n for(var i=0;i<nbLignes;i++) {\n \n table += \"<tr>\";\n \n for(var j=0;j<nbColonnes;j++) \n /* création d'un canvas dont la forme de l'id est \"i,j\" dans un td dont l'id est de la forme \"i,j!\" */ \n table += _tdCanvasElement(i,j,attributeHeight,attributeWidth); \n \n table += \"</tr>\"; \n }\n table += \"</table>\"\n return table;\n}", "createTable() {\n\t\tBirthday.dynamodb.createTable(Birthday.schema, (err) => {\n\t\t\tif (err) {\n\t\t\t\tconsole.error('Unable to create table. Error JSON:', JSON.stringify(err, null, 2));\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t}", "function drawTable(){\n\n\tvar tableHeaderRowCount = 1;\n\tvar table = document.getElementById(\"scoreTableBody\");\n\t\n\t//i'm lazy and just delete each row one by one\n\tvar rowCount = table.rows.length;\n\tfor(var i = tableHeaderRowCount; i< rowCount; i++){\n\t\tconsole.log(\"delet thsi\");\n\t\ttable.deleteRow(tableHeaderRowCount);\n\t}\n\n\t\n\t//then I draw each row again\n\tfor(var i in scoreBoardHistory){\n\tvar row = table.insertRow(scoreTable.size);\n\tvar cell1 = row.insertCell(0);\n\tvar cell2 = row.insertCell(1);\n\n\tvar x = scoreBoardHistory[i].playerID;\n\tvar y = scoreBoardHistory[i].score;\n\tcell1.innerHTML = x;\n\tcell2.innerHTML = y;\n\t}\n\t\n\n\t//var x = document.getElementById(\"myID\").value;\n\t//var y = document.getElementById(\"myScore\").value;\n\t//cell1.innerHTML = x;\n\t//cell2.innerHTML = y;\n}", "visitCreate_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function write(width, height, table) {\n w = width;\n h = height;\n for (var k = 0; k < h; k++) {\n createElement('tr', table);\n for (var l = 0; l < w; l++)\n createElement('td', table.children[k]);\n }\n}", "function createmountainTable() {\n let mountainChoice = document.getElementById(\"mountainChoice\").selectedIndex;\n // to select option from a specific dropdown, in this instance mountainChoice.\n let chosenMountain = document.getElementById(\"mountainChoice\").options[mountainChoice].value;\n let table = document.getElementById(\"tableBodyMountain\");\n table.innerHTML = \"\";\n\n for (let i = 0; i < objs.mountains.length; i++) {\n if (chosenMountain == objs.mountains[i].name) {\n let row = table.insertRow(table.rows.length);\n let cell1 = row.insertCell(0);\n cell1.innerHTML = \"Name\";\n let cell2 = row.insertCell(1);\n cell2.innerHTML = objs.mountains[i].name;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell3 = row.insertCell(0);\n cell3.innerHTML = \"View\";\n let cell4 = row.insertCell(1);\n let img = document.createElement(\"img\");\n img.src = \"images/\" + objs.mountains[i].img;\n img.alt = objs.mountains[i].name;\n cell4.appendChild(img);\n\n row = table.insertRow(table.rows.length);\n let cell5 = row.insertCell(0);\n cell5.innerHTML = \"Elevation\";\n let cell6 = row.insertCell(1);\n cell6.innerHTML = objs.mountains[i].elevation;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell7 = row.insertCell(0);\n cell7.innerHTML = \"Effort\";\n let cell8 = row.insertCell(1);\n cell8.innerHTML = objs.mountains[i].effort;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell9 = row.insertCell(0);\n cell9.innerHTML = \"Description\";\n let cell10 = row.insertCell(1);\n cell10.innerHTML = objs.mountains[i].desc;\n table.appendChild(row);\n\n row = table.insertRow(table.rows[i].length);\n let cell11 = row.insertCell(0);\n cell11.innerHTML = \"Coordinates-Latitude\";\n let cell12 = row.insertCell(1);\n cell12.innerHTML = objs.mountains[i].coords.lat\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell13 = row.insertCell(0);\n cell13.innerHTML = \"Coordinates-Longitude\";\n let cell14 = row.insertCell(1);\n cell14.innerHTML = objs.mountains[i].coords.lng\n table.appendChild(row);\n }\n }\n }", "function initTable() {\n \n var nbLignes = $(\"#nbLignes\").val();\n var nbColonnes = $(\"#nbColonnes\").val();\n var URL = $(\"#URL\").val();\n \n /* charger l'image en mémoire, puis une fois chargé, commencer a construire le tableau de canvas */\n var image = _loadImage(URL);\n \n image.onload = function() { \n \n _onImageLoad(nbLignes,nbColonnes,image); \n \n /* ajouter les ecouteurs de cliques sur les canvas et les bouttons ainsi les touches de clavier */\n var jeu = new Jeu(nbLignes,nbColonnes);\n _addAllListeners(jeu);\n \n };\n \n}", "async createTable(params) {\n try {\n const query = `CREATE TABLE IF NOT EXISTS core_tickData_${params.feed} (\n id UUID,\n ca timestamp, \n date timestamp, \n symbol text, \n price double, \n volume int,\n PRIMARY KEY ((id),ca)\n ) WITH CLUSTERING ORDER BY (ca DESC)`;\n return await this._core.DBManager.engine.execute(query);\n } catch (e) {\n console.log('Cassandra Error ', e);\n }\n }", "function criarItensTabela(dados) {\n\n\tconst linha = tabela.insertRow()\n\n\tconst colunaClienteNome = linha.insertCell(0)\n\tconst colunaPedidoDados = linha.insertCell(1)\n\tconst colunaPedidoHora = linha.insertCell(2)\n\n\tconst dados_pedido = dados.pedido_dados.substr(0, 10) + \" ...\"\n\n\tcolunaClienteNome.appendChild(document.createTextNode(dados.cliente_nome))\n\tcolunaPedidoDados.appendChild(document.createTextNode(dados_pedido.replace(/<br>/g, \" \")))\n\n\tconst data = new Date(Number(dados.pedido_data))\n\tconst date = moment(data).format('HH:mm:ss')\n\tcolunaPedidoHora.appendChild(document.createTextNode(date))\n\n\tcolunaClienteNome.style = \"text-align: center\"\n\tcolunaPedidoDados.style = \"text-align: center\"\n\tcolunaPedidoHora.style = \"text-align: center\"\n\n\tcriarBotoesTabela(linha, dados)\n\n\t//ordemCrescente()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : accSanInit AUTHOR : Clarice Salanda DATE : March 15, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : initializes data in table PARAMETERS : RETURN :
function accSanInit(){ var accStat=''; var accSanityStat=''; if(globalInfoType == "JSON"){ var devices = getDevicesNodeJSON(); }else{ var devices =devicesArr; } for(var i = 0; i < devices.length; i++){ accStat+="<tr>"; accStat+="<td>"+devices[i].HostName+"</td>"; if(devices[i].ConsoleIp == devices[i].RP0ConsoleIp){ accStat+="<td>"+devices[i].RP0ConsoleIp+"</td>"; accStat+="<td>"+devices[i].RP1ConsoleIp+"</td>"; }else{ accStat+="<td>"+devices[i].RP1ConsoleIp+"</td>"; accStat+="<td>"+devices[i].RP0ConsoleIp+"</td>"; } accStat+="<td>"+devices[i].ManagementIp+"</td>"; accStat+="<td>init</td>"; accStat+="</tr>"; //2nd Table of Device Sanity accSanityStat+="<tr>"; accSanityStat+="<td></td>"; accSanityStat+="<td>"+devices[i].HostName+"</td>"; accSanityStat+="<td>Console IP</td>"; if(devices[i].ConsoleIp == devices[i].RP0ConsoleIp){ accSanityStat+="<td>"+devices[i].RP0ConsoleIp+"</td>"; }else{ accSanityStat+="<td>"+devices[i].RP1ConsoleIp+"</td>"; } accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="</tr>"; accSanityStat+="<tr>"; accSanityStat+="<td></td>"; accSanityStat+="<td>"+devices[i].HostName+"</td>"; accSanityStat+="<td>Management IP</td>"; accSanityStat+="<td>"+devices[i].ManagementIp+"</td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="<td></td>"; accSanityStat+="</tr>"; if(devices[i].RP0ConsoleIp != "" && devices[i].RP1ConsoleIp != ""){ if(devices[i].ConsoleIp == devices[i].RP0ConsoleIp){ accSanityStat+="<td>"+devices[i].RP1ConsoleIp+"</td>"; }else{ accSanityStat+="<td>"+devices[i].RP0ConsoleIp+"</td>"; } } } $("#accSanTableStat > tbody").empty().append(accSanityStat); $("#accSanTable > tbody").empty().append(accStat); if(globalInfoType == "JSON"){ var devices = getDevicesNodeJSON(); }else{ var devices =devicesArr; } $('#accTotalNo').empty().append(devices.length); if(globalDeviceType == "Mobile"){ $("#accSanTableStat").table("refresh"); $("#accSanTable").table("refresh"); } }
[ "function connSanInit(){\n\tvar connStat='';\n\tvar connSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tconnStat+=\"<tr>\";\n\t\tconnStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tconnStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tconnStat+=\"<td>Init</td>\";\n\t\tconnStat+=\"</tr>\";\n\t}\n//2nd Table of Device Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n\t\tvar srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n\t\tvar dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n\t\tif(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\n\t\t\tconnSanityStat+=\"<tr>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\t\t\n\t\t\tconnSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"<td></td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#connSanityTableStat > tbody\").empty().append(connSanityStat);\n\t$(\"#connSanityTable > tbody\").empty().append(connStat);\n\tif(globalInfoType == \"JSON\"){\n\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#connTotalNo').empty().append(devices.length);\n\tif(globalDeviceType ==\"Mobile\"){\n\t\t$(\"#connSanityTableStat\").table(\"refresh\");\n\t\t$(\"#connSanityTable\").table(\"refresh\");\t\n\t}\n}", "function devSanInit(){\n\tvar devStat='';\n\tvar devSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tdevStat+=\"<tr>\";\n\t\tdevStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tdevStat+=\"<td>Init</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"</tr>\";\n//2nd Table of Device Sanity\n\t\tdevSanityStat+=\"<tr>\";\n\t\tdevSanityStat+=\"<td></td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].OSVersion+\"</td>\";\n\t\tdevSanityStat+=\"<td>Init</td>\";\n\t\tdevSanityStat+=\"<td>Waiting..</td>\";\n\t\tdevSanityStat+=\"</tr>\";\n\n\t}\n\t$(\"#devSanTableStat > tbody\").empty().append(devSanityStat);\n\t$(\"#devSanTable > tbody\").empty().append(devStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#devTotalNo').empty().append(devices.length);\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$(\"#devSanTableStat\").table(\"refresh\");\n\t\t$(\"#devSanTable\").table(\"refresh\");\n\t}\n\treturn;\n}", "function linkSanInit(){\n\tvar linkStat='';\n\tvar linkSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tlinkStat+=\"<tr>\";\n\t\tlinkStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tlinkStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tlinkStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tlinkStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tlinkStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tlinkStat+=\"<td>Init</td>\";\n\t\tlinkStat+=\"<td>Init</td>\";\n\t\tlinkStat+=\"<td>Init</td>\";\n\t\tlinkStat+=\"</tr>\";\n\t}\n//2nd Table of Link Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n var srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n var dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n if(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\n\t\t\tlinkSanityStat+=\"<tr>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"<td></td>\";\n\t\t\tlinkSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#linkSanityTableStat > tbody\").empty().append(linkSanityStat);\n\t$(\"#linkSanityTable > tbody\").empty().append(linkStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#linkTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#linkSanityTableStat\").table(\"refresh\");\n\t\t$(\"#linkSanityTable\").table(\"refresh\");\t\t\t\n\t}\n}", "function accSanXML(uptable,lowtable){\n\tvar accStat='';\n\tvar accSanityStat='';\n\tvar devFlag = false;\n\tvar upArr = ['HostName' , 'ConsoleIp1','ConsoleIp2','ManagementIp','Login']\n\tif(globalInfoType == \"XML\"){\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\taccStat+=\"<tr>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].getAttribute('HostName')+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp1')+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp2')+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].getAttribute('ManagementIp')+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].getAttribute('Login')+\"</td>\";\n\t\t\taccStat+=\"</tr>\";\n\t\t\tif(window['variable' + AccessSanity[pageCanvas] ].toString() == \"true\" && uptable[i].getAttribute('Login').toLowerCase() != 'fail' && uptable[i].getAttribute('Login').toLowerCase() != 'completed' && uptable[i].getAttribute('Login').toLowerCase() != 'cancelled' && uptable[i].getAttribute('Login').toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\taccSanityStat+=\"<tr>\";\t\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('TimeStamp')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('HostName')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('AccessType')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('IpAddress')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status1')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status2')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status3')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('State')+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status')+\"</td>\";\n\t\t\taccSanityStat+=\"</tr>\";\n\t\t}\n\t}else{\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\taccStat+=\"<tr>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].HostName+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].ConsoleIp1+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].ConsoleIp2+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].ManagementIp+\"</td>\";\n\t\t\taccStat+=\"<td>\"+uptable[i].Login+\"</td>\";\n\t\t\taccStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity.toString() == \"true\" && uptable[i].Login.toLowerCase() != 'fail' && uptable[i].Login.toLowerCase() != 'completed' && uptable[i].Login.toLowerCase() != 'cancelled' && uptable[i].Login.toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\taccSanityStat+=\"<tr>\";\t\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].TimeStamp+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].HostName+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].AccessType+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].IpAddress+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].Status1+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].Status2+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].Status3+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].State+\"</td>\";\n\t\t\taccSanityStat+=\"<td>\"+lowtable[i].Status+\"</td>\";\n\t\t\taccSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#accSanTableStat > tbody\").empty().append(accSanityStat);\n\t$(\"#accSanTable > tbody\").empty().append(accStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#accTotalNo').empty().append(devices.length);\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$(\"#accSanTableStat\").table(\"refresh\");\n\t\t$(\"#accSanTable\").table(\"refresh\");\n\t}\n\tTimeOut = setTimeout(function(){\n\t\taccSanXML2(devFlag);\n\t},2000);\n\treturn;\n}", "function initVLANsDataTable() {\n console.log(\"initVLANsDataTable\");\n\n var path = window.location.pathname;\n path = path.substr(0, path.indexOf(\"/vlans\"));\n\n var table = $('#vlans-dataTable').DataTable({\n \"ajax\": {\n \"url\": path+\"/vlans.json\",\n \"dataSrc\": \"\"\n },\n \"dom\":\n \"<'row'<'col-sm-5'i><'col-sm-7'p>>\" +\n //\"<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>\" +\n \"<'row'<'col-sm-6'l><'col-sm-6'f>>\" +\n \"<'row'<'col-sm-12 text-center'B>>\" +\n \"<'row'<'col-sm-12'tr>>\",\n \"buttons\": [\n 'columnsVisibility'\n ],\n \"autoWidth\": false,\n \"paging\": true,\n \"lengthChange\": true,\n \"lengthMenu\": [\n [25, 50, 100, 200, -1],\n [25, 50, 100, 200, \"All\"]\n ],\n \"pageLength\": -1,\n \"columns\": [\n { \"title\": \"Alias\", \"data\": \"alias\" },\n { \"title\": \"VLAN\", \"data\": \"vlan\" },\n ],\n \"order\": [[ 0, 'asc' ]],\n \"stateSave\": true,\n \"stateDuration\": 0\n });\n\n table.draw();\n\n if (HOST_REFRESH_TIMEOUT > 0) {\n setInterval(function() {\n table.ajax.reload(null, false);\n }, HOST_REFRESH_TIMEOUT);\n }\n}", "function init(){\n controllerInit(routerInitModel);\n serviceAuthorizeOps(globalEmitter,'admin',globalDataAccessCall);\n serviceAuthenticate(globalEmitter,'user',globalDataAccessCall);\n genericDataAccess(dataAccessInitModel);\n}", "function connSanXML(uptable,lowtable){\n\tvar connStat='';\n\tvar connSanityStat='';\n\tvar devFlag = false;\n\tif(globalInfoType == \"XML\"){\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tconnStat+=\"<tr>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('HostName')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('ManagementIp')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('Manufacturer')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('Model')+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].getAttribute('PortMapping')+\"</td>\";\n\t\t\tconnStat+=\"</tr>\";\n\t\t\tif(window['variable' + Connectivity[pageCanvas] ].toString() == \"true\" && uptable[i].getAttribute('PortMapping').toLowerCase() != 'fail' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'completed' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'cancelled' && uptable[i].getAttribute('PortMapping').toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n//2nd Table of Device Sanity\n\t\t\tconnSanityStat+=\"<tr>\";\t\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('TimeStamp')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcDevName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcSwitchPort')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortStatus')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstDevName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstSwitchPort')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortStatus')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('SwitchHostName')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('ConnectivityType')+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status')+\"</td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\n\t\t}\n\t}else{\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tconnStat+=\"<tr>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].HostName+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].ManagementIp+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].ConsoleIp+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].Manufacturer+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].Model+\"</td>\";\n\t\t\tconnStat+=\"<td>\"+uptable[i].PortMapping+\"</td>\";\n\t\t\tconnStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity.toString() == \"true\" && uptable[i].PortMapping.toLowerCase() != 'fail' && uptable[i].PortMapping.toLowerCase() != 'completed' && uptable[i].PortMapping.toLowerCase() != 'cancelled' && uptable[i].PortMapping.toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n//2nd Table of Device Sanity\n\t\t\tconnSanityStat+=\"<tr>\";\t\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].TimeStamp+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcDevName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcPortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcSwitchPort+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SrcPortStatus+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstDevName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstPortName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstSwitchPort+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].DstPortStatus+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].SwitchHostName+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].ConnectivityType+\"</td>\";\n\t\t\tconnSanityStat+=\"<td>\"+lowtable[i].Status+\"</td>\";\n\t\t\tconnSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#connSanityTableStat > tbody\").empty().append(connSanityStat);\n\t$(\"#connSanityTable > tbody\").empty().append(connStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#connTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#connSanityTableStat\").table(\"refresh\");\n\t\t$(\"#connSanityTable\").table(\"refresh\");\t\n\t}\n\tTimeOut = setTimeout(function(){\n\t\tconnSanXML2(devFlag);\n\t},2000);\n\treturn;\t\n}", "function enableIntInit(){\n\tvar enableStat='';\n\tvar enableSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n \t var devices = getDevicesNodeJSON();\n }else{\n\t var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tenableStat+=\"<tr>\";\n\t\tenableStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"</tr>\";\n\t}\n//2nd Table of Device Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n\t\tenableSanityStat+=\"<tr>\";\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n var srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n var dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n if(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\t\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\t\t\n\t\t}\n\t\tenableSanityStat+=\"</tr>\";\n\t}\n\t$(\"#enaSanityTableStat > tbody\").empty().append(enableSanityStat);\n\t$(\"#enaSanityTable > tbody\").empty().append(enableStat);\t\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#enableTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#enaSanityTableStat\").table(\"refresh\");\n\t\t$(\"#enaSanityTable\").table(\"refresh\");\n\t}\n}", "function initializeBuyCryptoDataTable() {\n state.buyDataTable = $(idSelectors.buyCryptoTable).DataTable( {\n \"ajax\" : {\n \"url\": api.getBuyCryptoData,\n \"type\": \"POST\",\n \"dataSrc\": \"\"\n },\n \"columns\" : [\n {\n className: 'details-control',\n orderable: false,\n data: null,\n defaultContent: '<button class=\"btn btn-primary btn-sm\">Buy</button>'\n },\n { \"data\": \"percent_change\" },\n { \"data\": \"name\" },\n { \"data\": \"abbreviation\" },\n { \"data\": \"worth_in_USD\" }\n ],\n \"createdRow\": function(row, data) {\n $(row).data('id', data.id);\n }\n });\n\n initializeDetailsControlEventListener(state.buyDataTable, IdNames.buyCryptoTable);\n}", "function enableSanXML(uptable,lowtable){\n\tvar enableStat='';\n\tvar enableSanityStat='';\n\tvar devFlag = false;\n\tif(globalInfoType == \"XML\"){\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tenableStat+=\"<tr>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('HostName')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('ManagementIP')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIP')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('Manufacturer')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('Model')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('Login')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('EnableInterface')+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].getAttribute('Verification')+\"</td>\";\n\t\t\tenableStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface.toString() == \"true\" && uptable[i].getAttribute('Verification').toLowerCase() != 'fail' && uptable[i].getAttribute('Verification').toLowerCase() != 'completed' && uptable[i].getAttribute('Verification').toLowerCase() != 'cancelled' && uptable[i].getAttribute('Verification').toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\t\t\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\tenableSanityStat+=\"<tr>\";\t\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('TimeStamp')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcDevName')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortName')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcAdminStatus')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortStatus')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcSpeed')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcMediaType')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstDevName')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortName')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstAdminStatus')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortStatus')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstSpeed')+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstMediaType')+\"</td>\";\n\t\t\tenableSanityStat+=\"</tr>\";\n\t\t}\n\t}else{\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tenableStat+=\"<tr>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].HostName+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].ManagementIP+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].ConsoleIP+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].Manufacturer+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].Model+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].Login+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].EnableInterface+\"</td>\";\n\t\t\tenableStat+=\"<td>\"+uptable[i].Verification+\"</td>\";\n\t\t\tenableStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface.toString() == \"true\" && uptable[i].Verification.toLowerCase() != 'fail' && uptable[i].Verification.toLowerCase() != 'completed' && uptable[i].Verification.toLowerCase() != 'cancelled' && uptable[i].Verification.toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\t\t\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\tenableSanityStat+=\"<tr>\";\t\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].TimeStamp+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcDevName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcPortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcAdminStatus+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcPortStatus+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcSpeed+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].SrcMediaType+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstDevName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstPortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstAdminStatus+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstPortStatus+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstSpeed+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+lowtable[i].DstMediaType+\"</td>\";\n\t\t\tenableSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#enaSanityTableStat > tbody\").empty().append(enableSanityStat);\n\t$(\"#enaSanityTable > tbody\").empty().append(enableStat);\t\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#enableTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#enaSanityTableStat\").table(\"refresh\");\n\t\t$(\"#enaSanityTable\").table(\"refresh\");\n\t}\n\tif(devFlag == false && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadConfigEnable.toString() == \"false\"){\n\t\tenableFlagSan = \"false\";\n\t}\n\tif(devFlag == true){\n\t\tenableFlagSan = \"true\";\n\t}else{\n\t\tclearTimeout(TimeOut);\n\t}\n\tif(autoTriggerTab.toString() == \"true\"){\n\t\tif(devFlag == true){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\t$('#liEnaInt a').trigger('click');\n\t\t}else if(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable.toString() == \"true\" && devFlag == false && LoadImageFlag.toString() == \"false\"){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\tLoadImageFlag = \"true\";\n\t\t\t$('#liLoadImg a').trigger('click');\n\t\t}else if(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadConfigEnable.toString() == \"true\" && devFlag == false && LoadConfigFlag.toString() == \"false\"){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\tLoadConfigFlag = \"true\";\n\t\t\t$('#liLoadConf a').trigger('click');\n\t\t}\n\t}else{\n\t\tif(devFlag == true){\n\t\t\tautoTrigger('enableint');\n\t\t}\n\t}\n\t\n\treturn;\n}", "function accSanityData(data){\n\tvar accStat='';\n\tvar accSanityStat='';\n\tvar mydata = data;\n\tif(globalInfoType == \"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n\t\tvar json = jQuery.parseJSON(data);\n if(json.MAINCONFIG){\n var uptable = json.MAINCONFIG[0].DEVICE;\n var lowtable = json.MAINCONFIG[0].STATUS;\n }\n\t}\n\tif(json.MAINCONFIG){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\taccSanXML(uptable,lowtable);\n\t\t },5000);\n\t\treturn;\n\t}\n\taccSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('accessSanity');\n\t},5000);\n}", "function initNamespacesDataTable() {\n console.log(\"initNamespacesDataTable\");\n\n var table = $('#namespaces-dataTable').DataTable({\n \"ajax\": {\n \"url\": \"namespaces.json\",\n \"dataSrc\": \"\"\n },\n \"dom\":\n \"<'row'<'col-sm-5'i><'col-sm-7'p>>\" +\n //\"<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>\" +\n \"<'row'<'col-sm-6'l><'col-sm-6'f>>\" +\n \"<'row'<'col-sm-12 text-center'B>>\" +\n \"<'row'<'col-sm-12'tr>>\",\n \"buttons\": [\n 'columnsVisibility'\n ],\n \"autoWidth\": false,\n \"paging\": true,\n \"lengthChange\": true,\n \"lengthMenu\": [\n [25, 50, 100, 200, -1],\n [25, 50, 100, 200, \"All\"]\n ],\n \"pageLength\": -1,\n \"columns\": [\n { \"title\": \"Name\", \"data\": \"namespace\", render: function ( data, type, full, meta ) {\n return '<a href=\"/'+data+'/vms\">'+data+'</a>';\n } },\n { \"title\": \"VLANs\", \"data\": \"vlans\", render: function ( data, type, full, meta ) {\n if (data == \"\") {\n data = \"Inherited\";\n }\n\n return '<a href=\"/'+full[\"namespace\"]+'/vlans\">'+data+'</a>';\n } },\n { \"title\": \"Active\", \"data\": \"active\" },\n ],\n \"order\": [[ 0, 'asc' ]],\n \"stateSave\": true,\n \"stateDuration\": 0\n });\n\n table.draw();\n\n if (HOST_REFRESH_TIMEOUT > 0) {\n setInterval(function() {\n table.ajax.reload(null, false);\n }, HOST_REFRESH_TIMEOUT);\n }\n}", "function initTable(num){\n\n // Filter dataset by OTU id\n var filteredDate=dataset.metadata.filter(sample=>sample.id.toString()===num.toString())[0];\n\n\n // Create an list to store demographic information\n var valueList=Object.values(filteredDate);\n var valueKey=Object.keys(filteredDate);\n var demoInfo=[]\n for (var i=0;i<valueKey.length;i++){\n var element=`${valueKey[i]}: ${valueList[i]}`\n demoInfo.push(element);\n };\n\n // Add Demographic Information table in HTML\n var panel=d3.select(\"#sample-metadata\")\n var panelBody=panel.selectAll(\"p\")\n .data(demoInfo)\n .enter()\n .append(\"p\")\n .text(function(data){\n var number=data.split(\",\");\n return number;\n });\n \n }", "function createTierCodesTable() {\n\t\t\tself.tableParams = new ngTableParams({\n\t\t\t\tpage: self.PAGE, /* show first page */\n\t\t\t\tcount: self.PAGE_SIZE /* count per page */\n\t\t\t}, {\n\t\t\t\tcounts: [],\n\n\t\t\t\tgetData: function ($defer, params) {\n\t\t\t\t\tself.recordsVisible = 0;\n\t\t\t\t\tself.data = null;\n\n\t\t\t\t\tself.defer = $defer;\n\t\t\t\t\tself.dataResolvingParams = params;\n\n\t\t\t\t\tvar includeCounts = false;\n\n\t\t\t\t\tvar id = params.filter()[\"productBrandTierCode\"];\n\t\t\t\t\tvar description = params.filter()[\"productBrandName\"];\n\n\t\t\t\t\tif (typeof id === \"undefined\") {\n\t\t\t\t\t\tid = EMPTY_STRING;\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof description === \"undefined\") {\n\t\t\t\t\t\tdescription = EMPTY_STRING;\n\t\t\t\t\t}\n\n if (id !== previousIdFilter || description !== previousDescriptionFilter) {\n\t\t\t\t\t\tself.firstSearch = true;\n\t\t\t\t\t}\n if (self.deletingLastItemPage === true) {\n includeCounts = true;\n self.deletingLastItemPage = false;\n } else {\n includeCounts = false;\n }\n\n\t\t\t\t\tif (self.firstSearch) {\n\t\t\t\t\t\tincludeCounts = true;\n\t\t\t\t\t\tparams.page(1);\n\t\t\t\t\t\tself.firstSearch = false;\n\t\t\t\t\t\tself.startRecord = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tpreviousDescriptionFilter = description;\n\t\t\t\t\tpreviousIdFilter = id;\n\t\t\t\t\tself.fetchData(includeCounts, params.page() - 1, id, description);\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function linkSanXML(uptable,lowtable){\n\tvar linkStat='';\n\tvar linkSanityStat='';\n\tvar devFlag = false;\n\tif(globalInfoType == \"XML\"){\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tlinkStat+=\"<tr>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].getAttribute('HostName')+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].getAttribute('ManagementIp')+\"</td>\";\n\t\t\tif(globalInfoType == \"JSON\"){\n\t \t var devices = getDevicesNodeJSON();\n\t\t }else{\n\t \t var devices =devicesArr;\n\t\t }\n\t\t\tfor(var x = 0; x < devices.length; x++){\n\t\t\t\tif(uptable[i].getAttribute('HostName') == devices[x].HostName){\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].ConsoleIp+\"</td>\";\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].Manufacturer+\"</td>\";\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].Model+\"</td>\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp')+\"</td>\";\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('Manufacturer')+\"</td>\";\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('Model')+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].getAttribute('Configuration')+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].getAttribute('Learning_Packets')+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].getAttribute('Forwarding_Test')+\"</td>\";\n\t\t\tlinkStat+=\"</tr>\";\n\t\t\tif(window['variable' + ConnectivityFlag[pageCanvas] ].toString() == \"yes\" && uptable[i].getAttribute('Forwarding_Test').toLowerCase() != 'fail' && uptable[i].getAttribute('Forwarding_Test').toLowerCase() != 'completed' && uptable[i].getAttribute('Forwarding_Test').toLowerCase() != 'cancelled' && uptable[i].getAttribute('Forwarding_Test').toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\tlinkSanityStat+=\"<tr>\";\t\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('TimeStamp')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcDevName')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortName')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortIpAdress')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('SrcPortStatus')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstDevName')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortName')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortIpAddress')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('DstPortStatus')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('State')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('Receive')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('Transmit')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('MinAveMax')+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].getAttribute('Status')+\"</td>\";\n\t\t\tlinkSanityStat+=\"</tr>\";\n\t\t}\n\t}else{\n\t\tfor(var i = 0; i < uptable.length; i++){\n\t\t\tlinkStat+=\"<tr>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].HostName+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].ManagementIp+\"</td>\";\n\t\t\tif(globalInfoType == \"JSON\"){\n\t \t var devices = getDevicesNodeJSON();\n\t\t }else{\n\t \t var devices =devicesArr;\n\t\t }\n\t\t\tfor(var x = 0; x < devices.length; x++){\n\t\t\t\tif(uptable[i].getAttribute('HostName') == devices[x].HostName){\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].ConsoleIp+\"</td>\";\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].Manufacturer+\"</td>\";\n\t\t\t\t\tlinkStat+=\"<td>\"+devices[x].Model+\"</td>\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('ConsoleIp')+\"</td>\";\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('Manufacturer')+\"</td>\";\n\t\t\t//linkStat+=\"<td>\"+uptable[i].getAttribute('Model')+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].Configuration+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].Learning_Packets+\"</td>\";\n\t\t\tlinkStat+=\"<td>\"+uptable[i].Forwarding_Test+\"</td>\";\n\t\t\tlinkStat+=\"</tr>\";\n\t\t\tif(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable.toString() == \"true\" && uptable[i].Forwarding_Test.toLowerCase() != 'fail' && uptable[i].Forwarding_Test.toLowerCase() != 'completed' && uptable[i].Forwarding_Test.toLowerCase() != 'cancelled' && uptable[i].Forwarding_Test.toLowerCase() != 'device not accessible'){\n\t\t\t\tdevFlag = true;\n\t\t\t}\n\t\t}\n\t\tfor(var i = 0; i < lowtable.length; i++){\n\t\t//2nd Table of Device Sanity\n\t\t\tlinkSanityStat+=\"<tr>\";\t\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].TimeStamp+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].SrcDevName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].SrcPortName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].SrcPortIpAdress+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].SrcPortStatus+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].DstDevName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].DstPortName+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].DstPortIpAddress+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].DstPortStatus+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].State+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].Receive+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].Transmit+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].MinAveMax+\"</td>\";\n\t\t\tlinkSanityStat+=\"<td>\"+lowtable[i].Status+\"</td>\";\n\t\t\tlinkSanityStat+=\"</tr>\";\n\t\t}\n\t}\n\t$(\"#linkSanityTableStat > tbody\").empty().append(linkSanityStat);\n\t$(\"#linkSanityTable > tbody\").empty().append(linkStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#linkTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#linkSanityTableStat\").table(\"refresh\");\n\t\t$(\"#linkSanityTable\").table(\"refresh\");\t\t\t\n\t}\n\tif(devFlag == false && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable.toString() == \"false\" && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadConfigEnable.toString() == \"false\"){\n\t\tlinkSanFlag = \"false\";\n\t}\n\tif(devFlag == true){\n\t\tlinkSanFlag = \"true\";\n\t}else{\n\t\tclearTimeout(TimeOut);\n\t}\n\tif(autoTriggerTab.toString() == \"true\"){\n\t\tif(devFlag == true){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\t$('#liLinkSan a').trigger('click');\t\n\t\t}else if(devFlag == false && globalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface.toString() == \"true\" && enableFlagSan.toString() == \"false\"){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\tenableFlagSan = \"true\";\n\t\t\t$('#liEnaInt a').trigger('click');\n\t\t}else if(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable.toString() == \"true\" && devFlag == false && LoadImageFlag.toString() == \"false\"){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\tLoadImageFlag = \"true\";\n\t\t\t$('#liLoadImg a').trigger('click');\n\t\t}else if(globalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadConfigEnable.toString() == \"true\" && devFlag == false && LoadConfigFlag.toString() == \"false\"){\n\t\t\tcheckFromSanity = \"true\";\n\t\t\tLoadConfigFlag = \"true\";\n\t\t\t$('#liLoadConf a').trigger('click');\n\t\t}\n\t}else{\n\t\tif(devFlag == true){\n\t\t\tautoTrigger('linksanity');\n\t\t}\n\t}\n\t\n\t\n\treturn;\n}", "function initColtura() {\n for (var i = 0; i < vm.user.colture.length; i++) {\n if (vm.user.colture[i].sensore == vm.numSensore) {\n vm.colturaCorrente = vm.user.colture[i];\n break;\n }\n }\n for (var i = 0; i < vm.user.sensori.length; i++) {\n if (vm.user.sensori[i].idSensore == vm.numSensore) {\n vm.sensoreCorrente = vm.user.sensori[i];\n break;\n }\n }\n\n }", "async function initialize() {\n const web3 = new Web3(await oracle_1.getWeb3Provider());\n // Get the provider and contracts\n const provider = await initProvider(web3);\n const title = await provider.getTitle();\n if (title.length == 0) {\n console.log(\"Initializing provider\");\n const res = await provider.initiateProvider(oracle_1.ProviderData);\n console.log(res);\n console.log(\"Successfully created oracle\", oracle_1.ProviderData.title);\n for (const spec in oracle_1.Responders) {\n const r = await provider.initiateProviderCurve({\n endpoint: spec,\n term: oracle_1.Responders[spec].curve\n });\n console.log(r);\n console.log(\"Successfully initialized endpoint\", spec);\n }\n }\n console.log(\"Oracle exists. Listening for queries\");\n provider.listenQueries({}, (err, event) => {\n if (err) {\n throw err;\n }\n handleQuery(provider, event, web3);\n });\n}", "function initializeNgTable(users){\n vm.tableParams = new NgTableParams({page: 1, count: 10},{data: users});\n }", "function initialize(callback){\n\n\tsoap.createClient(apiInfo.wsdl, { endpoint: apiInfo.endpoint }, function(err,client){ \n\t\tif(err){ console.log(err); callback(err); }\n\t\telse {\n\t\t\tclient.setSecurity(new soap.BasicAuthSecurity(apiInfo.httpUsername, apiInfo.httpPassword));\n\t\t\tsoapClient = client;\n\t\t\tcallback(null);\n\t\t}\n\t});\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the default caption passed in the constructor and in the setter is returned by getDefaultCaption, and acts as a default caption, i.e. is shown as a caption when no items are selected.
function testDefaultCaption() { select.render(sandboxEl); var item1 = new goog.ui.MenuItem('item 1'); select.addItem(item1); select.addItem(new goog.ui.MenuItem('item 2')); assertEquals(defaultCaption, select.getDefaultCaption()); assertEquals(defaultCaption, select.getCaption()); var newCaption = 'new caption'; select.setDefaultCaption(newCaption); assertEquals(newCaption, select.getDefaultCaption()); assertEquals(newCaption, select.getCaption()); select.setSelectedItem(item1); assertNotEquals(newCaption, select.getCaption()); select.setSelectedItem(null); assertEquals(newCaption, select.getCaption()); }
[ "static setAsDefault(captionAssetId){\n\t\tlet kparams = {};\n\t\tkparams.captionAssetId = captionAssetId;\n\t\treturn new kaltura.RequestBuilder('caption_captionasset', 'setAsDefault', kparams);\n\t}", "function build_caption(item) {\n\t\t\tif (item !== undefined) {\n\t\t\t\treturn caption(item);\t\n\t\t\t} else {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}", "buildCaption() {\n var table = this.table;\n var caption = table.options.caption;\n var paginationInfo = KingTableHtmlBuilder.options.paginationInfo\n ? this.buildPaginationInfo()\n : null;\n return caption || paginationInfo ? new VHtmlElement(\"div\", {\n \"class\": \"king-table-caption\"\n }, [\n caption ? new VHtmlElement(\"span\", {}, new VTextElement(caption)) : null,\n paginationInfo\n ? (caption ? new VHtmlElement(\"br\") : null)\n : null, paginationInfo]) : null;\n }", "function setupCaption() {\n $('.caption-detail', $detail).text(node.text);\n var capHelperText = '';\n if (node.hscs) {\n capHelperText = node.hscs + '次合绳';\n } else if (node.nzcs) {\n capHelperText = node.nzcs + '次捻制';\n } else if (node.lbcs >= 0) {\n capHelperText = (node.lbcs === 0 ? '不经过拉拔' : node.lbcs + '次拉拔');\n }\n $('.caption-helper', $detail).text(capHelperText);\n }", "function getRespondeeDialogCaption(selection) {\n\n var caption = '';\n\n if (selection == 'Members') {\n\n caption = 'Registered Linked Members';\n\n } else if (selection == 'Solicitor') {\n\n caption = 'Registered Solicitors';\n\n } else if (selection == 'Financial Institution') {\n\n caption = 'Registered Financial Institutions';\n\n } else if (selection == 'Others') {\n\n caption = 'Others';\n }\n\n return caption;\n\n}", "function setCaptionSettings() {\r\n var textAlign = $('select[name=\"[_veditor_][.bx-caption][text-align]\"]').val();\r\n var textColor = $('input[name=\"[_veditor_][.bx-caption][color]\"]').val();\r\n var bgColor = $('input[name=\"[_veditor_][.bx-caption][background-color]\"]').val();\r\n var textSize = $('input[name=\"[_veditor_][.bx-caption][font-size]\"]').val();\r\n var props = {\r\n 'text-align': textAlign,\r\n 'color': textColor,\r\n 'background-color': bgColor,\r\n 'font-size': textSize\r\n };\r\n\r\n $('div#tieImg').find('div.bx-caption-preview').css(props);\r\n $('div#toeImg').find('div.bx-caption-preview').css(props);\r\n }", "clearCaptionsStyles() {\n this.captionsStyles = Object.assign({}, DEFAULT_CAPTIONS_STYLES);\n this.setCaptionsStyles();\n }", "setCaption(html) {\n this.children.some((item) => {\n if (item instanceof NavbarCaption) {\n item.setCaption(html);\n return true;\n } else {\n return false;\n }\n });\n }", "function onSetDefault(idx) {\n Y.log('Setting default item: ' + idx, 'info', NAME);\n dcList.selected = idx;\n renderItems();\n callWhenChanged(Y.dcforms.listToString(dcList));\n }", "setAskMeContainerTitle() {\n if (this.botIntegrationContainer.classList.contains(\"container-show\")) {\n this.askMeContainerTitle.textContent = this.htmlTextContentCollection[this.languageCode].askMeContainerTitle[1];\n }\n else {\n this.askMeContainerTitle.textContent = this.htmlTextContentCollection[this.languageCode].askMeContainerTitle[0];\n }\n }", "addDefault(){\n if(this.validateChoices(this.state.defaultValue)){\n let choice;\n let defaultExist=false;\n for(choice in this.state.choices){\n if(this.state.choices[choice].toLowerCase() === this.state.defaultValue.toLowerCase()){\n defaultExist = true;\n }\n }\n if(!defaultExist){\n let newChoices = this.state.choices;\n newChoices.push(this.state.defaultValue);\n this.setState({choices: newChoices});\n }\n }\n }", "initDefaultSelectInfo() {\n const {\n type: chartType,\n selectLabel,\n selectSeries,\n } = this.options;\n\n if (selectLabel.use) {\n let targetAxis = null;\n if (chartType === 'heatMap' && selectLabel?.useBothAxis) {\n targetAxis = this.defaultSelectInfo?.targetAxis;\n }\n\n this.defaultSelectInfo = !this.defaultSelectInfo?.dataIndex\n ? { dataIndex: [], label: [], data: [] }\n : this.getSelectedLabelInfoWithLabelData(this.defaultSelectInfo.dataIndex, targetAxis);\n }\n\n if (selectSeries.use && !this.defaultSelectInfo) {\n this.defaultSelectInfo = { seriesId: [] };\n }\n }", "function validateDropDownIsSet(controls, defaultText) {\n\tvar errorsFound = _.filter(controls + \" option:selected\", function(element){\n\t\treturn (element.value == defaultText);\n\t});\n\n\treturn getElementNames(errorsFound);\n}", "function shouldShowFromDefaultWarning() {\n return $scope.item.from_default && $scope.getCurrentTextValue() == $scope.values.saved;\n }", "handlePlaceholderVisibility() {\n if (!this.multiple)\n return;\n const e = this.choicesInstance.containerInner.element.querySelector(\n \"input.choices__input\"\n );\n this.placeholderText = e.placeholder ? e.placeholder : this.placeholderText;\n const t = this.choicesInstance.getValue().length;\n e.placeholder = t ? \"\" : this.placeholderText ? this.placeholderText : \"\", e.style.minWidth = \"0\", e.style.width = t ? \"1px\" : \"auto\", e.style.paddingTop = t ? \"0px\" : \"1px\", e.style.paddingBottom = t ? \"0px\" : \"1px\";\n }", "function changeCaption(obj, htmlId) {\r\n\r\n var gname = obj.innerHTML;\r\n\r\n if (isExistingFuncName(CurModObj, gname) ||\r\n isExistingGridNameInFunc(CurFuncObj, gname)) {\r\n\r\n alert(\"Name \" + gname + \" alrady exists!\");\r\n return;\r\n }\r\n\r\n\r\n if (htmlId == PreviewHtmlGridId) { // while selecting existing grid\r\n\r\n NewGridObj.caption = gname;\r\n\r\n } else { // while within a step\r\n\r\n\tvar sO = CurStepObj;\r\n\tvar gridId = getGridIdOfHtmlId(htmlId); // find grid object\r\n\tvar gO = CurFuncObj.allGrids[gridId];\r\n\tgO.caption = gname;\r\n }\r\n}", "function getEmptyOption($select) {\r\n var model = $select.attr('model');\r\n var selectOptions = getWidgetOptions($select);\r\n \r\n var emptyOption = '<option value=\"-\">' + (selectOptions.emptyOptionCaption ? selectOptions.emptyOptionCaption : _options.addEmpty) +'</option>';\r\n return emptyOption;\r\n }", "function isDefault(text) {\n var _t;\n switch (text) {\n // Green buttons\n case \"Done\":\n case \"Okay\":\n case \"OK\":\n _t = document.createElement(\"button\");\n _t.innerText = text;\n _t.classList.add(\"fancybutton\", \"color-green\");\n return _t;\n // Red buttons\n case \"Cancel\":\n _t = document.createElement(\"button\");\n _t.innerText = text;\n _t.classList.add(\"fancybutton\", \"color-red\");\n return _t;\n // Close (Closes the prompt)\n case \"Close\":\n _t = document.createElement(\"button\");\n _t.innerText = text;\n _t.classList.add(\"fancybutton\", \"color-red\");\n _t.addEventListener(\"click\", () => {\n self.close();\n });\n return _t;\n default:\n return text;\n }\n }", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a row context with index
getRowContext(index) { return new Expression.ShadowContext(this, this.rows[index]); }
[ "get rowIndex() {\n return INDEX2ROW(getTop());\n }", "visitTable_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "get row() {\n return INDEX2ROW(getTop()) + 1;\n }", "visitTable_indexed_by_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndex_expr(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitOid_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getRowIndex(): number {\n const { table, row } = this;\n const rows = table.nodes;\n\n return rows.findIndex(x => x === row);\n }", "function index_to_row(i) { return Math.floor(i / cache_row_size); }", "_updateItemIndexContext() {\r\n const viewContainer = this._nodeOutlet.viewContainer;\r\n for (let renderIndex = 0, count = viewContainer.length; renderIndex < count; renderIndex++) {\r\n const viewRef = viewContainer.get(renderIndex);\r\n const context = viewRef.context;\r\n context.count = count;\r\n context.first = renderIndex === 0;\r\n context.last = renderIndex === count - 1;\r\n context.even = renderIndex % 2 === 0;\r\n context.odd = !context.even;\r\n context.index = renderIndex;\r\n }\r\n }", "visitIndex_attributes(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getIndex(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.idx : null;\n }", "visitLocal_xmlindex_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function addQueryRow(exploreId, index) {\n var query = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__[\"generateEmptyQuery\"])(index + 1);\n return Object(_actionTypes__WEBPACK_IMPORTED_MODULE_6__[\"addQueryRowAction\"])({ exploreId: exploreId, index: index, query: query });\n}", "get indexType()\n {\n return 1;\n }", "visitBitmap_join_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitCluster_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function row(numRow) {\n return numRow * ROW + ROW_OFFSET;\n}", "visitPipe_row_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function setGridViewCurrentRow(gridView, rowId) {\n for (var i = 0, len = gridView.rows.length; i < len; i++) {\n var nextRow = gridView.rows[i];\n if (nextRow.bindingContext.id === rowId) {\n nextRow.makeCurrent();\n return;\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reveals the background of the popup, if asked
function revealPopupBackground(systemPopup) { var settings = systemPopup.data("popup-settings"); var extra = systemPopup.data("popup-extra"); // Checks fade if (settings.withFade) { $(".popupOverlay", extra.parent).fadeIn(200); } else { $(".popupOverlay", extra.parent).css("display", "block"); } }
[ "static set popup(value) {}", "function showPopup () {\n $('#popup').css('z-index', '20000');\n $('#popup .popup-title').text($('#title').val());\n $('#popup .popup-content').text($('#content').val());\n $('.hide-container').show();\n $('#popup').show();\n }", "function unblockPopupBackground() {\n $(\"#background-main-div\").addClass(\"hidden\"); \n}", "function blockPopupBackground() {\n $(\"#background-main-div\").removeClass(\"hidden\"); \n}", "function disposePopupBackground(systemPopup) {\n var settings = systemPopup.data(\"popup-settings\");\n var extra = systemPopup.data(\"popup-extra\");\n // Check if fade should be used\n if (settings.withFade) {\n // Fade background out and then remove it\n $(\".popupOverlay\", extra.parent).fadeOut(200, function () {\n $(this).remove();\n });\n } else {\n // Remove background\n $(\".popupOverlay\", extra.parent).css(\"display\", \"\").remove();\n }\n extra.parent.removeClass(\"popupFixedParent\");\n }", "function htmlPopup(){\r\n var p01 = $('<div id=\"popup-image\"><div class=\"table\"><div class=\"table-cell\"><div id=\"inner-popup\"><a id=\"close-poup\" href=\"#\"><i class=\"fa fa-times\"></i></a><img id=\"img-popup\" src=\"\" /></div></div></div></div>');\r\n $(p01).appendTo('#wrapper').hide().fadeIn(650);\r\n }", "function popup (message) {\n $('.pop').show().css('display', 'flex')\n $('.message').html(message)\n }", "function hidePopup () {\n $('#popup').css('z-index', -20000);\n $('#popup').hide();\n $('#popup .popup-title').text('');\n $('#popup .popup-content').text('');\n $('.hide-container').hide();\n $('.container').css('background', '#FAFAFA');\n }", "function happycol_presentation_beginShow(args){\n\t//check for preshow\n\thappycol_enable_controls(args);\n\tif( \n\t\t\n\t\t//list of conditions for a preshow\n\t\targs.lightingDesigner == true \n\t\t\n\t\t){\n\t\thappycol_presentation_preshow(args);\n\t}else{\n\t\thappycol_presentation_theShow(args);\n\t}\n}", "function heri_popupCover(elm) {\n var newPic = heri_coverSize($(elm).attr('src'), 'l');\n $('div.popup-covers img.popup-cover').attr('src', newPic);\n $.facebox({div: '#comic-gn-popup'});\n}", "function picSavedPop(){\r\n\t\t$(\"#popUpPic\").html(\"<h2>Info</h2><p style='color:blue; text-align: center;'><b>New Picture Has Been Saved</b></p>\"+\r\n\t\t'<a href=\"#\" data-rel=\"back\" class=\"ui-btn ui-btn-right ui-btn-inline ui-icon-delete ui-btn-icon-notext ui-btn-a\"></a>').popup(\"open\"); \r\n\t\tsetTimeout(function(){ $(\"#popUpPic\").popup(\"close\"); }, 5000);\r\n\t}", "function PopUp(url, name, width,height,center,resize,scroll,posleft,postop)\r\n{\r\n\tshowx = \"\";\r\n\tshowy = \"\";\r\n\t\r\n\tif (posleft != 0) { X = posleft }\r\n\tif (postop != 0) { Y = postop }\r\n\t\r\n\tif (!scroll) { scroll = 1 }\r\n\tif (!resize) { resize = 1 }\r\n\t\r\n\tif ((parseInt (navigator.appVersion) >= 4 ) && (center))\r\n\t{\r\n\t\tX = (screen.width - width ) / 2;\r\n\t\tY = (screen.height - height) / 2;\r\n\t}\r\n\t\r\n\tif ( X > 0 )\r\n\t{\r\n\t\tshowx = ',left='+X;\r\n\t}\r\n\t\r\n\tif ( Y > 0 )\r\n\t{\r\n\t\tshowy = ',top='+Y;\r\n\t}\r\n\t\r\n\tif (scroll != 0) { scroll = 1 }\r\n\t\r\n\tself.name=\"ori_window\";\r\n\tvar Win = window.open( url, name, 'width='+width+',height='+height+ showx + showy + ',resizable='+resize+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no');\r\n\tWin.focus();\r\n\tWin.document.close;\r\n\r\n}", "function setBackground() {\n body.css({'background-image': 'url(' + photoURL + ')'});\n element.append(credit);\n element.append(switcher);\n //set credit\n $http.get(userInfoResource + owner)\n .success(function (response) {\n if (response.stat !== 'fail') {\n var creditName = (typeof response.person.realname !== 'undefined') ? response.person.realname._content : response.person.username._content;\n credit.html('<a target=\"_blank\" href=\"http://www.flickr.com/photos/' + owner + '\">by ' + creditName + '</a>');\n } else {\n credit.html('<a target=\"_blank\" href=\"http://www.flickr.com/photos/' + owner + '\">credit</a>'); //flickr api error\n }\n })\n .error(function () {\n credit.html('<a target=\"_blank\" href=\"http://www.flickr.com/photos/' + owner + '\">credit</a>'); //http error\n });\n }", "function showpwtopView( aquest, viure ) {\n\n if (viure==1) {\n\n aquest.style.backgroundColor = \"#a529254d\";\n aquest.style.boxShadow = \"0px 0px 1px 3px rgba(165, 41, 37, 0.3)\";\n\n } else {\n\n showpwtop.style.boxShadow = \"none\";\n showpwtop.style.backgroundColor = \"transparent\";\n\n }\n\n}", "function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}", "function popupScribd(url) { window.open(url,\"reader\",\"width=\"+900+\",height=\"+700+\",scrollbars=yes,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100\");\n return false;\n}", "function show_image_on_popup(image_path) {\n\tvar photo_enlarger_main_image = document.getElementById(\"photo_enlarger__photo\");\n\tphoto_enlarger_main_image.src = image_path;\n\t\n\ttoggle_photo_enlarger_display();\n}", "showOverlay_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'in');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_DISPLAYED;\n }", "function openAssessmentPlanModal () {\n\t'use strict';\n\t$('#topicDialogBackground').css('display', 'block');\n\t$('#assessment-plan').css('display', 'block');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========= Updates the Rover Position in the Grid ===========
function updateRoverPosition(rover) { board[rover.x][rover.y] = rover; }
[ "function setRoverPosition(rover, x, y) {\n rover = board[x][y];\n updateBoardGrid(rover);\n updateRoverPosition(rover);\n}", "function moveForward(marsRover){ // moving depending on the position with x and y\n console.log(\"moveForward was called\");\n if (marsRover.x >= 0 && marsRover.x <= 9 && marsRover.y >=0 && marsRover.y <= 9) { // the grid in 10x10\n switch(marsRover.direction) {\n case \"N\":\n marsRover.y -= 1 \n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"E\":\n marsRover.x += 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"S\":\n marsRover.y += 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"W\":\n marsRover.x -= 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n }\n } else {\n console.log(\"Something is wrong!\");\n }\n}", "function displayPosition() {\r\n\tconsole.log(\"Rover Current Position: [\" + myRover.position[0] + \", \" + myRover.position[1] + \"]\");\r\n}", "function updateMovingScorePosition(){\n\tlet direction = Math.floor(Math.random() * 4);\n\tlet xPosition = movingScore.i;\n\tlet yPosition = movingScore.j;\n\n\t// up\n\tif (direction == 0 && yPosition-1 > 0 && board[xPosition][yPosition-1] != 1){\n\t\tmovingScore.j--;\n\t}\n\n\t// down\n\telse if (direction == 1 && yPosition+1 < 9 && board[xPosition][yPosition+1] != 1){\n\t\tmovingScore.j++;\n\t}\n\n\t// left\n\telse if (direction == 2 && xPosition-1 > 0 && board[xPosition-1][yPosition] != 1){\n\t\tmovingScore.i--;\n\t}\n\n\t// right\n\telse if (direction == 3 && xPosition+1 < 9 && board[xPosition+1][yPosition] != 1){\n\t\tmovingScore.i++;\n\t}\n}", "function UpdatePosition() {\n\tboard[shape.i][shape.j] = 0;\n\tvar x = GetKeyPressed();\n\tif (x == 1) {\n\t\tif (shape.j > 0 && board[shape.i][shape.j - 1] != 1) {\n\t\t\tshape.j--;\n\t\t\tdirPacman = \"up\";\n\t\t}\n\t}\n\tif (x == 2) {\n\t\tif (shape.j < 9 && board[shape.i][shape.j + 1] != 1) {\n\t\t\tshape.j++;\n\t\t\tdirPacman = \"down\";\n\t\t}\n\t}\n\tif (x == 3) {\n\t\tif (shape.i > 0 && board[shape.i - 1][shape.j] != 1) {\n\t\t\tshape.i--;\n\t\t\tdirPacman = \"left\";\n\t\t}\n\t}\n\tif (x == 4) {\n\t\tif (shape.i < 9 && board[shape.i + 1][shape.j] != 1) {\n\t\t\tshape.i++;\n\t\t\tdirPacman = \"right\";\n\t\t}\n\t}\n\tif (board[shape.i][shape.j] == 5) {\n\t\tscore += 5;\n\t\tballsCount--;\n\t}\n\telse if(board[shape.i][shape.j] == 15){\n\t\tscore += 15;\n\t\tballsCount--;\n\t}\n\n\telse if(board[shape.i][shape.j] == 25){\n\t\tscore += 25;\n\t\tballsCount--;\n\t}\n\n\tboard[shape.i][shape.j] = 2;\n\n\t//make the movement of monsters and movingScore slower\n\tif (moveIterator % 5 == 0){\n\t\tupdateMonstersPosition();\n\t\tupdateMovingScorePosition();\n\t}\n\t++moveIterator;\n}", "function move(currentorder)\n\n/** \n * Every if of the function, checks the value of the objetct direction(string). First step is check where is looking the Rover.\nSedcond step is depending on where is looking the Rover, the function will ++ or -- a position into the Rover coordinates. \nOr change the value of the object direction.\n */ \n{\n if (Myrover.direction === 'up') {\n\n switch (currentorder) {\n case 'f':\n Myrover.position.x++\n break;\n case 'r':\n Myrover.direction = 'right';\n return;\n break;\n case 'b':\n Myrover.position.x--\n break;\n case 'l':\n Myrover.direction = 'left'\n return;\n break;\n };\n };\n\n\n if (Myrover.direction === 'right') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y++\n break;\n case 'r':\n Myrover.direction = 'down';\n return;\n break;\n case 'b':\n Myrover.position.y--\n break;\n case 'l':\n Myrover.direction = 'up';\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'down') {\n switch (currentorder) {\n case 'f':\n Myrover.position.x--\n break;\n case 'r':\n Myrover.direction = 'left'\n return;\n break;\n case 'b':\n Myrover.position.x++\n break;\n case 'l':\n Myrover.direction = 'right'\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'left') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y--\n break;\n case 'r':\n Myrover.direction = 'up'\n return;\n break;\n case 'b':\n Myrover.position.y++\n break;\n case 'l':\n Myrover.direction = 'down'\n return;\n break;\n };\n };\n}", "function checkGrid(rover) {\r\n\tif ( \trover.position[0] < 0 || rover.position[0] > 9 ) {\r\n if (rover.position[0] < 0) {\r\n myRover.position[0]++;\r\n }\r\n if (rover.position[0] > 9) {\r\n myRover.position[0]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse if (rover.position[1] < 0 || rover.position[1] > 9) {\r\n if (rover.position[1] < 0) {\r\n myRover.position[1]++;\r\n }\r\n if (rover.position[1] > 9) {\r\n myRover.position[1]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse {\r\n\t\treturn false;\r\n\t}\r\n}", "hitRWall(xpos){\n\t\tthis.pos.x = xpos - this.getCol().size.x / 2;\n\t\tthis.vel.x = 0;\n\t}", "function resetRods() {\n console.log(\"rods being set\");\n rod1.style.left = \"45%\";\n rod2.style.left = \"45%\";\n}", "_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }", "updatePosition(x, y) {\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t\t\t\r\n\t\tthis.currentTileRow = Math.floor( (this.y-this.levelGrid.yCanvas) / this.tileSideScale);\r\n\t\tthis.currentTileColumn = Math.floor( (this.x-this.levelGrid.xCanvas) / this.tileSideScale);\r\n\t}", "function setPosition(newxpos, newypos) {\n\n\n var newxposTile = Math.floor(newxpos);\n var newyposTile = Math.floor(newypos);\n\n\n\n if (!(validTile(newxposTile, newyposTile) & validTile(newxposTile + xtilesWindow - 1, newyposTile + ytilesWindow - 1))) {\n return;\n }\n\n\n if (newxposTile != xposTile || newyposTile != yposTile) {\n changeTilesSrc(newxposTile, newyposTile);\n }\n\n\n\n var right = newxpos - newxposTile;\n $(\"#videos\").css(\"right\", right * tileSize);\n\n var bottom = newypos - newyposTile;\n $(\"#videos\").css(\"bottom\", bottom * tileSize);\n\n xpos = newxpos;\n ypos = newypos;\n}", "function movePrey() {\n // Change the prey's velocity at random intervals\n\n /////////// Noise velocity instead of just random /////////////\n preyVX = map(noise(tx),0,1,-preyMaxSpeed,preyMaxSpeed);\n preyVY = map(noise(ty),0,1,-preyMaxSpeed,preyMaxSpeed);\n\n tx += 0.05;\n ty += 0.05;\n\n // Update prey position based on velocity\n preyX += preyVX;\n preyY += preyVY;\n\n // Screen wrapping\n if (preyX < 0) {\n preyX += width;\n }\n else if (preyX > width) {\n preyX -= width;\n }\n\n if (preyY < 0) {\n preyY += height;\n }\n else if (preyY > height) {\n preyY -= height;\n }\n }", "function updateGrid() {\n if (Object.keys(drawGrid).length) {\n const newGrid = { ...canvasSettings.currentGrid, ...drawGrid }\n for (let key in newGrid) {\n if (newGrid[key] === 'deleted' || newGrid[key][3] === 0) {\n delete newGrid[key]\n }\n }\n const newPosition = canvasSettings.historyPosition[canvasSettings.currentFrame - 1] + 1\n const newPositionFinal = [...canvasSettings.historyPosition]\n newPositionFinal[canvasSettings.currentFrame - 1] = newPosition\n const newMoveHistory = [...canvasSettings.moveHistory[canvasSettings.currentFrame - 1].slice(0, newPosition), drawGrid]\n const newMoveHistoryFinal = [...canvasSettings.moveHistory]\n newMoveHistoryFinal[canvasSettings.currentFrame - 1] = newMoveHistory\n const wholeGridCopy = [...canvasSettings.grid]\n wholeGridCopy[canvasSettings.currentFrame - 1] = newGrid\n dispatch(changeProperty({ currentGrid: newGrid, grid: wholeGridCopy, moveHistory: newMoveHistoryFinal, historyPosition: newPositionFinal }))\n }\n }", "move() {\n //this.xVel += xVel;\n this.x = this.x + this.xVel;\n this.y = this.y + this.yVel;\n this.checkWalls();\n this.checkBalls();\n }", "move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }", "function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}", "_resetPosition() {\n this._monitor = this._getMonitor();\n\n this._updateSize();\n\n this._updateAppearancePreferences();\n this._updateBarrier();\n }", "updateCircle() {\n const obj = this.newPos(); // Returns the random values as an object\n // Updates the circles css styling\n this.div.style.left = `${obj.posX}px`;\n this.div.style.bottom = `${obj.posY}px`;\n this.div.style.width = `${obj.radius}rem`;\n this.div.style.height = `${obj.radius}rem`;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Se crea una funcion para que con cualquier archivo que no se encuentrre retorne un error 404
function fileNotFound(req, h){ const response = req.response //Preguntamos que si la response es un mensaje de boom y si el codigo es 404 if (!req.path.startsWith('/api') && response.isBoom && response.output.statusCode === 404) { //Retornamos la vista de la pagina que muestra el error 404 de una forma visual mas agradable return h.view('404', {}, { layout: 'errLayout' }) .code(404) } return h.continue }
[ "function fileRouter(parsedUrl, res) {\n\tvar code;\n\tvar page;\n\tvar filePath = './' + parsedUrl.pathname;\n\tif (fs.existsSync(filePath)) {\n\t\t// We found the page, read it and set the code\n\t\tcode = 200;\n\t\tpage = fs.readFileSync(filePath);\n\t}\n\telse {\n\t\t// We didn't find the requested page, so read the 404 page and set the code to 404\n\t\t// indicating that for the user\n\t\tcode = 404;\n\t\tpage = fs.readFileSync('./404.html');\n\t}\n\t// Setting content type & code appropriately and ending the request\n\tres.writeHead(code, {'content-type': mime.lookup(filePath) || 'text/html' });\n\tres.end(page);\n}", "function check_file_exist(file){\n\tvar http = new XMLHttpRequest();\n\thttp.open('HEAD',file,false);\n\thttp.send();\n\treturn http.status == 404;\n}", "function subirFilePorTipo(tipo, id, nombreArchivo, res) {\n\n // validamos \n if (tipo === 'usuarios') {\n\n Usuario.findById(id, (err, usuarioDB) => {\n\n if (!usuarioDB) {\n return res.status(400).json({\n ok: false,\n mensaje: ' usuario no existe'\n })\n }\n\n if (err) {\n return res.status(500).json({\n ok: false,\n mensaje: ' no se puedo actualizar Imagen de usuario',\n err\n })\n }\n\n let pathViejo = './uploads/usuarios/' + usuarioDB.imagen;\n console.log(pathViejo);\n\n\n if (fs.existsSync(pathViejo)) {\n\n // si existe el path lo borro , para cargar la nueva imagen\n // es para tener una sola imagen por cada documento de la coleccion \n fs.unlinkSync(pathViejo); \n }\n\n usuarioDB.imagen = nombreArchivo; // le asignamos al usuario de la base de datos un nombre de archivo\n usuarioDB.save((err, usuarioActualizado) => {\n\n if (err) {\n return res.status(500).json({ // internal error server\n ok: false,\n mensaje: 'error en base de datos de usuarios',\n error: err\n })\n }\n\n if (!usuarioActualizado) {\n return res.status(404).json({ // not found\n ok: false,\n mensaje: 'no hay usuarios en la base de datos'\n })\n }\n\n\n return res.status(200).json({\n ok: true,\n mensaje: 'Imagen de usuario actualizado',\n usuarioActualizado\n });\n })\n });\n }\n\n if (tipo === 'hospitales') {\n\n Hospital.findById(id, (err, hospitalDB) => {\n\n if (!hospitalDB) {\n return res.status(400).json({\n ok: false,\n mensaje: ' hospital no existe'\n })\n }\n\n if (err) {\n return res.status(500).json({\n ok: false,\n mensaje: ' no se puedo actualizar imagen del hospital',\n err\n })\n }\n\n // hospitalDB.imagen es el campo reservado para la imagen en el modelo \n let pathViejo = './uploads/hospitales/' + hospitalDB.imagen;\n\n console.log(pathViejo);\n\n if (fs.existsSync(pathViejo)) {\n // si existe lo borro , para cargar la nueva imagen\n // es para tener una sola imagen por cada documento de la coleccion \n fs.unlinkSync(pathViejo); \n }\n hospitalDB.imagen = nombreArchivo; // le asignamos al hospital de la base de datos un nombre de archivo\n hospitalDB.save((err, hospitalActualizado) => {\n\n if (err) {\n return res.status(500).json({ // internal error server\n ok: false,\n mensaje: 'error en base de datos de hospitales',\n error: err\n })\n }\n if (!hospitalActualizado) {\n return res.status(404).json({ // not found\n ok: false,\n mensaje: 'no hay hospitales en la base de datos'\n })\n }\n\n return res.status(200).json({\n ok: true,\n mensaje: 'Imagen de hospital actualizado',\n hospitalActualizado\n })\n })\n });\n }\n\n if (tipo === 'medicos') {\n\n Medico.findById(id, (err, medicoDB) => {\n\n if (!medicoDB) {\n return res.status(400).json({\n ok: false,\n mensaje: ' medico no existe'\n })\n }\n\n if (err) {\n return res.status(500).json({\n ok: false,\n mensaje: ' no se puedo actualizar imagen del medico',\n err\n })\n }\n\n // medicoDB.imagen es el campo reservado para la imagen en el modelo \n let pathViejo = './uploads/medicos/' + medicoDB.imagen;\n\n console.log(pathViejo);\n\n if (fs.existsSync(pathViejo)) {\n // si existe lo borro , para cargar la nueva imagen\n // es para tener una sola imagen por cada documento de la coleccion \n fs.unlinkSync(pathViejo); \n }\n medicoDB.imagen = nombreArchivo; // le asignamos al hospital de la base de datos un nombre de archivo\n medicoDB.save((err, medicoActualizado) => {\n\n if (err) {\n return res.status(500).json({ // internal error server\n ok: false,\n mensaje: 'error en base de datos de medicos',\n error: err\n })\n }\n if (!medicoActualizado) {\n return res.status(404).json({ // not found\n ok: false,\n mensaje: 'no hay medicos en la base de datos'\n })\n }\n\n return res.status(200).json({\n ok: true,\n mensaje: 'Imagen de medico actualizado',\n medicoActualizado\n })\n })\n });\n }\n\n}", "function not_found_handler(req, res, next) {\n res.status(404);\n res.json({\n message: 'api not exist or wrong HTTP method'\n })\n}", "function serve(uri) {\n var file = fs.absolute(fs.join(ABSOLUTE_STATIC, uri\n .substr('static'.length + 1)));\n if (!file.indexOf(ABSOLUTE_STATIC) && fs.exists(file)) {\n return {\n status:200,\n 'Content-Type':MIME_TYPES[fs.extension(file)],\n // TODO add etag or last-modified header\n // TODO add support for caching\n body:fs.openRaw(file)\n };\n } else {\n return {\n status:404,\n headers:{},\n body:[]\n };\n }\n }", "function archivoSIS(nombreAD, cuerpo){\n var path = \"../archivo/\";\n var fileContent = cuerpo;\n var name = nombreAD;\n path1 = path + name;\n /*fs.stat( path + name , function(error, stats){\n console.log('verificando existe:' + stats.isFile());\n });*/\n fs.writeFile( path+name, fileContent,(err) =>{\n if(err)throw err;\n console.log(\"el file ha sido creado y llenando los datos\");\n })\n }", "function testResouceNotFound(){\n var content = \"test\";\n var options = {\n path: '/check/blablablabla',\n method: 'GET',\n headers: {\n 'Content-Length': content.length\n }\n };\n testResponse(options,content, function(res) {\n console.log('not found test callback');\n console.log(res.statusCode);\n assert(res.statusCode == 404);\n console.log(\"Resource not found - test succeeded\");\n });\n}", "function d(){\n var filename = \"file.mei\";\n downloadFile(filename, output);\n}", "async web (relativePath, systemPath, stripSlashes) {\n const indexNames = []\n const file = new File(join(systemPath, 'index.html'))\n try {\n await file.stat()\n } catch (err) {}\n const hasIndex = file.mode && file.isFile()\n if (hasIndex) {\n indexNames.push('index.html')\n }\n return handler(relativePath, systemPath, stripSlashes, false, !hasIndex, indexNames)\n }", "function handleNotFoundRequest(param) {\r\n const code = 404;\r\n const response = new Problem_1.Problem(code, \"/probs/resource-not-found\", \"Resource not found\", `Resource with id ${param} could not be found`);\r\n Logger_1.logger.info(JSON.stringify(response));\r\n return response;\r\n }", "async function addFile(){\n\t\trouter.push(`/files/${filetype}/create${filetype}/${fileFolderID}`)\n\t}", "function assetsHandler(url, response) {\n var extension = url.split(\".\")[1];\n var extensionType = {\n html: \"text/html\",\n css: \"text/css\",\n js: \"application/javascript\",\n ico: \"image/x-icon\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n json: \"application/json\"\n };\n var filePath = path.join(__dirname, \"..\", \"public\", url);\n fs.readFile(filePath, function(error, file) {\n if (error) {\n response.writeHead(500, { \"Content-Type\": \"text/html\" });\n response.end(\"<h1>sorry, something went wrong</h1>\");\n } else {\n response.writeHead(200, { \"Content-Type\": extensionType[extension] });\n response.end(file);\n }\n });\n}", "function funcionIntermedia(request, response, next){\n console.log('Ejecutado a las : ' +new Date());\n //netx ejecuta lo siguiente que hay en app.get('/concatenado.....')\n next(); //esta siempre es la ultima linea\n}", "function makeFile(name, ext, folder) {\r\n\tvar newFile = new File( folder + '/' + name + '.' + ext );\r\n\t\r\n\tif (newFile.open(\"w\")) {\r\n\t\tnewFile.close();\r\n\t}\r\n\telse {\r\n\t\tthrow new Error('Access is denied');\r\n\t}\r\n\treturn newFile;\r\n}", "function serveStaticFile(request, response, filename) {\n\n fs.stat(filename, function(error, stat) {\n\n if (error || !stat.isFile()) {\n console.error(error.stack);\n return;\n }\n \n // Prepare for streaming file to client\n var responseCode = 200;\n var responseHeaders = {\n 'Content-Type': mime.lookup(filename.indexOf(\".\") != -1 ? filename.substring(filename.lastIndexOf(\".\")+1) : filename),\n 'Content-Length': stat.size,\n 'Last-Modified': stat.mtime.toUTCString(),\n 'Expires': timeEpoch.toUTCString(),\n 'Cache-Control': 'no-cache'\n };\n var readOpts = {};\n \n // If the client requested a \"Range\", then prepare the headers\n // and set the read stream options to read the specified range.\n // Range is implemented for HTML5 <audio> and <video>. See note here:\n // http://stackoverflow.com/questions/1995589/html5-audio-safari-live-broadcast-vs-not\n if (request.headers['range']) {\n var range = request.headers['range'].substring(6).split('-');\n //console.log(range);\n readOpts.start = Number(range[0]);\n readOpts.end = Number(range[1]);\n if (range[1].length === 0) {\n readOpts.end = stat.size - 1;\n } else if (range[0].length === 0) {\n readOpts.end = stat.size - 1;\n readOpts.start = readOpts.end - range[1] + 1;\n }\n var contentLength = readOpts.end - readOpts.start + 1;\n responseCode = 206;\n responseHeaders['Accept-Ranges'] = \"bytes\";\n responseHeaders['Content-Length'] = contentLength;\n responseHeaders['Content-Range'] = \"bytes \" + readOpts.start + \"-\" + readOpts.end + \"/\" + stat.size;\n }\n \n // Stream the file\n response.writeHead(responseCode, responseHeaders);\n var file_stream = fs.createReadStream(filename, readOpts);\n // Detect if the connection is prematurely closed, and manually close the\n // file descriptor when it is. We have it be a named function because we\n // have to unbind it in the \"pump\" callback.\n function onClose() {\n file_stream.destroy();\n }\n request.connection.on(\"close\", onClose);\n // Listen for \"error\" events on the read stream, in case anything goes\n // wrong (though this is not likely).\n file_stream.addListener('error', function(error) {\n console.error(error, error.stack);\n response.end();\n });\n pump(file_stream, response, function() {\n request.connection.removeListener(\"close\", onClose);\n response.end();\n });\n });\n \n}", "downloadFile (existingFileId) {\n const options = this.configureGetOptions()\n if (!existingFileId) throw new Error('Invalid file id')\n return fetch(`${this.url}/files/${existingFileId}?alt=media`, options).then(\n this.parseAndHandleErrors\n )\n }", "function get_full_file(month) {\n\n //\n // Get the fullpath and append \".txt\"\n //\n return path.resolve(__dirname, '../tmp/' + month + '-wet.paths.gz.txt');\n\n}", "static findFiles (dir) {\n return Walk.dir(dir)\n .catch({code: 'ENOENT'}, error => {\n error.message = `No such file or directory \"${error.path}\"`\n error.simple = `Failed to read templates for \"${this.base_name}\"`\n throw error\n })\n }", "function respondStreamFile(res, filepath) {\n fs.access(filepath, fs.constants.F_OK, function (error) {\n if (!error) {\n var fileStream_1 = fs.createReadStream(filepath);\n fileStream_1.on('open', function () {\n fileStream_1.pipe(res);\n });\n fileStream_1.on('error', function (error) {\n res.writeHead(404);\n res.end(JSON.stringify(error));\n });\n }\n else {\n res.writeHead(404);\n res.end(JSON.stringify(error));\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait till dropdown exist and change data (torrent list)
function updateDropDown(){ const ul = $('ul.dropdown-menu') ul.arrive("div.active",{onceOnly: true},() => { let ids = $('div.active'); for ( let elements of ids){ data = { hash : elements.id, id : $(elements).attr("data"), status : "start" }; worker.postMessage(data); }; $("span.control").on('click',function(){ change(this); }); }) }
[ "function initDropdown(){\n $.ajax({\n url: '/playlists',\n type: 'GET',\n contentType: 'application/json',\n success: function(res) {\n var pDrop = ``;\n for(var i=0; i<res.length; i++){\n pl = res[i]\n var addD = `<option id=${pl._id}>${pl.name}</option>`\n pDrop = pDrop.concat(addD);\n }\n $('select#selectPlaylist').html(pDrop);\n }\n }); //close ajax brack\n \n }", "function bindeaRecuperadosServidorNEOption(a) { \n $('#sel-id_servidor-ne').change(function (event) {\n id = $(this).val();\n html = $(this).children(\":selected\").html();\n tabla = 'servidor'\n event.preventDefault();\n bindeaRecuperadosServidor(a);\n\n });\n }", "function loadAllDropDownListAtStart(){\n\t\t//load vào ddl customer\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/customer/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n \n //load bên edit\n $('#editFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl fabric supplier\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/fabricSupplier/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n \n //bên edit\n $('#editFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl chori agent\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/agent/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl factory\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/factory/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl width\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/width/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.width == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n \n $('#editFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show! 194');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl currency\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/currency/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n \n $('#editFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl Color\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/color/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDetailDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#editFabricInformationDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#addFabricInformationDetailEditVerDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t}", "function fillTeacherSelector() {\n var $dropdown = $(\"#teacher-select\");\n $($dropdown).empty();\n\n $.ajax({\n method: \"POST\",\n url: \"http://localhost:1340/graphql\",\n contentType: \"application/json\",\n data: JSON.stringify({\n query: teacherQuery\n })\n }).done(function(result) {\n // fill the teachers dropdown\n $.each(result.data.teachers, function() {\n // console.log(this);\n $dropdown.prepend($(\"<option />\").val(this.RefId).text(this.PersonInfo.Name.GivenName +\n \" \" + this.PersonInfo.Name.FamilyName));\n });\n // have to re-initialise component to render\n $($dropdown).formSelect();\n });\n}", "function f_GUI_Update_Select(frame, he_select){\n\t// Check that the 'he_select' is found and correct\n\tif (he_select != null)\n\t{\n\t\t// Update GUI elements concerned \n\t\the_select.html(''); // Clear the content of the select\n\t\t\n\t\t// Determine what to inspect in frame\n\t\tvar whatToInspect;\n\t\tswitch(frame.AppID){\n\t\t\tcase APP_ID.LIST:\n\t\t\t\twhatToInspect = frame.RADOME_Cmds;\n\t\t\t\tbreak;\n\t\t\tcase APP_ID.AUDIO:\n\t\t\t\twhatToInspect = frame.RADOME_AudioFiles;\n\t\t\t\tbreak;\t\t\t\t\n\t\t\tdefault :\n\t\t\t\twhatToInspect = frame.RADOME_Cmds;\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\t// Iterate over the data and append a select option\n\t\t$.each(whatToInspect, function(key, val){\n\t\t\t// Append option element to the select\n\t\t\the_select.append('<option value=\"' + val.id + '\">' + val.name + '</option>');\n\t\t\tif (frame.AppID == APP_ID.AUDIO)\n\t\t\t{\n\t\t\t\t// Update structure array concerned\n\t\t\t\tgRADOME_Conf.AudioTitle.push(val.name);\n\t\t\t\tgRADOME_Conf.AudioPath.push(gScope.RADOMEAudioPath + val.name);\n\t\t\t\tgRADOME_Conf.AudioDescription.push(\"Description de \"+val.name);\n\t\t\t}\n\t\t})\t\n\n\t\t// Refresh element\n\t\the_select.selectpicker('refresh');\n\t}\n\telse\n\t{\n\t\tf_RADOME_log(\"error in 'f_GUI_Update_Select' function : he_select is undefined\");\n\t}\n}", "function admin_post_edit_load_univ() {\n get_univ(faculty_selector_vars.countryCode, function (response) {\n\n var stored_univ = faculty_selector_vars.univCode;\n var obj = JSON.parse(response);\n var len = obj.length;\n var $univValues = '';\n\n $(\"select[name*='univCode']\").fadeIn();\n for (i = 0; i < len; i++) {\n var myuniv = obj[i];\n var current_univ = myuniv.country_code + '-' + myuniv.univ_code;\n if (current_univ == stored_univ) {\n var selected = ' selected=\"selected\"';\n } else {\n var selected = false;\n }\n $univValues += '<option value=\"' + myuniv.country_code + '-' + myuniv.univ_code + '\"' + selected + '>' + myuniv.univ_name + '</option>';\n\n }\n $(\"select[name*='univCode']\").append($univValues);\n\n });\n }", "function refresh()\n {\n var new_path = new Folder (ims_base_path.fullName + \"\\\\\" + dd_league.selection.toString() + \"\\\\\");\n dd_team.removeAll();\n populateDropdown(dd_team, new_path);\n }", "function makeDropDownList(){\n fetchInfluencers.then(response => {\n response.json().then(data => {\n var dropdownlist = document.getElementById(\"dropdownlist\");\n for (i = 0; i <= data.data.length; i++) {\n var option = document.createElement(\"option\");\n option.setAttribute(\"label\",data.data[i])\n option.setAttribute(\"value\",data.data[i])\n dropdownlist.add(option);\n }\n })\n })\n}", "function FindMyOne(url,destino)\n {\n $.ajax({\n type: 'POST',\n dataType: 'json',\n url: url,\n success: function (data) {\n for (var f=0;f<data.length;f++) {\n $('#'+destino).append('' +\n '<option value='+data[f].id+' selected>'+data[f].nombre+'<option>')\n $('#'+destino).trigger(\"chosen:updated\");\n }\n\n },\n error: function (req, stat, err) {\n fillcampo(req.responseText);\n }\n\n });\n }", "function refreshEditRecordingTestDropdown() {\r\n //get the tests data from the database so we can have recordings linked to tests\r\n StorageUtils.getAllObjectsInDatabaseTable('recordings.js', 'tests')\r\n //once we have the array then we can start populating the new recording form tests dropdoqn by looping through the array\r\n .then((testStorageArray) => {\r\n //filter tests for default project by fetching from local storage\r\n const defaultProjectId = Number(localStorage.getItem('DefaultProject'));\r\n //if we have any number greater than zero, which indicates no default, then filter\r\n defaultProjectId > 0\r\n ? (testStorageArray = testStorageArray.filter((test) => test.testProjectId == defaultProjectId))\r\n : null;\r\n\r\n //get a reference to the drop down in thee edit recording form\r\n var editRecordingDropDownMenu = $('.ui.fluid.selection.editRecording.test.dropdown .menu');\r\n //empty the dropdown of existing items\r\n editRecordingDropDownMenu.empty();\r\n //use for-of loop as execution order is maintained to insert all the tests, with references, in the dropdown\r\n for (let test of testStorageArray) {\r\n //we are not going to use templates here as we are not dealing with complex html structures\r\n editRecordingDropDownMenu.append(`<div class=\"item\" data-value=${test.id}>${test.testName}</div>`);\r\n }\r\n //then after the entire loop has been executed we need to initialise the dropdown with the updated items\r\n $('.ui.fluid.selection.editRecording.test.dropdown').dropdown({\r\n direction: 'upward',\r\n });\r\n });\r\n}", "clickOwnersDropdownButton(){\n this.ownersDropdownButton.waitForExist();\n this.ownersDropdownButton.click();\n }", "function admin_post_edit_load_faculty() {\n // $(\"select[name*='facultyName']\").hide();\n get_faculty(faculty_selector_vars.univCode, function (response) {\n\n var stored_faculty = faculty_selector_vars.facultyName;\n var obj = JSON.parse(response);\n var len = obj.length;\n var $facultyValues = '';\n\n $(\"select[name*='facultyName']\").fadeIn();\n for (i = 0; i < len; i++) {\n var myfaculty = obj[i];\n if (myfaculty.faculty_name == stored_faculty) {\n var selected = ' selected=\"selected\"';\n } else {\n var selected = false;\n }\n $facultyValues += '<option value=\"' + myfaculty.faculty_name + '\"' + selected + '>' + myfaculty.faculty_name + '</option>';\n }\n $(\"select[name*='facultyName']\").append($facultyValues);\n\n });\n }", "function load_drives_dropdown(){\n\tif ( $(\".assembly_constituency_dropdown\").val() != '' )\n\t{\n\t\tif (typeof(loadMyDrives) === 'function') {\n\t\tloadMyDrives()\n\t\t}\n\t}\n\t}", "function showSelectManufacturer() {\n var msg = callAPI(uRLBase + \"Manufacturer\", \"GET\");\n $('#commodity-owner').html('<option value=\"\"> --- Chọn nhà sản xuất ---</option>');\n\n if(msg)\n {\n $.each(msg, function(key, value){\n var newRow = '<option value=\"' + value['$class'] + '#' +value['tradeId'] + '\">' + value['companyName'] + '</option>';\n $('#commodity-owner').append(newRow);\n });\n }\n}", "function getDistinctTransmission() {\n $.ajax({\n url: 'api/',\n method: 'GET',\n data: {distinctTransmission: '1'},\n success: function(data) {\n // Fill the 'transmission' dropdown with results.\n $.each(data, function(index, value) {\n $('#selectTransmission').append(\"<option value=\\\"\"+value.transmission+\"\\\">\"+value.transmission+\"</option>\");\n });\n },\n error: function (xhr, ajaxOptions, thrownError) {\n // Log any error messages.\n console.log(xhr.status);\n console.log(thrownError);\n }\n });\n}", "function initierDropDown(tbl, selId) {\r\n // Fyll inn dropdown\r\n db.transaction(function(tx) {\r\n initierListe(tx, tbl, selId, oppdaterSelect);\r\n }, DbErrorHandler);\r\n}", "_startChoose(e) {\n let target = e.target;\n if (target.nodeName !== 'BUTTON') {\n target = target.parentElement;\n }\n this._chosenServer = target.dataset.server;\n let choices = this._state.packages[target.dataset.app];\n let chosen = choices.findIndex(choice => choice.Name === target.dataset.name);\n this._push_selection.choices = choices;\n this._push_selection.chosen = chosen;\n this._push_selection.show();\n }", "function updateLevelDropdown() {\n if (beginnerFlag === true && intermediateFlag === true && advancedFlag === true) {\n levelDropdown.selectpicker('val', 'allLevels');\n } else if (beginnerFlag === true) {\n levelDropdown.selectpicker('val', 'beginner');\n } else if (intermediateFlag === true) {\n levelDropdown.selectpicker('val', 'intermediate');\n } else if (advancedFlag === true) {\n levelDropdown.selectpicker('val', 'advanced');\n }\n noSeminarsParagraph();\n }", "function updateDrummerDropDowns() {\r\n\t//Create a new HTTP request\r\n\tvar req = new XMLHttpRequest(); \r\n\r\n\t//Construct a URL that will send a Select request for the desired table\r\n\tvar url = \"http://flip2.engr.oregonstate.edu:\" + port + \"/select-drummer\";\r\n\t\r\n\t//Make the call\r\n\treq.open(\"GET\", url, false); \r\n\treq.addEventListener('load',function(){\r\n\t\t//If the request status is valid, update the table\r\n\t\tif(req.status >= 200 && req.status < 400){\r\n\t\t\t//Parse the JSON response\r\n\t\t\tvar response = JSON.parse(req.responseText); \r\n\t\t\t\r\n\t\t\t/* DELETE OLD DROP CONTENTS OF EACH DROP DOWN MENU */\r\n\t\t\t\r\n\t\t\t//Delete contents from drop down 1\r\n\t\t\tif (document.getElementById(\"plays_drummer_id\").length > 0) {\r\n\t\t\t\t//Delete the options in reverse order to avoid missing options\r\n\t\t\t\tfor (i = (document.getElementById(\"plays_drummer_id\").length - 1); i >= 0; i--) {\r\n\t\t\t\t\tdocument.getElementById(\"plays_drummer_id\").remove(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Delete contents from drop down 2\r\n\t\t\tif (document.getElementById(\"update_drummer_id\").length > 0) {\r\n\t\t\t\t//Delete the options in reverse order to avoid missing options\r\n\t\t\t\tfor (i = (document.getElementById(\"update_drummer_id\").length - 1); i >= 0; i--) {\r\n\t\t\t\t\tdocument.getElementById(\"update_drummer_id\").remove(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Delete contents from drop down 3\r\n\t\t\tif (document.getElementById(\"search_drummer_kit\").length > 0) {\r\n\t\t\t\t//Delete the options in reverse order to avoid missing options\r\n\t\t\t\tfor (i = (document.getElementById(\"search_drummer_kit\").length - 1); i >= 0; i--) {\r\n\t\t\t\t\tdocument.getElementById(\"search_drummer_kit\").remove(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Delete contents from drop down 4\r\n\t\t\tif (document.getElementById(\"search_brand_drummer\").length > 0) {\r\n\t\t\t\t//Delete the options in reverse order to avoid missing options\r\n\t\t\t\tfor (i = (document.getElementById(\"search_brand_drummer\").length - 1); i >= 0; i--) {\r\n\t\t\t\t\tdocument.getElementById(\"search_brand_drummer\").remove(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Delete contents from drop down 5\r\n\t\t\tif (document.getElementById(\"search_stick_drummer\").length > 0) {\r\n\t\t\t\t//Delete the options in reverse order to avoid missing options\r\n\t\t\t\tfor (i = (document.getElementById(\"search_stick_drummer\").length - 1); i >= 0; i--) {\r\n\t\t\t\t\tdocument.getElementById(\"search_stick_drummer\").remove(i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* ADD UPDATED DROP DOWN CONTENTS \r\n\t\t\tnote: Javascript would not allow me to add the same option to 5 different menus, which is\r\n\t\t\twhy they are all separated. */\r\n\t\t\r\n\t\t\tfor (i = 0; i < response.length; i++) {\t\r\n\t\t\t\t//Add updated options to drop down menu 1\r\n\t\t\t\tvar option = document.createElement(\"option\");\r\n\t\t\t\toption.text = response[i].name;\r\n\t\t\t\toption.value = response[i].drummer_id;\r\n\t\t\t\tdocument.getElementById(\"plays_drummer_id\").add(option);\r\n\t\t\t\t\r\n\t\t\t\t//Add updated options to drop down menu 2\r\n\t\t\t\tvar option2 = document.createElement(\"option\");\r\n\t\t\t\toption2.text = response[i].name;\r\n\t\t\t\toption2.value = response[i].drummer_id;\r\n\t\t\t\tdocument.getElementById(\"update_drummer_id\").add(option2);\r\n\t\t\t\t\r\n\t\t\t\t//Add updated options to drop down menu 3\r\n\t\t\t\tvar option3 = document.createElement(\"option\");\r\n\t\t\t\toption3.text = response[i].name;\r\n\t\t\t\toption3.value = response[i].name;\r\n\t\t\t\tdocument.getElementById(\"search_drummer_kit\").add(option3);\r\n\t\t\t\t\r\n\t\t\t\t//Add updated options to drop down menu 4\r\n\t\t\t\tvar option4 = document.createElement(\"option\");\r\n\t\t\t\toption4.text = response[i].name;\r\n\t\t\t\toption4.value = response[i].name;\r\n\t\t\t\tdocument.getElementById(\"search_brand_drummer\").add(option4);\r\n\t\t\t\t\r\n\t\t\t\t//Add updated options to drop down menu 5\r\n\t\t\t\tvar option5 = document.createElement(\"option\");\r\n\t\t\t\toption5.text = response[i].name;\r\n\t\t\t\toption5.value = response[i].name;\r\n\t\t\t\tdocument.getElementById(\"search_stick_drummer\").add(option5);\r\n\t\t\t}\r\n\t\t} \r\n\t\t//If the request status isn't valid, display an error message with the request status\r\n\t\telse {\r\n\t\t\tconsole.log(\"Error in network request: \" + req.statusText);\r\n\t\t}\r\n\t});\t\r\n\treq.send(null); //no need to send additional data\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add Key Down Event On Delete Remove Selected Object from canvas
function OnkeyDown(event){ var activeObject = PhotoCollage.getActiveObject(); if (event.keyCode === 46) { PhotoCollage.remove(activeObject); } }
[ "function ondelete() {\n var index = getToggledIndex();\n if (index >= 0) {\n children[index].ontoggle();\n children.splice(index,1);\n ctx.onmodify();\n recalcHeight(); // this will redraw the screen\n }\n }", "delete() {\n this.deltaX = 0;\n this.deltaY = +5;\n // if bubble currently on the board, remove it\n if (this.row !== undefined && this.col !== undefined) {\n let row = this.board.pieces[this.row];\n let col = this.col;\n row[col] = null;\n }\n this.falling = true;\n this.collided = false;\n this.canvas.objects.push(this);\n }", "function onKeyUp() {\n d3.event.stopPropagation();\n if (d3.event.target.nodeName == 'BODY') {\n // Do not handle \"Backspace\" key event here as it clashes with editing actions in the spec editor.\n // Handle \"Delete\" key event only.\n if (d3.event.key === \"Delete\") {\n let selected = _svg.selectAll('.entity.selected');\n let nItemsSelected = selected._groups[0].length;\n if (nItemsSelected > 0) {\n let event = new CustomEvent(\"delete-entity\", {\n detail: {\n entity: selected.data()[0].data || selected.data()[0],\n }\n });\n container.dispatchEvent(event);\n }\n }\n }\n }", "onDeselectEvent(){ }", "function inputElem_delete_byKey(e) {\n\tvar elem = $(this);\n\t\n}", "function eliminakey(obj) {\r\n \tif(window.event.keyCode == 46){\r\n\t \tfor(i=0;i<obj.length;i++)\r\n\t\t{\t\r\n\t\t\tif(obj.options[i].selected)\r\n\t\t\t {\r\n\t\t\t\tobj.options[i] = null;\r\n\t\t\t\tobj.length-1;\r\n\t\t\t\ti--;\r\n\t\t\t }\t\r\n\t\t}\r\n\t}\r\n }", "function nickSelected(){\n window.removeEventListener(\"keydown\", handleKeys);\n document.getElementById(\"play\").addEventListener(\"click\", playClick);\n}", "function keyPressed() {\n if (keyCode === DELETE) {\n background(0);\n }\n\n// If the return key is pressed this will give the user an option to save\n// their canvas\n if (keyCode === RETURN) {\n save();\n save('myCanvas.jpg');\n }\n }", "function deleteTextField() {\r\n srcList.removeChild(this.parentElement)\r\n toggleSubmit()\r\n }", "function render_deselect(context)\n{\n\tif(selection_coordinates != null)\n\t{\n\t\tstroke_tile(selection_coordinates.x, selection_coordinates.y, grid_color, context);\n\t}\n\trender_pivot(context);\n}", "function deleteLine() {\n gMeme.lines.splice(gMeme.selectedLineIdx, 1)\n if (gMeme.selectedLineIdx >= gMeme.lines.length) {\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n }\n drawImgText(elImgText)\n}", "function startDelete(evt){\n if (evt.which === 46){\n //Delete was pressed down. Move all selected features to the recycle bin\n var selectedFeats = selectInteraction.getFeatures();\n\n //We already got pwned by the delete-while-iterating bug in the past\n\n selectedFeats.forEach(function (elem) {\n //added reference to the feature to the recycle bin\n recycleBin.push(elem);\n mainSource.removeFeature(elem);\n });\n\n //make sure the select interaction itself does not keep references to the deleted features\n selectedFeats.clear();\n viewer.showInstructs();\n }\n }", "deselect() {\n if (this.selected != null) {\n this.selected.deselect();\n this.selected = null;\n }\n }", "__removeParticleEventListener(){\n Utils.changeCursor(this.myScene.canvasNode, \"pointer\");\n this.myScene.canvasNode.addEventListener(\"mousedown\", this.__removeParticleDisposableEvent);\n }", "removeHitObject() {\n const pos = this.findObj(this.lastUpdated);\n if (pos >= 0) {\n const sprite = this.hitObjectSpriteList.filter(item => item.id === 'CIRCLE_' + this.lastUpdated);\n if (sprite.length > 0) {\n this.hitObjectStage.removeChild(sprite[0]);\n sprite[0].destroy();\n }\n this.hitObjects.splice(pos, 1);\n this.hitObjectSpriteList.splice(pos, 1);\n }\n }", "deleteDots() {\n let room_buffer = this._room_canvas;\n let canvas_objects = room_buffer.getObjects();\n canvas_objects.forEach(function (item, i) {\n if (item.type == 'debug') {\n room_buffer.remove(item);\n }\n });\n room_buffer.renderAll();\n }", "function erase(e) {\n database.database_call(`DELETE FROM subnote WHERE id=${id} `);\n alerted.note(\"The current note was deleted!\", 1);\n Alloy.Globals.RenderSubNotesAgain();\n $.view_subnotes.close();\n}", "deleteObject(_fabobject) {\n let room_buffer = this._room_canvas;\n //console.log(\"hallo\");\n getReferenceById(_fabobject.AGObjectID).kill();\n\n //check if removed element was linked to portal or has path points and remove that stuff\n //TODO wait for portal remove function in AGPortal\n\n if (_fabobject.type == 'enemy') {\n _fabobject.PathArray.forEach(function (ele) {\n room_buffer.remove(ele);\n });\n _fabobject.LineArray.forEach(function (ele) {\n room_buffer.remove(ele);\n });\n }\n\n if (_fabobject.type == 'portal') {\n //_fabobject.secDoor\n let fab_buffer = this.getFabricObject(_fabobject.secDoor);\n if (fab_buffer) {\n fab_buffer.secDoor = false;\n fab_buffer.set(\"fill\", this._colors[4][this._vision_mode]);\n }\n if (_fabobject.line) {\n this._room_canvas.remove(this.getFabricObject(_fabobject.secDoor).line.dot);\n this._room_canvas.remove(this.getFabricObject(_fabobject.secDoor).line);\n this.getFabricObject(_fabobject.secDoor).line = false;\n this._room_canvas.remove(_fabobject.line.dot);\n this._room_canvas.remove(_fabobject.line);\n _fabobject.line.line = false;\n }\n }\n this._room_canvas.remove(_fabobject);\n this._room_canvas.renderAll();\n this.listEvents();\n this.listConditions();\n this.listItems();\n this.listGlobalEvents();\n }", "onRemoveMealButtonPressed(event) {\n\t\tevent.currentTarget.parentNode.parentNode.removeChild(event.currentTarget.parentNode);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Images Looking for popImage class on outer wrapper
function popImage() { var imgCount = 0; var popImages = {}; popImages.imgSet = {}; popImages.viewer = ''; popImages.functions = { init: function(el) { popImages.viewer = el.data('popviewer'); popImages.imgSet.imgId = el.data('poptargets'); $('.popImage' + ' ' + el.data('poptargets')).each(function() { imgCount += 1; $(this).addClass('imageInWaiting'); var currentId = ''; var imgId = 'popImage' + imgCount; if (typeof $(this).attr('id') !== 'undefined') { currentId = $(this).attr('id'); } if (currentId !== '') { $(this).attr('id', currentId + ' ' + imgId); } }); $(popImages.viewer).addClass('popImageViewer'); $(popImages.viewer).append('<a href="" id="viewerLink"><img src="" id="viewerImage"/></a>'); }, populateViewer: function(cid) { var imgSrc = cid.attr('src'); var imgPid = cid.data('pid'); $('#viewerImage').attr('src', imgSrc); $('#viewerImage').data('pid', imgPid); } }; $('.popImage').each(function() { var toPop = $(this); popImages.functions.init(toPop); }); $(popImages.imgSet.imgId).click(function() { var clicked = $(this); popImages.functions.populateViewer(clicked); }); }
[ "function PopupInfoImages() {\n this.mainBlock = document.body;\n this.images = this.mainBlock.querySelectorAll('.js-img-wrap img');\n this.typeImages = ['png', 'jpg', 'gif'];\n this.typeVideos = ['mp4', 'webm'];\n\n // Add hover for all image with attr data-src\n for(let i = 0; i < this.images.length; i++) {\n if(this.images[i].dataset.src) {\n this.images[i].classList.add('info__block-img-pointer');\n }\n }\n\n function getMediaType(fileName) {\n var r = 'image';\n var ext = fileName.slice(fileName.lastIndexOf('.')+1);\n if ( ext === 'mp4' || ext === 'webm') r = 'video';\n return r;\n };\n\n // ch, hw - container's size, ih, iw - image size\n function getMediaHeight(ch, cw, ih, iw) {\n if ( (cw / ch) > (iw / ih)) {\n return ch; }\n else {\n let scale = cw / iw;\n return ih * scale;\n };\n };\n\n // Create popup with content\n this._createPopup = (src, href, title, descr, alt) => {\n var prevSlideIndex=0;\n if(src) {\n const sliderArray = src.split('::');\n const sliderAlt = alt.split('::');\n const sliderHrefs = href.split('::');\n const popup = document.createElement('div');\n popup.classList.add('popup');\n const typeFile = src.slice(src.lastIndexOf('.') + 1);\n const sliderTitles = title.split('::');\n const sliderDescrs = descr.split('::');\n const listWrap = document.createElement('div');\n const sliderList = document.createElement('ul');\n const prevBtn = document.createElement('button');\n const nextBtn = document.createElement('button');\n const closeBtn = document.createElement('button');\n const linkBtn = document.createElement('a');\n const visibilityBtn = document.createElement('button');\n const btnWrap = document.createElement('div');\n var sliderImage;\n var sliderElementsArray = [];\n\n prevBtn.classList.add('js-prev');\n nextBtn.classList.add('js-next');\n closeBtn.classList.add('js-close');\n btnWrap.classList.add('js-btn-wrap');\n linkBtn.classList.add('js-link');\n linkBtn.setAttribute('target', '_blank');\n linkBtn.setAttribute('href', sliderHrefs[0]);\n if(!sliderHrefs[0]) {\n linkBtn.classList.add('js-link--hide');\n }\n visibilityBtn.classList.add('js-visibility');\n prevBtn.innerHTML = '<i class=\"material-icons\">navigate_before</i>';\n nextBtn.innerHTML = '<i class=\"material-icons\">navigate_next</i>';\n visibilityBtn.innerHTML = '<i class=\"material-icons\">visibility</i>';\n linkBtn.innerHTML = '?';\n closeBtn.innerHTML = '<i class=\"material-icons\">close</i>';\n\n function getVideoElementProcessor(i, divi, imgi) {\n return function (e) {\n divi.appendChild(imgi);\n sliderElementsArray[i].ih = e.target.videoHeight;\n sliderElementsArray[i].iw = e.target.videoWidth;\n // console.log('e', Date.now());\n showBtn();\n }\n }\n\n for(let i = 0; i < sliderArray.length; i++) {\n sliderElementsArray.push({li: {}, img: {}, ih: 0, iw: 0});\n const sliderItem = document.createElement('li');\n const sliderItemDiv = document.createElement('div');\n const sliderImageDiv = document.createElement('div');\n const sliderTitle = document.createElement('h3');\n const sliderDescr = document.createElement('p');\n sliderTitle.innerHTML = sliderTitles[i];\n sliderDescr.innerHTML = sliderDescrs[i];\n if (getMediaType(sliderArray[i]) === 'image') { // if image\n sliderImage = document.createElement('img');\n sliderImage.setAttribute('src', sliderArray[i]);\n sliderImage.naturalHeight2 = sliderImage.naturalHeight;\n sliderImage.naturalWidth2 = sliderImage.naturalWidth;\n sliderImage.onload = ((ii, sliderItemi, sliderItemDivi) => {\n return (e) => {\n sliderElementsArray[ii].ih = e.target.naturalHeight;\n sliderElementsArray[ii].iw = e.target.naturalWidth;\n sliderItemi.appendChild(sliderItemDivi);\n resizeImage(ii);\n }\n })(i, sliderImageDiv, sliderImage);\n\n } else { // if video\n sliderImage = document.createElement('video');\n sliderImage.setAttribute('src', sliderArray[i]);\n //sliderImage.setAttribute('autoplay', 'autoplay');\n sliderImage.loop = true;\n // console.log('b', Date.now());\n sliderImage.addEventListener('loadeddata', getVideoElementProcessor(i, sliderImageDiv, sliderImage));\n };\n // console.log('a', Date.now());\n //sliderElementsArray.push({li: sliderItem, img: sliderImage, ih: 0, iw: 0});\n sliderElementsArray[i].li = sliderItem;\n sliderElementsArray[i].img = sliderImage;\n /*\n if (getMediaType(sliderArray[i]) === 'image') {\n sliderElementsArray[i].ih = sliderImage.naturalHeight;\n sliderElementsArray[i].iw = sliderImage.naturalWidth;\n }\n*/\n sliderImage.setAttribute('alt', (sliderAlt[i] || 'image'));\n\n\n sliderTitles[i] && sliderItemDiv.appendChild(sliderTitle);\n sliderItemDiv.appendChild(sliderImageDiv);\n sliderImageDiv.style.justifyContent = \"center\";\n sliderImageDiv.style.display = \"flex\";\n sliderImageDiv.style[\"flex-direction\"] = \"row\";\n //sliderImageDiv.appendChild(sliderImage);\n sliderDescrs[i] && sliderItemDiv.appendChild(sliderDescr);\n sliderList.appendChild(sliderItem);\n sliderItem.appendChild(sliderItemDiv);\n\n }; // i < sliderArray.length;\n\n\n listWrap.appendChild(sliderList);\n listWrap.appendChild(prevBtn);\n listWrap.appendChild(btnWrap);\n btnWrap.appendChild(closeBtn);\n //btnWrap.appendChild(linkBtn);\n listWrap.appendChild(nextBtn);\n popup.appendChild(listWrap);\n this.mainBlock.appendChild(popup);\n\n (sliderList.querySelector('h3')\n || sliderList.querySelector('p'));\n //&& btnWrap.appendChild(visibilityBtn); //don't want visibility button displayed\n let countSlide = 0;\n\n function resizeImage(count) {\n\n let li = sliderElementsArray[count].li;\n let img = sliderElementsArray[count].img;\n\n let ch = window.innerHeight * 0.6;\n let cw = window.innerWidth * 0.9;\n /*\n let ih = img.naturalHeight2;\n let iw = img.naturalWidth2;\n */\n let ih = sliderElementsArray[count].ih;\n let iw = sliderElementsArray[count].iw;\n // console.log('img', img);\n // console.log(ih, iw);\n let h = getMediaHeight(ch, cw, ih, iw);\n img.style.height = '' + h + 'px';\n img.style.width= '' + iw * h / ih + 'px';\n\n // console.log(img.naturalHeight2);\n };\n\n\n\n function resize2() {\n resizeImage(countSlide);\n }\n\n //window.addEventListener('resize', resize2);\n\n\n\n\n // operation with slider\n function showBtn() {\n if(countSlide === 0) {\n prevBtn.style.display = 'none';\n }\n else {\n prevBtn.style.display = 'block';\n }\n\n if(countSlide === sliderArray.length - 1) {\n nextBtn.style.display = 'none';\n }\n else {\n nextBtn.style.display = 'block';\n }\n\n const widthSlide = listWrap.getBoundingClientRect().width;\n sliderList.style.transform = `translateX(-${countSlide * widthSlide}px)`;\n const prevSliderElement = sliderList.children[prevSlideIndex];\n const currSliderElement = sliderList.children[countSlide];\n var prevMediaElement = prevSliderElement.querySelector('video');\n var currMediaElement = currSliderElement.querySelector('video');\n if (prevMediaElement) prevMediaElement.pause();\n if (currMediaElement) currMediaElement.play();\n resize2();\n }\n\n function showLink(href) {\n linkBtn.setAttribute('href', href);\n if(href) {\n linkBtn.classList.remove('js-link--hide');\n } else {\n linkBtn.classList.add('js-link--hide');\n }\n };\n\n showBtn();\n //setTimeout(showBtn, 3000);\n\n nextBtn.addEventListener('click', () => {\n prevSlideIndex = countSlide;\n if(countSlide < sliderArray.length - 1) {\n countSlide++;\n showBtn();\n showLink(sliderHrefs[countSlide]);\n }\n });\n\n\n prevBtn.addEventListener('click', () => {\n prevSlideIndex = countSlide;\n if(countSlide > 0) {\n countSlide--;\n showBtn();\n showLink(sliderHrefs[countSlide]);\n }\n });\n\n window.onkeydown = function(e) {\n if(e.keyCode === 39 && popup) {\n if(countSlide < sliderArray.length - 1) {\n countSlide++;\n showBtn();\n showLink(sliderHrefs[countSlide]);\n }\n }\n if(e.keyCode === 37 && popup) {\n if(countSlide > 0) {\n countSlide--;\n showBtn();\n showLink(sliderHrefs[countSlide]);\n }\n }\n };\n\n closeBtn.addEventListener('click', () => {\n popup.parentNode.removeChild(popup);\n });\n\n popup.addEventListener('click', e => {\n if(e.target === e.currentTarget) {\n popup.parentNode.removeChild(popup);\n }\n });\n\n document.onkeydown = function(e) {\n if(e.keyCode === 27 && popup) {\n popup.parentNode.removeChild(popup);\n }\n }\n\n window.addEventListener('resize', () => {\n showBtn();\n });\n\n let visibilityInd = true;\n\n // Hidden/Show title and description\n visibilityBtn.addEventListener('click', () => {\n if(visibilityInd) {\n visibilityBtn.children[0].innerHTML = 'visibility_off';\n const h3 = popup.querySelectorAll('h3');\n const p = popup.querySelectorAll('p');\n\n for(const par of p) {\n par.classList.add('hidden');\n }\n\n for(const title of h3) {\n title.classList.add('hidden');\n }\n }\n else {\n visibilityBtn.children[0].innerHTML = 'visibility';\n const h3 = popup.querySelectorAll('h3');\n const p = popup.querySelectorAll('p');\n\n for(const par of p) {\n par.classList.remove('hidden');\n }\n\n for(const title of h3) {\n title.classList.remove('hidden');\n }\n }\n visibilityInd = !visibilityInd;\n })\n\n\n setTimeout( () => {\n popup.style.opacity = 1;\n });\n\n resizeImage(countSlide);\n \n } // if (src)\n } // this.createPopup\n if(document.querySelector('.show-slides')) {\n $(\".show-slides\").click(e => {\n const img = $(e.currentTarget).find(\"img\").get(0);\n\n const src = $(img).attr(\"data-src\").slice(0, -2);\n const href = $(img).attr(\"data-href\").slice(0, -2);\n const title= $(img).attr(\"data-title\").slice(0, -2);\n const descr = $(img).attr(\"data-descr\").slice(0, -2);\n const alt = $(img).attr(\"data-alt\").slice(0, -2);\n\n this._createPopup(src, href, title, descr, alt);\n })\n }\n\n}", "function heri_popupCover(elm) {\n var newPic = heri_coverSize($(elm).attr('src'), 'l');\n $('div.popup-covers img.popup-cover').attr('src', newPic);\n $.facebox({div: '#comic-gn-popup'});\n}", "function clickPictures(){\r\n\tvar clickedElement = event.target;\r\n\r\n\tif (clickedElement.tagName === \"IMG\") {\r\n\tmagnifiedImage.src = clickedElement.src; //puts the clicked image into the image source\r\n\t}\t\r\n}", "function imagePopup(popId){\n\tvar img = document.getElementById(\"imageDiv\");\n\tvar imgTop = getY(img)+10;\n\tvar popup = document.getElementById(popId);\n\tpopup.style.top = imgTop+\"px\";\n\tpopup.style.visibility = \"visible\";\n}", "function imageClicked() {\n var currentSource = $(this).attr('src');\n var altSource = $(this).attr('data-src');\n $(this).attr('src', altSource);\n $(this).attr('data-src', currentSource);\n }", "function htmlPopup(){\r\n var p01 = $('<div id=\"popup-image\"><div class=\"table\"><div class=\"table-cell\"><div id=\"inner-popup\"><a id=\"close-poup\" href=\"#\"><i class=\"fa fa-times\"></i></a><img id=\"img-popup\" src=\"\" /></div></div></div></div>');\r\n $(p01).appendTo('#wrapper').hide().fadeIn(650);\r\n }", "function getCurrentImages () {\n\t\treturn Array.from(document.getElementsByClassName('img')).map(function(target){\n\t\t\treturn getImgExtension(target);\n\t\t});\n\t}", "function setupIconLibrarySelectionListener() {\n $('li[class^=ion]').click(function(e) {\n var originalElement = e.target;\n var imageName = originalElement.classList[0].slice(4);\n $('#IconLibraryModal').modal('hide');\n generateFlatIconFromImage('/img/ionicons/512/' + imageName + '.png');\n });\n}", "function lgm_addPreviewHandler(searchPattern, imgList) {\n\n for(var i=0; i < imgList.length; i++) {\n// for(var i=0; i < imgList.size(); i++) {\n\n var imgObj = gmGetElI(imgList[i]);\n// var imgObj = $(imgList.get(i));\n// alert(typeof imgObj);\n var imgName = gmGetAtI(imgObj, \"src\");\n// var imgName = imgObj.attr(\"src\");\n var s = searchPattern.test(imgName);\n// alert(imgName + \" \" + s);\n if( s ) {\n\n var tagdivid = \"div\" + i;\n var tagimgid = \"img\" + i;\n // var divid = \"#div\" + i;\n// var imgid = \"#img\" + i;\n var refid = null;\n //alert(imgName + \" \" + tagdivid + \" \" + tagimgid);\n\n var replaceUrl = gmGetReplaceUrl(elemSearchUrl, elemReplUrlLarge, imgName);\n // var replaceUrl = getReplaceUrl(elemSearchUrl, elemReplUrlLarge, imgObj.attr(\"src\"));\n\n imgObj.addEventListener('mouseover',\n// imgObj.onmouseover =\n function(e) {\n refid = this;\n const localTag = tagdivid;\n const localImg = tagimgid;\n replaceUrl = gmGetReplaceUrl(elemSearchUrl, elemReplUrl, this.src);\n // replaceUrl = getReplaceUrl(elemSearchUrl, elemReplUrl, this.src);\n var newImage = new Image();\n newImage.src = replaceUrl;\n var hDiv;\n var hImg;\n\n if (gmIsInstanceOf(gmGetElI(localImg), Image)) {\n // if ($(\"body\").find(imgid).is(\"img\")) {\n hDiv = gmGetElI(localTag);\n // hDiv = $(divid);\n\n hImg = gmGetElI(localImg);\n // hImg = $(imgid);\n } else {\n hDiv = gmCreateObj(null, \"div\", localTag);\n gmSetAtI(hDiv, \"class\", \"hi-preview\");\n // hDiv = $(\"<div id=\\\"\" + tagdivid + \"\\\" class=\\\"hi-preview\\\"></div>\");\n\n hImg = gmCreateObj(null, \"div\", localImg);\n gmSetAtI(hImg, \"class\", \"hi-wait\");\n gmSetInput(hImg, \"0\");\n // hImg = $(\"<div id=\\\"\" + tagimgid + \"\\\" class=\\\"hi-wait\\\">0</div>\");\n\n gmSetCoI(hDiv, \"\");\n gmAddObj(hImg, hDiv);\n\n gmAddObj(hDiv, null);\n // $(\"body\").append(hDiv);\n // $(divid).empty().append(hImg);\n }\n gmSetAtI(hDiv, \"style\", \"cursor:wait\");\n // hDiv.css(\"cursor\", \"wait\");\n\n gmSetAtI(hImg, \"style\", \"cursor:wait\");\n // hImg.css(\"cursor\", \"wait\");\n\n loopIdx = 0;\n lgm_showPreview(this, hDiv, hImg, newImage, 0);\n// };\n }\n );\n imgObj.addEventListener('mouseout',\n function(e) {\n refid = this;\n const localTag = tagdivid;\n const localImg = tagimgid;\n\n var bRemove = true;\n var evTarget = e.target;\n\n var jDiv = null;\n\n if (evTarget == refid) {\n jDiv = gmGetElI(localTag);\n } else {\n bRemove = false;\n }\n alert(refid.src + \"< >\" + bRemove + \"< >\" + evTarget.src + \"< >\" + (jDiv == null));\n if (bRemove) {\n if (gmIsObject(jDiv)) {\n gmSetAtI(jDiv, \"style\", \"cursor:auto\");\n gmDelObj(jDiv);\n// gmSetAtI(gmGetBody(), \"style\", \"background-color:blue\");\n\n }\n }\n //gmSetAtI(refid, \"style\", \"cursor:auto\");\n\n }\n );\n if (elemWithDownLink == 1) {\n var dlLink = gmCreateObj(null, \"a\");\n gmSetAtI(dlLink, \"id\", \"dl\" + tagdivid);\n gmSetAtI(dlLink, \"class\", \"hi-dlink\");\n gmSetCoI(dlLink, \"Download\");\n // var dlLink = $(\"<a href=\\\"\\\" id=\\\"dl\" + tagdivid + \"\\\" class=\\\"hi-dlink\\\">Download</a>\");\n\n gmSetAtI(dlLink, \"target\", \"#blank\");\n gmSetAtI(dlLink, \"href\", replaceUrl);\n // dlLink.attr({\"target\":\"#blank\",\"href\":replaceUrl});\n\n gmSetAtI(dlLink, \"title\", \"download [\" + gmGetAtI(dlLink, \"href\") + \"]\");\n // dlLink.attr(\"title\",\"download [\"+dlLink.attr(\"href\") +\"]\");\n// alert(dlLink);\n gmAddObj(dlLink, imgObj.parentNode);\n // imgObj.parent().after(dlLink);\n }\n\n// lgm_addBodyListener();\n }\n }\n}", "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "displayImages() {\n observeDocument(node => this.displayOriginalImage(node));\n qa('iframe').forEach(iframe => iframe.querySelectorAll('a[href] img[src]').forEach(this.replaceImgSrc));\n }", "function getProfileImageContainer()\n{\n //----------------------------\n // Query it by class\n //----------------------------\n\n return $(\".channel-header-profile-image-container\");\n}", "function alignSuccessStoryImages()\n{\n $(\".vspSuccessImgCover\").addClass(\"imgLiquidFill imgLiquid\");\n $(\".imgLiquidFill\").imgLiquid();\n}", "function addPopupFunction(){\r\n\t //var aClick=document.getElementById('cafe');\r\n\t //access all the elements of class openCloseImage\r\n\t var arrOpenLinks = getElementsByClass('openCloseImage');\r\n\t //exit the function if the array cannot be initialised\r\n\t if(!arrOpenLinks){return;};\r\n\t //add the event handler to each element in the array\r\n\t for (var i = 0; i < arrOpenLinks.length; i++){\r\n\t\t addEvent(arrOpenLinks[i],'click', openClosePopUp);\r\n\t }\r\n }", "function facebox_reveal_image(href, images, klass) {\n if (images) var extra_setup = facebox_setup_gallery(href, images, klass)\n var image = new Image()\n image.onload = function() {\n facebox_reveal('<div class=\"image\"><img src=\"' + image.src + '\" /></div>', klass, extra_setup)\n // load the next image in the background\n if (images) {\n var position = $.inArray(href, images)\n var next = new Image()\n next.src = images[position+1] ? images[position+1] : images[0]\n }\n }\n image.src = href\n }", "getDefaultImage() {\n return this.icon_.get(this.getBaseSize());\n }", "function removePreviousImage() {\n $capturedImage.empty();\n $capturedImage.removeAttr('style');\n $fridge.removeClass('hide');\n}", "function findMousePositionAndResizeImages(){\n $('.activeImg').css(dataService.getImageCss());\n $('#measureEnlarge').mousemove(function(event){\n enlargeOrShrinkImages(event);\n });\n $('#measureShrink').mousemove(function(event){\n enlargeOrShrinkImages(event);\n });\n}", "imageLoaded(){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inlined / shortened version of `kindOf` from
function miniKindOf(val) { if (val === void 0) return 'undefined'; if (val === null) return 'null'; var type = typeof val; switch (type) { case 'boolean': case 'string': case 'number': case 'symbol': case 'function': { return type; } } if (Array.isArray(val)) return 'array'; if (isDate(val)) return 'date'; if (isError(val)) return 'error'; var constructorName = ctorName(val); switch (constructorName) { case 'Symbol': case 'Promise': case 'WeakMap': case 'WeakSet': case 'Map': case 'Set': return constructorName; } // other return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); }
[ "function isTextual(type, value) {\n return t.logicalExpression(\"||\", t.binaryExpression(\"===\", type, t.stringLiteral(\"number\")), t.logicalExpression(\"||\", t.binaryExpression(\"===\", type, t.stringLiteral(\"string\")), t.logicalExpression(\"&&\", t.binaryExpression(\"===\", type, t.stringLiteral(\"object\")), t.binaryExpression(\"instanceof\", value, t.identifier(\"String\")))));\n}", "function assertKind(expected, obj) {\n if (support_smi_only_arrays) {\n assertEquals(expected == element_kind.fast_smi_only_elements,\n %HasFastSmiOnlyElements(obj));\n assertEquals(expected == element_kind.fast_elements,\n %HasFastElements(obj));\n } else {\n assertEquals(expected == element_kind.fast_elements ||\n expected == element_kind.fast_smi_only_elements,\n %HasFastElements(obj));\n }\n assertEquals(expected == element_kind.fast_double_elements,\n %HasFastDoubleElements(obj));\n assertEquals(expected == element_kind.dictionary_elements,\n %HasDictionaryElements(obj));\n assertEquals(expected == element_kind.external_byte_elements,\n %HasExternalByteElements(obj));\n assertEquals(expected == element_kind.external_unsigned_byte_elements,\n %HasExternalUnsignedByteElements(obj));\n assertEquals(expected == element_kind.external_short_elements,\n %HasExternalShortElements(obj));\n assertEquals(expected == element_kind.external_unsigned_short_elements,\n %HasExternalUnsignedShortElements(obj));\n assertEquals(expected == element_kind.external_int_elements,\n %HasExternalIntElements(obj));\n assertEquals(expected == element_kind.external_unsigned_int_elements,\n %HasExternalUnsignedIntElements(obj));\n assertEquals(expected == element_kind.external_float_elements,\n %HasExternalFloatElements(obj));\n assertEquals(expected == element_kind.external_double_elements,\n %HasExternalDoubleElements(obj));\n assertEquals(expected == element_kind.external_pixel_elements,\n %HasExternalPixelElements(obj));\n // every external kind is also an external array\n assertEquals(expected >= element_kind.external_byte_elements,\n %HasExternalArrayElements(obj));\n}", "function typeOf(obj) {\n var result = typeof obj;\n if (result !== 'object') { return result; }\n if (null === obj) { return result; }\n if (cajita.inheritsFrom(obj, DisfunctionPrototype)) { return 'function'; }\n if (cajita.isFrozen(obj) && typeof obj.call === 'function') {\n return 'function';\n }\n return result;\n }", "function findTheType(someVar) {\n return typeof someVar;\n}", "valueMatchesType(value) {\n return typeof value === this.valueType\n }", "function $type(obj){\n\tif (!obj) return false;\n\tvar type = false;\n\tif (obj instanceof Function) type = 'function';\n\telse if (obj.nodeName){\n\t\tif (obj.nodeType == 3 && !/\\S/.test(obj.nodeValue)) type = 'textnode';\n\t\telse if (obj.nodeType == 1) type = 'element';\n\t}\n\telse if (obj instanceof Array) type = 'array';\n\telse if (typeof obj == 'object') type = 'object';\n\telse if (typeof obj == 'string') type = 'string';\n\telse if (typeof obj == 'number' && isFinite(obj)) type = 'number';\n\treturn type;\n}", "function match(type, value) {\n}", "function isTyler(name) {\n if (name === \"Tyler\") {\n return true;\n }\n else {\n return false;\n }\n }", "function getType(item) {\n console.log(item + ' is a ' + typeof(item));\n}", "function assertType(value,type){var valid;var expectedType=getType(type);if(expectedType==='String'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='string');}else if(expectedType==='Number'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='number');}else if(expectedType==='Boolean'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='boolean');}else if(expectedType==='Function'){valid=(typeof value==='undefined'?'undefined':_typeof2(value))===(expectedType='function');}else if(expectedType==='Object'){valid=isPlainObject(value);}else if(expectedType==='Array'){valid=Array.isArray(value);}else{valid=value instanceof type;}return{valid:valid,expectedType:expectedType};}", "typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }", "function classify(value) {\n if (value == null) {\n return null;\n }\n else if (value instanceof HTMLElement) {\n return 'primitive';\n }\n else if (value instanceof Array) {\n return 'array';\n }\n else if (value instanceof Date) {\n return 'primitive';\n }\n else if (typeof value === 'object' && value.constructor === Object) {\n return 'object';\n }\n else if (typeof value === 'function') {\n return 'function';\n }\n else if (typeof value === 'object' && value.constructor != null) {\n return 'class-instance';\n }\n return 'primitive';\n}", "function resolveKind(id) {\n \t\t\t\t var k=resolveKindFromSymbolTable(id);\n \t\t\t\t\t\tif (!k) {\n \t\t\t\t\t\t\tif (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t k=\"CLASS_NAME\";\n \t\t\t\t\t\t } else if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t k=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t}\n \t\t\t\t\t }\n \t\t\t\treturn k;\n \t\t }", "isFunctionOrBreed(value) {\n doCheck(\n value.constructor.name === \"Function\" || value.constructor === BreedType,\n \"Attempt to call a non-function\"\n );\n }", "function instanceOf(obj, base) {\n while (obj !== null) {\n if (obj === base.prototype)\n return true;\n if ((typeof obj) === 'xml') { // Sonderfall mit Selbstbezug\n return (base.prototype === XML.prototype);\n }\n obj = Object.getPrototypeOf(obj);\n }\n\n return false;\n}", "check(target) {\n const targetType = typeof target;\n assert('string' === targetType, 'Type error, target should be a string, ' +\n `${targetType} given`);\n }", "function isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}", "visitType_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function dataTypeSeer(array) {\n\tfor (var i = 0; i < array.length; i++) {\n\t\tconsole.log(typeof array[i]);\n\t};\n}", "typesAreEquivalent(t1, t2) {\n if (t1 === null || t2 === null) {\n return true;\n }\n if (t1.constructor === ListType && t2.constructor === ListType) {\n return this.typesAreEquivalent(t1.memberType, t2.memberType);\n } else if (t1.constructor === DictType && t2.constructor === DictType) {\n return (\n this.typesAreEquivalent(t1.keyType, t2.keyType) &&\n this.typesAreEquivalent(t1.valueType, t2.valueType)\n );\n } else if (t1.constructor === IdType) {\n return this.typesAreEquivalent(t1.ref, t2);\n } else if (t2.constructor === IdType) {\n return this.typesAreEquivalent(t1, t2.ref);\n } else {\n return t1 === t2;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prompt to see if guest wants to continue shopping
function continueShopping(){ inquirer.prompt({ type: "confirm", name: "confirm", message: "Would you like to continue shopping?" }).then(function(answer){ if (answer.confirm === true){ start(); }else if(answer.confirm === false){ console.log("Thank you for shopping"); } }); }
[ "function purchasePrompt() {\n inquirer.prompt([{\n type: \"confirm\",\n name: \"purchase\",\n message: \"Would you like to make a purchase?\",\n default: true\n\n }]).then (function (user) {\n if (user.purchase === true) {\n itemSelect();\n } else {\n console.log(\"\\n =================================================\\n\");\n console.log(\"Thank you for stopping by. Come back and shop with us anytime!\");\n\n connection.end();\n }\n });\n}", "function supervisorContinue() {\n inquirer.prompt([\n {\n name: \"stayOn\",\n message: \"Do you want to continue supervising inventory?\",\n type: \"confirm\"\n }\n ])\n .then(answer => {\n if (answer.stayOn) {\n supervisorQuestions();\n } else {\n connection.end();\n process.exit();\n }\n }).catch(error => {\n if (error) {\n console.log(error.message);\n }\n });\n}", "function confirmTrip() {\n console.log(\n \"Destination: \" +\n myTrip[0] +\n \" Restaurant: \" +\n myTrip[1] +\n \" Transportation: \" +\n myTrip[2] +\n \" Entertainment \" +\n myTrip[3]\n );\n let userHappinessRequest = prompt(\n \"Are you satisfied with all your random selections?\"\n );\n\n if (userHappinessRequest === \"yes\") {\n console.log(\"Day Trip confirmed! Have fun!\");\n } else {\n newUserChoices();\n }\n}", "function promptAnotherAction() {\n inquirer.prompt([\n // Prompt user for yes or no\n {\n type: \"confirm\",\n message: \"Would you like to perform another action?\",\n name: \"anotherAction\",\n },\n ]).then(function (inquirerResponse) {\n // If yes to prompt\n if (inquirerResponse.anotherAction) {\n console.log();\n // Show products again\n promptSelection();\n } else {\n console.log(\"\\nGoodbye!\\n\");\n\n // End DB connection\n connection.end();\n }\n });\n}", "function continueManage() {\n // prompt if another action is needed \n inquirer\n .prompt(\n {\n name: \"confirm\",\n type: \"confirm\",\n message: \"Would you like to do something else?\",\n default: true\n\n })\n .then(function (answer) {\n if (answer.confirm) {\n managerOptions();\n }\n else {\n console.log(\"Thank you! Goodbye.\")\n connection.end();\n }\n });\n}", "function afterCart() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"afterAction\",\n message: \"What would you like to do next?\",\n choices: [\"Add another item\", \"Remove an item\", \"Check out\"]\n }\n ]).then(({ afterAction }) => {\n if (afterAction === \"Add another item\") {\n askProduct();\n }\n else if (afterAction === \"Remove an item\") {\n removeItem();\n }\n else if (afterAction === \"Check out\") {\n checkOut();\n }\n });\n}", "function continueShopping() {\n getProducts();\n }", "function continueShopping() {\n\tsaveFormChanges();\n\twindow.location.href = thisSiteFullurl + backURL;\n}", "function visitMarket() {\n let answer = rls.question(\n `The marketplace is booming with activity. \\nThe armory is stocked with wide selection of swords for Ξ7 a piece or leather armor for Ξ4 \\n You now have ${playerGold} gold coins. So, what would you like to buy, sword or armor? \\n`\n );\n if (answer === \"sword\") {\n if (playerGold >= 7) {\n console.log(\"Here is your beautiful sword\");\n\n playerGold -= 7;\n\n chooseVisit();\n } else {\n console.log(\"Not enough gold\");\n chooseVisit();\n }\n } else if (answer === \"armor\") {\n if (playerGold >= 4) {\n console.log(\"Here is your beautiful armor\");\n playerGold -= 4;\n chooseVisit();\n } else {\n console.log(\"Not enough gold\");\n chooseVisit();\n }\n } else {\n console.log(\"Please enter a valid selection\");\n visitMarket();\n }\n}", "function promptContinue() {\n\n\treturn inquirer.prompt([\n\t\t{\n\t\t\ttype: \"confirm\",\n\t\t\tname: \"continue\",\n\t\t\tmessage: \"Would you like to continue?\",\n\t\t\tdefault: true\n\t\t}\n\t]).then(function (answers) {\n\t\treturn answers.continue;\n\t});\n\n}", "function newOrder(){\n\t\tinquirer.prompt([{\n\t\t\tname: \"choice\",\n\t\t\ttype: \"confirm\",\n\t\t\tmessage: \"Would you like to place another order?\"\n\t\t}]).then(function(answer){\n\t\t\tif(answer.choice){\n\t\t\t\tuserRequest();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log('Thank you for shopping at BAMazon!');\n\t\t\t\tconnection.end();\n\t\t\t}\n\t\t})\n\t}", "function firstPrompt() {\n inquirer\n .prompt([\n { name: \"item\",\n type: \"input\",\n message: \"\\n What is the Id of the product you want to buy? \",\n validate: function (value) \n {\n if (isNaN(value) === false) \n {\n return true;\n }\n return false;\n }\n },\n {\n name: \"quantity\",\n type: \"input\",\n message: \"\\n How many would you like to buy? \",\n validate: function (value) \n {\n if (isNaN(value) === false)\n {\n return true;\n }\n return false;\n }\n }])\n .then(function (answer) \n { // Query db to confirm that the given item ID exists in the desired quantity\n var queryStr = 'SELECT item_id FROM products WHERE item_id=?';\n\n connection.query(queryStr, [item_id = answer.item], function (err, res) {\n if (err) throw err;\n\n // If the user has selected an invalid item ID, data attay will be empty\n // console.log('data = ' + JSON.stringify(data));\n if (res.length === 0) {\n console.log('ERROR: Invalid Item ID. Please select a valid Item ID.');\n firstPrompt();\n } else {\n var query = \"SELECT price, stock_quantity FROM products WHERE item_id= ? Limit 1\";\n connection.query(query, [answer.item], function (err, res) {\n if (err) { console.log(err) };\n\n if (res[0].stock_quantity >= answer.quantity) {\n console.log(\"Good news your order is in stock!\");\n // console.log(res[0].price);\n console.log(\"All right, your total cost is \" + res[0].price * answer.quantity + \"!\");\n connection.query(\"UPDATE products SET stock_quantity = stock_quantity-\" + answer.quantity + \" WHERE item_id = \" + answer.item);\n shopAgain();\n }\n else {\n console.log(\"We only have \" + res[0].stock_quantity + \" in our stock! \")\n shopAgain();\n\n };\n });\n }\n })\n });\n\n // to continue shopping or exit\n function shopAgain() {\n inquirer\n .prompt({\n name: \"action\",\n type: \"list\",\n message: \"\\n Whould you like to buy something else?\",\n choices: [\n \"Yes\",\n \"No\"\n ]\n })\n .then(function (answer2) {\n switch (answer2.action) {\n case \"Yes\":\n firstPrompt();\n break;\n case \"No\":\n connection.end();\n break;\n }\n });\n }\n}", "function start() {\n inquirer\n .prompt({\n name:\"postOrBid\",\n type:\"list\",\n message:\"Would you like to [POST] a new item, or [BID] on an existing item?\",\n choices:[\"POST\",\"BID\",\"QUIT\",\"RESTOCK\"]\n }).then(function(answer) {\n if(answer.postOrBid.toUpperCase()=== \"POST\") {\n postAuction();\n } else if (answer.postOrBid.toUpperCase()=== \"BID\") {\n bidAuction();\n } else if(answer.postOrBid.toUpperCase()=== \"RESTOCK\") {\n restockAuction();\n } else { \n connection.end();\n }\n });\n}", "function askPlayer() {\n inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Would you like to start a new game?\",\n default: true\n }\n ]).then(function(answer) {\n if (answer.confirm) {\n console.log(colors.gray(\"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"));\n startGame();\n }\n else {\n console.log(colors.green(\"\\nSorry to see you go. Bye!\"));\n }\n });\n}", "function afterAct() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"afterAction\",\n message: \"What would you like to do next?\",\n choices: [\"Add another item\", \"View my cart or make changes to my cart\", \"Check out\"]\n }\n ]).then(({ afterAction }) => {\n if (afterAction === \"Add another item\") {\n askProduct();\n }\n else if (afterAction === \"View my cart or make changes to my cart\") {\n showCart();\n }\n else if (afterAction === \"Check out\") {\n checkOut();\n }\n });\n}", "function promptUserPurchase() {\n\t\n\n\t// Prompt the user to select the product\n\tinquirer.prompt([\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tname: 'item_id',\n\t\t\tmessage: 'Please enter an ID of the product you would like to purchase.',\n\t\t\t//validate: validateInput,\n\t\t\tfilter: Number\n\t\t},\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tname: 'quantity',\n\t\t\tmessage: 'How many units of the product you would like to purchase?',\n\t\t\t\n\t\t\tfilter: Number\n\t\t}\n\t]).then(function(input) {\n\t\tvar item = input.item_id;\n\t\tvar quantity = input.quantity;\n\n\t\t// Check existing databass to confirm that selected item id exists in the quantity selected\n\t\tvar queryStr = 'SELECT * FROM products WHERE ?';\n\n\t\tconnection.query(queryStr, {item_id: item}, function(err, data) {\n\t\t\tif (err) throw err;\n\n\t\t\t// Dipslay an empty data array, if the user's input is invalid\n\t\t\tif (data.length === 0) {\n\t\t\t\tconsole.log('ERROR: Invalid Product ID. Please select a valid Product ID.');\n\t\t\t\tdisplayInventory();\n\n\t\t\t} else {\n\t\t\t\tvar productData = data[0];\n\n\t\t\t// Display if the quantity requested is in stock\n\t\t\t\tif (quantity <= productData.stock_quantity) {\n\t\t\t\t\tconsole.log('Congratulations, the product you have requested is in stock! Placing an order!');\n\n\t\t\t\t\t// Update query string\n\t\t\t\t\tvar updateQueryStr = 'UPDATE products SET stock_quantity = ' + (productData.stock_quantity - quantity) + ' WHERE item_id = ' + item;\n\t\t\t\t\t\n // Update the current inventory\n\t\t\t\t\tconnection.query(updateQueryStr, function(err, data) {\n\t\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\t\tconsole.log('Your oder has been placed! Your total is $' + productData.price * quantity);\n\t\t\t\t\t\tconsole.log('Thank you for shopping with us!');\n\t\t\t\t\t\tconsole.log(\"\\n---------------------------------------------------------------------\\n\");\n\n\t\t\t\t\t\t// Ends database connection\n\t\t\t\t\t\tconnection.end();\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log('We are sorry, but there is not enough product in stock to complete your order. Your order can not be placed at this time.');\n\t\t\t\t\tconsole.log('Please modify your order, or make another selection.');\n\t\t\t\t\tconsole.log(\"\\n---------------------------------------------------------------------\\n\");\n\n\t\t\t\t\tdisplayInventory();\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "function askOrderMore() {\n inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Order another item?\",\n default: true\n },\n ])\n .then(function(resp) {\n if (resp.confirm) {\n getOrder();\n } else {\n connection.end();\n }\n });\n}", "function askUnits() {\n inquirer.prompt([\n {\n type: \"number\",\n name: \"unitsPrompt\",\n message: \"How many units would you like to buy?\"\n }\n ]).then(({ unitsPrompt }) => {\n var anItem = new CartItem(currentItemID, currentItemName, currentItemPrice, unitsPrompt);\n //the function runs a query on the SQL database to determine if there is enough in stock\n connection.query(\"SELECT * FROM products WHERE item_id = ?\", [anItem.id], function (err, res) {\n if (err) throw err;\n var availableQ = res[0].stock_quantity;\n if (availableQ < anItem.quantityDesired) {\n console.log(chalk.blue(\"Sorry, there are only \") + chalk.magenta(availableQ) + chalk.blue(\" available.\"));\n console.log(chalk.magenta(\"Please select a smaller quanity.\"));\n askUnits();\n }\n else {\n customerCart.push(anItem);\n console.log(chalk.blue(\"Item successfully added to cart\"));\n afterAct();\n }\n });\n });\n}", "function productChoices() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"What is the ID of the product you would like to buy?\",\n name: \"productID\"\n },\n {\n type: \"input\",\n message: \"How many items would you like to buy?\",\n name: \"numberOfItems\"\n },\n // confirmation, yes equal to true by default\n {\n type: \"confirm\",\n message: \"Are sure you want to buy this item?\",\n name: \"confirmItem\",\n default: true\n }\n ])\n .then(answers => {\n // if yes update order from users input\n if (answers.confirmItem === true) {\n updateOrder(answers.productID, answers.numberOfItems);\n } else {\n // no equals false and will close the order\n console.log('Thank you')\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renders markers that track the highest red flower height so far
function renderHeightMarker() { var hrfy = canvas.height - yValFromPct( highestRedFlowerPct ); // highest red flower y value currently var chmp = 100-pctFromYVal(HeightMarker.y); // current height marker percentage if ( Math.floor( highestRedFlowerPct ) > Math.floor(chmp) ) { // initializes animations if new highest red flower HeightMarker.y = hrfy; // y value HeightMarker.baa = true; // bounce animation active HeightMarker.bat = 0; // bounce animation time elapsed HeightMarker.laa = true; // line animation active HeightMarker.lat = 0; // line animation time elapsed $("#height_number").text( Math.floor( highestRedFlowerPct ) ); renderHeightAnnouncement(); } //new highest height marker bounce animation (size expansion & contraction) if ( HeightMarker.baa ) { HeightMarker.bat++; var a = -0.12; // corresponds to animation duration ( higher value is longer duration; 0 is infinite) var b = 2; // extent of expansion ( higher value is greater expansion ) var x = HeightMarker.bat; var y = a*Math.pow(x,2) + b*x; // current marker expansion extent (quadratic formula; y = ax^2 + bx + c) HeightMarker.w = canvas.width*0.025 + y; if ( y <= 0 ) { HeightMarker.baa = false; HeightMarker.bat = 0; } } //new highest height line animation if ( HeightMarker.laa ) { HeightMarker.lat++; var lad = 40; // line animation duration var o = 1 - HeightMarker.lat/lad; // opacity ctx.beginPath(); ctx.lineWidth = 2; var lGrad = ctx.createLinearGradient( HeightMarker.chrfx-canvas.width, HeightMarker.y, HeightMarker.chrfx+canvas.width, HeightMarker.y ); lGrad.addColorStop("0", "rgba( 161, 0, 0, 0 )"); lGrad.addColorStop("0.4", "rgba( 161, 0, 0, " + 0.3*o + ")"); lGrad.addColorStop("0.5", "rgba( 161, 0, 0, " + 1*o + ")"); lGrad.addColorStop("0.6", "rgba( 161, 0, 0, " +0.3*o + ")"); lGrad.addColorStop("1", "rgba( 161, 0, 0, 0 )"); ctx.strokeStyle = lGrad; ctx.moveTo( HeightMarker.chrfx-canvas.width, HeightMarker.y ); ctx.lineTo( HeightMarker.chrfx+canvas.width, HeightMarker.y ); ctx.stroke(); if ( HeightMarker.lat > lad ) { HeightMarker.laa = false; HeightMarker.lat = 0; } } //draws marker if ( highestRedFlowerPct > 0 ) { ctx.beginPath(); // top triangle ctx.fillStyle = "#D32100"; ctx.moveTo( canvas.width, HeightMarker.y ); ctx.lineTo( canvas.width, HeightMarker.y - HeightMarker.h/2 ); ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); ctx.fill(); ctx.beginPath(); // bottom triangle ctx.fillStyle = "#A10000"; ctx.moveTo( canvas.width, HeightMarker.y ); ctx.lineTo( canvas.width, HeightMarker.y + HeightMarker.h/2 ); ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); ctx.fill(); } }
[ "function markerColor(magnitude) {\n if (magnitude<1) {\n return \"#459E22\"}\n else if (magnitude<2) {\n return \"#7FB20E\"}\n else if (magnitude<3) {\n return \"#BEBE02\"}\n else if (magnitude<4) {\n return \"#B19A0F\"}\n else if (magnitude<5) {\n return \"#B54C0B\"}\n else if (magnitude>=5) {\n return \"#C00000\"}\n else {return \"black\"}\n }", "function drawMarkers() {\n\t\tlet ctx = ctrPicker.colorWheel.getContext('2d');\n\t\t\n\t\t// alias\n\t\tconst MRK = CPicker.markers;\n\t\tconst mainHue = MRK.hue[0].angle;\n\t\t\n\t\tctx.save();\n\t\t\n\t\tMRK.hue.forEach((item) => {\n\t\t\tctx.beginPath();\n\t\t\tctx.arc(item.x, item.y, MARK_SIZE, 0, 6.283185307179586);\n\t\t\tctx.fillStyle = getCSS_hsl(item.angle, 1, 0.5);\n\t\t\tctx.fill();\n\t\t\tctx.lineWidth = 2.1; ctx.strokeStyle = 'white';\n\t\t\tctx.stroke();\n\t\t\tctx.lineWidth = 1.9; ctx.strokeStyle = 'black';\n\t\t\tctx.stroke();\n\t\t});\n\t\t\n\t\tMRK.satv.forEach((item) => {\n\t\t\tctx.beginPath();\n\t\t\tctx.arc(item.x, item.y, MARK_SIZE, 0, 6.283185307179586);\n\t\t\tctx.fillStyle = getCSS_hsl(\n\t\t\t\t...getHSLfromHSV(mainHue, item.sat, item.val)\n\t\t\t);\n\t\t\tctx.fill();\n\t\t\tctx.lineWidth = 2.1; ctx.strokeStyle = 'black';\n\t\t\tctx.stroke();\n\t\t\tctx.lineWidth = 1.9; ctx.strokeStyle = 'white';\n\t\t\tctx.stroke();\n\t\t});\n\t\tctx.restore();\n\t}", "function aggregationMapMarkerStyler (cluststerInfo, map) {\n var mapZoomLevel = map.getZoom(),\n aggregationId = cluststerInfo.get('itemId'),\n hotelCount = cluststerInfo.get('itemSize'),\n styles = {};\n\n // IE8 resolving\n if($.browser.msie && $.browser.version<=8) {\n $('.aggregationMarker').css({\n \"background-color\": \"#02ADF7\",\n filter: \"alpha(opacity=60)\"\n });\n }\n\n var currentMarker = document.getElementById(aggregationId);\n\n if (currentMarker == null) {\n return;\n }\n\n if(mapZoomLevel <= 2) {\n if (hotelCount <= 192) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n }\n else if(mapZoomLevel == 3) {\n if (hotelCount <= 122) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\t\t\t\n } \n else if(mapZoomLevel == 4) {\n if (hotelCount <= 73) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n } \n else if(mapZoomLevel == 5) {\n if (hotelCount <= 41) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 55) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 73) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(18);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(19);\n $(currentMarker).css(styles);\n }\n } \n else if(mapZoomLevel == 6) {\n if (hotelCount <= 22) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 30) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 41) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 55) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 73) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 862) {\n styles = calculateMarkerStyle(18);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(19);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(20);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(21);\n $(currentMarker).css(styles);\n }\n } \n else if(mapZoomLevel == 7) {\n if (hotelCount <= 12) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 16) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 22) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 30)\n {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 41) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 55) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 73) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(18);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(19);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(20);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(21);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1536) {\n styles = calculateMarkerStyle(22);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(23);\n $(currentMarker).css(styles);\n }\n } \n else if(mapZoomLevel == 8) {\n if (hotelCount <= 7) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 9) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 12) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 16) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 22) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 30) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 41) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 55) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 73) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\t\t\t\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(18);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(19);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(20);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(21);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1142) {\n styles = calculateMarkerStyle(22);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 1327) {\n styles = calculateMarkerStyle(23);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(24);\n $(currentMarker).css(styles);\n }\n } \n else if(mapZoomLevel >= 9) {\n if (hotelCount <= 3) {\n styles = calculateMarkerStyle(0);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 5) {\n styles = calculateMarkerStyle(1);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 7) {\n styles = calculateMarkerStyle(2);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 9) {\n styles = calculateMarkerStyle(3);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 12) {\n styles = calculateMarkerStyle(4);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 16) {\n styles = calculateMarkerStyle(5);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 22) {\n styles = calculateMarkerStyle(6);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 30) {\n styles = calculateMarkerStyle(7);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 41) {\n styles = calculateMarkerStyle(8);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 55) {\n styles = calculateMarkerStyle(9);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 73) {\n styles = calculateMarkerStyle(10);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 95) {\n styles = calculateMarkerStyle(11);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 122) {\n styles = calculateMarkerStyle(12);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 154) {\n styles = calculateMarkerStyle(13);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 192) {\n styles = calculateMarkerStyle(14);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 237) {\n styles = calculateMarkerStyle(15);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 290) {\n styles = calculateMarkerStyle(16);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 352) {\n styles = calculateMarkerStyle(17);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 424) {\n styles = calculateMarkerStyle(18);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 507) {\n styles = calculateMarkerStyle(19);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 602) {\n styles = calculateMarkerStyle(20);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 711) {\n styles = calculateMarkerStyle(21);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 836) {\n styles = calculateMarkerStyle(22);\n $(currentMarker).css(styles);\n }\n else if (hotelCount <= 979) {\n styles = calculateMarkerStyle(23);\n $(currentMarker).css(styles);\n }\n else {\n styles = calculateMarkerStyle(24);\n $(currentMarker).css(styles);\n }\n }\n}", "function markerSize(AcresBurned) {\n return Math.sqrt(AcresBurned) * 100 ;\n }", "function renderHeightAnnouncement() {\n var fsi = 2.5; // font size max increase\n var td = 0.5; // top decrease (per animation segment)\n var ha = -3; // height adjustment\n var dur = 300; // duration (of each animation segment)\n var c = \"rgba( 130, 0, 0, 1 )\"; // color (default to dark red)\n if ( highestRedFlowerPct >= 80) {\n td = -0.5; \n ha = 15;\n c = \"rgba(17, 17, 17, 1)\";\n }\n $(\"#height_announcement\").finish(); // clears the previous height announcement animation if it hasn't completed yet\n $(\"#height_announcement\")\n .text( Math.floor( highestRedFlowerPct ) + \"%\" )\n .css({ \n top: 100-highestRedFlowerPct+ha + \"%\",\n left: pctFromXVal( HeightMarker.chrfx ) + \"%\",\n opacity: 1,\n color: c,\n })\n .animate({ \n fontSize: \"+=\"+fsi+\"pt\",\n top: \"-=\"+td+\"%\",\n opacity: 1,\n }, dur, \"linear\")\n .animate({ \n fontSize: \"-=\"+fsi+\"pt\",\n top: \"-=\"+td*2+\"%\",\n opacity: 0, \n }, dur*2, \"easeOutQuart\", function() { // (uses easing plugin)\n //callback resets original values\n $(\"#height_announcement\").css({\n fontSize: \"10pt\",\n }); \n }\n );\n}", "displacementFor(i, j, time){\n return this.map.heightForPosition(i,j);\n }", "render() {\n\n let mapViewport = {\n center: [47.3511, -120.7401],\n zoom: 6\n }\n\n let legend = \n <div className='info legend'>\n <i style={{background:\"#C7E5D7\"}}></i>0-30%<br></br>\n <i style={{background:\"#9DD1B9\"}}></i>30-40%<br></br>\n <i style={{background:\"#81C4A5\"}}></i>40-50%<br></br>\n <i style={{background:\"#65B891\"}}></i>50-60%<br></br>\n <i style={{background:\"#539777\"}}></i>60-70%<br></br>\n <i style={{background:\"#41765D\"}}></i>70-80%<br></br>\n <i style={{background:\"#2E5442\"}}></i>80-90%<br></br>\n <i style={{background:\"#1C3328\"}}></i>90+%<br></br>\n </div>;\n\n // Returns a map that contains a legend and and the map itself. This data is layered over the initial tile layer.\n return (\n <Map ref=\"map\" id=\"map\" viewport={mapViewport} style={{ height: '470px' }}>\n <TileLayer\n url='https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoia3lsZWF2YWxhbmkiLCJhIjoiY2pvdzd3NGtzMGgxMjNrbzM0cGhwajRxNyJ9.t8zAjKz12KLZQ8GLp2hDFQ'\n attribution='Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>'\n minZoom='2'\n maxZoom='20'\n id='mapbox.streets'\n />\n {this.state.data.length > 0 ? \n <div>\n <GeoJSON ref=\"geojson\" key={hash(this.state.geojsondata)} data={this.state.geojsondata} style={this.addStyle} onEachFeature={this.onEachFeature.bind(this)}/>\n \n {this.state.listOfCounties ? \n this.state.listOfCounties.includes(this.props.county) ?\n <GeoJSON ref=\"geojson2\" key={hash(this.props.county)} data={this.getSpecificCountyData()} style={this.addSpecificStyling} onEachFeature={this.onEachFeature.bind(this)}/>\n :\n <div />\n :\n <div />}\n \n </div>\n : \n <div />}\n\n <Control position=\"bottomright\"> {/* Legend popup */}\n <div>\n {legend}\n </div>\n </Control>\n <Control position=\"topright\"> {/* Main County Information popup */}\n <div className='info legend'>\n {this.state.countyInfoPopup}\n </div>\n </Control>\n <Control position='bottomleft'> {/* Home County popup on map */}\n \n {this.state.listOfCounties ? \n this.state.listOfCounties.includes(this.props.county) ?\n <div className='info'>\n Home County: {this.props.county}\n </div>\n :\n <div className='info'>\n Enter your Home County in the Form Above\n </div>\n :\n <div/>\n }\n \n </Control>\n </Map>\n );\n }", "function renderFlagpole()\n{\n \n push();\n strokeWeight(5);\n stroke(180);\n line(flagpole.x_pos,floorPos_y,flagpole.x_pos,floorPos_y - 250);\n fill(255,0,0);\n noStroke();\n \n if(flagpole.isReached)\n {\n \n rect(flagpole.x_pos,floorPos_y-250,50,50);\n \n }\n else\n {\n \n rect(flagpole.x_pos,floorPos_y-50,50,50);\n }\n \n \n pop();\n}", "function drawHighway(numLanesPerDirection) {\r\n //drawLane(0, 50, 800, 70, \"northBound\",'grey');\r\n var yPosition = 0;\r\n //Drawing 3 lanes going east\r\n for (lanenum = 0; lanenum < numLanesPerDirection; lanenum++) {\r\n drawLane(0, lanenum * 73, 800, 70, \"east\", \"grey\");\r\n }\r\n //Drawing 3 lanes going west\r\n for (lanenum = 0; lanenum < numLanesPerDirection; lanenum++) {\r\n drawLane(0, lanenum * 73 + 230, 800, 70, \"west\", \"grey\");\r\n }\r\n //Draw guard rails\r\n fill(\"black\");\r\n rect(0, 210, 800, 8);\r\n rect(0, 225, 800, 8);\r\n rect(0, 440, 800, 8);\r\n rect(0, 0, 800, 8);\r\n}", "function setHueMarkerByMse(index, newLoc) {\n\t\tlet angle = Math.atan2(-newLoc.y + CANV_MID, newLoc.x - CANV_MID);\n\t\tCPicker.markers.hue[index].angle = angle * RAD_TO_DEG;\n\t\tlet radius = (WHEEL_RAD_OUT + WHEEL_RAD_IN) / 2;\n\t\tCPicker.markers.hue[index].x = radius * Math.cos(angle) + CANV_MID;\n\t\tCPicker.markers.hue[index].y = -radius * Math.sin(angle) + CANV_MID;\n\t}", "function colorBestRoad(){\n let actual = nodeSearch(end);\n do {\n actual.element.style.opacity = 0.3;\n actual = actual.parent;\n } while(actual != null);\n}", "transparentMarker(){\n\t\tthis.moveableSprites.forEach(moveableFocus =>{\n\t\t\tmoveableFocus.alpha -= 0.7;\n\t\t})\n\t\tthis.hitmarker.forEach(hit =>{\n\t\t\thit.alpha -= 0.2;\n\t\t})\n\t}", "drawCountryColorChart(count, max) {\n\n info(\"worldmap : masking (colorChart)\")\n const [enterSel, updateSel, mergeSel, exitSel] = this.D3.mkSelections(\n this.g.selectAll(\"path\"), this.outlineData.features, \"path\")\n exitSel.remove()\n\n function cname(countryFeature) {\n return matchCountryNames(countryFeature[\"properties\"][\"sovereignt\"].toLowerCase())\n }\n\n mergeSel\n .attr(\"d\", this.path)\n .attr(\"fill\", (features) => {\n const frac = count.getOrElse(cname(features), 0) / max;\n return this.countriesColorPalette(frac)\n })\n .on('mouseover', (features) => eventOnMouseOver(features, this.tooltip, cname(features) + \":\\n\" + count.getOrElse(cname(features), 0) + \" events reported\"))\n .on('mouseout', (d) => eventOnMouseOut(d, this.tooltip))\n\n this.colorchartShown = true;\n }", "get needleOutline() {\n return brushToString(this.i.hy);\n }", "function renderPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches[i].display();\n\t}\n\tfillIcon.display();\n}", "function setMarkerStopped(marker) {\n marker.getIcon().fillColor = \"red\";\n }", "drawBlood() {\n log(LogLevel.DEBUG, 'TileSplat drawBlood');\n for (let i = 0; i < this.data.drips.length; i++) {\n const drip = this.data.drips[i];\n const text = new PIXI.Text(drip.glyph, this.style);\n text.x = drip.x;\n text.y = drip.y;\n text.pivot.set(drip.width / 2, drip.height / 2);\n text.angle = drip.angle;\n this.tile.addChild(text);\n }\n }", "function brushEvent() {\n var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); });\n var extents = actives.map(function(p) { return y[p].brush.extent(); });\n \n foreground.style(\"display\", function(d) {\n return actives.every(function(p, i) {\n return extents[i][0] <= d[p] && d[p] <= extents[i][1];\n }) ? null : \"none\";\n });\n }", "function drawMarkers(plot, ctx) {\n \"use strict\"\n var tmp, maxIndex;\n var xMin = plot.getOptions().xaxis.min;\n var xMax = plot.getOptions().xaxis.max;\n var px = plot.getAxes().xaxis;\n var py = plot.getAxes().yaxis;\n var canvas = $(plot.getCanvas());\n var ctx = canvas[0].getContext('2d'); \n var offset = plot.getPlotOffset();\n var radius = 10;\n var dx, dy; //coordinates of highest point\n var sx, sy; // coordinates of indicator shape\n var max; //maximum value of series at set timeframe\n //indicator dimensions\n var IND_HEIGHT = 24; \n var IND_WIDTH = 30;\n var textOffset_x = 0; //indicator text horizontal offset\n\n //draw indicator for each series \n $.each(plot.getData(), function (i, val) {\n tmp = splitArray(val.datapoints.points, val.datapoints.pointsize, xMax, xMin);\n //acquire the index of the highest value for each series\n maxIndex = tmp.y.indexOf(Math.max.apply(Math, tmp.y)); \n max = tmp.y[maxIndex];\n //transform data point x & y values to canvas coordinates\n dx = px.p2c(tmp.x[maxIndex]) + offset.left;\n dy = py.p2c(tmp.y[maxIndex]) + offset.top - 12;\n sx = dx + 2;\n sy = dy - 22;\n\n //draw indicator\n ctx.beginPath(); \n ctx.moveTo(sx, sy + IND_HEIGHT);\n ctx.lineTo(sx, sy + 30);\n ctx.lineTo(sx + 5, sy + IND_HEIGHT);\n ctx.closePath();\n ctx.fillStyle = val.color; \n\n //set horizontal text offset based on value. \n /*\n TODO:\n Make this more robust - base length adjustment on number of chars instead\n */\n if (max < 10) {\n textOffset_x = 12;\n }\n else if (max >= 10 && max < 100) {\n textOffset_x = 8;\n }\n else if (max >= 100 && max <= 1000) {\n textOffset_x = 4;\n }\n\n ctx.rect(sx,sy, IND_WIDTH, IND_HEIGHT);\n ctx.fillStyle = val.color; \n ctx.fill(); \n\n ctx.fillStyle = '#fff' \n ctx.font = '11pt Calibri';\n ctx.fillText(max, sx + textOffset_x ,sy + 16 ); \n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subject to validation of searchparameters in info as per FN_INFOS.findSensorTypes, return all sensortypes which satisfy search specifications in info. Note that the searchspecs can filter the results by any of the primitive properties of sensor types. The returned value should be an object containing a data property which is a list of sensortypes previously added using addSensorType(). The list should be sorted in ascending order by id. The returned object will contain a lastIndex property. If its value is nonnegative, then that value can be specified as the index property for the next search. Note that the index (when set to the lastIndex) and count searchspec parameters can be used in successive calls to allow scrolling through the collection of all sensortypes which meet some filter criteria. All user errors must be thrown as an array of objects.
async findSensorTypes(info) { const searchSpecs = validate('findSensorTypes', info); //@TODO var nextInteger; var findsensorType={nextInteger:{},data:{}}; var index=0; var findObj={ id: searchSpecs.id, index: searchSpecs.index, count: searchSpecs.count, quantity: searchSpecs.quantity, unit: searchSpecs.unit, manufacturer: searchSpecs.manufacturer, modelNumber: searchSpecs.modelNumber }; if(findObj.id==null && findObj.manufacturer==null && findObj.modelNumber==null && findObj.unit==null && findObj.quantity==null){ //console.log(searchSpecs.index); for(var i=findObj.index;i<(findObj.index+findObj.count);i++){ this.data.push(this.sensorTypes[i]); this.nextInteger=i+1; } findsensorType.nextInteger=this.nextInteger; findsensorType.data= this.data; this.data=[]; }else{ for(var v of this.sensorTypes){ if(v.id==findObj.id||v.manufacturer==findObj.manufacturer||v.modelNumber==findObj.modelNumber|| v.quantity==findObj.quantity) { this.data.push(v); } } findsensorType.nextInteger=-1; findsensorType.data= this.data; this.data=[]; } // console.log(this.sorted_sensor_data); return findsensorType; }
[ "function _findSensors(object, sensorType) {\n\t\t\tscope.log('finding sensors');\n\t\t\tvar sensorNames = [];\n\n\t\t\tfor ( var name in scope.sensorRegistry[ sensorType ] ) {\n\t\t\t\tif (!scope.sensorRegistry[ sensorType ].hasOwnProperty(name)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t//this.log('Checking the registry for ' + name);\n\n\t\t\t\tfor ( var i = 0; i < scope.sensorRegistry[ sensorType ][ name ].length; i ++ ) {\n\n\t\t\t\t\tif ( scope.sensorRegistry[ sensorType ][ name ][ i ] === object ) {\n\t\t\t\t\t\t// this object is controlled by the sensor a\n\t\t\t\t\t\t// this.log('Found ' + i + ' in ' + sensorType + ':' + name + ' and it is ' + object);\n\t\t\t\t\t\tsensorNames.push(name);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tscope.log('The clicked object can be affected by the following sensors of type ' + sensorType + ':');\n\t\t\tscope.log(sensorNames);\n\n\t\t\treturn sensorNames;\n\t\t}", "async addSensorType(info) {\n const sensorType = validate('addSensorType', info);\n //@TODO\n\t //saving value in another variable as sensorType has timestamp and value as integer not number and while adding them into the array they were getting duplicated \n\tvar obj2={\n\t\tid: info.id,\n\t\tmanufacturer: info.manufacturer,\n\t\tmodelNumber: info.modelNumber,\n\t\tquantity: info.quantity,\n\t\tunit: info.unit,\n\t\tlimits: info.limits\n\t};\n\t let e=0;\n\t var y;\n\n\t for(y of this.sensorTypes){\n if(y.id==sensorType.id){\n y.manufacturer=obj2.manufacturer;\n y.modelNumber=obj2.modelNumber;\n y.quantity=obj2.quantity;\n\t\t y.unit=obj2.unit;\n\t\t y.limits=obj2.limits;\n e=e+1;\n\t\t \n\t\t \n\t }\n\t }\n\n\n\n\n\t\n\tif(e==0||this.sensorTypes.length==0){\n\t\tthis.sensorTypes.push(obj2);\n\t\t\n\t\t\n\t}\n\t \n\t \n\t \n\t\n\t\n }", "function recordsetDialog_searchByType(stype) {\r\n\tfor (ii = 0; ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (MM.rsTypes[ii].type == stype) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}", "function _findSensorsInChildrenOf(obj, sensorType) {\n\t\t\tif ( sensors[ sensorType ] === undefined ) {\n\t\t\t\tsensors[ sensorType ] = {};\n\t\t\t}\n\n\t\t\tif ( undefined === obj.children ) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor ( var i = 0; i < obj.children.length; i ++ ) {\n\t\t\t\tvar checkNode = obj.children[ i ];\n\n\t\t\t\tvar eventName;\n\n\t\t\t\t// check this node\n\t\t\t\tif ( 'undefined' !== typeof checkNode.userData.originalVrmlNode\n\t\t\t\t\t&& sensorType === checkNode.userData.originalVrmlNode.node\n\t\t\t\t\t&& checkNode.userData.originalVrmlNode.enabled !== false\n\t\t\t\t) {\n\t\t\t\t\t// find the first route, we only use TimeSensor to get from one to the next\n\t\t\t\t\teventName = checkNode.name;\n\t\t\t\t\tscope.log(sensorType + ': ' + eventName);\n\t\t\t\t\tsensors[ sensorType ][ eventName ] = checkNode;\n\t\t\t\t}\n\n\t\t\t\t// check its children recursively\n\t\t\t\tif ( checkNode.children !== undefined ) {\n\t\t\t\t\t_findSensorsInChildrenOf(checkNode, sensorType);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}", "function searchProductsByType(type) {\n\n let productsByType = new Promise(function(resolve, reject) {\n let products = [];\n let possibleTypes = ['Book', 'Clothing', 'Electronics', 'Food'];\n let pattern = new RegExp(type, \"i\");\n let validType;\n\n possibleTypes.forEach(function(possibleType) {\n if(pattern.test(possibleType) === true) {\n validType = possibleType;\n }\n })\n\n if(validType === undefined) {\n reject(\"Invalid type: \" + type);\n }\n else {\n setTimeout(function() {\n catalog.forEach(function(item) {\n if((item.type).toLowerCase() == type.toLowerCase()) {\n products.push(item);\n }\n });\n\n resolve(products);\n }, 1000);\n \n }\n \n })\n\n return productsByType;\n }", "async addSensorData(info) {\n const sensorData = validate('addSensorData', info);\n //@TODO\n\t//JSON.stringify(data,null,2);\n\n\tvar obj={sensorId: info.sensorId,\n\t\ttimestamp: info.timestamp,\n\t\tvalue: info.value\n\t\n\t};\n\t var compare_obj={limits:{}};\n\t var err_obj={\n\t\t sensorId: {},\n\t\t timestamp:{},\n\t\t value: {},\n\t\t Status: {}\n\t };\n\t //doing the following operation to sort out the data as it is being added by statuses=ok or error or out of range\n\t for(var v of this.sensors){\n if(v.id==obj.sensorId){\n var sensor_expected_min=Number(v.expected.min);\n var sensor_expected_max=Number(v.expected.max);\n var obj_number_value=Number(obj.value);\n if(sensor_expected_min>obj_number_value || sensor_expected_max<obj_number_value)\n {\n err_obj.sensorId=obj.sensorId;\n err_obj.timestamp=obj.timestamp;\n err_obj.value=obj.value;\n err_obj.Status='Out of Range';\n this.sorted_sensor_data.push(err_obj);\n //console.log(err_obj);\n //console.log(v);\n }else{\n err_obj.sensorId=obj.sensorId;\n err_obj.timestamp=obj.timestamp;\n err_obj.value=obj.value;\n err_obj.Status='ok';\n this.sorted_sensor_data.push(err_obj);\n //console.log(err_obj);\n //console.log(v);\n }\n for(var h of this.sensorTypes){\n if(h.id==v.model){\n var sensor_type_limits_min=Number(h.limits.min);\n var sensor_type_limits_max=Number(h.limits.max);\n if(sensor_type_limits_min>obj_number_value || sensor_type_limits_max<obj_number_value){\n\t\t\t err_obj.sensorId=obj.sensorId;\n err_obj.timestamp=obj.timestamp;\n err_obj.value=obj.value;\n err_obj.Status='error';\n this.sorted_sensor_data.push(err_obj);\n //console.log(err_obj);\n //console.log(h);\n }\n }\n }\n }\n\t }\n\n\n\n\t let c=0;\n\t var x;\n\t for(x of this.sensorData){\n\t if(x.sensorId===sensorData.sensorId && x.timestamp===obj.timestamp){\n\t x.sensorId=obj.sensorId;\n\t x.timestamp=obj.timestamp;\n\t x.value=obj.value;\n c=c+1;\n\t \n\n\t }\n\t }\n\t \n\t if(c==0||this.sensorData.length==0){\n\t\t this.sensorData.push(obj);\n\n\t\t \n\t\n\t }\n\t \n\t\n\t \n\t \n\n }", "async listAll() {\n\t\tlet searchParams = this.type ? { type: this.type } : {};\n\t\tlet records = await StockModel\n\t\t\t.find(searchParams)\n\t\t\t.select({ 'name': 1, 'latest': 1, '_id': 0, 'type': 1 })\n\t\t\t.sort({ 'type': 'asc', 'latest': 'desc' });\n\t\treturn { 'status': 200, records };\n\t}", "findAllByType(req, res){\n Event.getAllByType(req.params.typeId, req.params.userId, (err, data) => {\n if (err) {\n if (err.kind === \"not_found\") {\n res.status(404).send({\n message: `Not found event with TypeId ${req.params.typeId}.`\n });\n } else {\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving events by type.\"\n });\n }\n }else {\n res.send(data);\n }\n });\n }", "searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }", "function searchSkeptical(parameters){\n\t// Third call: skeptical around me\n\tparameters[\"scope\"] = \"local\";\n\tparameters[\"status\"] = \"skeptical\";\n\n\t// Event min Timestamp\n\tparameters[\"timemin\"] = timeMin;\n\n\t// Event max Timestamp\n\ttimeMax = toTimestamp(new Date()); // Now\n\tparameters[\"timemax\"] = timeMax;\n\n\tparameters[\"type\"] = \"all\";\n\tparameters[\"subtype\"] = \"all\"\n\n\t// Event radius (metres)\n\tparameters[\"radius\"] = SKEPTICAL_METERS * 1000;\n\n if (navigator.geolocation) {\n var options = { timeout: 2000 }; // milliseconds\n navigator.geolocation.getCurrentPosition(\n \tfunction(position){\n\n \t\t// Geolocation Success\n \t\tparameters[\"lat\"] = position.coords.latitude;\n \t\t\tparameters[\"lng\"] = position.coords.longitude;\n\n \t\t\turl = URLSERVER.concat(buildUrl(\"/richieste\", parameters));\n\n \t\t\t$.ajax({\n\t\t\t\t\turl: url,\n\t\t\t\t\ttype: 'GET',\n\t\t\t\t\tsuccess: function(responseSkeptical, status, richiesta) {\n\t\t\t\t // Update events local with new informations\n\t\t\t\t\t\t// Add new event from remote servers\n\t\t\t\t\t\tif(responseSkeptical.events){\n\t\t\t\t\t\t\t\t$.each(responseSkeptical.events, function(index, event){\n\t\t\t\t\t\t\t\t\tvar eventIDRemote = event.event_id;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t// Check if the event already exists in eventArray\n\t\t\t\t\t\t\t\t\tvar result = $.grep(eventArray, function(e){ return e.eventID == eventIDRemote; });\n\t\t\t\t\t\t\t\t\tif (result.length == 0) {\n\t\t\t\t\t\t\t\t\t\t// New event from remote server\n\t\t\t\t\t\t\t\t\t \tcreateEvent(event);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif(responseSkeptical.events.length > 0)\n\t\t\t\t\t\t\t\tskepticalAlert(\"Sono stati trovati eventi scettici vicino a te! Aiutaci a risolverli\");\t\n\t\t\t\t\t\t\t}\n\t\t\t \t\t},\n\t\t\t\t error: function(err) {\n\t\t\t\t errorAlert(\"Skeptical Ajax error\");\n\t\t\t\t }\n\t\t\t\t});\n \t},\n \tfunction(){\n \t\t// Geolocation error\n \t\tconsole.log(\"Errore GeoLocalizzazione per trovare gli eventi scettici\");\n \t}, \n \toptions);\n } else\n errorAlert(\"Il browser non supporta le geolocalizzazione\");\n}", "function getTestSensorList() {\n // Saves the name of all registered sensors included in the test into a list\n for (let sensor in sensorList) {\n // Check if sensor is included in the test\n if (testingDetails.type.indexOf(sensorList[sensor].name) !== -1) {\n vm.sensorListTestNames.push(sensorList[sensor].name);\n }\n }\n\n // Check if test is reusing data from the previous test\n if (testingDetails.useNewData === false) {\n for (let sensorName in vm.sensorListTestNames) {\n for (let sensor in sensorList) {\n // If Test is in Rerun Mode only add the rerun sensors of the test to this list\n if (sensorList[sensor].name === RERUN_PREFIX + vm.sensorListTestNames[sensorName]) {\n vm.sensorListTest.push(sensorList[sensor]);\n }\n }\n }\n } else {\n for (let sensor in sensorList) {\n if (testingDetails.type.indexOf(sensorList[sensor].name) !== -1) {\n vm.sensorListTest.push(sensorList[sensor]);\n vm.sensorListTestNames.push(sensorList[sensor].name);\n }\n }\n }\n\n }", "function searchByType ( type ) {\n if (checkType(type)) {\n\t\t// this is a valid type\n return rp( {\n url: 'http://www.thecocktaildb.com/api/json/v1/1/filter.php?c=' + type,\n json: true\n }).then(function (res) {\n return res.drinks;\n }, function (err) {\n return err;\n });\n } else {\n return Promise.resolve(false);\n }\n}", "function performSearch(srch, srchType, btnIndex){\n //Make the inputs into the URL and call the API\n //Reset variables\n currentFoodResults = [[],[],[],[],[]];\n currentWineResults = [[],[],[],[],[],[],[]];\n varietalInformation = null;\n foodRunFlag = false;\n wineRunFlag = false;\n numResults = 5;\n maxResults = 0;\n\n if(buttonTrigger === false){//Make API call if new search\n\n if(srchType === \"wine\"){ //If searching for a wine\n foodUrl = makeSearchIntoFoodURL(matchFoodToWine(userSearch, varietals)); //find food that pairs for the search\n wineUrl = makeSearchIntoWineURL(userSearch);\n varietalInformation = varietalInfo[userSearch];\n } else { //Otherwise\n foodUrl = makeSearchIntoFoodURL(userSearch); //assume search was for food\n wineUrl = makeSearchIntoWineURL(matchFoodToWine(userSearch, ingredients)); //Get a wine varietal to search\n }\n\n getFoods(foodUrl, extractFoodResults);\n getWines(wineUrl, extractWineResults);\n\n } else if(buttonTrigger === true) {//Skip the API call and reference the cached result\n extractFoodResults(foodResults[btnIndex][1], btnIndex);\n extractWineResults(wineResults[btnIndex][1], btnIndex);\n }\n }", "function createSearchResultsFromJsonArray(jsonObj) {\n var instance, i;\n var searchResults = []; \n for (i = 0; i < jsonObj.data.length; i += 1) {\n instance = new SearchResult(jsonObj.data[i]);\n searchResults.push(instance);\n }\n return searchResults;\n }", "function eCSearch( dev_obj ){\n /*\n key points\n we are gathering information from a nS about what element to look at\n if it does not exist in its related itO according to list, we add it to the nS or the selectTags if its missing\n if its there we properly update nS and selectTags at that index\n */\n /*\n abelasts\n 1 for select tags\n 1 for nS\n \n */\n \n // .list, desired items\n // .look spot where to look and assert for list, if an object the items should be keys\n // .same indicator to look at the same set of values\n // .order iterableObject on how to create the numbersystem\n // .sT if in use the index to access selectTags from the self\n // .nS if in use the index to access numberSystem from the self\n // make eCSST an iterableObject\n // look through innerHTML, innerText, textContext\n // holds the found elements that meet the query in ultraObject.elementFound\n \n \n /*[addding the dev_obj to ultraObject.args ]*/ //{\n var eCSearch_dev_obj = ultraObject.args.add( {value:ultraObject.iterify( {iterify:dev_obj} ) } )\n // } /**/\n \n if( dev_obj.sT === undefined ){\n \n \n /*[the object handling everything with the choosing tags in addition the numberSystem ]*/ //{\n // make this selectTags +scope +abelast +self\n var eCSSelectTags_0_i = ultraObject.scope.add( {value:ultraObject.selectTags.add( {value:ultraObject.iterableObject()} )} )\n ultraObject.selectTags.abelast.add( {value:ultraObject.scope[eCSSelectTags_0_i]} )\n // } /**/\n \n \n }\n \n /*[if the developer already had the function make the selectTags]*/ //{\n //make this selectTags +scope\n else if( ultraObject.isInt( {type:dev_obj.sT} ) ){\n \n \n var eCSSelectTags_0_i = ultraObject.scope.add( {value:dev_obj.sT} )\n \n \n }\n // } /**/\n \n /* if we had the number system now we can turn this to a loop and start adding data to our database*/ //{\n if( ultraObject.isInt( {type:dev_obj.nS} ) === 'true' ){\n \n \n var eCSNS_0_i = ultraObject.scope.add( {value:dev_obj.nS} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS = 'true'\n \n \n \n }\n // } /**/\n \n \n console.group( 'items needed to search for elements based on keywords' )\n ultraObject.objInvloved(ultraObject.iterify({\n iterify:[\n ultraObject.allTags[ultraObject.scope[dev_obj.aT]],\n ultraObject.misc[ultraObject.scope[dev_obj.list]],\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]]\n ]\n })\n )\n \n /*objIO -self -ablelast */ //{\n ultraObject.objIO.minus( {index:ultraObject.objIO.abelast.length-1} )\n ultraObject.objIO.abelast.minus( {index:ultraObject.objIO.abelast.length-1} )\n // } /**/\n \n console.groupEnd()\n \n /* look at each requirement preFillForm must fill in the document by the end user*/ //{\n var eCSearchFL_0_i = {\n forLoop_0_i:0,\n forLoopLength: ultraObject.misc[ultraObject.scope[dev_obj.list]].length,\n fn:function( dev_obj ){\n \n /*it should start with the first element if none is given*/ //{\n if( dev_obj.nS === undefined ){\n \n \n ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect = 0\n \n \n }\n \n \n else if( dev_obj.nS !== undefined ){\n \n debugger\n ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect = ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ][0]\n \n \n \n }\n // } /**/\n \n /*at this point you need to us the nS to modify indexSelect*/ //{\n // use propertyUndefined to see if the nS is there then receive external output of an updated nS\n // to properly modify indexSelect so elements are not queired again\n eCSearchFL_1_i.forLoop_0_i = ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect\n // } /**/\n \n /* where every tag is looked at in relation to the respective list*/ //{\n return ultraObject.forLoop( eCSearchFL_1_i )\n // } /**/\n },\n args:dev_obj,\n }\n // } /**/\n \n /* where every tag is looked at in relation to the respective list*/ //{\n var eCSearchFL_1_i = {\n forLoop_0_i:ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ].indexSelect,\n forLoopLength:ultraObject.allTags[ultraObject.scope[dev_obj.aT]].length,\n fn:function( dev_obj ){\n \n /* if were looking at the same element*/ //{\n if( eCSearchFL_0_i.forLoop_0_i > 0 && ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i-1 ].eCSIndex === eCSearchFL_1_i.forLoop_0_i ){\n \n \n //if PROBLEM use propertyUndefined to validate the selectedTag for interragtion is there as well as its eCSIndex\n \n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement = 'true'\n \n \n }\n \n \n else if( eCSearchFL_0_i.forLoop_0_i > 0 && ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i-1 ].eCSIndex !== eCSearchFL_1_i.forLoop_0_i ){\n \n \n //if PROBLEM use propertyUndefined to validate the selectedTag for interragtion is there as well as its eCSIndex\n \n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement = 'false'\n \n \n }\n // } /**/\n \n /* possible places to look to fill in the element to satisfy end users query*/ //{\n // PROBLEM if you have scoping problems with this fn look here\n return ultraObject.forLoop( eCSearchFL_2_i )\n // } /**/\n },\n args:dev_obj,\n }\n // } /**/\n /* possible places to look to fill in the element to satisfy end users query*/ //{\n // PROBLEM if you have scoping problems with this fn look here\n var eCSearchFL_2_i = {\n forLoop_0_i:0,\n forLoopLength:ultraObject.misc[ultraObject.scope[dev_obj.look]].length,\n fn:function( dev_obj ){\n \n \n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement ==='true' ){\n \n /* it better be in the scope */ //{\n // im really counting on this to be in the proper spot in the scope if not i have to take it from the scope everytime and get it from the abelast\n var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n // }\n \n if( ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the digits and metadata for the numberSystem*/ //{\n ultraObject.numberSystem({\n operation:'create',\n nS:ultraObject.scope[ eCSNS_0_i ],\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n }),\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n })\n })\n // } /**/\n \n }\n \n\n \n if( ultraObject.selectTags[ ultraObject.scope[eCSSelectTags_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the ideal select tag for this function*/ //{\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ].add({\n value:ultraObject.iterableObject()\n })\n // } /**/\n \n }\n \n /*adjusting this digits itO to that of the numberSystem */ //{\n ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ].nSM[ eCSearchFL_0_i.forLoop_0_i ][0] ][0] = eCSearchFL_1_i.forLoop_0_i\n //helps change the number when the match is found so the NS doesnt take over\n //if problems look here idk if it supposed to follow the nSM or not\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].item = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].query = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ][ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].xMark = ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].keyword = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].valuePhrase = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][1]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].eCSIndex = eCSearchFL_1_i.forLoop_0_i\n // } /**/\n \n \n return 'premature'\n \n \n }\n \n \n else if( ultraObject.allTags[ ultraObject.scope[dev_obj.aT] ][eCSearchFL_1_i.forLoop_0_i][ ultraObject.misc[ultraObject.scope[dev_obj.look] ][eCSearchFL_2_i.forLoop_0_i][0] ] !== undefined || dev_obj.all === 'true' ){\n \n \n if( ultraObject.allTags[ ultraObject.scope[dev_obj.aT] ][eCSearchFL_1_i.forLoop_0_i][ ultraObject.misc[ultraObject.scope[dev_obj.look] ][eCSearchFL_2_i.forLoop_0_i][0] ].indexOf( ultraObject.misc[ ultraObject.scope[dev_obj.list] ][eCSearchFL_0_i.forLoop_0_i][0] ) !== -1 || dev_obj.all === 'true' ){\n \n /*numberSystem access or creation*/ //{\n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS !== 'true' ){\n \n\n ultraObject.numberSystem({\n operation:'create',\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n }),\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n })\n })\n var eCSNS_0_i = ultraObject.scope.add( {value:ultraObject.nS.abelast[ultraObject.nS.abelast.length-1]} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS = eCSNS_0_i\n // i do this because i need a closure so that all algorithms in the loop can access it\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS = 'true'\n \n \n }\n \n \n else if( ultraObject.isInt({type:dev_obj.nS}) === 'true' ){\n \n \n var eCSNS_0_i = ultraObject.scope.add( {value:dev_obj.nS} )\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS = eCSNS_0_i\n \n \n }\n \n \n else if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].createdNS === 'true'){\n \n \n var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n \n \n }\n // } /**/\n \n if( ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the digits and metadata for the numberSystem*/ //{\n ultraObject.numberSystem({\n operation:'create',\n nS:ultraObject.scope[ eCSNS_0_i ],\n nSM:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,\n eCSearchFL_0_i.forLoop_0_i\n ]\n })\n ]\n }),\n digits:ultraObject.iterify({\n iterify:[\n ultraObject.iterify({\n iterify:[\n eCSearchFL_0_i.forLoop_0_i,[\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoop_0_i,\n eCSearchFL_1_i.forLoopLength+1]\n ]\n })\n ]\n })\n })\n // } /**/\n \n }\n \n \n if( ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ][ eCSearchFL_0_i.forLoop_0_i ] === undefined ){\n \n /*creating the ideal select tag for this function*/ //{\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i] ].add({\n value:ultraObject.iterableObject()\n })\n // } /**/\n \n }\n \n /*adjusting this digits itO to that of the numberSystem */ //{\n ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ][ ultraObject.nS[ ultraObject.scope[eCSNS_0_i] ].nSM[ eCSearchFL_0_i.forLoop_0_i ][0] ][0] = eCSearchFL_1_i.forLoop_0_i\n //helps change the number when the match is found so the NS doesnt take over\n //if problems look here idk if it supposed to follow the nSM or not\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].item = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][ eCSearchFL_0_i.forLoop_0_i ].query = ultraObject.allTags[ultraObject.scope[dev_obj.aT]][ eCSearchFL_1_i.forLoop_0_i ][ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].xMark = ultraObject.misc[ultraObject.scope[dev_obj.look]][eCSearchFL_2_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].keyword = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][0]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].valuePhrase = ultraObject.misc[ultraObject.scope[dev_obj.list]][eCSearchFL_0_i.forLoop_0_i][1]\n ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]][eCSearchFL_0_i.forLoop_0_i].eCSIndex = eCSearchFL_1_i.forLoop_0_i\n // } /**/\n return 'premature'\n \n }\n \n \n }\n \n \n },\n args:dev_obj,\n bubble:'true'\n }\n // } /**/\n ultraObject.forLoop( eCSearchFL_0_i )\n delete ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].sameElement\n // } /**/\n \n /*selectTags -scope */ //{\n ultraObject.scope.minus( {index:eCSSelectTags_0_i} )\n // } /**/\n \n /*nS */ //{\n // this is a good example when an itO was never accessed by an outer function\n // here you never need to take it out the scope it was never in the scope\n // var eCSNS_0_i = ultraObject.selectTags[ultraObject.scope[eCSSelectTags_0_i]].nS\n // ultraObject.scope.minus( {index:eCSNS_0_i} )\n // } /**/\n \n // find the first that matches the condition, and hold it when all four match exit, if the form doesn't like what I did each value must try everything in the allTapgs itO before telling the end user they cant figure out whats going on.grabs three and swaps one\n \n // so like\n /*\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n | 0 | 1 | 2 | 3 |\n +---+---+---+---+\n \n [0,0,0,0] -> [0,0,0,3] -> [0,0,1,0] -> [0,0,1,3] -> [0,0,3,3] -> [0,3,3,3] [1,0,0,0] -> [1,0,0,3] -> [1,3,3,3] -> [3,3,3,3]\n \n to cover every posibility in the table\n \n for this we need to make a number system that allows to cover every item\n */\n }// seaches for elements with the queried filters and does things to them", "function getDeviceTypes() {\n \n}", "function refreshDiscovery(){\n\n\t//show \"load\" gif in room_config page\n\t$('.box').fadeIn('slow');\n\n\n\t//discovery for sensors\n\tfor ( var i in sensor_types) {\n\t\t\tvar type = sensor_types[i];\n\t\t\twebinos.discovery.findServices(new ServiceType(type), {\n\t\t\t\tonFound: function (service) {\n\t\t\t\t\tconsole.log(\"Service \"+service.serviceAddress+\" found (\"+service.api+\")\");\n\n\t\t\t\t\tif(service.serviceAddress.split(\"/\")[0]==pzh_selected || pzh_selected==\"\"){\n\t\t\t\t\t\t//flag used to avoid to change sensors state\n\t\t\t\t\t\tvar flag=false;\n\t\t\t\t\t\tfor(var j in sensors){\n\t\t\t\t\t\t\tif((service.id)==sensors[j].id){\n\t\t\t\t\t\t\t\tflag=true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\t \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//put it inside sensors[]\n\t\t\t\t\t\tsensors[service.id] = service;\n\t\t\t\t\t\tservice.bind({\n\t\t\t\t\t\t\tonBind:function(){\n\t\t\t \t\t\tconsole.log(\"Service \"+service.api+\" bound\");\n\t\t\t \t\t\tconsole.log(service);\n\t\t\t \t\t\tservice.configureSensor({timeout: 120, rate: 500, eventFireMode: \"fixedinterval\"}, \n\t\t\t \t\t\t\tfunction(){\n\t\t\t \t\t\t\t\tvar sensor = service;\n\t\t\t \t\t\tconsole.log('Sensor ' + service.api + ' configured');\n\t\t\t \t\t\tvar params = {sid: sensor.id};\n\t\t\t \t\t\t\tvar values = sensor.values;\n\t\t\t \t\t\t\tvar value = (values && values[values.length-1].value) || '&minus;';\n\t\t\t \t\t\t\tvar unit = (values && values[values.length-1].unit) || '';\n\t\t\t \t\t\t\tvar time = (values && values[values.length-1].time) || '';\n\n\t\t\t \t\t\tservice.addEventListener('onEvent', \n\t\t\t \t\t\tfunction(event){\n\t\t\t \t\tconsole.log(\"New Event\");\n\t\t\t \t\tconsole.log(event);\n\t\t\t \t\tonSensorEvent(event);\n\t\t\t \t\t},\n\t\t\t \t\t\tfalse\n\t\t\t \t\t);\n\n\t\t\t \t\t\tif(flag==false){\n\t\t\t\t\t \t\t//event listener is active (value=1)\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsensorEventListener_state.push({\n\t\t\t\t\t\t\t\t\t\t\t key: service.id,\n\t\t\t\t\t\t\t\t\t\t\t value: 1\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tfunction (){\n\t\t\t\t\t\t\t\t\t\tconsole.error('Error configuring Sensor ' + service.api);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t \t\t}\n\t\t\t\t\t\t});\n\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\t\n\t\t// discovering actuators\n\t\tfor ( var i in actuator_types) {\n\t\t\tvar type = actuator_types[i];\n\t\t\twebinos.discovery.findServices(new ServiceType(type), {\n\t\t\t\tonFound: function (service) {\n\t\t\t\t\tconsole.log(\"Service \"+service.serviceAddress+\" found (\"+service.api+\")\");\n\t\t\t\t\tif(service.serviceAddress.split(\"/\")[0]==pzh_selected || pzh_selected==\"\"){\n\t\t\t\t\t\t//put it in actuators[]\n\t\t\t\t\t\tactuators[service.id] = service;\n\t\t\t\t\t\tservice.bind({\n\t\t\t\t\t\t\tonBind:function(){\n\t\t\t \t\t\tconsole.log(\"Service \"+service.api+\" bound\");\n\t\t\t\t\t\t\t\tvar params = {aid: service.id};\n\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\n\t\t//load rules GUI\n\t\tsetTimeout(initRulesUI,1000);\n\t\tsetTimeout(refreshRules,1000);\n\n \t\t/** load file and GUI of room_config **/\n \t\tload_data_from_file(room_config_file);\n\n}", "function displaySpeciesData(data) {\r\n cartegoriesCounter = 0;\r\n var listBox = document.getElementById(\"searchResults\");\r\n listBox.innerHTML = \"\";\r\n listBox.innerHTML = \"<p>Name: \" + data.results[0].name + \"</p>\" +\r\n \"<br><p>Classification: \" + data.results[0].classification + \"</p><br>\" +\r\n \"<p>Designation: \" + data.results[0].designation + \"</p><br>\" +\r\n \"<p>Average Height: \" + data.results[0].average_height + \"</p><br>\" +\r\n \"<p>Skin Colors: \" + data.results[0].skin_colors + \"</p><br>\" +\r\n \"<p>Hair Colors: \" + data.results[0].hair_colors + \"</p><br>\" +\r\n \"<p>Eye Colors: \" + data.results[0].eye_colors + \"</p><br>\" +\r\n \"<p>Average Lifespan: \" + data.results[0].average_lifespan + \"</p><br>\" +\r\n \"<p>Language: \" + data.results[0].language + \"</p><br>\";\r\n for (var j = 0; data.results[0].people.length > j; ++j) {\r\n callExtraWebService(\"This Specie includes\", data.results[0].people[j], extraData);\r\n }\r\n }", "function recordsetDialog_searchDisplayableRecordset(SBRecordset,currentIndex) {\r\n\tvar cIdx = recordsetDialog.findPreferedType(SBRecordset);\r\n\tif (cIdx == -1) {\r\n\t\tcIdx = currentIndex;\r\n\t}\r\n\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[cIdx].serverModel) {\r\n\t\tif (recordsetDialog.canDialogDisplayRecordset(MM.rsTypes[cIdx].command, SBRecordset)) {\t\r\n\t\t\treturn cIdx;\r\n\t\t}\r\n\t}\r\n\tfor (ii = 0;ii < MM.rsTypes.length;ii++) {\r\n\t\tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[ii].serverModel) {\r\n\t\t\tif (recordsetDialog.canDialogDisplayRecordset(MM.rsTypes[ii].command, SBRecordset)) {\r\n\t\t\t\treturn ii;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the current word to the user.
function printWord() { $("#word").text(current_word.displayed_word); }
[ "function displayCurrentWord(){\n\t/** Change the html to the current word status */\n\tdocument.querySelector(\"#correctorGuess\").innerHTML = currentWordArray.join(\" \");\n}", "function printHint() {\n $('#hint').text(current_word.hint);\n}", "showWordProgress() {\n console.log(`The word now looks like this: ${this.currWord}`)\n }", "function wordInfo() {\n\n var word = prompt(\"What word are we looking at?\")\n\n console.log(\"Your word is: \" + word);\n\n length = word.length;\n\n console.log(\"Your word is \" + length + \" characters long\");\n\n thirdChar = word[3];\n\n console.log(\"The third character in your word is: \" + thirdChar);\n\n low = word.toLowerCase();\n\n console.log(\"lower case: \" + low);\n\n up = word.toUpperCase();\n\n console.log(\"UPPER CASE: \" + up);\n\n console.log(\"Example: Here's your |\" + word + \"| in a sentence... Don't worry, it doesn't need to make sense\") \n\n sub = word.slice(1,4);\n\n console.log(\"Sub-word: \" + sub);\n}", "function showWord(words) {\n const randIndex = Math.floor(Math.random() * words.length);\n currentWord.innerHTML = words[randIndex];\n}", "function displayWord(word) {\n splitWord = word.split(\"\");\n firstLetter = splitWord[0];\n $.each(splitWord, function (index) {\n $(\".word\").append(\n `<div class=\"letter-box b-neon-blue\" id=\"${index}\"></div>`\n );\n });\n }", "function printSentence() {\n if (this[\"isChallenging\"] === true && this[\"isRewarding\"] === true) {\n console.log(`Learning the programming languages: \"${this[\"languages\"].join(\", \")}\" is rewarding and challenging.`);\n } else {\n console.log(\"Hä?\")\n };\n}", "function printCommand(cmd) {\r\n\r\n\t// Get the command to show\r\n\tvar command = cmd || submit.value;\r\n\r\n\t// Pull from the global namespace\r\n\tterminal.innerHTML += Filesystem.user + '@' + Filesystem.host + ':' + Filesystem.path + '$ ' + command + '\\n';\r\n\r\n}", "function printDefinition() {\n $(\"#dictionaryDisplay\").removeClass(\"hide\");\n $(\"#dictionaryDisplay\").append(\"<p id='noun'> Noun: \" + noun + \"</p>\");\n $(\"#dictionaryDisplay\").append(\"<p id ='verb'> Verb: \" + verb + \"</p>\");\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adverb'> Adverb: \" + adverb + \"</p>\"\n );\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adjective'> Adjective: \" + adjective + \"</p>\"\n );\n }", "function printWin() {\n $('#hint').text(userString.winMessage).css(\"color\", \"#000000\");\n}", "function showCurrentWord() { \n var wordChoiceDiv = document.getElementById(\"wordChoices\");\n wordChoiceDiv.innerHTML = \"<div id=\\\"wordChoices\\\"></div>\"; // Clears the Div tag for each word\n console.log(currentWord); \n for (var i = 0; i < currentWord.length; i++) { // for every letter in the currentWord, type an underscore\n var newSpan = document.createElement(\"span\");\n newSpan.innerHTML= \"_ \";\n newSpan.setAttribute(\"id\",\"letter-\"+i);\n wordChoiceDiv.appendChild(newSpan); \n } \n }", "function showWord(word) {\n $($playedWords).append($(\"<li>\", { text: word }));\n}", "displayWord() {\n var string = \"\";\n\n for (var i = 0; i < this.lettersArr.length; i++) {\n var char = this.lettersArr[i].toString();\n string += char;\n };\n\n return string;\n }", "function lookAtMe()\n{\n\t// First, the variable newText is created to hold all of the required text to print.\n\tvar newText = \"\";\n\t// The player's basic information is concatenated into newText.\n\tnewText += yourAppearance[0];\n\t// Space is added.\n\tnewText += \"<br>\";\n\t// The player's current clothing is concatenated into newText.\n\tnewText += yourAppearance[1];\n\t// Space is added.\n\tnewText += \"<br>\";\n\t// The player's current damage is concatenated into newText.\n\tnewText += yourAppearance[2];\n\t// The total body of text is printed.\n\tprintText(newText);\n}", "function printPlayerWord() {\n document.getElementById(\"playerWord\").innerHTML = \"\";\n for (var i = 0; i < playerWord.length; i++) {\n document.getElementById(\"playerWord\").innerHTML += playerWord[i];\n }\n document.getElementById(\"guessed\").innerHTML = pastLetters;\n}", "function fillDisplayWord (letter) {\n\n}", "function addWord () {\n if (guide.choices().length > 0) {\n var choices = guide.choices();\n var choice = choices[Math.floor(Math.random() * choices.length)];\n guide.choose(choice);\n $scope.sentence += ' ' + choice;\n } else {\n $interval.cancel(sentenceInterval);\n if (guide.isComplete()) {\n $scope.sentence += '.'; // if complete, add period.\n }\n }\n }", "function outputWriter(word, occurence){\n\tvar displayedMessage = \"\\\"\" + word + \"\\\" appears \" + occurence + \" time(s)\";\n\tvar ul = document.getElementById(\"display\");\n\tvar li = document.createElement(\"li\");\n\tli.appendChild(document.createTextNode(displayedMessage));\n\tul.append(li);\n}", "function print() {\n document.write(\"atspaudintas su f-ja\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to clear the fileds
function ClearFields() { self.model.code = ""; self.model.component = ""; }
[ "function clear_form(){\n $(form_fields.all).val('');\n }", "function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }", "clearData(){\n //reset table data \n this.config.currentData = {};\n this.config.pageCount=1; //table page count (will calculating later)\n this.config.pageLimit=10; //table page limit\n this.config.tableData={};\n this.config.currentPage=1; //table current page\n this.config.currentData={}; //table current data\n\n //clean body\n this.config.body.innerHTML = '';\n //clean pagination\n this.config.pagination.innerHTML = '';\n }", "function clearForm() {\n form.reset();\n }", "function clearFields(){\n $('.addTrain').val('');\n $('.addDestination').val('');\n $('.addDepartTime').val('');\n $('.addTripTime').val('');\n }", "function clearDataForm() {\r\r\n $(\"#datInputDateTime\").val(\"\");\r\r\n $(\"#numTotalPeople\").val(\"\");\r\r\n}", "function clearInputs() {\n var i;\n controlElem.value = '';\n for (i = 0; i < dilutions.length; i += 1) {\n dilElems[i].value = '';\n }\n updateResults();\n }", "clearValidations() {\n this.validateField(null);\n setProperties(this, {\n '_edited': false,\n 'validationErrorMessages': [],\n validationStateVisible: false\n });\n }", "reset() {\n\t\t\t\tif (!isNone(fields)) {\n\t\t\t\t\t$(fields).each(function() {\n\t\t\t\t\t\t// reset parsley field.\n\t\t\t\t\t\t$(this).parsley().reset();\n\t\t\t\t\t\tif ($(this).is('form')) {\n\t\t\t\t\t\t\t$('form .form-control-feedback').remove();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}", "function clear() {\n resetStore();\n }", "function clearFormFields() {\n newTaskNameInput.value = \"\";\n newTaskDescription.value = \"\";\n newTaskAssignedTo.value = \"\";\n newTaskDueDate.value = \"\";\n newTaskStatus.value = \"\";\n}", "clearInputs() {\r\n titleBook.value = '';\r\n authorBook.value = '';\r\n isbnBook.value = ''; \r\n}", "static reset() {\n Document._definitions.delete(this)\n }", "function onClickReset() {\r\n cleanInputs();\r\n resetFieldsUi();\r\n}", "reset() {\n this.vertices = new Set();\n this.edges = new Set();\n this.faces = new Set();\n }", "function resetFields() {\n\n fields.forEach(field => {\n field.innerHTML = \"\";\n });\n\n}", "function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}", "function clearForm(){\n $('#cduForm')[0].reset();\n $( \"#uiuTable tr:gt(0)\").remove();\n uiu=[];\n}", "clear() {\n this.name = '';\n this.adj.clear();\n this.node.clear();\n clear(this.graph);\n }", "clearAllFilters() {\n this.currentFilters = []\n\n each(this.filters, filter => {\n filter.value = ''\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns bounding boxes of the selected regions.
getSelectedRegionsBounds() { const regions = this.lookupSelectedRegions().map((region) => { return { id: region.ID, x: region.x, y: region.y, width: region.boundRect.width, height: region.boundRect.height, }; }); return regions; }
[ "lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }", "function getBoundingBox() {\n var rect = self.getViewRect();\n \n return new T5.Geo.BoundingBox(\n T5.GeoXY.toPos(T5.XY.init(rect.x1, rect.y2), radsPerPixel),\n T5.GeoXY.toPos(T5.XY.init(rect.x2, rect.y1), radsPerPixel));\n }", "getSelectedRegions() {\r\n const regions = this.lookupSelectedRegions().map((region) => {\r\n return {\r\n id: region.ID,\r\n regionData: region.regionData,\r\n };\r\n });\r\n return regions;\r\n }", "function getRegionBounds(def) {\n var _getHistRange = getHistRange(def);\n\n var _getHistRange2 = _slicedToArray(_getHistRange, 2);\n\n var minRange = _getHistRange2[0];\n var maxRange = _getHistRange2[1];\n\n return [minRange].concat(def.dividers.map(function (div) {\n return div.value;\n }), maxRange);\n }", "function findBoundingBox() {\n\t\n\n\t//first locate center-of-mass, as starting location for boundary box sides... \n\tCOMx = 0\n\tCOMy = 0\n\ttotalPredicates = 0\n\tbiggestRadius = 0\n\n\t//If no predicates are selected find bound box for all predicates...\n\tif(selectedPredicates.length==0){\n\n\n\t\tfor(i=0;i<myPredicates.length;i++){\n\n\t\t\tCOMx += myPredicates[i].stageX\n\t\t\tCOMy += myPredicates[i].stageY\n\t\t\ttotalPredicates++\n\t\t\t\n\t\t}\n\n\t\tCOMx = COMx/totalPredicates\n\t\tboundaryLeft = boundaryRight = COMx\n\t\tCOMy = COMy/totalPredicates\n\t\tboundaryTop = boundaryBottom = COMy\n\t\t\n\n\t\t//go through predicates, expanding bounding box as necessary...\n\t\tfor(i=0;i<myPredicates.length;i++){\n\n\t\t\t//keep track of biggest radius\n\t\t\tif(myPredicates[i].radius>biggestRadius){\n\t\t\t\tbiggestRadius = myPredicates[i].radius\n\t\t\t}\n\n\t\t\t//expand bounding box if needed\n\t\t\tif(myPredicates[i].stageX<boundaryLeft){\n\t\t\t\tboundaryLeft = myPredicates[i].stageX\n\t\t\t}\n\t\t\tif(myPredicates[i].stageX>boundaryRight){\n\t\t\t\tboundaryRight = myPredicates[i].stageX\n\t\t\t}\n\t\t\tif(myPredicates[i].stageY<boundaryTop){\n\t\t\t\tboundaryTop = myPredicates[i].stageY\n\t\t\t}\n\t\t\tif(myPredicates[i].stageY>boundaryBottom){\n\t\t\t\tboundaryBottom = myPredicates[i].stageY\n\t\t\t}\n\t\t\t\n\t\t}\n\n\n\t//Otherwise find bounding box only for selected predicates...\n\t}else{\n\n\n\t\tfor(i=0;i<myPredicates.length;i++){\n\t\t\tif(myPredicates[i].selected){\n\t\t\t\tCOMx += myPredicates[i].stageX\n\t\t\t\tCOMy += myPredicates[i].stageY\n\t\t\t\ttotalPredicates++\n\t\t\t}\n\t\t}\n\n\t\tCOMx = COMx/totalPredicates\n\t\tboundaryLeft = boundaryRight = COMx\n\t\tCOMy = COMy/totalPredicates\n\t\tboundaryTop = boundaryBottom = COMy\n\t\t\n\n\t\t//go through predicates, expanding bounding box as necessary...\n\t\tfor(i=0;i<myPredicates.length;i++){\n\t\t\tif(myPredicates[i].selected){\n\n\n\n\t\t\t\t//keep track of biggest radius\n\t\t\t\tif(myPredicates[i].radius>biggestRadius){\n\t\t\t\t\tbiggestRadius = myPredicates[i].radius\n\t\t\t\t}\n\n\n\n\t\t\t\t//expand bounding box if needed\n\t\t\t\tif(myPredicates[i].stageX<boundaryLeft){\n\t\t\t\t\tboundaryLeft = myPredicates[i].stageX\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageX>boundaryRight){\n\t\t\t\t\tboundaryRight = myPredicates[i].stageX\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageY<boundaryTop){\n\t\t\t\t\tboundaryTop = myPredicates[i].stageY\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageY>boundaryBottom){\n\t\t\t\t\tboundaryBottom = myPredicates[i].stageY\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\n\n\t//find center of bounding box\n\tclusterCenterX = (boundaryRight+boundaryLeft)/2\n\tclusterCenterY = (boundaryBottom+boundaryTop)/2\n\n//Debugging visual for bounding box, cluster center...\n/*\n\tfill(255,0,0)\n\tellipse(clusterCenterX,clusterCenterY,20,20)\n\tstroke(0,0,255)\n\tnoFill()\n\trectMode(CORNERS)\n\trect(boundaryLeft-(150*globalScale),boundaryTop-(150*globalScale),boundaryRight+(150*globalScale),boundaryBottom+(150*globalScale))\n*/\n}", "function GetContentRegionAvail(out = new ImVec2()) {\r\n return bind.GetContentRegionAvail(out);\r\n }", "function getBoundsSearchFunction(boxes) {\n var index;\n if (!boxes.length) {\n // Unlike rbush, flatbush doesn't allow size 0 indexes; workaround\n return function() {return [];};\n }\n index = new Flatbush(boxes.length);\n boxes.forEach(function(ring) {\n var b = ring.bounds;\n index.add(b.xmin, b.ymin, b.xmax, b.ymax);\n });\n index.finish();\n\n function idxToObj(i) {\n return boxes[i];\n }\n\n // Receives xmin, ymin, xmax, ymax parameters\n // Returns subset of original @bounds array\n return function(a, b, c, d) {\n return index.search(a, b, c, d).map(idxToObj);\n };\n}", "getBlocksAABB() {\n // always include top left and available width to anchor the bounds\n let aabb = new Box2D(0, 0, this.sceneGraph.availableWidth, 0);\n // we should only autosize the nodes representing parts\n objectValues(this.parts2nodes).forEach((node) => {\n aabb = aabb.union(node.getAABB());\n // add in any part list items for this block\n const blockId = this.elementFromNode(node);\n objectValues(this.listNodes[blockId]).forEach((node) => {\n aabb = aabb.union(node.getAABB());\n });\n });\n // add any nested constructs\n objectValues(this.nestedLayouts).forEach((layout) => {\n aabb = layout.getBlocksAABB().union(aabb);\n });\n return aabb;\n }", "selectAllRegions() {\r\n let r = null;\r\n for (const region of this.regions) {\r\n r = region;\r\n r.select();\r\n if ((typeof this.callbacks.onRegionSelected) === \"function\") {\r\n this.callbacks.onRegionSelected(r.ID);\r\n }\r\n }\r\n if (r != null) {\r\n this.menu.showOnRegion(r);\r\n }\r\n }", "function getBoundingBox() {\n if (!bounds) { return } // client does not want to restrict movement\n\n if (typeof bounds === 'boolean') {\n // for boolean type we use parent container bounds\n var sceneWidth = owner.clientWidth;\n var sceneHeight = owner.clientHeight;\n\n return {\n left: sceneWidth * boundsPadding,\n top: sceneHeight * boundsPadding,\n right: sceneWidth * (1 - boundsPadding),\n bottom: sceneHeight * (1 - boundsPadding),\n }\n }\n\n return bounds\n }", "generateBoundingBox() {\n this.n = parseFloat(waypoints[0].lat);\n this.s = parseFloat(waypoints[0].lat);\n this.e = parseFloat(waypoints[0].lon);\n this.w = parseFloat(waypoints[0].lon);\n for (let i = 1; i < waypoints.length; i++) {\n\n if (waypoints[i].lat > this.n) {\n this.n = parseFloat(waypoints[i].lat);\n }\n\t else if (waypoints[i].lat < this.s) {\n this.s = parseFloat(waypoints[i].lat);\n }\n if (waypoints[i].lon > this.e) {\n this.e = parseFloat(waypoints[i].lon);\n }\n\t else if (waypoints[i].lon < this.w) {\n this.w = parseFloat(waypoints[i].lon);\n }\n }\n\n // creating the polylines for the bounding box\n \n // if square bounding box is not selected, then the quadtree\n // will be split as a rectangle\n let nEnds = [[this.n,this.w],[this.n,this.e]];\n let sEnds = [[this.s,this.w],[this.s,this.e]];\n let eEnds = [[this.n,this.e],[this.s,this.e]];\n let wEnds = [[this.n,this.w],[this.s,this.w]];\n \n if (document.getElementById(\"squareBB\").checked) {\n const EW = distanceInMiles(nEnds[0][0],nEnds[0][1],nEnds[1][0],nEnds[1][1]);\n const NS = distanceInMiles(eEnds[0][0],eEnds[0][1],eEnds[1][0],eEnds[1][1]);\n let difference;\n //check if the difference between the east west is longer than the north south\n if (EW > NS) {\n difference = (EW - NS) / 69;\n this.n += difference / 2;\n this.s -= difference / 2;\n\n }\n\t else {\n difference = (NS - EW) / (Math.cos(Math.abs(this.n - this.s) / 2) * 69);\n this.e += difference / 2;\n this.w -= difference / 2;\n }\n\n nEnds = [[this.n,this.w],[this.n,this.e]];\n sEnds = [[this.s,this.w],[this.s,this.e]];\n eEnds = [[this.n,this.e],[this.s,this.e]];\n wEnds = [[this.n,this.w],[this.s,this.w]];\n }\n this.boundingPoly.push(\n L.polyline(nEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(sEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(eEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(wEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n }) \n );\n\t\n for (let i = 0; i < 4; i++) {\n this.boundingPoly[i].addTo(map);\n }\n }", "static childBounds(svgElement) {\n var result \n svgElement.childNodes.forEach(ea => {\n var r = ea.getBoundingClientRect() \n var b = rect(r.x, r.y, r.width, r.height)\n result = (result || b).union(b)\n })\n return result\n }", "function _getBoundingBox(feature) {\n if (!feature.bbox) {\n return;\n }\n return {\n south: feature.bbox[0],\n west: feature.bbox[1],\n north: feature.bbox[2],\n east: feature.bbox[3]\n };\n}", "function getLabelBBox(textWidth, textHeight, align, baseline, angle, margin){\n \n var polygon = getLabelPolygon(textWidth, textHeight, align, baseline, angle, margin);\n var corners = polygon.corners();\n var bbox;\n if(angle === 0){\n var min = corners[2]; // topLeft\n var max = corners[1]; // bottomRight\n \n bbox = new pvc.Rect(min.x, min.y, max.x - min.x, max.y - min.y);\n } else {\n bbox = polygon.bbox();\n }\n \n bbox.sourceCorners = corners;\n bbox.sourceAngle = angle;\n bbox.sourceAlign = align;\n bbox.sourceTextWidth = textWidth;\n \n return bbox;\n }", "set boundingBoxMode(value) {}", "function BoundingBox() {\n this._internalModel = new BoundingBoxFilterModel();\n}", "createRangeBySelectedCells() {\n const sq = this.wwe.getEditor();\n const range = sq.getSelection().cloneRange();\n const selectedCells = this.getSelectedCells();\n const [firstSelectedCell] = selectedCells;\n const lastSelectedCell = selectedCells[selectedCells.length - 1];\n\n if (selectedCells.length && this.wwe.isInTable(range)) {\n range.setStart(firstSelectedCell, 0);\n range.setEnd(lastSelectedCell, lastSelectedCell.childNodes.length);\n sq.setSelection(range);\n }\n }", "getBoundingBoxes() {\n const { data } = this.state;\n const facesToPercentage = [];\n\n for (let i = 0; i < data.length; i += 1) {\n const top = data[i].top_row * 100;\n const left = data[i].left_col * 100;\n const bottom = data[i].bottom_row * 100;\n const right = data[i].right_col * 100;\n\n const box = {\n top, left, bottom, right,\n };\n\n facesToPercentage.push(box);\n }\n\n this.setState({\n data: facesToPercentage,\n });\n }", "deleteSelectedRegions() {\r\n const collection = this.lookupSelectedRegions();\r\n for (const region of collection) {\r\n this.deleteRegion(region);\r\n }\r\n this.selectNextRegion();\r\n if (this.callbacks.onManipulationEnd !== null) {\r\n this.callbacks.onManipulationEnd();\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
using the inventory array of objects, we apply a callback to inventory with Array.map. This will apply the getGoodsFromDesigner function as a callback, that callback will go over the key/value pairs and return all the designer's shoes on new lines.
function listInventory(inventory){ return inventory.map(function(designerObject){ return getGoodsFromDesigner(designerObject) }).join('\n'); }
[ "function renderInventory(inventory){\n return inventory.map(function(designerObject){\n return renderGoodsStringForDesigner(designerObject)\n }).join('\\n');\n}", "function getGoodsFromDesigner(designerObject){\n return getShoesFromDesigner(designerObject.name, designerObject.shoes).join('\\n');\n}", "function getShoesFromDesigner(designerName, listOfShoes){\n return shoeList.map(function(shoe){\n return [designerName, shoe.name, shoe.price].join(', ';)\n });\n}", "function renderShoesForDesigner(designer, shoeList){\n return shoeList.map(function(shoe){\n return [designer, shoe.name, shoe.price].join(', ')\n });\n}", "function renderGoodsStringForDesigner(designerObject){\n return renderShoesForDesigner(designerObject.name, designerObject.shoes).join('\\n')\n}", "function renderInventory() {\n\tconsole.log(\"Rendering inventory\");\n\tpopulateDistributors();\n\tpopulateInventory();\n}", "function updateInventory(){\n console.log(\"updating inventory...\");\n debugLog += \"updating inventory... \"+ '\\n';\n for(var i = 0; i < soldItems.length; i++){\n var indexOfMatchingBarcodes = [];\n var matchFound = false;\n var sellingItem = soldItems[i];\n var sellingBarcode = sellingItem[3];\n var sellingQTY = sellingItem[4];\n console.log(\"removing item \" + sellingBarcode + \" in the amount of \"+ sellingQTY);\n debugLog += \"removing item \" + sellingBarcode + \" in the amount of \"+ sellingQTY + '\\n';\n \n var invItem;\n for(var j = 0; j < inventory.length; j++){\n invItem = inventory[j]\n if(invItem[invUPCCol] === sellingBarcode){ //barcode match\n matchFound = true;\n indexOfMatchingBarcodes.push(j);\n }\n }\n //check if there was more than one match, if so, also match on size & color fields\n if(matchFound){\n var barcodeMatchItem;\n if(indexOfMatchingBarcodes.length == 1){\n barcodeMatchItem = inventory[indexOfMatchingBarcodes[0]];\n console.log(\"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode);\n debugLog += \"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + '\\n';\n barcodeMatchItem[invQtyCol]-=sellingQTY; //reduce inventory by QTY of sold item \n console.log(\"Item now has quantity: \" + barcodeMatchItem[invQtyCol]);\n debugLog += \"Item now has quantity: \" + barcodeMatchItem[invQtyCol] + '\\n';\n }\n else{\n //check that the barcodeMatchItem matches other fields of sellingItem (we already know barcode is a match)\n for(var k = 0; k < indexOfMatchingBarcodes.length; k++){\n console.log(\"Found \" + indexOfMatchingBarcodes.length + \" matching barcodes, narrowing search\");\n debugLog += \"Found \" + indexOfMatchingBarcodes.length + \" matching barcodes, narrowing search\" + '\\n';\n barcodeMatchItem = inventory[indexOfMatchingBarcodes[k]];\n if(barcodeMatchItem[invSzCol] === sellingItem[2] && barcodeMatchItem[invColorCol] === sellingItem[1]){\n console.log(\"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + \"and matches other fields\");\n debugLog += \"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + \"and matches other fields\" + '\\n';\n barcodeMatchItem[invQtyCol]-=sellingQTY; //reduce inventory by QTY of sold item \n console.log(\"Item now has quantity: \" + barcodeMatchItem[invQtyCol]);\n debugLog += \"Item now has quantity: \" + barcodeMatchItem[invQtyCol] + '\\n';\n }\n }\n }\n }\n else{\n console.log(\"Couldn't find match for \" + soldItems[i][3]);\n debugLog += \"Couldn't find match for \" + soldItems[i][3] + '\\n';\n }\n matchFound = false;\n indexOfMatchingBarcodes = [];\n }\n console.log(inventory);\n console.log(\"inventory successfully updated\");\n debugLog += \"inventory successfully updated\" + '\\n';\n writeInventory();\n }", "function allInventory() {\n\n\t//Connection to Mysql to request data\n\tconnection.query(\"SELECT * FROM bamazon_db.products\", function(err, res) {\n\t\tif (err) throw err;\n\n\t\tvar t = new Table;\n\n\t\t//Organize inventory using easy-table\n\t\tres.forEach(function(product) {\n\t\t\tt.cell('Product Id', product.id)\n\t\t\tt.cell('Description', product.product)\n\t\t\tt.cell('Price', product.price)\n\t\t\tt.cell('Quantity', product.quantity)\n\t\t\tt.newRow()\n\t\t})\n\n\t\t//Display inventory in easy-table\n\t\tconsole.log(\"\\n\")\n\t\tconsole.log(t.toString())\n\n\t\t//Returns to top of manager block\n\t\tmanage();\n\t\t}\n\t)\n}", "function processResults(prod_list, inventory_list, name) {\n\n\tvar master_list = [];\n\n\tconsole.log(\"prod_list is \" + prod_list);\n\tconsole.log(\"inventory_list is \" + inventory_list);\n\tif (validateResults(prod_list, inventory_list, name) == false) {\n\t\treturn master_list;\n\t}\n\n\tfor (i = 0; i < prod_list.length; i++) {\n\t\tfor(j = 0; j < inventory_list.length; j++) {\n\t\t\tif (prod_list[i]['name'] == inventory_list[j]['name']){\n\t\t\t\tmaster_list[i] = prod_list[i];\n\t\t\t\tmaster_list[i]['inventory'] = inventory_list[j]['inventory'];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn master_list;\n}", "function createInventory(){\n\treturn {};\n}", "function lookAtInventory()\n{\n\t// First, the variable newText is created to hold all of the required text to print.\n\tvar newText = \"\";\n\t// If there's anything in the inventory:\n\tif ((inventory !== undefined) && (inventory.length > 0)) {\n\t\t// Append the beginning of the inventory readout.\n\t\tnewText += \"You're carrying | \";\n\t\t// One by one, the items in the inventory are appended to newText.\n\t\tfor (var obj in inventory)\n\t\t{\n\t\t\t// If that item belongs to the array and not the prototype:\n\t\t\tif (inventory.hasOwnProperty(obj))\n\t\t\t{\n\t\t\t\t// Append that item's name to the description text.\n\t\t\t\tnewText += (inventory[obj].ident + \" | \");\n\t\t\t}\n\t\t}\n\t// Otherwise, print that the player is carrying nothing.\n\t} else {\n\t\tnewText += \"You're not carrying anything with you.\"\n\t}\n\t// To conclude, the total body of text is printed.\n\tprintText(newText);\n}", "renderLineItems(invoiceLineItems) {\n if (invoiceLineItems && invoiceLineItems.length) {\n return invoiceLineItems.map(({ _id, description, amount }) => {\n return (\n <li key={_id}>\n Item Description: {description} <br />\n Item Amount: ${amount}\n </li>\n );\n });\n } else {\n return;\n }\n }", "getShoe(save) {\n if (save == null)\n return null;\n let shoe = _.cloneDeep(save)\n let base = data.shoes[shoe.id];\n shoe.name = base.name;\n shoe.icon = base.icon\n shoe.legProtection = base.legProtection;\n shoe.modifierText = []\n shoe.flags = [];\n\n // vanity prefixes/suffixes in name\n let prefixes = []\n let suffixes = []\n\n for (let x in shoe.modifiers) {\n let mod = data.modifiers[shoe.modifiers[x].id];\n let values = [];\n\n switch (shoe.modifiers[x].suffix) {\n case false: {\n prefixes.push(mod.prefix)\n break;\n }\n case true: {\n suffixes.push(mod.suffix)\n break;\n }\n }\n\n for (let z in mod.flags) {\n shoe.flags.push(mod.flags[z])\n }\n\n for (let z in mod.statMods) {\n let value = this.getValue(mod, z, shoe.modifiers[x].quality)\n if (mod.statMods[z].percentage != undefined) {\n value *= 100;\n }\n values.push(utils.round(value, 2))\n }\n\n // format header\n let text = mod.description.format(...values)\n // {\"{0} - {1}\".format(mod.name, text)}\n shoe.modifierText.push(<p key={x+1}><b>{mod.name}</b>{\" - \"}{text}{\" ({0}% Quality)\".format(utils.round(shoe.modifiers[x].quality * 100, 0))}</p>)\n // shoe.modifierText.push(<p key={-x}>{\"Quality: {0}%\".format(utils.round(shoe.modifiers[x].quality * 100, 2))}</p>)\n }\n\n let prefixedName = \"\";\n let suffixedName = \"\";\n\n for (let x in prefixes) {\n prefixedName += prefixes[x] + \" \"\n }\n for (let x in suffixes) {\n suffixedName += \" \" + suffixes[x]\n }\n\n shoe.name = prefixedName + shoe.name + suffixedName;\n\n shoe.modifierText.push(<p key={-2000}>{\"Leg Protection: {0}%\".format(utils.round(shoe.legProtection * 100, 2))}</p>)\n\n return shoe;\n }", "function BuildMfgReportSupplyLevels(data) {\n // NOTIFY PROGRESS\n console.log('building mfg report supply levels', data);\n // DEFINE LOCAL VARIABLES\n var supplies = data.supplies;\n var orders = data.orders;\n\n // ZERO OUT SUPPLIES\n Object.keys(supplies).forEach(function(supplyKey) {\n supplies[supplyKey].qty = 0;\n });\n\n // ITERATE OVER ORDERS\n Object.keys(orders).forEach(function(orderKey) {\n\n // LOCAL VARIABLES\n var sku = orders[orderKey].sku;\n\n // ITERATE OVER UPDATES - CONSUMED MATERIALS\n Object.keys(orders[orderKey].updates).forEach(function(updateKey) {\n\n // REFLECT THE UPDATES\n supplies[updateKey].qty += orders[orderKey].updates[updateKey];\n //console.log(updateKey, orders[orderKey].updates[updateKey]);\n });\n\n // ADDRESS PRODUCED MATERIALS\n if(sku == \"330SSPCN\" || sku == \"360SSHZL\" || sku == \"360SSALM\" || sku == \"320SSCSH\" || sku == \"400SSPNT\" || sku == \"330BNPCN\" || sku == \"360BNHZL\" || sku == \"360BNALM\") {\n supplies[sku].qty += orders[orderKey].qty\n }\n \n });\n\n // UPDATE PRODUCED\n\n\n // RETURN\n return supplies;\n }", "updatedShelf(shelf, author) {\n return shelf.map( (elem) => {\n return this.bookFromAuthorData(elem, author)\n })\n }", "function displayInventory() {\n queryString = \"SELECT * FROM products\";\n\n // db query\n db.query(queryString, function(err, data) {\n if (err) throw err;\n console.log(chalk.bgGreen.white(\"Current Inventory:\"));\n console.log(\".................\\n\");\n\n var stringOutPut = \"\";\n for (var i = 0; i < data.length; i++) {\n stringOutPut = \"\";\n stringOutPut += chalk.red(\"Item ID: \") + data[i].item_id + \" // \";\n stringOutPut +=\n chalk.red(\"Product Name: \") + data[i].product_name + \" // \";\n stringOutPut += chalk.red(\"Department: \") + data[i].department_name + \" // \";\n stringOutPut += chalk.red(\"Price: \") + '$' + data[i].price + \"\\n\";\n\n console.log(chalk.yellow(stringOutPut));\n }\n console.log(\"--------------------------------------------\\n\");\n\n // Prompt the user for item/quantity they would like to purchase\n purchasePrompt();\n });\n}", "function createInventoryItemsUI(inventory) {\n invBtns = [];\n invBtnSelectedIndex = 0;\n inv2ndBtns = [];\n inv2ndBtnSelectedIndex = 0;\n inventoryGrid.innerHTML = \"\";\n secondaryInventoryGrid.innerHTML = \"\";\n if (inventory.owner == \"chest\" && inventory.contents.length == 0) {\n hideInventory(true);\n return;\n }\n if (inventory.owner == \"merchant\" || (inventory.owner == \"player\" && merchantObj.playerActive)) {\n invPrice.style.display = \"flex\";\n } else {\n invPrice.style.display = \"none\";\n }\n let questButtons = [];\n for (let i = 0; i < inventory.contents.length; i++) {\n const content = inventory.contents[i];\n const btn = inventoryItemButton(inventory, content);\n if (btn.classList.contains(\"quest-item\")) {\n questButtons.push(btn);\n } else {\n inventoryGrid.append(btn);\n }\n }\n //Place quest items last in the inventory\n if (questButtons.length > 0) {\n for (let i = 0; i < questButtons.length; i++) {\n const questButton = questButtons[i];\n inventoryGrid.append(questButton);\n }\n }\n buttonsUpdate();\n if (inventory.contents.length > 0) {\n setInventoryHoverInfo(inventory.contents[0].item);\n }\n }", "function getDetails(money) {\n // let salePriceArray = Object.values(sale);\n // let saleItemArray = Object.keys(sale);\n\n for (let i = 0; i < sale.length; i++) {\n if (money >= sale[i].harga) {\n money -= sale[i].harga;\n purchasedItems.push(sale[i].merk);\n }\n }\n\n return money;\n }", "function zooInventory(zoo){\n let finalArr = [];\n myZoo.forEach((animal)=>{\n let tempAnimalString = `${animal[0]} the ${animal[1][0]} is ${animal[1][1]}.`;\n finalArr.push(tempAnimalString);\n })\n return finalArr;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds data to new node at end of list If list is empty, create new node and as head
append(data) { if (this.head == null) { this.head = new Node(data); return; } let currentNode = this.head; while (currentNode.next != null) { currentNode = currentNode.next; } currentNode.next = new Node(data); }
[ "addAfter(key, data) {\n if (this.head == null) return;\n\n let currentNode = this.head;\n while (currentNode != null && currentNode.data != key) {\n currentNode = currentNode.next;\n }\n\n if (currentNode) {\n let tempNode = currentNode.next;\n currentNode.next = new Node(data);\n currentNode.next.next = tempNode;\n return;\n }\n }", "addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }", "addToTail(value) {\n const newNode = {\n value: value,\n next: null\n };\n\n if (!this.head && !this.tail) {\n this.head = newNode;\n this.tail = newNode;\n return;\n }\n this.tail.next = newNode;\n this.tail = newNode;\n }", "addBefore(key, data) {\n if (this.head == null) return;\n \n let currentNode = this.head;\n let prevNode = null;\n\n while (currentNode != null && currentNode.data != key) {\n prevNode = currentNode;\n currentNode = currentNode.next;\n }\n\n if (currentNode) {\n let tempNode = new Node(data);\n tempNode.next = currentNode;\n if (prevNode) {\n prevNode.next = tempNode;\n } else {\n this.head = tempNode;\n }\n return;\n }\n }", "push (value) {\n var node = new Node(value)\n var currentNode = this.head\n\n // 1st use-case: an empty list\n if (!currentNode) {\n this.head = node\n this.length++\n return node\n }\n\n // 2nd use-case: a non-empty list\n while (currentNode.next) {\n currentNode = currentNode.next\n }\n\n currentNode.next = node\n this.length++\n\n return node\n }", "prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }", "addToBack(value){\n let newNode = new DLNode(value);\n if(this.isEmpty()){\n this.tail = newNode;\n this.head = newNode;\n return this;\n }\n\n newNode.prev = this.tail;\n this.tail.next = newNode;\n this.tail = newNode;\n return this;\n }", "addToBack(value) {\n var newNode = new SLLNode(value);\n\n if (this.head == null) {\n this.head = newNode;\n return;\n }\n\n var runner = this.head;\n\n while (runner.next != null) {\n // console.log(runner.value)\n runner = runner.next;\n }\n runner.next = newNode;\n }", "insert() {\n let newNode = new Node(1);\n newNode.npx = XOR(this.head, null);\n // logic to update the next pointer of the previous element once the next element is being set.\n\n // (null ^ 1)^ null will nullify null and the output will be 1\n if(this.head !== null) {\n let next = XOR(this.head.npx, null);\n this.head.npx = XOR(newNode, next)\n }\n\n // change the head node to the last node\n this.head = newNode;\n }", "insertAfter(value, newVal) {\n let current = this.head;\n\n while(current) {\n if (current.value === value) {\n let node = new Node(newVal);\n node.next = current.next;\n current.next = node;\n return;\n } \n current = current.next;\n }\n }", "function addOne(dataItem, data) {\n var last = data[data.length - 1];\n dataItem.id = last.id + 1;\n data.push(dataItem);\n return dataItem;\n }", "setTail(node) {\n if (!this.tail) {\n this.head = node;\n this.tail = node;\n } else {\n node.prev = this.tail;\n this.tail = node;\n }\n }", "_addList(list) {\n let head = rdf.nil;\n\n const prefix = \"list\" + (++this.counters.lists) + \"_\";\n\n for (let i = list.length - 1 ; i >= 0 ; --i) {\n let node = N3.DataFactory.blankNode(prefix + (i + 1));\n //this._addQuad(node, rdf.type, rdf.List);\n this._addQuad(node, rdf.first, list[i]);\n this._addQuad(node, rdf.rest, head);\n\n head = node;\n }\n\n return head;\n }", "function addBack (value, sList) {\n let node = new SLNode(value); // first contruct our new node from the value\n let current = sList.head;\n if (current === null) { // if list is empty, we simply set head to our node\n current = node;\n } else {\n while (current.next) { // otherwise, we traverse list until the last node\n current = current.next;\n }\n current.next = node; // then set the last node's next pointer to the new node\n }\n return sList;\n}", "prependDataBeforeVal(val, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner.data === val){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }", "append(node) {\n\n // Checks if argument is a node:\n if (node instanceof YngwieNode) {\n\n // If given node has parent, detach that node from it's parent:\n if (node._parent) {\n node.detach();\n }\n\n // Set new node as last sibling:\n if (this._first !== undefined) {\n node._prev = this._last; // Sets new last child's previous node to old last node\n this._last._next = node; // Set old last child next element to new last child\n this._last = node; // Set new last child to given node\n } else {\n // If ther are no children, then this node is an only child:\n this._first = node;\n this._last = node;\n }\n\n // Set parent\n node._parent = this;\n\n // Return instance:cosnole\n return this;\n\n }\n\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_0__.default(\"Can only apppend YngwieNode to other YngwieNodes\", node);\n\n }", "function populateTree(data) {\n for (let n=0;n<data.children.length;n++) {\n populateTree(data.children[n]);\n }\n console.log(\"adding node:'\"+ data.name + \"' id:\"+data.id);\n nodeListByName[data.name]=data.id;\n}", "_addToLists(list) {\n const listObj = {\n index: this.lists.length,\n name: list.getAttribute('name'),\n element: list,\n editable: this.isEditable(list),\n };\n if(this.lists.length === 0) this.activeList = listObj;\n this.lists.push(listObj);\n }", "function populateRankList(node, ranklist) {\n //console.log(node.r.toLowerCase());\n node.listPosition = ranklist[node.r.toLowerCase()].length;\n ranklist[node.r.toLowerCase()].push(node);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get child that is in visible in this tree
getChildInTree() { if (!this._children || this._children.length === 0) return null; for (var ch of this._children) { if (ch.isStartingPerson) return ch; if (ch.getChildInTree()) return ch; } return null; }
[ "function areChildrenVisible(item) {\n // we do not want to populate item with \n if (typeof item.ChildrenVisible != \"undefined\") {\n return item.ChildrenVisible;\n } else {\n return true;\n }\n }", "_getAriaActiveDescendant() {\n return this._useActiveDescendant ? this._listKeyManager?.activeItem?.id : null;\n }", "isVisible() {\n return this.toolbar.is(\":visible\");\n }", "function findAndGetChild(childName, parent) {\n for (var _i = 0, _a = parent.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.name === childName) {\n return child;\n }\n }\n return null;\n}", "getTopColumn(){\n\t\tif(this.parent.isGroup){\n\t\t\treturn this.parent.getTopColumn();\n\t\t}else{\n\t\t\treturn this;\n\t\t}\n\t}", "getLayerVisibility(layer) {\r\n return this.layerVisibility[layer];\r\n }", "getMenuElement () {\n // NOTE non-standard jquery \":has\" selector here\n // 10207 is \"View Cell History\"\n var menuElem = $('div.clsPopupMenu:has(tr[data-client-id=\"10207\"])')\n if (menuElem.length > 0) {\n return menuElem.get(0)\n }\n // note callers will check to see if the menu element is in the DOM so null is an acceptable response here:\n return null\n }", "function setChildrenVisibleState(item) {\n if (typeof item.ChildrenVisible == \"undefined\" || item.ChildrenVisible) {\n item.ChildrenVisible = false;\n } else {\n item.ChildrenVisible = true;\n }\n }", "reverseVisibility(){\n for(let i = 0; i < this.children[2].children.length; i++){\n this.children[2].children[i].visible = !this.children[2].children[i].visible;\n }\n }", "function isExpandedView(entryTarget)\n{\n return $(entryTarget).parent().hasClass(\"cards\");\n}", "parentEditable() {\n var parent = this.parent();\n var editable = false;\n\n while (parent) {\n if (parent.getAttribute('contenteditable') == 'true' &&\n parent.getAttribute(this.config.attribute.plugin) == this.config.attribute.plugin) {\n editable = parent;\n break;\n }\n\n parent = parent.parentElement;\n }\n\n return editable;\n }", "function getFirstVisibleRect(element) {\n // find visible clientRect of element itself\n var clientRects = element.getClientRects();\n for (var i = 0; i < clientRects.length; i++) {\n var clientRect = clientRects[i];\n if (isVisible(element, clientRect)) {\n return {element: element, rect: clientRect};\n }\n }\n // Only iterate over elements with a children property. This is mainly to\n // avoid issues with SVG elements, as Safari doesn't expose a children\n // property on them.\n if (element.children) {\n // find visible clientRect of child\n for (var j = 0; j < element.children.length; j++) {\n var childClientRect = getFirstVisibleRect(element.children[j]);\n if (childClientRect) {\n return childClientRect;\n }\n }\n }\n return null;\n}", "async getChildLocationAncestor(ID) {\r\n // Determine the ID if not present\r\n const isNewID = ID != undefined;\r\n if (ID == undefined)\r\n ID = this.getData().ID;\r\n // Obtain this module's path, and child's path\r\n const path = this.getData().path || [];\r\n const childPath = isNewID ? [...path, ID] : path;\r\n // Request the location\r\n const locationAncestor = (await this.request({\r\n type: locationAncestor_type_1.LocationAncestorType,\r\n use: providers => {\r\n // Get the index of this module class\r\n const nextIndex = childPath.length;\r\n // Get the module with the next (lower priority) index\r\n const provider = providers[nextIndex].provider;\r\n return [provider];\r\n },\r\n data: {\r\n ID: ID,\r\n path: childPath,\r\n },\r\n }))[0];\r\n // Make sure to initialise the correct state\r\n if (this.state.inEditMode)\r\n locationAncestor.setEditMode(true);\r\n if (this.state.inDropMode)\r\n locationAncestor.setDropMode(true);\r\n // Return the ancestor\r\n return locationAncestor;\r\n }", "findSelectableElement(event) {\n const path = event.composedPath();\n for (let i = 0; i < path.length; i += 1) {\n const element = path[i];\n if (element === this) {\n return;\n }\n if (this.isSelectableElement(element)) {\n return element;\n }\n }\n }", "child(root, index) {\n if (Text.isText(root)) {\n throw new Error(\"Cannot get the child of a text node: \".concat(JSON.stringify(root)));\n }\n\n var c = root.children[index];\n\n if (c == null) {\n throw new Error(\"Cannot get child at index `\".concat(index, \"` in node: \").concat(JSON.stringify(root)));\n }\n\n return c;\n }", "function getChildByName(node,name){return node.getChildMeshes(false,function(n){return n.name===name;})[0];}// Look through only immediate children. This will return null if no mesh exists with the given name.", "getVisibility() {\n errors.throwNotImplemented(\"getting visibility (dequeue options)\");\n }", "function getToggledIndex() {\n var i = 0;\n for (var obj of children) {\n if (typeof obj.isToggled != \"undefined\" && obj.isToggled())\n return i;\n i += 1;\n }\n return -1;\n }", "async getVisibility(location, ...args) {\n return this.use().getVisibility(location, ...args);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loops through all the items accessible through the iterator and tells them to accept a visitor, if they know how to do so. If they don't, they are IGNORED! no return value.
function Iterator_iterateVisitor(objVisitor) { var strRoutine = "Iterator_iterateVisitor"; var strAction = ""; try { //check that what we were passed is really a visitor? strAction = "loop through the current items provided by this iterator"; for (this.first(); !this.isDone(); this.next()) { strAction = "calling currentItem on iterator"; var objCurrentItem = this.currentItem(); strAction = "checking if acceptVisitor method is defined for this item"; if (objCurrentItem.acceptVisitor != undefined) { strAction = "calling accept visitor on currentItem"; objCurrentItem.acceptVisitor(objVisitor); } //end if this item can accept visitors } //next currentItem } //end try catch (e) { this.errors.add(this.module, strRoutine, strAction, e); throw new Error(strRoutine + " failed"); } //end catch } //end function Iterator_iterateVisitor
[ "each(visitor, context) {\n return this.items.forEach(visitor, context);\n }", "accept(visitor, params) {\n throw new Error('Not Supported');\n }", "visitCollection_item(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "iterate(enter, leave) {\n for (let depth = 0; ; ) {\n let mustLeave = false\n if (this.type.isAnonymous || enter(this) !== false) {\n if (this.firstChild()) {\n depth++\n continue\n }\n if (!this.type.isAnonymous) mustLeave = true\n }\n for (;;) {\n if (mustLeave && leave) leave(this)\n mustLeave = this.type.isAnonymous\n if (this.nextSibling()) break\n if (!depth) return\n this.parent()\n depth--\n mustLeave = true\n }\n }\n }", "function visitAllMethods(visitor) {\r\n\r\n var classes = clover.pageData.classes;\r\n for (var i = 0; i < classes.length; i++) {\r\n var classData = classes[i];\r\n var methods = classData.methods;\r\n for (var j = 0; j < methods.length; j++) {\r\n var method = methods[j];\r\n visitor(method);\r\n }\r\n }\r\n}", "function visitAllClasses(visitor) {\r\n for (var i = 0; i < clover.pageData.classes.length; i++) {\r\n var classData = clover.pageData.classes[i];\r\n visitor(classData);\r\n }\r\n}", "applyNodeFilters(name: string, node: NodeInterface): NodeInterface {\n return this.filters.reduce((nextNode, filter) => {\n // Allow null to be returned\n if (nextNode && typeof filter.node === 'function') {\n return filter.node(name, nextNode);\n }\n\n return nextNode;\n }, node);\n }", "visitIncluding_or_excluding(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIn_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModel_iterate_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function traverseNoKeys (nodePath, visitor, state, skipKeys) {\n visitors.explode(visitor);\n return traverse.node(nodePath.node, visitor, nodePath.scope, state, nodePath, skipKeys);\n}", "visitYield_arg(ctx) {\r\n console.log(\"visitYield_arg\");\r\n if (ctx.FROM() !== null) {\r\n return [this.visit(ctx.test())];\r\n } else {\r\n return this.visit(ctx.testlist());\r\n }\r\n }", "function walkNodes ($nodes, currentItem) {\n $nodes.each(function (i, node) {\n var $node = $(node);\n var props = splitUnique($node.attr('itemprop'));\n\n if (props && currentItem) {\n var value = null;\n if ($node.is('[itemscope]')) {\n value = parseItem(node, currentItem);\n } else {\n value = parsePropertyValue(node);\n walkNodes($node.children(), currentItem);\n }\n currentItem.addProperties(props, value);\n } else if ($node.is('[itemscope]') && !$node.is('[itemprop]')) {\n var newItem = parseItem(node, currentItem);\n if (newItem !== Item.ERROR) {\n items.push(newItem);\n }\n } else {\n walkNodes($node.children(), currentItem);\n }\n });\n }", "function check_generator(obj) {\r\n return typeof(obj) == 'object' && typeof(obj.next) == 'function'; \r\n }", "visitNested_item(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitFor_each_row(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "forEach(cb) {\n for (var item = this._head; item; item = item.next) {\n cb(item.data);\n }\n }", "visitIdentified_by(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function any( iterable )\n {\n var res = false;\n \n foreach(function (x)\n {\n if ( x )\n {\n res = true;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
expand one level of tree
function expand1Level(d) { var q = [d]; // non-recursive var cn; var done = null; while (q.length > 0) { cn = q.shift(); if (done !== null && done < cn.depth) { return; } if (cn._children) { done = cn.depth; cn.children = cn._children; cn._children = null; cn.children.forEach(collapse); } if (cn.children) { q = q.concat(cn.children); } } // no nodes to open }
[ "function expandAll(d) {\n root.children.forEach(expand);\n update(root);\n }", "function propagateExpanded(data, state) {\n data.data.expanded = state;\n data.children.forEach(child => propagateExpanded(child, state));\n }", "function MoveUpOneLevel()\r\n{\r\n var treeFrame = GetTreeFrame();\r\n var selectedNode = treeFrame.getSelectedTreeNode();\r\n if(selectedNode != null) //tree could be expanded but no node selected\r\n {\r\n var parentNode = selectedNode.getParent();\r\n if(parentNode != null) //check we are not at the top of the tree\r\n {\r\n var parentTag = parentNode.getTag();\r\n treeFrame.setSelectedTreeNode(parentTag);\r\n }\r\n }\r\n}", "function expandChildren(node)\n{\n node.children = node._children;\n node._children = null;\n}", "function expandup( node ) {\n\tvar classlist = $( node ).attr( \"class\" );\n\tvar i;\n\tvar j;\n\tvar pnode;\n\n\tif( node == \"#commentbox\" ) {\n\t\treturn;\n\t}\n\ti = classlist.indexOf( \"descendent-of-\" );\n\tif( i >= 0 ) {\n\t\tpnode = classlist.substr( i );\n\t\tj = pnode.indexOf ( \" \" );\n\t\tif( j > 0 ) {\n\t\t\tpnode = pnode.substr( 0, j );\n\t\t}\n\t\tpnode = \"#\" + pnode;\n\t\tpnode = pnode.replace( \"descendent-of-\", \"\" );\n\t\texpandup( pnode );\n\t}\n\t$( node ).expand();\n}", "function expandParentsNavTree(a, id) {\n\t//show this ul and all of its parents\n\tvar node = a;\n\tif (node != null)\n\t{\n\t\twhile (node.id != id)\n\t\t{\n\t\t\tif (String(node.tagName).toUpperCase() == \"LI\")\n\t\t\t{\n\t\t\t\tvar children = nodeChildrenByTagName(node, \"A\", 1);\n\t\t\t\tif (children[0]) {\n\t\t\t\t\tnodeAddClass(children[0], 'current');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (String(node.tagName).toUpperCase() == \"UL\")\n\t\t\t{\n\t\t\t\tnode.style.display = 'block';\n\t\t\t}\n\t\t\tnode = node.parentNode;\n\t\t}\n\t}\n}", "function collapseAll(){\n function recurse(node){\n if (node.children) node.children.forEach(recurse); // recurse to bottom of tree\n if (node.children){ // hide children in _children then remove\n node._children = node.children;\n node.children = null;\n } \n }\n\n recurse(root);\n update();\n}", "function expandActiveItem() {\n if (settings.expandActiveItem === true) {\n var activeItem = settings.activeSelector;\n\n $(activeItem, mlnParentList).each(function() {\n var $this = $(this);\n\n $this.parents('.' + classHasChild).last()\n .addClass(classChildExpandedOnLoad);\n\n $this.parents('.' + classHasChild + '.' + classHasChild)\n .addClass(classChildExpandedOnLoad);\n\n $('.' + classChildExpandedOnLoad, mlnParentList).each(function() {\n if (isPageLoaded === false ||\n mlnParentList.closest('.' + classParent).hasClass(classNavbar) &&\n viewport().width < dataBreakpoint &&\n isPageLoaded !== true) {\n\n mlnToggleChild('show', $(this), false);\n }\n\n if (mlnParentList.closest('.' + classParent).hasClass(classNavbar) &&\n viewport().width >= dataBreakpoint) {\n\n mlnToggleChild('hide', $(this), false);\n }\n });\n });\n\n isPageLoaded = true;\n }\n }", "assignLevel(node, level) {\n node.level = level;\n if (level+1 > this.depth) {\n this.depth++;\n } \n for (let i = 0; i < node.children.length; i++) { \n this.assignLevel(node.children[i], level+1);\n }\n }", "function doExpand() {\n _result = expand(_specs);\n}", "function layerList_ExpandAll(expand) {\n //alert(layerListWidget.operationalItems.items[0].children.items[10].visible);\n var ctSpans = document.getElementsByClassName(\"esri-layer-list__child-toggle\");\n if (ctSpans.length > 0) {\n for (var i = 0; i < ctSpans.length; i++)\n if (ctSpans[i].hasOwnProperty(\"data-item\")) {\n if (ctSpans[i][\"data-item\"].open) // If root node already expanded, assume the rest is also expanded, and exit function\n return;\n ctSpans[i][\"data-item\"].open = expand;\n }\n }\n }", "_expandHeading(heading) {\n heading.expanded = true;\n }", "function wrapTree(target){ \n\t\tvar tree = $(target); \n\t\ttree.addClass('tree'); \n\t\t \n\t\twrapNode(tree, 0); \n\t\t \n\t\tfunction wrapNode(ul, depth){ \n\t\t\t$('>li', ul).each(function(){ \n\t\t\t\tvar node = $('<div class=\"tree-node\"></div>').prependTo($(this)); \n\t\t\t\tvar text = $('>span', this).addClass('tree-title').appendTo(node).text(); \n\t\t\t\t$.data(node[0], 'tree-node', { \n\t\t\t\t\ttext: text \n\t\t\t\t}); \n\t\t\t\tvar subTree = $('>ul', this); \n\t\t\t\tif (subTree.length){ \n\t\t\t\t\t$('<span class=\"tree-folder tree-folder-open\"></span>').prependTo(node); \n\t\t\t\t\t$('<span class=\"tree-hit tree-expanded\"></span>').prependTo(node); \n\t\t\t\t\twrapNode(subTree, depth+1); \n\t\t\t\t} else { \n\t\t\t\t\t$('<span class=\"tree-file\"></span>').prependTo(node); \n\t\t\t\t\t$('<span class=\"tree-indent\"></span>').prependTo(node); \n\t\t\t\t} \n\t\t\t\tfor(var i=0; i<depth; i++){ \n\t\t\t\t\t$('<span class=\"tree-indent\"></span>').prependTo(node); \n\t\t\t\t} \n\t\t\t}); \n\t\t} \n\t\treturn tree; \n\t}", "function expandParent(cell, notebook) {\n let nearestParentCell = findNearestParentHeader(cell, notebook);\n if (!nearestParentCell) {\n return;\n }\n if (!getHeadingInfo(nearestParentCell).collapsed &&\n !nearestParentCell.isHidden) {\n return;\n }\n if (nearestParentCell.isHidden) {\n expandParent(nearestParentCell, notebook);\n }\n if (getHeadingInfo(nearestParentCell).collapsed) {\n setHeadingCollapse(nearestParentCell, false, notebook);\n }\n }", "function preorder(root){\n if(root===null) return;\n root.draw();\n preorder(root.lchild);\n preorder(root.rchild);\n}", "_expandPanel(panel) {\n panel.expanded = true;\n }", "buildTree() {\n this.clear();\n\n const columnsCount = this.#sourceSettings.getColumnsCount();\n let columnIndex = 0;\n\n while (columnIndex < columnsCount) {\n const columnSettings = this.#sourceSettings.getHeaderSettings(0, columnIndex);\n const rootNode = new TreeNode();\n\n this.#rootNodes.set(columnIndex, rootNode);\n this.buildLeaves(rootNode, columnIndex, 0, columnSettings.origColspan);\n\n columnIndex += columnSettings.origColspan;\n }\n\n this.rebuildTreeIndex();\n }", "promote (node) {\r\n if (!node) {\r\n return\r\n }\r\n\r\n const parent = node.parent\r\n\r\n if (!parent) {\r\n return\r\n }\r\n\r\n const grandparent = parent.parent\r\n\r\n // set the node to the proper grandparent side\r\n if (grandparent && parent === grandparent.left) {\r\n grandparent.left = node\r\n } else if (grandparent) {\r\n grandparent.right = node\r\n } else {\r\n this.root = node\r\n }\r\n node.parent = grandparent\r\n\r\n if (parent.left === node) {\r\n parent.left = null\r\n } else {\r\n parent.right = null\r\n }\r\n\r\n parent.parent = null\r\n\r\n // parent would still have the leftover subtree of the side that did not get promoted\r\n return parent\r\n }", "get canExpand() {\n return this._hasChildren && !this.node.singleTextChild;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels the modification of the formula
cancelModification() { this.input.value = this.getFormula(); }
[ "abort() { \n this.reset = true;\n }", "cancel() {\n\t\tthis.reconciling = false;\n\t}", "function resetEquation() {\n let initial_html = `<span class=\"nonterminal\">${initialNonterminal_}</span>`;\n $('#cfg-equation').html(initial_html);\n reapplyNonterminalClickEvent();\n testMatchingEquations();\n historyStack_ = [];\n historyListElem_.innerHTML = '';\n addHistoryElement(initial_html, null);\n $('#undo-button').prop('disabled', true);\n}", "revert() {\n this.innerHTML = this.__canceledEdits;\n }", "function cancel() {\n history.goBack();\n }", "function cancelled() {\n fire(\"refresh-cancelled\");\n finish();\n }", "undoAction() {\n this.element.executeOppositeAction(this.details);\n }", "function cancelEditOp(editItem, dispItem, opt_setid) {\r\n switchItem2(editItem, dispItem);\r\n var editwrapper = document.getElementById(editItem);\r\n var inputElems = cbTbl.findNodes(editwrapper,\r\n function (node) {\r\n return node.nodeName.toLowerCase() == 'input' &&\r\n (!node.type || node.type.toLowerCase() != 'hidden') &&\r\n node.value;\r\n });\r\n for (var i = 0; i < inputElems.length; ++i) {\r\n var inputElem = inputElems[i];\r\n var newVal = '';\r\n if (inputElem.id) {\r\n var origElem = document.getElementById(inputElem.id + '.orig');\r\n newVal = (origElem && origElem.value) ? origElem.value : newVal;\r\n }\r\n inputElems[i].value = newVal;\r\n }\r\n set_isset(false, opt_setid);\r\n}", "function Sequence$cancel(){\n\t cancel();\n\t action && action.cancel();\n\t while(it = nextHot()) it.cancel();\n\t }", "function calcfalse()\r\n\t{\r\n\t\tcalculating = false;\r\n\t}", "function reset_form_input_reward_tensor(){\n document.getElementById(\"reward_tensor\").value=\"\"\n}", "_cancelComment() {\n this._comment = '';\n this._displayFormActions = false;\n }", "function cancelLibFunc() {\r\n\r\n displayAtLastGrid(\"\");\r\n}", "cancel() {\n let parser = this._parser;\n if (parser) {\n this._parser = null;\n // This will call back to onUpdateCheckError with a CANCELLED error\n parser.cancel();\n }\n }", "cancel() {\n console.log('Canceling the transaction')\n return this.replace({\n from: this.manager.address,\n to: this.manager.address,\n value: 0,\n })\n }", "cancel() {\n if (this.raf) {\n cancelAnimationFrame(this.raf);\n }\n }", "function recordsetDialog_onClickCancel(theWindow)\r\n{\r\n // No need to do any additional processing for now.\r\n dwscripts.setCommandReturnValue(recordsetDialog.UI_ACTION_CANCEL);\r\n theWindow.close();\r\n}", "function cancelNewProm(){\n $('#editprom').remove();\n // If there are no proms, this would show the placeholder again\n // If there are proms, placeholder would be removed -> no effect\n $('#prom-placeholder').show();\n }", "function cancelWheel(e) {\n e = e || window.event;\n e.preventDefault ? e.preventDefault() : (e.returnValue = false);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Colorplaceholder and select elements
function recolorSelect( $this ) { var val = $this.val(); $('#result').append('<div>value=' + val + '</div>'); if ( val != '' ) { $this.removeClass('color-placeholder'); } else { $this.addClass('color-placeholder'); } }
[ "function selectPlaceholder(selectID){\n var selected = $(selectID + ' option:selected');\n var val = selected.val();\n $(selectID + ' option' ).css('color', '#000');\n selected.css('color', '#d5d5d5');\n if (val == \"\") {\n $(selectID).css('color', '#d5d5d5');\n };\n $(selectID).change(function(){\n var val = $(selectID + ' option:selected' ).val();\n if (val == \"\") {\n $(selectID).css('color', '#d5d5d5');\n }else{\n $(selectID).css('color', '#000');\n };\n });\n }", "function setupColorControls()\n{\n dropper.onclick = () => setDropperActive(!isDropperActive()) ;\n color.oninput = () => setLineColor(color.value);\n colortext.oninput = () => setLineColor(colortext.value);\n\n //Go find the origin selection OR first otherwise\n palettedialog.setAttribute(\"data-palette\", getSetting(\"palettechoice\") || Object.keys(palettes)[0]);\n\n palettedialogleft.onclick = () => { updatePaletteNumber(-1); refreshPaletteDialog(); }\n palettedialogright.onclick = () => { updatePaletteNumber(1); refreshPaletteDialog(); }\n refreshPaletteDialog();\n}", "function f_refectSpEditBackgroundColor(){\n var bc = $('#sp-taginfo-background-color-input');\n var bcp = $('#sp-taginfo-background-color-picker');\n var backgroundColor = bcp.val().toUpperCase();\n bc.val(backgroundColor);\n fdoc.find('.spEdit').css('background-color',backgroundColor);\n }", "function chwColorChooser(property){\n this.property = property;\n this.element = document.getElementById('chw' + this.property + 'Input');\n this.customGroup = document.getElementById('chw' + this.property + 'CustomGroup');\n this.custom = document.getElementById('chw' + this.property + 'CustomInput');\n this.customOption = document.getElementById('chw' + this.property + 'CustomOption');\n /*\n The color code that replaces the value entered\n by the user, if that vakue is wrong\n */\n this.storedColorCode = \"#000000\";\n /*\n Choice of color changed\n */\n this.colorChoiceChanged = function(){\n if (this.element.value.indexOf('#') == 0){\n this.customGroup.style.display=\"inline\";\n }\n else {\n this.customGroup.style.display=\"none\";\n }\n }\n\n /*\n Show the color with the color code the user entered\n */\n this.showCustomColor = function(){\n if (this.custom.value.match(\"^#(([0-9a-fA-F][9a-fA-F][0-9a-fA-F])|((([0-9a-fA-F]{2})[9a-fA-F]([0-9a-fA-F]){3})))$\")){\n// if (this.custom.value.match(\"^#(([9a-fA-F]{3})|(([9a-fA-F][0-9a-fA-F]){3}))$\")){\n this.custom.style.backgroundColor = this.custom.value;\n this.custom.style.color = \"#000\";\n }\n else if (this.custom.value.match(\"^(([0-9a-fA-F][9a-fA-F][0-9a-fA-F])|((([0-9a-fA-F]{2})[9a-fA-F]([0-9a-fA-F]){3})))$\")){\n// else if (this.custom.value.match(\"^(([9a-fA-F]{3})|(([9a-fA-F][0-9a-fA-F]){3}))$\")){\n this.custom.style.backgroundColor = '#' + this.custom.value;\n this.custom.style.color = \"#000\";\n }\n else if(this.custom.value.match(\"(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)\")){\n this.custom.style.backgroundColor = this.custom.value;\n this.custom.style.color = \"#FFF\";\n }\n else if(this.custom.value.match(\"(^[0-9a-fA-F]{3}$)|(^[0-9a-fA-F]{6}$)\")){\n this.custom.style.backgroundColor = '#' + this.custom.value;\n this.custom.style.color = \"#FFF\";\n }\n }\n\n /*\n Store the previeous color code, which is valid\n */\n this.customColorValueFocus = function(){\n this.storedColorCode = this.custom.value;\n }\n\n /*\n Validate the color code entered by the user\n */\n this.validateCustomColor = function(){\n var selectedFirst = this.element.selectedIndex;\n if(this.custom.value.match(\"^#[0-9a-fA-F]{3}$\")){\n this.customOption.value = '#' + this.custom.value.charAt(1) + this.custom.value.charAt(1) +\n this.custom.value.charAt(2) + this.custom.value.charAt(2) +\n this.custom.value.charAt(3) + this.custom.value.charAt(3);\n }\n else if(this.custom.value.match(\"^[0-9a-fA-F]{3}$\")){\n this.customOption.value = '#' + this.custom.value.charAt(0) + this.custom.value.charAt(0) +\n this.custom.value.charAt(1) + this.custom.value.charAt(1) +\n this.custom.value.charAt(2) + this.custom.value.charAt(2);\n }\n else if(this.custom.value.match(\"^[0-9a-fA-F]{6}$\")){\n this.customOption.value = '#' + this.custom.value;\n }\n else if(this.custom.value.match(\"^#[0-9a-fA-F]{6}$\")){\n this.customOption.value = this.custom.value;\n }\n else{\n this.custom.value = this.storedColorCode;\n this.showCustomColor();\n return false;\n }\n this.element.selectedIndex = selectedFirst;\n }\n this.showCustomColor();\n}", "function selectColor(input) {\n \n\n if(input == \"color\") {\n userColor();\n } else if(input == \"rainbow\") {\n rainbowColor();\n } else {\n greyScale();\n }\n\n }", "function ColorSelector() {\n\t\n\t/* This is for showing and hiding the group of palette buttons\n\t * and the Custom button. It doesn't affect the state of the\n\t * color picker. The argument is the DOM representation of the\n\t * control's main button. */\n\tthis.showHideColorSelect = function (button) {\n\t\tvar fieldid = $(button).attr(\"data-linkedfield\");\n\t\tvar buttondiv = $('#' + fieldid + \"-select\");\n\t\tbuttondiv.toggle();\n\t\t//bench.currentPromotion.canvas.renderAll();\n\t};\n\t\n\t/* This is for the Custom button in the color controls.\n\t * btn is a button in a td, and the color picker is in\n\t * the next td. */\n\tthis.showHideColorPicker = function (btn) {\n\t\tvar picker = $(btn).parent().parent().find(\"input\");\n\t\tvar style = this.elemToLinkedStyle(picker);\n\t\tpicker.prop(\"defaultValue\", style.getColor());\n\t\tpicker.toggle();\n\t};\n\t\n\t/* Set field to the color indicated by a palette button.\n\t * setterFunc is a callback function to handle the details of\n\t * setting the color in the style. */\n\tthis.setToPaletteColor = function (input, setterFunc) {\n\t\tvar style = this.elemToLinkedStyle(input);\n\t\tvar color = $(input).attr(\"data-color\");\n\t\tsetterFunc (style, color);\n//\t\tstyle.setLocalColor (color);\n//\t\tstyle.fabricObject.fill = color;\n\t\tbench.currentPromotion.canvas.renderAll();\n\t};\n\t\n\t/* Set field to the color indicated by the color picker */\n\tthis.setToInputColor = function (input, setterFunc) {\n\t\tvar style = benchcontent.elemToLinkedStyle(input);\n\t\tvar color = $(input).val();\n\t\tsetterFunc (style, color);\n\t\tbench.currentPromotion.canvas.renderAll();\n\t};\n\t\n\t/* For the a DOM element which has the data-linkedfield attribute,\n\t * return the linked style by its index.\n\t */\n\tthis.elemToLinkedStyle = function (elem) {\n\t\tvar target = $(elem).attr(\"data-linkedfield\");\n\t \treturn bench.currentPromotion.styleSet.styles[parseInt(target, 10)];\n\t};\n}", "color_picker(el){\n $(el).colorpicker();\n }", "function selectedColor(color){\n\n color.addEventListener('click', e=>{\n eliminarSeleccion();\n e.target.style.border = '2px solid #22b0b0';\n\n // Agregar color seleccionado al input de color\n document.querySelector('input[name=color]').value = e.target.style.background;\n\n })\n}", "function setCorrectLabels() {\n var data = JSON.parse(getAllData());\n var lastPrice = data.basePrice;\n jQuery(\"select\").each(function () {\n var attrId = parseInt(\n jQuery(this)\n .prop(\"id\")\n .replace(/[^\\d.]/g, \"\")\n );\n\n if (jQuery(this).val() != \"\" && jQuery(this).val() != data.chooseText) {\n var optionPrice =\n data.attributes[attrId].options[jQuery(this)[0].selectedIndex - 1]\n .price;\n lastPrice = parseFloat(lastPrice) + parseFloat(optionPrice);\n }\n var code = data.attributes[attrId].code;\n if (!jQuery(this).is(\":visible\")) {\n var cSelect = jQuery(this);\n var options = data.attributes[attrId].options;\n jQuery(\"#\" + attrId).remove();\n cSelect.parent().append('<div id=\"' + attrId + '\"></div>');\n options.forEach(function (cObj) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length > 0) {\n if (cSelect.val() == cObj.id) {\n jQuery(\"#\" + attrId).append(\n '<div title=\"' +\n cObj.label +\n '\" ><img style=\"outline: 4px solid #FDBA3E;\" id=\"' +\n cObj.id +\n '\" class=\"colors\" src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n } else {\n jQuery(\"#\" + attrId).append(\n '<div title=\"' +\n cObj.label +\n '\" ><img id=\"' +\n cObj.id +\n '\" class=\"colors\" src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n }\n } else {\n jQuery(\"#\" + attrId).append(\n '<div><img class=\"invalidOptions\" id=\"' +\n cObj.id +\n '\"src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n }\n });\n jQuery(\"#\" + attrId).append(\"<br><br><br>\");\n }\n });\n var currency = jQuery(\".regular-price\").children(\"span\").text();\n jQuery(\n jQuery(\".regular-price\")\n .children(\"span\")\n .text(currency[0] + lastPrice)\n );\n}", "function initColorsSelectBox() {\n\tvar SelectNode = document.getElementById(\"ColorSet\");\n\tvar colorSetKeys = Object.keys(colorSetsObj);\n\tvar key;\n\tfor (key in colorSetKeys) {\n\t\tvar option = document.createElement(\"option\");\n\t\toption.value = colorSetKeys[key];\n\t\toption.text = colorSetsObj[colorSetKeys[key]].picker_label;\n\t\tSelectNode.add(option);\n\t}\n}", "function resetOptionBackground() {\r\nconst options = document.getElementsByName(\"option\");\r\noptions.forEach((option) => {\r\n document.getElementById(option.labels[0].id).style.backgroundColor = \"\"\r\n})\r\n}", "function tShirtColor() {\n if (designSelector.value === \"Select Theme\") {\n colorListDiv.style.visibility = \"hidden\";\n } else if (designSelector.value === \"js puns\") {\n showColorOptions(puns);\n } else if (designSelector.value === \"heart js\") {\n showColorOptions(heart);\n }\n}", "colorHtml() {\n return '';\n // delete the empty return above and uncomment the return below to restore the option for picking the color scheme\n /*\n return `Coloring Scheme: <select id=\"ColoringScheme\">\n <option value=\"rainbow\">Rainbow</option></select>`;\n //new option goes here if added\n */\n }", "function f_refectSpEditBackgroundColorOpacity(){\n // background-colorに入力値がある場合のみ動作\n if($('#sp-taginfo-background-color-input').val()){\n // range value to value\n var value = $('#sp-taginfo-background-color-opacity-input');\n var range = $('#sp-taginfo-background-color-opacity-range');\n var rangeVal = range.val();\n value.val(rangeVal);\n\n // apply to .spEdit\n var spEdit = fdoc.find('.spEdit');\n var spEidtRgb = spEdit.css('background-color');\n var spEidtRgbArr = rgbToArr(spEidtRgb);\n var rgba = 'rgba('+spEidtRgbArr[0] + ',' + spEidtRgbArr[1] + ',' + spEidtRgbArr[2] + ',' + rangeVal + ')';\n spEdit.css('background-color',rgba);\n }\n }", "function airsliderSlidesColorPicker() {\n $('.air-admin #air-slides .air-slides-list .air-slide-settings-list .air-slide-background-type-color-picker-input').wpColorPicker({\n // a callback to fire whenever the color changes to a valid color\n change: function(event, ui){\n // Change only if the color picker is the user choice\n var btn = $(this);\n if(btn.closest('.air-content').find('input[name=\"air-slide-background-type-color\"]:checked').val() == '1') {\n var area = btn.closest('.air-slide').find('.air-elements .air-slide-editing-area');\n var opacity_per = $.trim(btn.closest('.air-content').find('.air-slide-background-opacity').val());\n area.css('background-color', airsliderConvertHex(ui.color.toString(),opacity_per));\n }\n },\n // a callback to fire when the input is emptied or an invalid color\n clear: function() {},\n // hide the color picker controls on load\n hide: true,\n // show a group of common colors beneath the square\n // or, supply an array of colors to customize further\n palettes: true\n });\n }", "function showColorColoredBox(css) {\n document.getElementById(\"boxColor\").style.backgroundColor = `${r}, ${g}, ${b}`;\n }", "function focusAddIconColor(id, element, color){\n\tvar forElement \t\t= null; \n\tvar colorElement\t= null;\n\tvar elementInvalid\t= null;\n\tif( element == 1 ){\n\t\tforElement \t= $(id).attr('id');\n\t\telementInvalid = $('#'+forElement).closest('.mdl-textfield');\n\t\tif ( !elementInvalid.hasClass('is-invalid')) {\n\t\t\t$('.mdl-input-group').find('.mdl-icon i').removeAttr('style');\n\t\t}\n\t} else {\n\t\tforElement \t\t= $(id).find('button.selectpicker').attr('data-id');\n\t\t$('.mdl-input-group').find('.mdl-icon i').removeAttr('style');\n\t}\n\t$(id).closest('.mdl-input-group').find('.mdl-icon i').css('color', color);\n}", "function showcolor(){\n let getColorSelected = document.querySelector(\"#colors-selection\").value; //get color selected value\n console.log(getColorSelected)\n if(getColorSelected == null || getColorSelected == undefined){ //set default value if user don't choose the color\n return selectedArticle[0]\n } else {\n selectedArticle[\"selectedColor\"]=getColorSelected;\n console.log(selectedArticle)\n }\n }", "function initColorEditFormFromField(field){\n\tfieldId = getFieldIdFromCurrentNode(field);\n\tfieldValue = jQuery(field).val();\t\n\tif (fieldValue=='transparent') fieldValue='#000000';\n\tR = parseInt(fieldValue.substring(1,3), 16);\n\tG = parseInt(fieldValue.substring(3,5), 16);\n\tB = parseInt(fieldValue.substring(5,7), 16);\n\tHSL = RGB_to_HSL(R, G, B);\n\t\n\tsliderPosition = 100 - (HSL.L + s_h_offset);\n\tsliderId = \"lightness-picker_\" + fieldId;\n\tupdateSliderPosition(sliderId, sliderPosition);\n\t\n\tselectorXPosition = parseInt((parseInt(HSL.H))/ 3.6) - c_w_offset;\n\tselectorYPosition = 100 - ( parseInt(HSL.S) + c_h_offset );\n\tselectorId = \"color-selector_\" + fieldId;\n\tupdateSelectorPosition(selectorId, selectorXPosition, selectorYPosition);\n\t\n\thueFieldId = \"#hue-field_\" + fieldId ;\n\tjQuery(hueFieldId).attr({\"value\" : HSL.H});\n\tlightnessFieldId = \"#lightness-field_\" + fieldId ;\n\tjQuery(lightnessFieldId).attr({\"value\" : HSL.L});\n\tsaturationFieldId = \"#saturation-field_\" + fieldId;\n\tjQuery(saturationFieldId).attr({\"value\" : HSL.S});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accumulates without regard to direction, does not look for phased registration names. Same as `accumulateDirectDispatchesSingle` but without requiring that the `dispatchMarker` be the same as the dispatched ID.
function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } }
[ "function accumulator(xf) {\n function xformed(source, additional) {\n // Return a new accumulatable object who's accumulate method transforms the `next`\n // accumulating function.\n return accumulatable(function accumulateXform(next, initial) {\n // `next` is the accumulating function we are transforming. \n accumulate(source, function nextSource(accumulated, item) {\n // We are essentially wrapping next with `xf` provided the `item` is\n // not `end`.\n return item === end ? next(accumulated, item) :\n xf(additional, next, accumulated, item);\n }, initial);\n });\n }\n\n return xformed;\n}", "_dispatchEvents() {\n //todo: this doesnt let us specify order that events are disptached\n //so we will probably have to check each one\n //info here: https://stackoverflow.com/a/37694450/10232\n for (let handler of this._eventHandlers.values()) {\n handler.dispatch();\n }\n }", "_dispatch(event, ...args) {\n const handlers = this._handlers && this._handlers[event];\n if (!handlers) return;\n handlers.forEach(func => {\n func.call(null, ...args);\n });\n }", "function mapActionCreatorsToProps(dispatch) {\n return bindActionCreators({}, dispatch)\n}", "function redirecting_dispatch(dispatch, result)\n{\n\treturn (event) =>\n\t{\n\t\tswitch (event.type)\n\t\t{\n\t\t\t// In case of navigation from @preload()\n\t\t\tcase Preload:\n\t\t\t\t// `throw`s a special `Error` on server side\n\t\t\t\treturn result.redirect = location_url(event.location)\n\t\t\n\t\t\tdefault:\n\t\t\t\t// Proceed with the original\n\t\t\t\treturn dispatch(event)\n\t\t}\n\t}\n}", "findForcedReduction() {\n let { parser } = this.p,\n seen = []\n let explore = (state, depth) => {\n if (seen.includes(state)) return\n seen.push(state)\n return parser.allActions(state, (action) => {\n if (\n action &\n (262144 /* Action.StayFlag */ | 131072) /* Action.GotoFlag */\n );\n else if (action & 65536 /* Action.ReduceFlag */) {\n let rDepth = (action >> 19) /* Action.ReduceDepthShift */ - depth\n if (rDepth > 1) {\n let term = action & 65535 /* Action.ValueMask */,\n target = this.stack.length - rDepth * 3\n if (\n target >= 0 &&\n parser.getGoto(this.stack[target], term, false) >= 0\n )\n return (\n (rDepth << 19) /* Action.ReduceDepthShift */ |\n 65536 /* Action.ReduceFlag */ |\n term\n )\n }\n } else {\n let found = explore(action, depth + 1)\n if (found != null) return found\n }\n })\n }\n return explore(this.state, 0)\n }", "function incr(type, target) {\n results[type] = results[type] || {};\n results[type][target] = results[type][target] || 0;\n results[type][target]++;\n }", "function mappedReducer(reducer, child) {\n var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n _ref3$selectors = _ref3.selectors,\n selectors = _ref3$selectors === undefined ? {} : _ref3$selectors,\n _ref3$actions = _ref3.actions,\n actions = _ref3$actions === undefined ? {} : _ref3$actions;\n\n if (!(0, _lodash.isFunction)(reducer)) throw new Error('reslice.mappedReducer: expected reducer function, got: ' + (typeof reducer === 'undefined' ? 'undefined' : _typeof(reducer)));\n checkDistinctNames(selectors, actions);\n return { $$mapped: true, $$reducer: reducer, $$child: child, $$selectors: selectors, $$actions: actions };\n}", "function plus(){\n\tmemory[pointer]++;\n}", "dispatch(event) {\n for (let handler of this._handlers) {\n handler(event);\n }\n }", "dispatchJobs() {\n\t\tconst job = this.getJob(this.logKeys);\n\n\t\tif (!job) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.stat_collector) {\n\t\t\tthis.stat_collector.add(job.key)\n\t\t}\n\n\t\treturn job;\n\t}", "function traverse(uidPath, uid, memory, cls){\n\t\tcounter++;\n\t\tif(counter > 5000){\n\t\t\tconsole.log(uid);\n\t\t}\n\n\t\t//Get action object\n\t\tvar actionObj = tree.actions[uid];\n\n\t\t//evaluate each precondition for the action object\n\t\tvar trig = false;\n\t\tfor(var j = 0; j < actionObj.preconditions.length; j++){\n\t\t\tvar pre = actionObj.preconditions[j];\n\n\t\t\t//check to see if we get a false value\n\t\t\tif(!evaluatePrecondition(pre)){\n\t\t\t\ttrig = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t//If something doesn't pass, we return\n\t\tif(trig) return;\n\n\t\t//Now we can loop through each expression and evaluate them\n\t\tfor(var k = 0; k < actionObj.expressions.length; k++){\n\t\t\tvar exp = actionObj.expressions[k];\n\n\t\t\t//Evaluate the expression and write to the hypothetical memory\n\t\t\tevaluateExpression(exp, memory);\n\t\t}\n\n\t\t//We can assume now that we've succesfully passed the preconditions\n\t\t//This means we can add the action to the uid list\n\t\tuidPath.push(uid);\n\n\t\t//Now we have to see if there's a class for this action\n\t\t//If so, we add it to the list\n\t\tvar myClass = \"\";\n\t\tif(actionObj.cls != undefined && cls === \"\"){\n\t\t\tmyClass = actionObj.cls;\n\t\t} else {\n\t\t\tmyClass = cls;\n\t\t}\n\n\t\t//If the action is a leaf, push the uidPath on the available paths\n\t\t// and then push a new distance to conversation types on dists\n\t\tif(actionObj.isLeaf()){\n\t\t\tuids.push(uidPath);\n\n\t\t\tvar combineMem = Memory.prototype.combine(myCharacter.memBank.totalMemVec, memory, myCharacter.memBank.timeStep);\n\t\t\tvar normMem = combineMem.normalize();\n\t\t\t//Get the dot product\n\t\t\tvar dotproduct = normMem.dot(normalComposedMemory);\n\t\t\tvar dotproduct = Math.round(dotproduct * 1000) / 1000\n\t\t\t//Get the dist to the conversation type\n\t\t\tvar dist = Math.abs(that.conversationType - dotproduct);\n\n\t\t\tdists.push(dist);\n\n\t\t\tclasses.push(myClass);\n\n\t\t\treturn;\n\t\t}\n\n\t\t//Now we run the traversal algorithm for each child action\n\t\tfor(var i = 0; i < actionObj.children.length; i++){\n\t\t\tvar actionUID = actionObj.children[i];\n\t\t\tvar action = tree.actions[actionUID];\n\n\t\t\ttraverse(uidPath.slice(), actionUID, memory.copy(), myClass);\n\t\t}\n\t}", "function reductions(source, xf, initial) {\n var reduction = initial;\n\n return accumulatable(function accumulateReductions(next, initial) {\n // Define a `next` function for accumulation.\n function nextReduction(accumulated, item) {\n reduction = xf(reduction, item);\n\n return item === end ?\n next(accumulated, end) :\n // If item is not `end`, pass accumulated value to next along with\n // reduction created by `xf`.\n next(accumulated, reduction);\n }\n\n accumulate(source, nextReduction, initial);\n });\n}", "performReduction() {\n //console.log(\"called performReduction\");\n var reduced_expr = this.reduce();\n if (reduced_expr !== undefined && reduced_expr != this) { // Only swap if reduction returns something > null.\n\n console.warn('performReduction with ', this, reduced_expr);\n\n if (!this.stage) return Promise.reject();\n\n this.stage.saveState();\n Logger.log('state-save', this.stage.toString());\n\n // Log the reduction.\n let reduced_expr_str;\n if (reduced_expr === null)\n reduced_expr_str = '()';\n else if (Array.isArray(reduced_expr))\n reduced_expr_str = reduced_expr.reduce((prev,curr) => (prev + curr.toString() + ' '), '').trim();\n else reduced_expr_str = reduced_expr.toString();\n Logger.log('reduction', { 'before':this.toString(), 'after':reduced_expr_str });\n\n var parent = this.parent ? this.parent : this.stage;\n if (reduced_expr) reduced_expr.ignoreEvents = this.ignoreEvents; // the new expression should inherit whatever this expression was capable of as input\n parent.swap(this, reduced_expr);\n\n // Check if parent expression is now reducable.\n if (reduced_expr && reduced_expr.parent) {\n var try_reduce = reduced_expr.parent.reduceCompletely();\n if (try_reduce != reduced_expr.parent && try_reduce !== null) {\n Animate.blink(reduced_expr.parent, 400, [0,1,0], 1);\n }\n }\n\n if (reduced_expr)\n reduced_expr.update();\n\n return Promise.resolve(reduced_expr);\n }\n return Promise.resolve(this);\n }", "function decorateStoreWithCall(Store, call) {\n const names = Object.keys(call.actions).reduce((result, key) => {\n if (key === 'name') {\n return result;\n }\n // remove ACTION_CONSTANT variants generated by alt\n if (result.indexOf(key.toLowerCase()) === -1) {\n result.push(key);\n }\n return result;\n }, []);\n names.forEach(reducerName => {\n createStoreHandler(reducerName, Store, call);\n });\n}", "function onRecalculationPhase() {\n if (p.recalcQueued) {\n p.recalcPhase = 0;\n recalculateDimensions();\n } else if (p.recalcPhase == 1 && p.lastLocus) {\n p.recalcPhase = 2;\n p.flipper.moveTo(p.lastLocus, onRecalculationPhase, false);\n } else {\n Monocle.defer(afterRecalculate);\n }\n }", "function func(accumulator, currentValue, currentIndex, sourceArray) {\n return accumulator + currentValue;\n}", "function selectorFactory(dispatch, mapStateToProps, mapDispatchToProps) {\n //cache the DIRECT INPUT for the selector\n //the store state\n let state\n //the container's own props\n let ownProps\n\n //cache the itermediate results from mapping functions\n //the derived props from the state\n let stateProps\n //cache the derived props from the store.dispatch\n let dispatchProps\n\n //cache the output\n //the return merged props(stateProps + dispatchProps + ownProps) to be injected to wrappedComponent\n let mergedProps\n\n // the source selector is memorizable.\n return function selector(nextState, nextOwnProps) {\n //before running the actual mapping function, compare its arguments with the previous one\n const propsChanged = !shallowEqual(nextOwnProps, ownProps)\n const stateChanged = !strictEqual(nextState, state)\n\n state = nextState\n ownProps = nextOwnProps\n \n //calculate the return mergedProps based on different scenarios \n //to MINIMIZE the call to actual mapping functions\n //notice: the mapping function itself can be optimized by Reselect, but it is not the concern here\n \n //case 1: both state in redux and own props change\n if (propsChanged && stateChanged) {\n //derive new props based on state\n stateProps = mapStateToProps(state, ownProps)\n //since the ownProps change, update dispatch callback if it depends on props\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n //merge the props\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 2: only own props changes\n if (propsChanged) {\n //only update stateProps and dispatchProps if they rely on ownProps\n if (mapStateToProps.length !== 1) stateProps = mapStateToProps(state, ownProps) //it just call the mapping function\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 3: only store state changes\n // 1.since stateProps depends on state so must run mapStateToProps again\n // 2.for dispatch, since store.dispatch and ownProps remain the same, no need to update\n if (stateChanged) {\n const nextStateProps = mapStateToProps(state, ownProps)\n const statePropsChanged = !shallowEqual(nextStateProps, stateProps)\n stateProps = nextStateProps\n //if stateProps changed, update mergedProps by calling the mergeProps function\n if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 4: no change, return the cached result if no change in input\n return mergedProps;\n }\n}", "function accumulate(source, next, initial) {\n // If source is accumulatable, call accumulate method.\n isMethodAt(source, 'accumulate') ?\n source.accumulate(next, initial) :\n // ...otherwise, if source has a reduce method, fall back to accumulation\n // with reduce, then call `next` with `end` token and result of reduction.\n // Reducible sources are expected to return a value for `reduce`.\n isMethodAt(source, 'reduce') ?\n next(source.reduce(next, initial), end) :\n // ...otherwise, if source is nullish, end. `null` is considered to be\n // an empty source (akin to an empty array). This approach takes\n // inspiration from Lisp dialects, where `null` literally _is_ an empty\n // list. It also just makes sense: `null` is a non-value, and should\n // not accumulate.\n source == null ?\n next(initial, end) :\n // Otherwise, call `next` with value, then `end`. I.e, values without\n // a `reduce`/`accumulate` method are treated as sources containing\n // one item.\n next(next(initial, source), end);\n}", "function increment(event){\n if (isRunning){\n return;\n }\n var target = event.data.target;\n // Get the value of the target\n var value = parseInt(readInput(target));\n // Increment it\n value++;\n // Output incremented value back to target\n output(target, value);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates "Select all" control in a data table js
function updateDataTableSelectAllCtrl(table){ var $table = table.table().node(); var $chkbox_all = $('tbody input[type="checkbox"]', $table); var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table); var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0); // If none of the checkboxes are checked if($chkbox_checked.length === 0){ chkbox_select_all.checked = false; if('indeterminate' in chkbox_select_all){ chkbox_select_all.indeterminate = false; } // If all of the checkboxes are checked } else if ($chkbox_checked.length === $chkbox_all.length){ chkbox_select_all.checked = true; if('indeterminate' in chkbox_select_all){ chkbox_select_all.indeterminate = false; } // If some of the checkboxes are checked } else { chkbox_select_all.checked = true; if('indeterminate' in chkbox_select_all){ chkbox_select_all.indeterminate = true; } } }
[ "function selectAll(astrTable, aobjSelectAll) {\n var lstrSelected;\n var lobjSelected;\n var lobjStatus;\n var lintCount;\n var lobjTable = document.getElementById(astrTable);\n var lintNumRows = lobjTable.rows.length;\n for (lintCount=0;lintCount < lintNumRows;lintCount++) {\n lobjStatus= document.getElementById(\"value[\" + lintCount + \"].status\");\n if(lobjStatus.value != \"HIDE\"){\n lstrSelected = \"value[\" + lintCount + \"].selected\";\n lobjSelected = document.getElementById(lstrSelected);\n if( ! lobjSelected.disabled ) {\n lobjSelected.checked = aobjSelectAll.checked;\n }\n }\n }\n }", "function selectAllData() // sad = select all data \r\n{\r\n\tvar sad = document.getElementById('stateDisplay');\r\n\tsad.focus();\r\n\tsad.select();\r\n}", "function make_cb_select_all (ev, ui) {\n ui.panel.find ('thead, tfoot').find ('.check-column :checkbox').on ('click.wp-toggle-checkboxes', function (event) {\n var $this = jQuery (this);\n var $table = $this.closest ('table');\n var controlChecked = $this.prop ('checked');\n var toggle = event.shiftKey || $this.data ('wp-toggle');\n\n $table.children ('tbody')\n .filter (':visible')\n .children ()\n .children ('.check-column')\n .find (':checkbox')\n .prop ('checked', function () {\n if (jQuery (this).is (':hidden,:disabled')) {\n return false;\n }\n if (toggle) {\n return !jQuery (this).prop ('checked');\n } else if (controlChecked) {\n return true;\n }\n return false;\n });\n\n $table.children ('thead, tfoot')\n .filter (':visible')\n .children ()\n .children ('.check-column')\n .find (':checkbox')\n .prop ('checked', function () {\n if (toggle) {\n return false;\n } else if (controlChecked) {\n return true;\n }\n return false;\n });\n });\n}", "function do_select_all() {\n var baseurl = document.getElementById('selfurl');\n // Make asynchronous call to self page with flag to select all for current page\n YUI().use(\"io-base\", function(Y) {\n var uri = baseurl.value + \"&do_select_all=1\";\n var cfg = {\n method: 'POST',\n sync: false\n };\n request = Y.io(uri, cfg);\n });\n checkbox_select(true, '[selected]', 'selected');\n checkbox_select(true, '[changed]', 'changed');\n}", "function reset_table(data_table) {\n\t$(\".li-sub-select\").remove();\n\t\t\t\t\n\t//Clean the table and show all\n\t//First, get the settings of the table\n\tvar settings = data_table.fnSettings();\n\t\t\t\t\n\t//Get the number of column\n\tvar columns_number = settings.aoPreSearchCols.length\n\t\t\t\t\n\t//Clean the value of the search for each column\n\tfor(i = 0; i < columns_number; i++) {\n\t\tsettings.aoPreSearchCols[i].sSearch = '';\n\t}\n\t\t\t\t\n\t//Apply the changes to the fn filters\n\tdata_table.fnDraw();\n}", "function changeSelectAll(aobjClicked,astrSelectAll){\n var objSelectAll=document.getElementById(astrSelectAll);\n if(!aobjClicked.checked){\n objSelectAll.checked = false;\n }\n }", "function selectAllCoutryMenuCheckBox(){ \n\tif(document.getElementById('countryMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('countryMenuAddId').checked=true;\n\t\tdocument.getElementById('countryMenuViewId').checked=true;\n\t\tdocument.getElementById('countryMenuUpdateId').checked=true;\n\t\tdocument.getElementById('countryMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('countryMenuAddId').checked=false;\n\t\tdocument.getElementById('countryMenuViewId').checked=false;\n\t\tdocument.getElementById('countryMenuUpdateId').checked=false;\n\t\tdocument.getElementById('countryMenuDeleteId').checked=false;\n\t}\n}", "function selectAllDepartmentMenuCheckBox(){ \n\tif(document.getElementById('departmentMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('departmentMenuAddId').checked=true;\n\t\tdocument.getElementById('departmentMenuViewId').checked=true;\n\t\tdocument.getElementById('departmentMenuUpdateId').checked=true;\n\t\tdocument.getElementById('departmentMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('departmentMenuAddId').checked=false;\n\t\tdocument.getElementById('departmentMenuViewId').checked=false;\n\t\tdocument.getElementById('departmentMenuUpdateId').checked=false;\n\t\tdocument.getElementById('departmentMenuDeleteId').checked=false;\n\t}\n}", "function selectAllCustomerMenuCheckBox(){ \n\tif(document.getElementById('customerMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('customerMenuAddId').checked=true;\n\t\tdocument.getElementById('customerMenuViewId').checked=true;\n\t\tdocument.getElementById('customerMenuUpdateId').checked=true;\n\t\tdocument.getElementById('customerMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('customerMenuAddId').checked=false;\n\t\tdocument.getElementById('customerMenuViewId').checked=false;\n\t\tdocument.getElementById('customerMenuUpdateId').checked=false;\n\t\tdocument.getElementById('customerMenuDeleteId').checked=false;\n\t}\n}", "function selectAllCurrencyMenuCheckBox(){ \n\tif(document.getElementById('currencyMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('currencyMenuAddId').checked=true;\n\t\tdocument.getElementById('currencyMenuViewId').checked=true;\n\t\tdocument.getElementById('currencyMenuUpdateId').checked=true;\n\t\tdocument.getElementById('currencyMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('currencyMenuAddId').checked=false;\n\t\tdocument.getElementById('currencyMenuViewId').checked=false;\n\t\tdocument.getElementById('currencyMenuUpdateId').checked=false;\n\t\tdocument.getElementById('currencyMenuDeleteId').checked=false;\n\t}\n}", "function selectAllEmpStatusMenuCheckBox(){ \n\tif(document.getElementById('empStatusMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('empStatusMenuAddId').checked=true;\n\t\tdocument.getElementById('empStatusMenuViewId').checked=true;\n\t\tdocument.getElementById('empStatusMenuUpdateId').checked=true;\n\t\tdocument.getElementById('empStatusMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('empStatusMenuAddId').checked=false;\n\t\tdocument.getElementById('empStatusMenuViewId').checked=false;\n\t\tdocument.getElementById('empStatusMenuUpdateId').checked=false;\n\t\tdocument.getElementById('empStatusMenuDeleteId').checked=false;\n\t}\n}", "function selectAllRegionMenuCheckBox(){ \n\tif(document.getElementById('regionMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('regionMenuAddId').checked=true;\n\t\tdocument.getElementById('regionMenuViewId').checked=true;\n\t\tdocument.getElementById('regionMenuUpdateId').checked=true;\n\t\tdocument.getElementById('regionMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('regionMenuAddId').checked=false;\n\t\tdocument.getElementById('regionMenuViewId').checked=false;\n\t\tdocument.getElementById('regionMenuUpdateId').checked=false;\n\t\tdocument.getElementById('regionMenuDeleteId').checked=false;\n\t}\n}", "function selectAllNationalityMenuCheckBox(){ \n\tif(document.getElementById('nationalityMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('nationalityMenuAddId').checked=true;\n\t\tdocument.getElementById('nationalityMenuViewId').checked=true;\n\t\tdocument.getElementById('nationalityMenuUpdateId').checked=true;\n\t\tdocument.getElementById('nationalityMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('nationalityMenuAddId').checked=false;\n\t\tdocument.getElementById('nationalityMenuViewId').checked=false;\n\t\tdocument.getElementById('nationalityMenuUpdateId').checked=false;\n\t\tdocument.getElementById('nationalityMenuDeleteId').checked=false;\n\t}\n}", "function selectAllLocationMenuCheckBox(){ \n\tif(document.getElementById('locationMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('locationMenuAddId').checked=true;\n\t\tdocument.getElementById('locationMenuViewId').checked=true;\n\t\tdocument.getElementById('locationMenuUpdateId').checked=true;\n\t\tdocument.getElementById('locationMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('locationMenuAddId').checked=false;\n\t\tdocument.getElementById('locationMenuViewId').checked=false;\n\t\tdocument.getElementById('locationMenuUpdateId').checked=false;\n\t\tdocument.getElementById('locationMenuDeleteId').checked=false;\n\t}\n}", "function selectAllHolidayMenuCheckBox(){ \n\tif(document.getElementById('holidayMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('holidayMenuAddId').checked=true;\n\t\tdocument.getElementById('holidayMenuViewId').checked=true;\n\t\tdocument.getElementById('holidayMenuUpdateId').checked=true;\n\t\tdocument.getElementById('holidayMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('holidayMenuAddId').checked=false;\n\t\tdocument.getElementById('holidayMenuViewId').checked=false;\n\t\tdocument.getElementById('holidayMenuUpdateId').checked=false;\n\t\tdocument.getElementById('holidayMenuDeleteId').checked=false;\n\t}\n}", "function selectAllExpenseTypeMenuCheckBox(){ \n\tif(document.getElementById('expenseTypeMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('expenseTypeMenuAddId').checked=true;\n\t\tdocument.getElementById('expenseTypeMenuViewId').checked=true;\n\t\tdocument.getElementById('expenseTypeMenuUpdateId').checked=true;\n\t\tdocument.getElementById('expenseTypeMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('expenseTypeMenuAddId').checked=false;\n\t\tdocument.getElementById('expenseTypeMenuViewId').checked=false;\n\t\tdocument.getElementById('expenseTypeMenuUpdateId').checked=false;\n\t\tdocument.getElementById('expenseTypeMenuDeleteId').checked=false;\n\t}\n}", "function selectAllJobTitleMenuCheckBox(){ \n\tif(document.getElementById('jobTitleMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('jobTitleMenuAddId').checked=true;\n\t\tdocument.getElementById('jobTitleMenuViewId').checked=true;\n\t\tdocument.getElementById('jobTitleMenuUpdateId').checked=true;\n\t\tdocument.getElementById('jobTitleMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('jobTitleMenuAddId').checked=false;\n\t\tdocument.getElementById('jobTitleMenuViewId').checked=false;\n\t\tdocument.getElementById('jobTitleMenuUpdateId').checked=false;\n\t\tdocument.getElementById('jobTitleMenuDeleteId').checked=false;\n\t}\n}", "function selectAllProjActivityMenuCheckBox(){ \n\tif(document.getElementById('projActivityMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('projActivityMenuAddId').checked=true;\n\t\tdocument.getElementById('projActivityMenuViewId').checked=true;\n\t\tdocument.getElementById('projActivityMenuUpdateId').checked=true;\n\t\tdocument.getElementById('projActivityMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('projActivityMenuAddId').checked=false;\n\t\tdocument.getElementById('projActivityMenuViewId').checked=false;\n\t\tdocument.getElementById('projActivityMenuUpdateId').checked=false;\n\t\tdocument.getElementById('projActivityMenuDeleteId').checked=false;\n\t}\n}", "function selectAllEmployeeMenuCheckBox(){ \n\tif(document.getElementById('employeeMenuSelectAllId').checked==true){\n\n\t\tdocument.getElementById('employeeMenuAddId').checked=true;\n\t\tdocument.getElementById('employeeMenuViewId').checked=true;\n\t\tdocument.getElementById('employeeMenuUpdateId').checked=true;\n\t\tdocument.getElementById('employeeMenuDeleteId').checked=true;\n\t}else{\n\t\tdocument.getElementById('employeeMenuAddId').checked=false;\n\t\tdocument.getElementById('employeeMenuViewId').checked=false;\n\t\tdocument.getElementById('employeeMenuUpdateId').checked=false;\n\t\tdocument.getElementById('employeeMenuDeleteId').checked=false;\n\t}\n}", "function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======== onChangePolicyInitFxn ======== onChange callback function for the policyInitFunction config
function onChangePolicyInitFxn(inst, ui) { let subState = inst.policyInitFunction !== 'Custom'; ui.policyInitCustomFunction.hidden = subState; }
[ "function onChangeEnablePolicy(inst, ui)\n{\n let subState = !inst.enablePolicy;\n\n ui.enablePinParking.hidden = subState;\n ui.policyInitFunction.hidden = subState;\n ui.policyFunction.hidden = subState;\n\n onChangePolicyInitFxn(inst,ui);\n onChangePolicyFxn (inst,ui);\n}", "function handleOnSelectPolicyDone(underPolicyId, underPolicyNo, riskBaseId) {\r\n if(underPolicyNo.indexOf(\"(\")>0){\r\n underPolicyNo = underPolicyNo.split(\"(\")[0];\r\n }\r\n setInputFormField(\"externalId\", underPolicyId);\r\n setInputFormField(\"externalNo\", underPolicyNo);\r\n setInputFormField(\"riskBaseId\", riskBaseId);\r\n getInitialValuesForNewInsured();\r\n}", "registerOnValidatorChange(fn) {\n this._onValidatorChange = fn;\n }", "function on_change_key_config()\n{\n\tkey_config = key_config_presets[key_config_menu.selectedIndex];\n}", "function onChangeConfigurePinLFXT (inst, ui)\n {\n let subState = !inst.enableLFXTClock;\n\n ui.bypassLFXT.hidden = subState;\n ui.lfxtDriveLevel.hidden = subState;\n }", "function onChangeConfigurePinHFXT (inst, ui)\n {\n let subState = !inst.enableHFXTClock;\n\n ui.bypassHFXT.hidden = subState;\n ui.hfxtFrequency.hidden = subState;\n }", "function validate(inst, vo)\n{\n if (inst.enablePolicy) {\n if (inst.policyInitFunction === 'Custom') {\n if (!isCName(inst.policyInitCustomFunction)) {\n logError(vo, inst, \"policyInitCustomFunction\",\n \"Not a valid C identifier\");\n }\n if (inst.policyInitCustomFunction === '') {\n logError(vo, inst, \"policyInitCustomFunction\",\n \"Must contain a valid function name if the \" +\n \"Policy Init Function field == 'Custom'\");\n }\n }\n if (inst.policyFunction === 'Custom') {\n if (!isCName(inst.policyCustomFunction)) {\n logError(vo, inst, \"policyCustomFunction\",\n \"is not a valid C identifier\");\n }\n if (inst.policyCustomFunction === '') {\n logError(vo, inst, \"policyCustomFunction\",\n \"Must contain a valid function name if the \" +\n \"Policy Function field == 'Custom'\");\n }\n }\n }\n\n if ((inst.enableHFXTClock)) {\n if ((inst.hfxtFrequency == '0')) {\n if (inst.bypassHFXT) {\n logError(vo, inst, 'hfxtFrequency',\n 'If HFXT is enabled in bypass mode, please specify ' +\n 'the external crystal square wave frequency.');\n } else {\n logError(vo, inst, 'hfxtFrequency',\n 'Specify the desired HFXT oscillator frequency.');\n }\n }\n }\n\n if ((inst.initialPerfLevel - inst.customPerfLevels) > 3) {\n logError(vo, inst, ['initialPerfLevel', 'customPerfLevels'],\n 'The initial performance level refers to an undefined custom ' +\n 'performace level.');\n }\n\n if (!isCName(inst.resumeShutdownHookFunction)) {\n logError(vo, inst, \"resumeShutdownHookFunction\", 'Not a valid C identifier');\n }\n\n if (inst.advancedConfiguration) {\n if (!isCName(inst.isrClockSystem)) {\n logError(vo, inst, \"isrClockSystem\", 'Not a valid C identifier');\n }\n }\n}", "function decorateInitWithCounter(policy) {\n const baseInit = policy.init;\n policy._initCalled = 0;\n policy.init = function () {\n policy._initCalled++;\n baseInit.apply(policy, arguments);\n };\n return policy;\n }", "function initializeDeliveryOptionChangeListener() {\n let elements = document.querySelectorAll(\".delivery-option\");\n for (var i = 0; i < elements.length; i++) {\n elements[i].addEventListener(\"change\", function() {\n let loadingElement = document.querySelector(\".item-delivery-options\");\n let observer = new MutationObserver(function(entries) {\n if (!document.querySelector(\".item-delivery-options.loading\")) {\n reinitializeAfterpayPopup(); \n observer.disconnect();\n }\n });\n observer.observe(loadingElement, {attributeFilter: ['class']});\n });\n }\n}", "async fileInputChanged () {\n Doc.hide(this.errMsg)\n if (!this.fileInput.value) return\n const loaded = app().loading(this.form)\n const config = await this.fileInput.files[0].text()\n if (!config) return\n const res = await postJSON('/api/parseconfig', {\n configtext: config\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.errMsg.textContent = res.msg\n Doc.show(this.errMsg)\n return\n }\n if (Object.keys(res.map).length === 0) return\n this.dynamicOpts.append(...this.setConfig(res.map))\n this.reorder(this.dynamicOpts)\n const [loadedOpts, defaultOpts] = [this.loadedSettings.children.length, this.defaultSettings.children.length]\n if (loadedOpts === 0) Doc.hide(this.loadedSettings, this.loadedSettingsMsg)\n if (defaultOpts === 0) Doc.hide(this.defaultSettings, this.defaultSettingsMsg)\n if (loadedOpts + defaultOpts === 0) Doc.hide(this.showOther, this.otherSettings)\n }", "function policy_name_is_predefined() {\n var cf = document.forms[0];\n var i;\n\n if(cf.category.selectedIndex == CATEGORY_APP || cf.category.selectedIndex == CATEGORY_GAME) {\n if (cf.apps.options.selectedIndex != cf.apps.options.length-1\n && cf.name.value == cf.apps.options[cf.apps.selectedIndex].text) {\n /* User selected predefined rules no need to check */\n return false;\n }\n }\n\n for(i=0; i<predef_qos.length; i++) {\n if(cf.name.value == predef_qos[i][_name]) {\n return true;\n }\n }\n return false;\n}", "function propertyChangeHandler(scope, element, key, newVal, oldVal) {\n var dataSet = scope.dataset || scope.scopedataset,\n isBoundToServiceVariable;\n /*Checking if widget is bound to service variable*/\n if (CONSTANTS.isStudioMode && scope.binddataset) {\n isBoundToServiceVariable = _.startsWith(scope.binddataset, 'bind:Variables.') && FormWidgetUtils.getBoundVariableCategory(scope) === \"wm.ServiceVariable\";\n }\n /*Monitoring changes for properties and accordingly handling respective changes.*/\n switch (key) {\n case 'dataset':\n /*Displaying no data message when bound to service variable in studio mode*/\n if (isBoundToServiceVariable && CONSTANTS.isStudioMode) {\n FormWidgetUtils.appendMessage(element);\n } else {\n /*generating the radioset based on the values provided*/\n constructRadioSet(scope, element, newVal);\n }\n break;\n case 'displayfield':\n case 'datafield':\n case 'usekeys':\n case 'orderby':\n if (CONSTANTS.isRunMode || !isBoundToServiceVariable) {\n /*generating the radioset based on the values provided*/\n constructRadioSet(scope, element, dataSet);\n }\n break;\n case 'selectedvalue':\n /*generating the radioset based on the values provided*/\n dataSet = FormWidgetUtils.getParsedDataSet(dataSet, scope, element);\n assignModelValue(scope, dataSet);\n break;\n case 'disabled':\n element.find('input[type=\"radio\"]').attr('disabled', newVal);\n break;\n case 'layout':\n element.removeClass(oldVal).addClass(newVal);\n break;\n }\n }", "_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }", "_handlePrivacyRequest () {\n const privacyMode = this.preferencesController.getFeatureFlags().privacyMode\n if (!privacyMode) {\n this.platform && this.platform.sendMessage({\n action: 'approve-legacy-provider-request',\n selectedAddress: this.publicConfigStore.getState().selectedAddress,\n }, { active: true })\n this.publicConfigStore.emit('update', this.publicConfigStore.getState())\n }\n }", "handleApproachChanged() {\n if (this.currentApproachName.startsWith('RN')) {\n this.approachMode = WT_ApproachType.RNAV;\n if (this.currentLateralActiveState === LateralNavModeState.APPR) {\n this.isVNAVOn = true;\n }\n \n if (this.currentVerticalActiveState === VerticalNavModeState.GS) {\n this.currentVerticalActiveState = VerticalNavModeState.GP;\n }\n\n if (this.currentVerticalArmedStates.includes(VerticalNavModeState.GS)) {\n this.currentVerticalArmedStates = [VerticalNavModeState.GP];\n }\n }\n\n if (this.currentApproachName.startsWith('ILS') || this.currentApproachName.startsWith('LDA')) {\n this.approachMode = WT_ApproachType.ILS;\n if (this.currentLateralActiveState === LateralNavModeState.APPR) {\n this.isVNAVOn = false;\n }\n\n if (this.currentVerticalActiveState === VerticalNavModeState.GP) {\n this.currentVerticalActiveState = VerticalNavModeState.GS;\n }\n\n if (this.currentVerticalArmedStates.includes(VerticalNavModeState.GP)) {\n this.currentVerticalArmedStates = [VerticalNavModeState.GS];\n }\n }\n }", "setCtrlCHandler(fn) {\n this.ctrlCHandler = fn;\n }", "constructor(scope, id, props) {\n super(scope, id, { type: CfnAccessPointPolicy.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3objectlambda_CfnAccessPointPolicyProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnAccessPointPolicy);\n }\n throw error;\n }\n cdk.requireProperty(props, 'objectLambdaAccessPoint', this);\n cdk.requireProperty(props, 'policyDocument', this);\n this.objectLambdaAccessPoint = props.objectLambdaAccessPoint;\n this.policyDocument = props.policyDocument;\n }", "constructor(scope, id, props) {\n super(scope, id, { type: CfnMultiRegionAccessPointPolicy.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_CfnMultiRegionAccessPointPolicyProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnMultiRegionAccessPointPolicy);\n }\n throw error;\n }\n cdk.requireProperty(props, 'mrapName', this);\n cdk.requireProperty(props, 'policy', this);\n this.attrPolicyStatusIsPublic = cdk.Token.asString(this.getAtt('PolicyStatus.IsPublic', cdk.ResolutionTypeHint.STRING));\n this.mrapName = props.mrapName;\n this.policy = props.policy;\n }", "onChangeSkinningType() {\n let data = {\n detail: {\n type: this.controls['Skinning Type'],\n },\n };\n window.dispatchEvent(new CustomEvent('on-change-skinning-type', data));\n }", "function ConfigFunction () {\n\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if the number is within [avg, avg+5]
function fromAvg(temp) { return (temp >= result.avg && temp <= (result.avg + 5)); }
[ "function toAvg(temp) {\n return (temp <= result.avg && temp >= (result.avg - 5));\n}", "function under50(num) {\n return num < 50;\n}", "function check(num1, num2) {\n var sum = 0;\n sum = sum + num1 + num2;\n if (sum <= 25) {\n console.log(\"true\")\n } else {\n console.log(\"false\")\n }\n}", "function checkForNumber(min, max, avg) {\n if ((isNaN(min)) || (isNaN(max)) || (isNaN(avg))) {\n alert('You have entered a value that is not a number!');\n return false;\n } else if (min > max) {\n alert('Your minimum value is greater than your maximum value');\n return false;\n }\n}", "function isValidStat(stat) {\n return (stat >= 0 && stat <= 5);\n}", "function betterThanAverage(classGrades, yourGrade){\n let classAvg = 0;\n for(let i = 0; i < classGrades.length; i++){\n //take each class point\n classAvg += classGrades[i]\n }\n classAvg = classAvg / classGrades.length;\n //return true if your grade is bigget than the class Average\n return yourGrade > classAvg\n}", "function isValidScore(value) {\n\tvar result = false;\n\tif (value != '' && typeof value != \"undefined\") {\n\t\tif (IsNumeric(value)) {\n\t\t\tvalue = parseFloat(value);\n\t\t\tif (value >= 0 && value <= 5) {\n\t\t\t\tresult = true;\n\t\t\t} else {\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t} else {\n\t\t\tresult = false;\n\t\t}\n\t} else {\n\t\tresult = true;\n\t}\n\treturn result;\n}", "function CheckOn (value, index, ar) {\n return (value > b.minVariance && value < -1 * b.minVariance)\n}", "function isAvgWhole(arr) {\n\tlet a = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\ta += arr[i];\n\t}\n\t\n\treturn Number.isInteger(a / arr.length);\n}", "function intWithinBounds(n, lower, upper) {\n\treturn n >= lower && n < upper && Number.isInteger(n);\n}", "function average(x1, x2, x3, x4, x5) {\n var sum = x1 + x2 + x3 + x4 + x5;\n var avg = sum / 5;\n return console.log(avg)\n}", "function hasDivisableBy5(array) {\n\tvar bool = false;\n\tarray.forEach(function(number) {\n\t\tif(number % 5 === 0) {\n\t\t\tbool = true;\n\t\t} \n\t});\n\treturn bool;\n}", "function sumRange(num1, num2) {\n let sum = num1 + num2;\n if (sum >= 50 && 80 >= sum) return 65;\n else return 80;\n}", "function totalUnderWhat (first, second, third, fourth){\n if (first + second +third < fourth) {\n return true;\n\n } else {return false;\n\n }\n\n}", "function isNear(val, target, threshold) {\n return Math.abs(val - target) <= threshold;\n}", "function fitWithinVal(arrayToSum, num) {\n\tvar sum = 0;\n\tvar output = [];\n\tfor (var i = 0; i < arrayToSum.length; i++) {\n\t\tif (sum + arrayToSum[i] <= num) {\n\t\t\tsum = sum + arrayToSum[i];\n\t\t\toutput.push(arrayToSum[i]);\n\t\t}\n\t}\n\treturn output;\n}", "inRange (number, start, end) {\n if (end === undefined) {\n end = start\n start = 0\n }\n if (start > end) {\n let temp = end\n end = start\n start = temp\n }\n let isInRange = (number >= start && number < end)\n return isInRange\n }", "function isGreaterThan20(num){\r\n if(num>20){\r\n return true\r\n }\r\n}", "function boundary(N) {\n // if(N > 20 && N <= 100) {\n // return true\n // }\n // if(N === 400) {\n // return true\n // }\n // else {\n // return false;\n // }\n\n if ((N > 20 && N <= 100) || N === 400) {\n return true;\n } else {\n return false;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A cache of compiled shaders, keyed by shader source strings. Compilation of long shaders can be time consuming. By using this class, the application can ensure that each shader is only compiled once.
function ShaderCache() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, gl = _ref.gl, _ref$_cachePrograms = _ref._cachePrograms, _cachePrograms = _ref$_cachePrograms === void 0 ? false : _ref$_cachePrograms; (0, _classCallCheck2.default)(this, ShaderCache); (0, _assert.default)(gl); this.gl = gl; this.vertexShaders = {}; this.fragmentShaders = {}; this.programs = {}; this._cachePrograms = _cachePrograms; }
[ "function recompileShader() {\n shaderSourceChanged = true;\n}", "function _compileShaders()\n\t{\n\t\tvar vertexShader = _loadShaderFromDOM( _vertexShaderId );\t\t// Get shaders and compile them.\n\t\tvar fragmentShader = _loadShaderFromDOM( _fragmentShaderId );\n\n\t\t_renderingProgram = gl.createProgram();\n\t\tgl.attachShader( _renderingProgram, vertexShader );\t\t\t\t// Link shaders to program.\n\t\tgl.attachShader( _renderingProgram, fragmentShader );\n\t\tgl.linkProgram( _renderingProgram );\n\n\t\tif( !gl.getProgramParameter( _renderingProgram, gl.LINK_STATUS ) )\n\t\t\talert( \"Failed to set up shaders!\" );\n\t}", "getProgramFromShaders(vsCode, fsCode) {\n return this.programs.find((element) => {\n return this.isSameShader(element.vsCode, vsCode) && this.isSameShader(element.fsCode, fsCode);\n });\n }", "function genShaderPrograms(){\r\n\r\n\tif(!(gl.program1 = util_InitShaders(gl, VSHADER_SOURCE1, FSHADER_SOURCE1))) {\r\n\t\tconsole.log(\"Error building program 1\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(!(gl.program2 = util_InitShaders(gl, VSHADER_SOURCE2, FSHADER_SOURCE2))) {\r\n\t\tconsole.log(\"Error building program 2\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(!(gl.program3 = util_InitShaders(gl, VSHADER_SOURCE3, FSHADER_SOURCE3))) {\r\n\t\tconsole.log(\"Error building program 3\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}", "function _glsl() {\n\treturn {\n\t\ttransform(code, id) {\n\t\t\tif (/\\.glsl$/.test(id) === false) return;\n\t\t\tvar transformedCode = 'export default ' + JSON.stringify(\n\t\t\t\tcode\n\t\t\t\t\t.replace( /[ \\t]*\\/\\/.*\\n/g, '' ) // remove //\n\t\t\t\t\t.replace( /[ \\t]*\\/\\*[\\s\\S]*?\\*\\//g, '' ) // remove /* */\n\t\t\t\t\t.replace( /\\n{2,}/g, '\\n' ) // # \\n+ to \\n\n\t\t\t) + ';';\n\t\t\treturn {\n\t\t\t\tcode: transformedCode,\n\t\t\t\tmap: { mappings: '' }\n\t\t\t};\n\t\t}\n\t};\n}", "function getShader(filepath, type)\n {\n var shaderScriptType = type;\n var shaderPath = filepath;\n \n if (!shaderPath || shaderPath.length == 0)\n return 0;\n \n var shader = Gles.createShader(type);\n \n if (shader == 0) return 0;\n \n //added method\n Gles.shaderSourceFile(shader, filepath);\n Gles.compileShader(shader);\n \n if (Gles.getShaderiv(shader, Gles.COMPILE_STATUS) != 1) {\n var error = Gles.getShaderInfoLog(shader);\n log(\"Error while compiling \" + id + \":\");\n log(shader);\n \n Gles.deleteShader(shader);\n return 0;\n }\n \n return shader;\n }", "function Shader(glContext, vertexPath, fragmentPath)\n{\n this.uniforms = new Array();\n this.uniforms.count = 0;\n \n \n this.worldViewProjectionHandle = -1;\n this.worldMatrixHandle = -1;\n this.projectionMatrixHandle = -1;\n this.textureHandle = -1;\n \n //attribute handles \n this.positionHandle = -1;\n this.normalHandle = -1;\n this.colorHandle = -1;\n this.uvCoordinateHandle = -1;\n \n this.vertexShaderSource = \"\";\n this.vertexShaderLength = 0;\n this.vertexShaderHandle = -1;\n \n this.fragmentShaderSource = \"\";\n this.fragmentShaderLength = 0;\n this.fragmentShaderHandle = -1;\n \n this.programHandle = -1;\n \n this.loadShader(glContext, vertexPath, fragmentPath);\n \n \n //get attribute handles\n this.colorHandle = gl.getAttribLocation( this.programHandle, \"a_Color\" );\t\n this.positionHandle = gl.getAttribLocation( this.programHandle, \"a_Position\" );\t\n this.uvCoordinateHandle = gl.getAttribLocation( this.programHandle, \"a_UVCoordinates\" );\n this.normalHandle = gl.getAttribLocation(this.programHandle, \"a_Normal\");\n \n //get uniform handles\n this.worldViewProjectionHandle = gl.getUniformLocation(this.programHandle, \"u_WorldViewProjection\");\n this.worldMatrixHandle = gl.getUniformLocation(this.programHandle, \"u_WorldMatrix\");\n this.projectionMatrixHandle = gl.getUniformLocation(this.programHandle, \"u_ProjectionMatrix\");\n this.textureHandle = gl.getUniformLocation(this.programHandle, \"u_Texture\");\n}", "async function fetchSources(shaderDescriptions) {\n // Make a promise for each source\n const descriptionArray = shaderDescriptions.shaders;\n const promises = descriptionArray.map((description) => fetch(description.path));\n return Promise.all(promises)\n}", "GetShaderEngine () {\n return this.ShaderEngine\n }", "function CSSCache()\n{\n this._blocks = new Object(); // hash table url -> CSSBlock\n this._dates = new Object(); // hash table url -> modification date \n}", "function initShaders( vertexShaderId, fragmentShaderId )\n{\n var vertShdr;\n\tvar fragShdr;\n\t\n\n\n\t// --- Compiling vertex shader\n var vertElem = document.getElementById( vertexShaderId );\n if ( !vertElem ) { \n alert( \"Unable to load vertex shader \" + vertexShaderId );\n return -1;\n }\n else {\n vertShdr = gl.createShader( gl.VERTEX_SHADER );\n gl.shaderSource( vertShdr, vertElem.text );\n gl.compileShader( vertShdr );\n if ( !gl.getShaderParameter(vertShdr, gl.COMPILE_STATUS) ) {\n var msg = \"Vertex shader failed to compile. The error log is:\"\n \t+ \"<pre>\" + gl.getShaderInfoLog( vertShdr ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n }\n\n\n\n\t// --- Compiling fragment shader\n var fragElem = document.getElementById( fragmentShaderId );\n if ( !fragElem ) { \n alert( \"Unable to load vertex shader \" + fragmentShaderId );\n return -1;\n }\n else {\n fragShdr = gl.createShader( gl.FRAGMENT_SHADER );\n gl.shaderSource( fragShdr, fragElem.text );\n gl.compileShader( fragShdr );\n if ( !gl.getShaderParameter(fragShdr, gl.COMPILE_STATUS) ) {\n var msg = \"Fragment shader failed to compile. The error log is:\"\n \t+ \"<pre>\" + gl.getShaderInfoLog( fragShdr ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n }\n\n\n\n\t// --- Creating program\n var program = gl.createProgram();\n gl.attachShader( program, vertShdr );\n gl.attachShader( program, fragShdr );\n gl.linkProgram( program );\n \n if ( !gl.getProgramParameter(program, gl.LINK_STATUS) ) {\n var msg = \"Shader program failed to link. The error log is:\"\n + \"<pre>\" + gl.getProgramInfoLog( program ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n\n return program;\n}", "compileCubemapShader() {\n this._cubemapMaterial === null && (this._cubemapMaterial = Sl(), this._compileMaterial(this._cubemapMaterial));\n }", "_getOptionsFromHandle(handle) {\n const shaderHandles = this.gl.getAttachedShaders(handle);\n const opts = {};\n for (const shaderHandle of shaderHandles) {\n const type = this.gl.getShaderParameter(this.handle, GL.SHADER_TYPE);\n switch (type) {\n case GL.VERTEX_SHADER:\n opts.vs = new VertexShader({handle: shaderHandle});\n break;\n case GL.FRAGMENT_SHADER:\n opts.fs = new FragmentShader({handle: shaderHandle});\n break;\n default:\n }\n }\n return opts;\n }", "function importShader () {\n function createVertexShader (vert) {\n return createShader(require(`../shader/${vert}.vert`), 'vertex')\n }\n\n const noneVs = createVertexShader('nothing')\n\n function createProgram (name, frag, vert = noneVs, prg = prgs) {\n const fs = createShader(require(`../shader/${frag}.frag`), 'fragment')\n prg[name] = new Program(vert, fs)\n if (!prg[name]) throw new Error('program error')\n }\n\n try {\n // video\n createProgram('video', 'video')\n\n // Post Effect\n createProgram('postVideo', 'post/video')\n\n const postVs = createVertexShader('post/post')\n for (const name of POST_LIST) {\n createProgram(name, `post/${name}`, postVs, postPrgs)\n }\n\n // Particle\n createProgram('particleVideo', 'particle/video')\n createProgram('picture', 'particle/picture')\n createProgram('reset', 'particle/reset')\n createProgram('resetVelocity', 'particle/resetVelocity')\n createProgram('position', 'particle/position')\n createProgram('velocity', 'particle/velocity')\n createProgram('particleScene', 'particle/scene', createVertexShader('particle/scene'))\n\n // Pop\n createProgram('popVelocity', 'particle/pop_velocity')\n createProgram('popPosition', 'particle/pop_position')\n createProgram('popScene', 'particle/pop_scene', createVertexShader('particle/pop_scene'))\n\n // render\n createProgram('scene', 'scene', createVertexShader('scene'))\n } catch (error) {\n throw error\n }\n}", "function createCache() {\n var keys = [];\n\n function cache(key, value) {\n // Use (key + \" \")\n if (keys.push(key + \" \") > Expr.cacheLength) {\n // Only keep the most recent entries.\n delete cache[keys.shift()];\n }\n return (cache[key + \" \"] = value);\n }\n return cache;\n }", "async function cacheResources() {\n const cache = await caches.open(STATIC_CACHE);\n await cache.addAll(FILES_TO_CACHE);\n return self.skipWaiting();\n}", "function updateForTextures(_ref) {\n var vs = _ref.vs,\n sourceTextureMap = _ref.sourceTextureMap,\n targetTextureVarying = _ref.targetTextureVarying,\n targetTexture = _ref.targetTexture;\n var texAttributeNames = Object.keys(sourceTextureMap);\n var sourceCount = texAttributeNames.length;\n var targetTextureType = null;\n var samplerTextureMap = {};\n var updatedVs = vs;\n var finalInject = {};\n\n if (sourceCount > 0 || targetTextureVarying) {\n var vsLines = updatedVs.split('\\n');\n var updateVsLines = vsLines.slice();\n vsLines.forEach(function (line, index, lines) {\n // TODO add early exit\n if (sourceCount > 0) {\n var updated = processAttributeDefinition(line, sourceTextureMap);\n\n if (updated) {\n var updatedLine = updated.updatedLine,\n inject = updated.inject;\n updateVsLines[index] = updatedLine; // sampleInstructions.push(sampleInstruction);\n\n finalInject = (0, _src.combineInjects)([finalInject, inject]);\n Object.assign(samplerTextureMap, updated.samplerTextureMap);\n sourceCount--;\n }\n }\n\n if (targetTextureVarying && !targetTextureType) {\n targetTextureType = getVaryingType(line, targetTextureVarying);\n }\n });\n\n if (targetTextureVarying) {\n (0, _assert.default)(targetTexture);\n var sizeName = \"\".concat(SIZE_UNIFORM_PREFIX).concat(targetTextureVarying);\n var uniformDeclaration = \"uniform vec2 \".concat(sizeName, \";\\n\");\n var posInstructions = \" vec2 \".concat(VS_POS_VARIABLE, \" = transform_getPos(\").concat(sizeName, \");\\n gl_Position = vec4(\").concat(VS_POS_VARIABLE, \", 0, 1.);\\n\");\n var inject = {\n 'vs:#decl': uniformDeclaration,\n 'vs:#main-start': posInstructions\n };\n finalInject = (0, _src.combineInjects)([finalInject, inject]);\n }\n\n updatedVs = updateVsLines.join('\\n');\n }\n\n return {\n // updated vertex shader (commented texture attribute definition)\n vs: updatedVs,\n // type (float, vec2, vec3 of vec4) target texture varying\n targetTextureType: targetTextureType,\n // required vertex and fragment shader injects\n inject: finalInject,\n // map of sampler name to texture name, can be used to set attributes\n // usefull when swapping textures, as source and destination texture change when swap is called.\n samplerTextureMap: samplerTextureMap\n };\n} // builds and returns an object contaning size uniform for each texture", "isSameShader(firstShader, secondShader) {\n return firstShader.localeCompare(secondShader) === 0;\n }", "static domShaderSrc(elmID) {\n var elm = document.getElementById(elmID);\n if (!elm || elm.text == \"\") { console.log(elmID + \" shader not found or no text.\"); return null; }\n\n return elm.text;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Injects .html plot in a iframe tag
newPlotWidgetIframe(name, url) { var that = this; G.addWidget(1).then(w => { w.setName(name); w.$el.append("<iframe src='" + url + "' width='100%' height='100%s'/>"); that.widgets.push(w); w.showHistoryIcon(false); w.showHelpIcon(false); }); }
[ "plotExternalHTML(url, plot_name) {\n fetch(url)\n .then((response) => {\n if (response.ok) {\n return response.json()\n } else {\n throw new Error('Something went wrong');\n }\n })\n .then((responseJson) => {\n let data = JSON.parse(responseJson);\n this.newPlotWidgetIframe(plot_name, data.url);\n })\n .catch(error => console.log(error));\n }", "function getQFrameHtml() {\n var jsUrl = qlikServerBaseUrl + qlikServerPrefix + 'resources';\n\n return '<html>'\n + '<head>'\n + '<script src=\"' + jsUrl + '/assets/external/requirejs/require.js\"></script>'\n + '</head>'\n + '<body><p>Isolated iframe to load Qlik.js </p>'\n + '<script>'\n + 'try {'\n + 'require.config({ baseUrl: \"' + jsUrl + '\" });'\n + 'require([\"js/qlik\"], function(q) { parent.qlikIsolated._qFrameLoadSuccess(q); });'\n + '} catch(e) { parent.qlikIsolated._qFrameLoadFailure(e); }'\n + '</script>'\n + '</body>'\n + '</html>';\n }", "function loadFrameFromHTML(src, frame, callback) {\n var fn = function () {\n Monocle.Events.deafen(frame, 'load', fn);\n frame.whenDocumentReady();\n Monocle.defer(callback);\n }\n Monocle.Events.listen(frame, 'load', fn);\n if (Monocle.Browser.env.loadHTMLWithDocWrite) {\n frame.contentDocument.open('text/html', 'replace');\n frame.contentDocument.write(src);\n frame.contentDocument.close();\n } else {\n frame.contentWindow['monCmptData'] = src;\n frame.src = \"javascript:window['monCmptData'];\"\n }\n }", "function plotQtl(div, symptom){\n\t$.get('/scripts/plot_qtl/run?symptom='+symptom).done(function(data){\n\t\tvar data = extractBodyFromHTML(data);\n\t\t//var dataURI = createDataUri(data);\n\t\t$(div).html(data);\n\t\trunScanone();\n\t});\n}", "function create_iframe(textarea) {\n var $textarea = $(textarea),\n $iframe = $('<iframe />').attr(\n 'src', $textarea.data('mmSettings').base_url),\n $codemirror = $textarea.next('.CodeMirror');\n\n $iframe\n .addClass('CodeMirror-preview')\n .on({\n 'load': function() {\n var $this = $(this);\n $this.data('load', true);\n\n if( $this.data('replace') !== undefined ) {\n $this.trigger('_update', {html: $this.data('replace')});\n }\n },\n '_resize': function() {\n $(this).css({\n 'height': $(this).prev().outerHeight()\n });\n },\n '_update': function(e, data) {\n $(this)\n .contents()\n .find('body')\n .html(data.html);\n }\n })\n .trigger('_resize')\n .appendTo($codemirror);\n\n /* update iframe contents for the first time */\n update_preview($codemirror.get(0).CodeMirror);\n}", "function appendIframeScript(url) {\n // This may run before or after the page is fully loaded, so account for\n // both cases to avoid flakiness.\n return `\n function appendIframe() {\n var frame = document.createElement('iframe');\n frame.src = '${url}';\n document.body.appendChild(frame);\n }\n window.onload = appendIframe;\n if (document.readyState === 'complete')\n appendIframe();`\n }", "function updateHtmlElements() {\n\n // Plot containers\n plotContainers.forEach((c, i) => {\n c.position(bounds[i].west - 1, bounds[i].north - 1);\n c.size(plotSize - 1, plotSize - 1);\n });\n\n // Options panel\n optionsPanel.position(\n 1 + bounds[0].west,\n bounds[0].south + 0.12 * (sketch.height - bounds[0].south)\n );\n optionsPanel.size(\n bounds[1].east - bounds[0].west,\n 0.8 * (sketch.height - bounds[0].south)\n );\n\n }", "function injectGraphs(URL, element) {\n document.getElementById(element).setAttribute('src', URL);\n }", "function appendPopupIFrame(p, src, title){\r\n\t\tpopupIframe = document.createElement(\"IFRAME\");\r\n\t\tpopupIframe.setAttribute(\"src\", src);\r\n\t\tpopupIframe.setAttribute(\"title\", title);\r\n\t\tpopupIframe.setAttribute(\"id\", \"popup-iframe-id\");\r\n\t\tpopupIframe.setAttribute(\"scrolling\", \"no\");\r\n\t\tpopupIframe.setAttribute(\"marginheight\", \"0\");\r\n\t\tpopupIframe.setAttribute(\"marginwidth\", \"0\");\r\n\t\tpopupIframe.setAttribute(\"class\", \"popup-iframe-class\");\r\n\t\tpopupIframe.style.width = \"100%\"; //Always consume full width of container\r\n\t\tpopupIframe.style.height = \"100%\"; //When gauth renders in iframe it will message its height back to the client\r\n\t\tpopupIframe.style.border = \"none\";\r\n\t\tpopupIframe.frameBorder = \"0\"; //for IE\r\n\t\tp.appendChild(popupIframe);\r\n\t}", "function updateIFrame(value) {\n iDoc().open();\n iDoc().close();\n iDoc().location.hash = value;\n }", "function appendElement(){\n\t\tif(document && document.body){\n\t\t\tdocument.body.appendChild(iframe);\n\t\t\treturn;\n\t\t}\n\t\tsetTimeout(function(){appendElement()}, 100);\n\t}", "function addPageWeb(link, page_nb, out_of) {\n\tvar url\t\t= link;\n\tvar domElement\t= document.createElement('iframe')\n\tdomElement.src\t= url\n\tdomElement.style.border\t= 'none'\n\n\t// create the plane\n\tvar mixerPlane\t= new THREEx.HtmlMixer.Plane(mixerContext, domElement)\n\tmixerPlane.object3d.scale.multiplyScalar(2)\n\n\tvar parent = new THREE.Object3D();\n\tscene.add(parent)\n\n\tparent.rotation.y = page_nb * 6.28 / out_of;\n\tparent.add(mixerPlane.object3d);\n\tparent.children[0].position.z = -2;\n\n\treturn parent;\n}", "function inject(html, url) {\n\tvar inlineScript = `<script data-streamurl=\"${url}\">${clientScript}</script>`;\n\treturn inlineScript + html;\n}", "setHtml(element, html){\n element.html(html);\n }", "async createIframeURL(fid) {\n this.setOrgID(fid);\n // var iframe_url = this.state.iframe_url + \"?orgID=\" + this.state.oid;\n // console.log(iframe_url);\n // var iframe_copy_text =\n // '<iframe src=\"' + iframe_url + '\" width=\"100%\" height=\"450\"></iframe>';\n //this.setState({ iframe_url });\n //this.setState({ iframe_copy_text });\n }", "function setFrameContent(frameClass, content) {\n\n $('.' + frameClass + '.' + FRAME_SELECTOR + ' .' + FRAME_CONTENT_SELECTOR).html(content);\n}", "function getInnerContent() {\n if (curOpt.url) {\n return '<iframe src=\\'' + curOpt.url + '\\' horizontalscrolling=\\'no\\' verticalscrolling=\\'no\\' width=\\'' + curOpt.width + '\\' height=\\'' + curOpt.height + '\\' frameBorder=\\'0\\'></iframe>';\n } else if (curOpt.selector) {\n var html = $(curOpt.selector).html();\n return html;\n }\n }", "function createIframe(videoURL) {\n return $('<iframe/>').attr({\n src: videoURL,\n width: '100%',\n height: '100%'\n });\n }", "function injectResults(iframe, htmlCode, cssCode, Javascript){\r\n\r\n\tvar ifr = iframe.contentWindow.document;\r\n\tvar htmlInput = htmlCode.value;\r\n\tvar cssInput = cssCode.value;\r\n\tvar jsInput = Javascript.value;\r\n\r\n\tifr.open();\r\n\tifr.write(\"<style>\" + cssInput + \"</style>\" + htmlInput + \"<script>\" + jsInput + \"</script>\");\r\n\tifr.close();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method replaces the url domain with localhost domain when we are in development mode (when localhost is the current location).
function urlReplace(url) { if (window.location.host.indexOf('localhost') !== -1) { var urlNew = new URL(url); urlNew.host = 'localhost'; urlNew.protocol = window.location.protocol; return urlNew.toString(); } return url; }
[ "function saveDomain() {\n getCurrentUrl().then(function(url){\n var domain,\n protocol,\n full;\n\n domain = TOCAT_TOOLS.getDomainFromUrl(url);\n protocol = TOCAT_TOOLS.getProtocolFromUrl(url);\n full = protocol + '://' + domain;\n\n TOCAT_TOOLS.saveDomain(full);\n });\n }", "function getHost() {\n return location.protocol + '//' + location.host\n }", "function resolveHost(domain)\r\n{\r\n var hostString = \"www\";\r\n \r\n if(domain == \"lexis\" || domain == \"nexis\") \r\n hostString = \"w3\"; \r\n \r\n return hostString;\r\n}", "function isLocalhost(){\n return window.location.origin.includes(\"localhost:8088\");\n}", "getUrl() {\n return process.env.ENVIRONMENT === \"DEV\" ? \"http://localhost:3001\" : \"prod\";\n }", "function getServerUrl() {\n\n if (SERVER_URL === null) {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13 \n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n\n SERVER_URL = url;\n\n }\n\n return SERVER_URL; \n }", "function __fixUrl( configDirs, url ) {\n var match,\n replacement;\n\n // Replace {variables}\n while ( VAR_REGEX.test( url ) ) {\n match = VAR_REGEX.exec( url );\n replacement = configDirs[ match[ 1 ] ] || \"\";\n url = url.replace( match[0], replacement );\n }\n\n // Replace non-protocol double slashes\n url = url.replace( /([^:])\\/\\//g, \"$1/\" );\n\n return url;\n }", "function allowDomain() {\n chrome.tabs.query({\n 'active': true,\n 'lastFocusedWindow': true\n }, function (tabs) {\n var url = tabs[0].url;\n var parsedURL = parseURL(url);\n PREFS.siteWhitelist.push(parsedURL.parent_domain);\n savePrefs(PREFS);\n checkTab(tabs[0]);\n });\n}", "function processUrlTemplate(url, document_ = document) {\n const scriptUrl = currentScriptUrl(document_);\n if (scriptUrl) {\n url = url.replace('{current_host}', scriptUrl.hostname);\n url = url.replace('{current_scheme}', scriptUrl.protocol.slice(0, -1));\n }\n return url;\n}", "function domainParse(){\n var l = location.hostname\n return {\n \"prot\": location.protocol,\n \"host\": l,\n \"statics\" : 'cdn.kaskus.com'\n };\n}", "function getServerUrl() {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13\n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n return url;\n }", "function getRootUrl(url) {\n var domain = url.replace('http://','').replace('https://','').replace('www.', '').split(/[/?#]/)[0];\n return domain;\n}", "getServiceBaseHostURL() {\n let routeInfo = this.store.peekRecord('nges-core/engine-route-information', 1);\n\n //if(!routeInfo) routeInfo = this.store.peekRecord('nges-core/engine-route-information', 2);\n let hostUrl = 'http://' + routeInfo.appCode + '.' + routeInfo.appModuleCode + config.NGES_SERVICE_HOSTS.APP_SERVICE_POST_HOST;\n return hostUrl;\n }", "function PT_getSubdomain() {\n var PT_regexParse = new RegExp('[a-z\\-0-9]{2,63}\\.[a-z\\.]{2,5}$');\n var PT_urlParts = PT_regexParse.exec(window.location.hostname);\n\n return window.location.hostname.replace(PT_urlParts[0], '').slice(0, -1);\n}", "function convertToCurrentProtocol(url)\n{\n if(url && url.replace)\n {\n url = url.replace(/http[s]?:/i, document.location.protocol);\n }\n \n return url;\n}", "function setupConfig() {\n var origin = 'https://developer.mozilla.org';\n if (window.URL) {\n var url = new URL(window.location.href);\n if (url.searchParams) {\n var param = url.searchParams.get('origin');\n if (param) {\n origin = param;\n }\n }\n }\n window.ieConfig = {\n origin: origin\n };\n}", "function setDomainOpts(){\r\n\tvar split1 = location.href.split('ikariam.');\r\n\tvar split2 = split1[1].split('/');\r\n\tvar ext = split2[0];\r\n\tvar opts = new Array();\r\n\topts['ext'] = ext;\r\n\tif ( ext == 'fr' ){\r\n\t\topts['lvl'] = ' Niveau';\r\n\t\topts['inactives'] = 'Inactifs';\t\r\n\t}\r\n\telse if ( ext == 'de' ){\r\n\t\topts['lvl'] = ' Stufe';\r\n\t\topts['inactives'] = 'Inaktívak';\t\r\n\t}\r\n\telse if ( ext == 'com' ){\r\n\t\topts['lvl'] = ' Level';\t\r\n\t\topts['inactives'] = 'Inaltívak';\r\n\t}\r\n\telse if ( ext == 'es' ){\r\n\t\topts['lvl'] = ' Nivel';\r\n\t\topts['inactives'] = 'Inaktívak';\r\n\t}\r\n\telse if ( ext == 'gr' ){\r\n\t\topts['lvl'] = 'ÎľĎ�ÎŻĎ�ξδο';\r\n\t\topts['inactives'] = 'Inactives';\r\n\t}\r\n\telse if ( ext == 'hu' ){\r\n\t\topts['lvl'] = 'ÎľĎ�ÎŻĎ�ξδο';\r\n\t\topts['inactives'] = 'Inaktívak';\r\n\t}\r\n\telse {\r\n\t\topts['lvl'] = ' Level';\t\r\n\t\topts['inactives'] = 'Inactives';\t\r\n\t}\t\t\r\n\treturn opts;\r\n}", "function isCurrentUrlFacebook() {\n return window.location.host === 'facebook.com' || window.location.host === 'www.facebook.com'\n}", "function change_GNPS_domainName() {\n\n if($scope.result.datasets == null) return;\n\n for(var i = 0; i < $scope.result.datasets.length; i++){\n if($scope.result.datasets[i].title.substr(0,4) == \"GNPS\"){\n $scope.result.datasets[i].source_title = \"GNPS\";\n }\n else{\n $scope.result.datasets[i].source_title = $scope.result.datasets[i].source;\n }\n }\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We extend nylas observables with our own methods. This happens on require of nylasobservables
extendRxObservables() { return require('nylas-observables'); }
[ "function wrap(observable) { return new Wrapper(observable); }", "createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(d => {\n d.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }", "createEventObservable(eventName, infoWindow) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._infoWindows.get(infoWindow).then(i => {\n i.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }", "createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(m => {\n m.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }", "makeObservable(propertyNames) {\n var that = this;\n for (var propertyName of propertyNames) {\n // wrap into anonymous function to get correct closure behavior\n (function(pn) {\n const fieldName = \"_\" + pn;\n that[fieldName] = that[pn]; // ensure initial value is set to created field\n Object.defineProperty(that, pn, {\n enumerable: true,\n configurable: true,\n get() { return that[\"_\" + pn]; },\n set(value) {\n const oldValue = that[fieldName];\n that[fieldName] = value;\n that._firePropertyChanged(pn, oldValue, value);\n }\n });\n const subscribeFunctionName = pn + \"Changed\";\n that[subscribeFunctionName] = (listenerFunction) => that._listen(pn, listenerFunction);\n })(propertyName);\n }\n }", "initialize() {\n\t\tconst weekTR = {ends:{value:7,unit:'days'},starts:{value:60,unit:'minutes'}};\n\t\tconst monthTR = {ends:{value:1,unit:'months'},starts:{value:60,unit:'minutes'}};\n\t\t\n\t\tthis.models['UserElectricityNowModel'] = this.master.modelRepo.get('UserElectricityNowModel');\n\t\tthis.models['UserElectricityNowModel'].subscribe(this);\n\t\t\n\t\tthis.models['UserElectricityDayModel'] = this.master.modelRepo.get('UserElectricityDayModel');\n\t\tthis.models['UserElectricityDayModel'].subscribe(this);\n\t\t\n\t\tconst model_ElectricityWeek = new UserApartmentModel({name:'UserElectricityWeekModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:weekTR});\n\t\tmodel_ElectricityWeek.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityWeekModel',model_ElectricityWeek);\n\t\tthis.models['UserElectricityWeekModel'] = model_ElectricityWeek;\n\t\t\n\t\tconst model_ElectricityMonth = new UserApartmentModel({name:'UserElectricityMonthModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:monthTR});\n\t\tmodel_ElectricityMonth.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityMonthModel',model_ElectricityMonth);\n\t\tthis.models['UserElectricityMonthModel'] = model_ElectricityMonth;\n\t\t\n\t\t\n\t\tthis.models['MenuModel'] = this.master.modelRepo.get('MenuModel');\n\t\tthis.models['MenuModel'].subscribe(this);\n\t\t\n\t\tthis.view = new UserElectricityView(this);\n\t\t// If view is shown immediately and poller is used, like in this case, \n\t\t// we can just call show() and let it start fetching... \n\t\t//this.show(); // Try if this view can be shown right now!\n\t}", "_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }", "function Subject() {\n // create an Observers list instance, passing all methods on\n this.observers = new ObserverList()\n}", "emit(...args) {\n debug('emitting event', ...args);\n super.emit(...args);\n }", "initDomEvents() {\n const me = this;\n\n // Set thisObj and element of the configured listener specs.\n me.scheduledBarEvents.element = me.schedulerEvents.element = me.timeAxisSubGridElement;\n me.scheduledBarEvents.thisObj = me.schedulerEvents.thisObj = me;\n\n // same listener used for different events\n EventHelper.on(me.scheduledBarEvents);\n EventHelper.on(me.schedulerEvents);\n }", "observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }", "addObserver(observer){\n \n this.observers.push(observer)\n }", "_startEventStreams() {\n let commandService = this.getService('core', 'commandService');\n\n // Create a stream for all the Discord events\n Object.values(Discord.Constants.Events).forEach((eventType) => {\n let streamName = eventType + '$';\n this.streams[streamName] =\n Rx.Observable\n .fromEvent(\n this.discord,\n eventType,\n function (...args) {\n if (args.length > 1) {\n return args;\n }\n return args[0];\n },\n );\n this.logger.debug(`Created stream nix.streams.${streamName}`);\n });\n\n // Create Nix specific event streams\n this.streams.command$ =\n this.streams.message$\n .filter((message) => message.channel.type === 'text')\n .filter((message) => commandService.msgIsCommand(message));\n\n // Apply takeUntil and share to all streams\n for (let streamName in this.streams) {\n this.streams[streamName] =\n this.streams[streamName]\n .do((data) => this.logger.silly(`Event ${streamName}: ${data}`))\n .takeUntil(this.shutdown$)\n .share();\n }\n\n let eventStreams = Rx.Observable\n .merge([\n ...Object.values(this.streams),\n this.streams.guildCreate$.flatMap((guild) => this.onNixJoinGuild(guild)),\n this.streams.command$.flatMap((message) => commandService.runCommandForMsg(message)),\n ])\n .ignoreElements();\n\n return Rx.Observable.of('').merge(eventStreams);\n }", "function Subject() {\n this.observers = new ObserverList();\n}", "_bindClockEvents() {\n this._clock.on(\"start\", (time, offset) => {\n offset = new _Ticks.TicksClass(this.context, offset).toSeconds();\n this.emit(\"start\", time, offset);\n });\n\n this._clock.on(\"stop\", time => {\n this.emit(\"stop\", time);\n });\n\n this._clock.on(\"pause\", time => {\n this.emit(\"pause\", time);\n });\n }", "constructor() {\n this.model = new TimerModel();\n this.view = new TimerView(this.model);\n\n this.model.registerObserver(this.view);\n\n this.subsribeToEvents();\n }", "_bindEventListenerCallbacks() {\n this._onShowAllBound = this._onShowAll.bind(this);\n this._onClearBound = this._onClear.bind(this);\n this._onCloseModalBound = this._onCloseModal.bind(this);\n }", "activatePolyfill_() {}", "rx(theta, q) {\n this.data.push('rx', theta, q);\n return this;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert MusicXML to timing, lyric, and mouth shape data
function convertXML2TimingList(xml) { var timingList = []; var lyricList = []; var mouthList = []; var curTimeSec = 0; // physical time in sec var tempo = 110; // default tempo var secPerDivision; var durationDiv; // duration of a note in division unit var durationSec; // duration of a note in sec unit console.log('lyric2mouth'); var lyric2mouth = new Lyric2Mouth(mouth2soundMapJP); try { // Parse measures in a document var measureList = xml.getElementsByTagName('measure'); // querySelectorAll... which is faster? for (var i=0; i < measureList.length; i++) { var measureElm = measureList[i]; var soundElm = measureElm.querySelector('sound'); if (soundElm != null) { var tempoAttr = soundElm.getAttribute('tempo'); if (tempoAttr != null) { tempo = tempoAttr; secPerDivision = 60 / tempo / divisions; // physical sec per tick (division) console.log('tempo: ' + tempo + ', secPerDivision: ' + secPerDivision); } } // Parse notes in a measure var noteList = measureElm.getElementsByTagName('note'); for (var j=0; j < noteList.length; j++) { var noteElm = noteList[j]; var durationElm = noteElm.querySelector('duration'); if (durationElm != null) { // Duration durationDiv = durationElm.textContent; durationSec = secPerDivision * durationDiv; timingList.push(curTimeSec); // start time of this note // Lyrics var textElm = noteElm.querySelector('lyric > text'); var lyric = (textElm != null ? textElm.textContent : restSymbolForLyric); lyricList.push(lyric); // Mouth shape mouthList.push(lyric2mouth.convert(lyric)); curTimeSec += durationSec; } } } } catch (e){ alert(e); } return {timing: timingList, lyric: lyricList, mouth: mouthList}; }
[ "function convertSongScript2XML(scriptArray) {\n var xmlSource = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n + '<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 2.0 Partwise//EN\"'\n + ' \"http://www.musicxml.org/dtds/partwise.dtd\">'\n + '<score-partwise>'\n + ' <identification>'\n + ' <encoding>'\n + ' <software>Scratch - sb2musicxml</software>'\n + ' <encoding-date></encoding-date>'\n + ' </encoding>'\n + ' </identification>'\n + ' <part-list>'\n + ' <score-part id=\"P1\">'\n + ' <part-name>MusicXML Part</part-name>'\n + ' </score-part>'\n + ' </part-list>'\n + ' <part id=\"P1\">'\n + ' <measure number=\"1\">'\n + ' <attributes>'\n + ' <divisions></divisions>'\n + ' <time>'\n + ' <beats></beats>'\n + ' <beat-type></beat-type>'\n + ' </time>'\n + ' </attributes>'\n + ' <sound/>'\n + ' </measure>'\n + ' </part>'\n + '</score-partwise>'\n \n var xml = (new DOMParser()).parseFromString(xmlSource, 'text/xml');\n \n // Insert date\n var date = new Date();\n //xml.getElementsByTagName('encoding-date')[0].textContent = date.toLocaleDateString().split('/').join('-');\n xml.querySelector('encoding-date').textContent = [date.getFullYear(), ('0' + (date.getMonth() + 1)).slice(-2), ('0' + date.getDate()).slice(-2)].join('-');\n\n // Default values (may be overwritten later)\n var tempo = 110;\n var beats = 2;\n var beatType = 4;\n var durationPerMeasure; // duration of a measure\n xml.querySelector('divisions').textContent = divisions; // default divisions\n xml.querySelector('sound').setAttribute('tempo', tempo); // default tempo\n xml.querySelector('beats').textContent = beats; // default beats\n xml.querySelector('beat-type').textContent = beatType; // default beat-type\n \n // Start parsing\n var measureNumber = 1;\n var initialNoteFlag = true;\n var cumSumDuration = 0 ; // cumulative duration to check whether a new measure needs to be created or not\n var curMeasureElm = xml.querySelector('measure[number=\"1\"]'); // current measure\n var syllabicState = 'single'; // for English lyric\n var reservedElmForNextMeasure = null; \n\n // Create a note with sound\n function _createSoundNote(step, alter, octave, duration, lyricText, syllabicState) {\n var pitchElm = xml.createElement('pitch'); // pitch {step, alter, octave}\n var stepElm = xml.createElement('step');\n stepElm.textContent = step;\n pitchElm.appendChild(stepElm);\n if (alter != 0) {\n var alterElm = xml.createElement('alter');\n alterElm.textContent = alter;\n pitchElm.appendChild(alterElm);\n }\n var octaveElm = xml.createElement('octave');\n octaveElm.textContent = octave;\n pitchElm.appendChild(octaveElm);\n\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n\n var lyricElm = xml.createElement('lyric'); // lyric {text, syllabic}\n var textElm = xml.createElement('text');\n textElm.textContent = lyricText;\n lyricElm.appendChild(textElm);\n var syllabicElm = xml.createElement('syllabic');\n syllabicElm.textContent = syllabicState;\n lyricElm.appendChild(syllabicElm);\n\n var noteElm = xml.createElement('note'); // note {pitch, duration, lyric}\n noteElm.appendChild(pitchElm);\n noteElm.appendChild(durationElm);\n noteElm.appendChild(lyricElm);\n\n return noteElm;\n }\n\n // Create a new 'rest' note\n function _createRestNote(duration) {\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n var noteElm = xml.createElement('note'); // note {rest, duration}\n noteElm.appendChild(xml.createElement('rest'));\n noteElm.appendChild(durationElm);\n return noteElm;\n }\n\n // Create sound \n function _createTempo(tempo) {\n var soundElm = xml.createElement('sound');\n soundElm.setAttribute('tempo', tempo);\n return soundElm;\n }\n\n // Overwrite duration-related variables (this needs to be called when 'beatType' or 'beats' is updated)\n function _updateDurationSettings() {\n durationPerMeasure = divisions * (4 / beatType) * beats;\n }\n\n // Check the duration of current measure, and create new measure if necessary\n // Also, add one empty measure with 'rest' if the initial note is NOT 'rest'\n function _createNewMeasureIfNecessary(duration, restFlag) {\n if (initialNoteFlag) {\n if (restFlag) { // if initial note is 'rest'\n cumSumDuration = 0; // reset cumSumDuration\n } else { // if initial note is sound (not 'rest'), add one empty measure\n curMeasureElm.appendChild(_createRestNote(durationPerMeasure));\n cumSumDuration = durationPerMeasure; // enforce to create measure=2 immediately after this\n }\n initialNoteFlag = false;\n }\n cumSumDuration += duration;\n if (cumSumDuration > durationPerMeasure) { // create new measure\n curMeasureElm = xml.createElement('measure');\n curMeasureElm.setAttribute('number', ++measureNumber); // increment number\n if (reservedElmForNextMeasure !== null) {\n curMeasureElm.appendChild(reservedElmForNextMeasure);\n console.log('append reserved tempo')\n reservedElmForNextMeasure = null;\n }\n xml.querySelector('part').appendChild(curMeasureElm); \n cumSumDuration = duration;\n } \n }\n\n // Find duration: variable or value\n function _extractDuration(arrayOrValue) {\n var duration = 0;\n if (Array.isArray(arrayOrValue) && arrayOrValue.length > 0 && arrayOrValue[0] === 'readVariable') { // variable\n duration = mapNoteDuration[arrayOrValue[1]];\n } else if (arrayOrValue > 0) { // value\n duration = arrayOrValue * divisions;\n }\n return duration; \n }\n\n _updateDurationSettings(); // update duration settings using default values\n \n for (var i=0; i < scriptArray.length; i++) { // for (var i in scriptArray) {\n if (i==0) continue; // skip\n // Tempo and beat settings\n if (scriptArray[i][0] === 'setTempoTo:') {\n tempo = scriptArray[i][1];\n console.log('tempo: ' + tempo);\n if (cumSumDuration == durationPerMeasure) {\n reservedElmForNextMeasure = _createTempo(tempo); // will add to the next measure\n } else {\n var soundElm = curMeasureElm.querySelector('sound');\n if (soundElm) {\n soundElm.setAttribute('tempo', tempo); // add or overwrite\n } else {\n curMeasureElm.appendChild(_createTempo(tempo)); // add immediately\n }\n console.log('add tempo immediately')\n }\n }\n if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beats') {\n beats = scriptArray[i][2];\n console.log('beats: ' + beats);\n xml.querySelector('beats').textContent = beats; // overwrite default beats\n _updateDurationSettings();\n }\n if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beat-type') {\n beatType = scriptArray[i][2];\n console.log('beat-type: ' + beatType);\n xml.querySelector('beat-type').textContent = beatType; // overwrite default beat-type\n _updateDurationSettings();\n }\n // Add sound note\n if (scriptArray[i][0] === 'noteOn:duration:elapsed:from:'){\n var duration = _extractDuration(scriptArray[i][2]);\n if (duration > 0) {\n if (scriptArray[i-1][0] === 'say:') { // if lyric exists\n try {\n var midiPitch = scriptArray[i][1];\n var step = chromaticStep[midiPitch % 12]; // chromatic step name ('C', etc.)\n var alter = chromaticAlter[midiPitch % 12]; // -1, 0, 1\n var octave = Math.floor(midiPitch / 12) - 1;\n var lyricText = scriptArray[i-1][1];\n if (lyricText.split('').slice(-1)[0] == '-') {\n lyricText = lyricText.replace(/-$/, ''); // remove the last char '-'\n if (syllabicState == 'single' || syllabicState == 'end') {\n syllabicState = 'begin';\n } else if (syllabicState == 'begin' || syllabicState == 'middle') {\n syllabicState = 'middle';\n }\n } else {\n if (syllabicState == 'single' || syllabicState == 'end') {\n syllabicState = 'single';\n } else if (syllabicState == 'begin' || syllabicState == 'middle') {\n syllabicState = 'end';\n }\n }\n console.log('midiPitch: ' + midiPitch + ', duration: ' + duration + ', ' + lyricText, ',' + syllabicState);\n \n // --- Append node ---\n var noteElm = _createSoundNote(step, alter, octave, duration, lyricText, syllabicState);\n _createNewMeasureIfNecessary(duration, false);\n curMeasureElm.appendChild(noteElm);\n } catch (e) {\n alert(e);\n }\n } else {\n console.log('No \"say\" block at i= ' + i);\n }\n } else {\n console.log('No variable at i= ' + i);\n }\n }\n // Add rest\n if (scriptArray[i][0] === 'rest:elapsed:from:') {\n var duration = _extractDuration(scriptArray[i][1]);\n if (duration > 0) {\n try {\n console.log('rest, duration: ' + duration);\n\n // --- Append node ---\n var noteElm = _createRestNote(duration);\n _createNewMeasureIfNecessary(duration, true);\n curMeasureElm.appendChild(noteElm);\n } catch (e) {\n alert(e);\n }\n } else {\n console.log('No variable at i= ' + i);\n }\n }\n }\n return xml;\n}", "function parse(lrc)\n{\n str=lrc.split(\"[\");\n //str[0]=\"\"\n //str[1]=\"xx:xx.xx]lyrics1\"\n //str[2]=\"yy:yy.yy]lyrics2\"\n //Skip str[0]\n for(var i=1;i<str.length;i++)\n {\n //str[i] format is 00:11.22]x\n //time format is 00:11.22\n var time=str[i].split(']')[0];\n //lyrics format is \"x\"\n var lyrics=str[i].split(']')[1];\n var minute=time.split(\":\")[0];\n var second=time.split(\":\")[1];\n //xx:xx.xx is converted into total seconds\n var sec=parseInt(minute)*60+parseInt(second);\n //save total seconds\n timeArray[i-1]=sec-sessionStorage.time;\n //save lyrics\n lyricsArray[i-1]=lyrics;\n }\n var allLyrics=document.getElementById(\"poemContent\");\n var counter = 0;\n for(var i=0;i<timeArray.length;i++) {\n allLyrics.innerHTML += '<p class=\"sentence\" id=\"' + i + '\">' + lyricsArray[i] + '</p>';\n\n }\n\n\n}", "static convertXMLToSRT(xml) {\n let subs = [];\n let index = 1;\n let reg = /(?:<text start=\"(.+?)\" dur=\"(.+?)\">(.+?)<\\/text>)/gs;\n xml.replace(reg, function ($0, $1, $2, $3) {\n subs.push({\n \"id\": index++,\n \"startTime\": +$1,\n \"endTime\": (+$1) + (+$2),\n \"text\": Tools.decodeHTML($3)\n });\n return $0;\n });\n return Subtitles.subToSRT(subs);\n }", "function musicXML(source, callback) {\n var part = kPartWise, musicXML, impl, type, xmlHeader;\n\n // Create the DOM implementation\n impl = domino.createDOMImplementation();\n\n // Create the DOCTYPE\n type = impl.createDocumentType(part.type, part.id, part.url);\n\n // Create the document itself\n musicXML = impl.createDocument('', '', null);\n\n // Create the <?xml ... ?> header\n xmlHeader = musicXML.createProcessingInstruction('xml',\n 'version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"');\n\n // Append both the header and the DOCTYPE\n musicXML.appendChild(xmlHeader);\n musicXML.appendChild(type);\n\n // Start serializing the MusicJSON document\n musicXML.appendChild(toXML(musicXML, source[part.type], part.type));\n\n callback(null, musicXML);\n}", "parseTrack() {\n\t\tlet done = false;\n\t\tif (this.fetchString(4) !== 'MTrk') {\n\t\t\tconsole.log('ERROR: No MTrk');\n\t\t\tthis.error = { code: 4, pos: ppos, msg: 'Failed to find MIDI track.' };\n\t\t\treturn;\n\t\t}\n\t\t// this.trks.push(new MIDItrack());\n\t\tlet len = this.fetchBytes(4);\n\t\t// console.log('len = '+len);\n\t\twhile (!done) {\n\t\t\tdone = this.parseEvent();\n\t\t}\n\t\tthis.labelCurrentTrack();\n\t\t// console.log('Track '+tpos);\n\t\t// console.log(this.trks[tpos].events);\n\t\t// console.log(trackDuration);\n\t\tif (trackDuration > this.duration) {\n\t\t\tthis.duration = trackDuration;\n\t\t}\n\t\ttrackDuration = 0;\n\t\tnoteDelta.fill(0);\n\t}", "parse() {\n\t\t// console.log('Started parsing');\n\t\tthis.parseHeader();\n\t\tif (this.error !== null) {\n\t\t\tif (this.error.code <= 2 && this.error.code !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.trks = new Array(this.ntrks);\n\t\tlet t0 = (new Date()).getTime();\n\t\tlet i;\n\t\tfor (i = 0; i < this.ntrks; i++) {\n\t\t\tthis.trks[i] = new MIDItrack();\n\t\t}\n\t\tfor (tpos = 0; tpos < this.ntrks; tpos++) {\n\t\t\tisNewTrack = true;\n\t\t\tthis.trks[tpos].usedInstruments.push();\n\t\t\tthis.parseTrack();\n\t\t\t// console.log(this.trks[tpos].events);\n\t\t}\n\t\tlet lowestQuantizeError = Infinity;\n\t\tlet bestBPB = 0;\n\t\tfor (i = 0; i < 16; i++) {\n\t\t\tlet total = 0;\n\t\t\tfor (let j = 0; j < this.trks.length; j++) {\n\t\t\t\ttotal += this.trks[j].quantizeErrors[i];\n\t\t\t}\n\t\t\t// console.log('BPB: ' + (i+1) + ', error: ' + total);\n\t\t\tif (total < lowestQuantizeError && i < 8) {\n\t\t\t\tlowestQuantizeError = total;\n\t\t\t\tbestBPB = i + 1;\n\t\t\t}\n\t\t}\n\t\tthis.blocksPerBeat = bestBPB;\n\t\t// console.log(this);\n\t\t// console.log(this.noteCount+' notes');\n\t\t// console.log('MIDI data loaded in '+((new Date).getTime() - t0)+' ms');\n\t}", "function parseRDF(self, xmpXml) {\n try {\n var parser = new DOMParser\n , xmlDoc = parser.parseFromString(xmpXml, 'application/xml')\n , rdfDesc = lastDesc(firstChild(xmlDoc.documentElement));\n\n readNS(self, rdfDesc);\n return rdfDesc;\n } catch (err) {\n throw new Error('cannot parse XMP XML');\n }\n }", "function createPlaylistFromMemory() {\n\tlist = openFileAndParseXML(\"videoList.xml\");\n\talert(list);\n\n\tvar items = list.getElementsByTagName(\"item\");\n\t\n\tif(items == null) {\n\t\treturn null;\n\t}\n\t\n\t//tja+mich+CLIP+ZIB+20+DURATION+00:06:38.942\n\t//+ENTRY++TITLE+1:+Signation+URL+2012-09-26_200_tl01_ZIB-20_Signation__47674401__o\n\t//+ENTRY++TITLE+2:+Zeugenschwund+beim+U-Ausschuss+URL+2012-09-26_2000\n\t//+CLIP+ZIB+20+DURATION+00:06:38.942\n\t//+ENTRY++TITLE+1:+Signation+URL+2012-09-26_200_tl01_ZIB-20_Signation__47674401__o\n\t//+ENTRY++TITLE+2:+Zeugenschwund+beim+U-Ausschuss+URL+2012-09-26_2000\n\tvar playlistString = \"playlistFromMemory\";\n\t\t\n var videoNames = [ ];\n var videoURLs = [ ];\n var videoDurations = [ ];\n var entryTitles = [[],[]];\n\tvar entryURLs = [[],[]];\n for (var index = 0; index < items.length; index++)\n {\n var titleElement = items[index].getElementsByTagName(\"title\")[0].firstChild.data;\n var durationElement = items[index].getElementsByTagName(\"duration\")[0].firstChild.data;\n\t\tvar entries = items[index].getElementsByTagName('entry');\n\t\t\n\t\tplaylistString += \" CLIP \" + titleElement + \" DURATION \" + durationElement;\n\t\t\t\t\n\t\tvar entryTitleElement = [ ];\n\t\tvar entryURLElement = [ ]\n\t\tfor (var j = 0; j < entries.length; j++)\n\t\t{\n\t\t\tentryTitleElement[j] = entries[j].getElementsByTagName(\"title\")[0].firstChild.data;\n\t\t\tif(j == 0)\tvar linkElement = entries[j].getElementsByTagName(\"link\")[0];\n\t\t\t\tentryURLElement[j] = entries[j].getElementsByTagName(\"link\")[0].firstChild.data;\t\n\t\t\t\t\n\t\t\tplaylistString += \" ENTRY \" + entryTitleElement[j] + \" URL \" + entryURLElement[j];\n\t\t}\n\t }\n\t \n\t alert(playlistString);\n\t \n\t tmp_pli = new Playlist(playlistString);\n\t return tmp_pli;\n}", "function texttoMusic(string) {\n \n //There are three different synths users can choose.\n switch (selectedSound) {\n case 1:\n var synth = new Tone.SimpleSynth().fan(waveform).toMaster();\n break;\n\n case 2:\n var synth = new Tone.MonoSynth().fan(waveform).toMaster();\n break;\n\n case 3:\n var synth = new Tone.SimpleFM().fan(waveform).toMaster();\n break;\n }\n \n //Generates a waveform to add to the novelty.\n //If a waveform already exists this skips creation.\n if(waveContext == 0) {\n //the waveform HTML generation.\n waveContext = $(\"<canvas>\", {\n \"id\" : \"waveform\"\n }).appendTo(\"#soundgroup\").get(0).getContext(\"2d\");\n }\n\t\n var waveformGradient;\n\n //Analyses and draws the waveform based on incoming data from the synth\n function drawWaveform(values){\n //draw the waveform\n waveContext.clearRect(0, 0, canvasWidth, canvasHeight);\n var values = waveform.analyse();\n\t\twaveContext.beginPath();\n\t\twaveContext.lineJoin = \"round\";\n\t\twaveContext.lineWidth = 6;\n\t\twaveContext.strokeStyle = waveformGradient;\n\t\twaveContext.moveTo(0, (values[0] / 255) * canvasHeight);\n\t\tfor (var i = 1, len = values.length; i < len; i++){\n \t\tvar val = values[i] / 255;\n\t\t var x = canvasWidth * (i / len);\n\t\t var y = val * canvasHeight;\n\t\t waveContext.lineTo(x, y);\n\t\t}\n\t\twaveContext.stroke();\n\t }\n\n //Calculates the size the waveform canvas element should be.\n var canvasWidth, canvasHeight;\n function sizeCanvases(){\n\t canvasWidth = $(\"#page\").width();\n\t canvasHeight = 255;\n\t waveContext.canvas.width = canvasWidth;\n\t waveContext.canvas.height = canvasHeight;\n\n\t //Form the gradient the waveform will use.\n\t waveformGradient = waveContext.createLinearGradient(0, 0, canvasWidth, canvasHeight);\n\t waveformGradient.addColorStop(0, \"#ddd\");\n\t waveformGradient.addColorStop(1, \"#000\"); \n }\n\n sizeCanvases();\n\t \n //Loops while the synth is outputting in order to draw the waveform.\n function loop(){\n requestAnimationFrame(loop);\n //Get waveform values in order to draw it.\n var waveformValues = waveform.analyse();\n drawWaveform(waveformValues);\n }\n loop();\n \n var j = 0.0;\n var k = \"\";\n \n //Converts ASCII to a note based on the tonemap.\n for(i = 0; i < string.length; i++) {\n var ascii = string[i].charCodeAt();\n if (ascii > 31 && ascii < 84) {\n ascii = ascii - 32;\n }\n else {\n ascii = ascii - 84;\n }\n k = \"+\" + j;\n \n //Triggers the note at the set interval k.\n synth.triggerAttack(tonemap[ascii], k);\n j += 0.25;\n }\n //Stops the synth after all notes have been played.\n synth.triggerRelease(k);\n \n //Starts the progress bar.\n progressBar(j);\n}", "function musicJSON(root) {\n if (!root) {\n return false;\n }\n\n // Create the main MusicJSON root\n var musicJSON = {};\n\n // Start the recursive serializing of the MusicXML document\n musicJSON[root.tagName.toLowerCase()] = parseElement(root);\n\n return musicJSON;\n}", "function _createSoundNote(step, alter, octave, duration, lyricText, syllabicState) {\n var pitchElm = xml.createElement('pitch'); // pitch {step, alter, octave}\n var stepElm = xml.createElement('step');\n stepElm.textContent = step;\n pitchElm.appendChild(stepElm);\n if (alter != 0) {\n var alterElm = xml.createElement('alter');\n alterElm.textContent = alter;\n pitchElm.appendChild(alterElm);\n }\n var octaveElm = xml.createElement('octave');\n octaveElm.textContent = octave;\n pitchElm.appendChild(octaveElm);\n\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n\n var lyricElm = xml.createElement('lyric'); // lyric {text, syllabic}\n var textElm = xml.createElement('text');\n textElm.textContent = lyricText;\n lyricElm.appendChild(textElm);\n var syllabicElm = xml.createElement('syllabic');\n syllabicElm.textContent = syllabicState;\n lyricElm.appendChild(syllabicElm);\n\n var noteElm = xml.createElement('note'); // note {pitch, duration, lyric}\n noteElm.appendChild(pitchElm);\n noteElm.appendChild(durationElm);\n noteElm.appendChild(lyricElm);\n\n return noteElm;\n }", "function findtags(musicfile){\n const tracks = document.querySelectorAll('.track')\n const jsmediatags = window.jsmediatags\n\n jsmediatags.read(musicfile, {\n onSuccess: function(tags){\n tracks.forEach(track => {\n let picture = tags.tags.picture\n if(picture){\n let base64String = ''\n for(let i = 0; i < picture.data.length; i++){\n base64String += String.fromCharCode(picture.data[i])\n }\n const imgSrc = 'data:'+ picture.format + ';base64,' + window.btoa(base64String);\n track.dataset.picture = imgSrc\n }\n \n track.dataset.title = tags.tags.title\n track.dataset.artist = tags.tags.artist\n track.dataset.album = tags.tags.album\n \n })\n \n \n },\n onError: function(error){\n console.log(error.type,error.info)\n \n }\n })\n}", "function parseWeatherData (src) {\n\tvar data = {}, nodes, node, l, i, subnode;\n\n\tvar parser = new DOMParser();\n\n\ttry {\n\t\tvar doc = parser.parseFromString(src, 'application/xml');\n\n\t\tnodes = doc.getElementsByTagName('TOWN');\n\n\t\tdata.city = decode1251(unescape(nodes[0].getAttribute('sname'))).replace('+', ' ');\n\n\t\tnodes = doc.getElementsByTagName('FORECAST');\n\n\t\tl = nodes.length; i = 0;\n\n\t\tforecasts_count = l;\n\n\t\tnode = nodes[0];\n\n\t\tdata.day = node.getAttribute('day');\n\t\tdata.month = node.getAttribute('month');\n\t\tdata.weekday = node.getAttribute('weekday');\n\t\tdata.tod = node.getAttribute('tod');\n\t\tdata.forecasts = {};\n\n\t\tvar forecast, tmp;\n\n\t\tdo {\n\t\t\tforecast = {};\n\n\t\t\tsubnode = node.getElementsByTagName('PHENOMENA')[0];\n\n\t\t\tforecast = util.defaults(forecast, getMappedAttributes(subnode, {\n\t\t\t\t'cloudiness':'clouds',\n\t\t\t\t'precipitation':'precip',\n\t\t\t\t'rpower':'rpower',\n\t\t\t\t'spower':'spower'\n\t\t\t}));\n\n\t\t\tsubnode = node.getElementsByTagName('PRESSURE')[0];\n\n\t\t\ttmp = getMappedAttributes(subnode, {\n\t\t\t\t'min':'min',\n\t\t\t\t'max':'max'\n\t\t\t});\n\n\t\t\tforecast.press = tmp.min + '-' + tmp.max;\n\n\t\t\tsubnode = node.getElementsByTagName('TEMPERATURE')[0];\n\n\t\t\ttmp = getMappedAttributes(subnode, {\n\t\t\t\t'min':'min',\n\t\t\t\t'max':'max'\n\t\t\t});\n\n\t\t\tforecast.temp = parseInt((parseInt(tmp.min) + parseInt(tmp.max)) / 2);\n\n\t\t\tsubnode = node.getElementsByTagName('WIND')[0];\n\n\t\t\ttmp = getMappedAttributes(subnode, {\n\t\t\t\t'min':'min',\n\t\t\t\t'max':'max',\n\t\t\t\t'direction':'wdir'\n\t\t\t});\n\n\t\t\tforecast.wspeed = parseInt((parseInt(tmp.min) + parseInt(tmp.max)) / 2);\n\t\t\tforecast.wdir = tmp.wdir;\n\n\t\t\tsubnode = node.getElementsByTagName('RELWET')[0];\n\n\t\t\tforecast = util.defaults(forecast, getMappedAttributes(subnode, {\n\t\t\t\t'max':'hum'\n\t\t\t}));\n\n\t\t\tdata.forecasts[i] = forecast;\n\n\t\t\tnode = nodes[++i];\n\t\t}\n\t\twhile (i < l);\n\t}\n\tcatch(e) {\n\t\tdata = {error:true};\n\t}\n\n\treturn data;\n}", "function normalizeMeasures(part) {\n const measuresLengths = part.measures.map(a => a.beat.length);\n console.log(\"12121212121212122\", measuresLengths);\n const lcmOfBeatLength = Util.lcm(...measuresLengths);\n // 1.转换成对0 2.把track内所有小节beat统一长度\n\n // 不能用foreach,foreach会直接bypass掉empty的(稀疏数组遍历)\n // part.measures.forEach((measure, measureIndex) => {});\n for (\n let measureIndex = 0;\n measureIndex <= part.measures.length - 1;\n measureIndex += 1\n ) {\n // console.log(\"measure::::::::::\", part.measures[measureIndex]);\n if (!part.measures[measureIndex]) {\n //建一个空小节\n //potential bug here\n part.measures[measureIndex] = {\n measure: measureIndex + 1,\n sequence: \"\",\n beat: Util.createUnderScores(lcmOfBeatLength),\n matchZero: true\n };\n } else {\n // 对位处理成对0\n if (!part.measures[measureIndex].matchZero) {\n // 对位转成对0,抽出对应的音//potential bug here, super mario....seemingly solved\n // const sequenceArray = JSON.parse(\n // `[${part.measures[measureIndex].sequence}]`.replace(\n // /([ABCDEFG]#*b*[1-9])/g,\n // '\"$1\"'\n // )\n // );\n let newSeqArray = part.measures[measureIndex].beat\n .split(\"\")\n .map((beatDigit, index) => {\n if (beatDigit.match(/\\d/g)) {\n return part.measures[measureIndex].sequence[index];\n } else {\n return \"\";\n }\n });\n newSeqArray = newSeqArray.filter(seq => !!seq); // 排掉空的\n console.log(\"bbbbbbbbbbb\", newSeqArray);\n\n // TO FIX HERE!!!\n // let s = JSON.stringify(newSeqArray.filter(note => note != \"\")).replace(\n // /\"/g,\n // \"\"\n // );\n // s = s.substring(1, s.length - 1); // 去掉数组的前后方括号\n // part.measures[measureIndex].sequence = s;\n part.measures[measureIndex].sequence = newSeqArray;\n part.measures[measureIndex].matchZero = true;\n }\n // console.log(\"jjjjjjjjjjjjjj\", part.measures[measureIndex].sequence);\n //对0的,beat延展就行了,原来000的可能变成0--0--0-- (根据最小公倍数)\n if (part.measures[measureIndex].beat.length < lcmOfBeatLength) {\n const ratio = lcmOfBeatLength / part.measures[measureIndex].beat.length;\n // console.log(\"[][][]\");\n // console.log(lcmOfBeatLength);\n // console.log(part.measures[measureIndex].beat.length);\n const append = Util.createScores(ratio - 1);\n part.measures[measureIndex].beat = part.measures[measureIndex].beat\n .split(\"\")\n .join(append);\n part.measures[measureIndex].beat += append;\n }\n }\n }\n\n console.log(\"=== measure after normalization===\");\n console.log(part.measures);\n\n //把所有measure合成一大段 应了老话「不要看小节线」\n part.tonepart = part.measures.reduce((a, b) => {\n // console.log(\"?\", a.sequence);\n return {\n // potential bug: if a/b is empty string, no comma here, seemingly solved\n // sequence: `${a.sequence}${a.sequence && b.sequence ? \",\" : \"\"}${\n // b.sequence\n // }`,\n sequence: a.sequence.concat(b.sequence),\n beat: `${a.beat}${b.beat}`\n };\n });\n console.log(\"=== final part in this part ===\");\n console.log(part.tonepart);\n}", "partsInit() {\n\t\t\tfunction loadXML (callback){\n\t\t\t\tlet xmlDoc;\n\t\t\t\t$.ajax({\n\t\t\t\t\turl: 'content/stories.xml',\n\t\t\t\t\ttype: 'GET',\n\t\t\t\t\tdataType: 'xml',\n\t\t\t\t\tsuccess: function(response){callback(response);}\n\t\t\t\t});\n\t\t\t\treturn xmlDoc;\n\t\t\t}\n\t\t\tloadXML((rs)=>{\n\t\t\t\tlet xml = $(rs);\n\t\t\t\tlet parts = xml.find('stories').children();\n\t\t\t\t\n\t\t\t\tfor (let p = $('.part'), q = 0; q < p.length; q++) {\n\t\t\t\t\t\n\t\t\t\t\tlet points = [];\n\t\t\t\t\tlet pointsNumber = parts.eq(q).children().length;\n\t\t\t\t\tfor (let pointsCount = 0; pointsCount<pointsNumber; pointsCount++){\n\t\t\t\t\t\tlet pointContent = parts.eq(q).children().eq(pointsCount).find('content').text();\n\t\t\t\t\t\tlet pointYear = parts.eq(q).children().eq(pointsCount).find('year').text();\n\t\t\t\t\t\tlet point = new Point(pointContent, pointYear);\n\t\t\t\t\t\tpoints.push(point);\n\t\t\t\t\t}\n\t\t\t\t\ttimeline._parts.push(new Part(p.eq(q), points));\n\t\t\t\t}\n\t\t\t});\n\t\t}", "formatMotionData(obj){\n var orientationX = {label:'orientationX',values:[]},\n orientationY = {label:'orientationY',values:[]},\n orientationZ = {label:'orientationZ',values:[]},\n accelerationX = {label:'accelerationX',values:[]},\n accelerationY = {label:'accelerationY',values:[]},\n accelerationZ = {label:'accelerationZ',values:[]},\n speed = {label:'speed',values:[]},\n distance = {label:'distance',values:[]}, earliestTime, skipsTime, latestTime;\n\n var totals = {\n s:0, d:0\n };\n var curVals = {};\n try{\n var newObj = obj[0];\n if(newObj){\n var previousTime;\n var avg = 0;\n for(let val in newObj){\n if(!isNaN(val)){\n var curVal = newObj[val];\n if(curVal){\n curVals = curVal;\n curVal.hasOwnProperty('speed') && speed.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['speed']}) && !isNaN(curVal['speed']) && (totals.s += curVal['speed']);\n curVal.hasOwnProperty('ox') && orientationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ox']});\n curVal.hasOwnProperty('oy') && orientationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oy']});\n curVal.hasOwnProperty('oz') && orientationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oz']});\n curVal.hasOwnProperty('ax') && accelerationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ax']});\n curVal.hasOwnProperty('ay') && accelerationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ay']});\n curVal.hasOwnProperty('az') && accelerationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['az']});\n curVal.hasOwnProperty('distance') && distance.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['distance']}) && !isNaN(curVal['distance']) && (totals.d += curVal['distance']);\n if(parseInt(val,10) < earliestTime || !earliestTime){\n earliestTime = parseInt(val,10);\n }\n if(parseInt(val,10) > latestTime || !latestTime){\n latestTime = parseInt(val,10);\n }\n if(parseInt(val,10) - previousTime > 10000){\n skipsTime = true;\n }\n previousTime = parseInt(val,10);\n }\n }\n }\n }\n }\n catch(e){\n console.error(e);\n }\n var data = {\n skipsTime:skipsTime,\n acceleration:[accelerationX,accelerationY,accelerationZ],\n speed:[speed],\n distance:[distance],\n orientation:[orientationX,orientationY,orientationZ],\n currentValues:curVals\n };\n data['acceleration'].earliestTime = earliestTime;\n data['acceleration'].latestTime = latestTime;\n data['acceleration'].skipsTime = skipsTime;\n data['speed'].earliestTime = earliestTime;\n data['speed'].latestTime = latestTime;\n data['speed'].skipsTime = skipsTime;\n data['speed'].avg = totals.s ? totals.s / speed.values.length : 0;\n data['distance'].earliestTime = earliestTime;\n data['distance'].latestTime = latestTime;\n data['distance'].skipsTime = skipsTime;\n data['distance'].avg = totals.d ? totals.d / speed.values.length : 0;\n data['orientation'].earliestTime = earliestTime;\n data['orientation'].latestTime = latestTime;\n data['orientation'].skipsTime = skipsTime;\n return data;\n }", "function convertToTimesFormat(callback){\n\t\t\t\tfor (var i = getTags.length - 1; i >= 0; i--){\n\t\t\t\t\t// quoraTags is what we're passing to the NY Times API, formatted accordingly\n\t\t\t\t\tvar tag = \"title:\" + getTags[i];\n\t\t\t\t\tquoraTags.push(tag);\n\t\t\t\t}\n\t\t\t\tcallback();\n\t\t\t}", "function MidiFile(data) {\n function readChunk(stream) {\n var id = stream.read(4);\n var length = stream.readInt32();\n return {\n 'id': id,\n 'length': length,\n 'data': stream.read(length)\n };\n }\n \n var lastEventTypeByte;\n \n function readEvent(stream) {\n var event = {};\n event.deltaTime = stream.readVarInt();\n var eventTypeByte = stream.readInt8();\n if ((eventTypeByte & 0xf0) == 0xf0) {\n /* system / meta event */\n if (eventTypeByte == 0xff) {\n /* meta event */\n event.type = 'meta';\n var subtypeByte = stream.readInt8();\n var length = stream.readVarInt();\n switch(subtypeByte) {\n case 0x00:\n event.subtype = 'sequenceNumber';\n if (length != 2) throw \"Expected length for sequenceNumber event is 2, got \" + length;\n event.number = stream.readInt16();\n return event;\n case 0x01:\n event.subtype = 'text';\n event.text = stream.read(length);\n return event;\n case 0x02:\n event.subtype = 'copyrightNotice';\n event.text = stream.read(length);\n return event;\n case 0x03:\n event.subtype = 'trackName';\n event.text = stream.read(length);\n return event;\n case 0x04:\n event.subtype = 'instrumentName';\n event.text = stream.read(length);\n return event;\n case 0x05:\n event.subtype = 'lyrics';\n event.text = stream.read(length);\n return event;\n case 0x06:\n event.subtype = 'marker';\n event.text = stream.read(length);\n return event;\n case 0x07:\n event.subtype = 'cuePoint';\n event.text = stream.read(length);\n return event;\n case 0x20:\n event.subtype = 'midiChannelPrefix';\n if (length != 1) throw \"Expected length for midiChannelPrefix event is 1, got \" + length;\n event.channel = stream.readInt8();\n return event;\n case 0x2f:\n event.subtype = 'endOfTrack';\n if (length != 0) throw \"Expected length for endOfTrack event is 0, got \" + length;\n return event;\n case 0x51:\n event.subtype = 'setTempo';\n if (length != 3) throw \"Expected length for setTempo event is 3, got \" + length;\n event.microsecondsPerBeat = (\n (stream.readInt8() << 16)\n + (stream.readInt8() << 8)\n + stream.readInt8()\n )\n return event;\n case 0x54:\n event.subtype = 'smpteOffset';\n if (length != 5) throw \"Expected length for smpteOffset event is 5, got \" + length;\n var hourByte = stream.readInt8();\n event.frameRate = {\n 0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30\n }[hourByte & 0x60];\n event.hour = hourByte & 0x1f;\n event.min = stream.readInt8();\n event.sec = stream.readInt8();\n event.frame = stream.readInt8();\n event.subframe = stream.readInt8();\n return event;\n case 0x58:\n event.subtype = 'timeSignature';\n if (length != 4) throw \"Expected length for timeSignature event is 4, got \" + length;\n event.numerator = stream.readInt8();\n event.denominator = Math.pow(2, stream.readInt8());\n event.metronome = stream.readInt8();\n event.thirtyseconds = stream.readInt8();\n return event;\n case 0x59:\n event.subtype = 'keySignature';\n if (length != 2) throw \"Expected length for keySignature event is 2, got \" + length;\n event.key = stream.readInt8(true);\n event.scale = stream.readInt8();\n return event;\n case 0x7f:\n event.subtype = 'sequencerSpecific';\n event.data = stream.read(length);\n return event;\n default:\n // console.log(\"Unrecognised meta event subtype: \" + subtypeByte);\n event.subtype = 'unknown'\n event.data = stream.read(length);\n return event;\n }\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf0) {\n event.type = 'sysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf7) {\n event.type = 'dividedSysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else {\n throw \"Unrecognised MIDI event type byte: \" + eventTypeByte;\n }\n } else {\n /* channel event */\n var param1;\n if ((eventTypeByte & 0x80) == 0) {\n /* running status - reuse lastEventTypeByte as the event type.\n eventTypeByte is actually the first parameter\n */\n param1 = eventTypeByte;\n eventTypeByte = lastEventTypeByte;\n } else {\n param1 = stream.readInt8();\n lastEventTypeByte = eventTypeByte;\n }\n var eventType = eventTypeByte >> 4;\n event.channel = eventTypeByte & 0x0f;\n event.type = 'channel';\n switch (eventType) {\n case 0x08:\n event.subtype = 'noteOff';\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n return event;\n case 0x09:\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n if (event.velocity == 0) {\n event.subtype = 'noteOff';\n } else {\n event.subtype = 'noteOn';\n }\n return event;\n case 0x0a:\n event.subtype = 'noteAftertouch';\n event.noteNumber = param1;\n event.amount = stream.readInt8();\n return event;\n case 0x0b:\n event.subtype = 'controller';\n event.controllerType = param1;\n event.value = stream.readInt8();\n return event;\n case 0x0c:\n event.subtype = 'programChange';\n event.programNumber = param1;\n return event;\n case 0x0d:\n event.subtype = 'channelAftertouch';\n event.amount = param1;\n return event;\n case 0x0e:\n event.subtype = 'pitchBend';\n event.value = param1 + (stream.readInt8() << 7);\n return event;\n default:\n throw \"Unrecognised MIDI event type: \" + eventType\n /* \n console.log(\"Unrecognised MIDI event type: \" + eventType);\n stream.readInt8();\n event.subtype = 'unknown';\n return event;\n */\n }\n }\n }\n \n stream = Stream(data);\n var headerChunk = readChunk(stream);\n if (headerChunk.id != 'MThd' || headerChunk.length != 6) {\n throw \"Bad .mid file - header not found\";\n }\n var headerStream = Stream(headerChunk.data);\n var formatType = headerStream.readInt16();\n var trackCount = headerStream.readInt16();\n var timeDivision = headerStream.readInt16();\n \n if (timeDivision & 0x8000) {\n throw \"Expressing time division in SMTPE frames is not supported yet\"\n } else {\n ticksPerBeat = timeDivision;\n }\n \n var header = {\n 'formatType': formatType,\n 'trackCount': trackCount,\n 'ticksPerBeat': ticksPerBeat\n }\n var tracks = [];\n for (var i = 0; i < header.trackCount; i++) {\n tracks[i] = [];\n var trackChunk = readChunk(stream);\n if (trackChunk.id != 'MTrk') {\n throw \"Unexpected chunk - expected MTrk, got \"+ trackChunk.id;\n }\n var trackStream = Stream(trackChunk.data);\n while (!trackStream.eof()) {\n var event = readEvent(trackStream);\n tracks[i].push(event);\n //console.log(event);\n }\n }\n \n return {\n 'header': header,\n 'tracks': tracks\n }\n}", "function processMostUniqueWords(songs) {\n // we will need to process lyric sections in the same way as part II \n // next we will need to process lyric sections for unique words \n // we will need two additional fields in our store for this section: \n // we will need to store the lyric sections\n // we will also need to store the unique words count \n const artistAttributions = [];\n const artistLyrics = [];\n songs.map(song => {\n // go through the lyrics_text and break out into lyric sections \n const lyricText = song.lyrics_text.split('\\n\\n');\n // go through each item in the array of lyric sections and sanitize the data for more artist attributions \n lyricText.map(section => {\n // now we are at the lyric section level for each song\n // we want to properly attribute a section to the artist or artists who sing it\n // we need to sanitize the string and return an array of artist(s)\n const regex = /\\[(.*?)\\]/g;\n const sectionAttribution = section.match(/\\[(.*?)\\]/g);\n const sectionLyricsSeparated = section.replace(regex, '');\n // console.log({sectionLyricsSeparated});\n // console.log({sectionAttribution});\n \n const attributionsHeadersSeparated = sectionAttribution[0].split(':');\n if (attributionsHeadersSeparated.length == 1) {\n // if length equals 1 it means there is no additional attribution on this section and we can attribute it to the primary_artist \n artistAttributions.push(song.primary_artist);\n artistLyrics.push({\n artistName: song.primary_artist,\n artistLyrics: sectionLyricsSeparated\n });\n\n \n } else {\n // else continue to find artists in headers \n const artistStr = attributionsHeadersSeparated[1].replace(/]/i, '');\n const artistStr2 = artistStr.replace(/Both/i, '');\n // noticed there were occurrences of the word Both throughout some of the data \n\n const headersStripped = artistStr2\n .split(',').join('').split('+').join('').split('&')\n // TODO: super ugly ^ go back and fix this \n headersStripped.map(artist => {\n artistAttributions.push(artist.trim())\n const trimmedName = artist.trim();\n let obj = {\n artistName: trimmedName,\n artistLyrics: sectionLyricsSeparated\n }\n artistLyrics.push(obj);\n \n });\n\n\n }\n\n\n });\n });\n // console.log(artistAttributions);\n console.log(artistLyrics);\n\n // assignLyricSectionToArtist(artistAttributions);\n // assignLyricTextToArtist(artistLyrics);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a byte from the keyboard memory bank. This is an odd system where bits in the address map to the various bytes, and you can read the OR'ed addresses to read more than one byte at a time. This isn't used by the ROM, I don't think. For the last byte we fake the Shift key if necessary.
readKeyboard(addr, clock) { addr -= BEGIN_ADDR; let b = 0; // Dequeue if necessary. if (clock > this.keyProcessMinClock) { const keyWasPressed = this.processKeyQueue(); if (keyWasPressed) { this.keyProcessMinClock = clock + KEY_DELAY_CLOCK_CYCLES; } } // OR together the various bytes. for (let i = 0; i < this.keys.length; i++) { let keys = this.keys[i]; if ((addr & (1 << i)) !== 0) { if (i === 7) { // Modify keys based on the shift force. switch (this.shiftForce) { case ShiftState.NEUTRAL: // Nothing. break; case ShiftState.FORCE_UP: // On the Model III the first two bits are left and right shift, // though we don't handle the right shift anywhere. keys &= ~0x03; break; case ShiftState.FORCE_DOWN: keys |= 0x01; break; } } b |= keys; } } return b; }
[ "async readByte() {\n while (this.r === this.w) {\n if (this.eof)\n return Deno.EOF;\n await this._fill(); // buffer is empty.\n }\n const c = this.buf[this.r];\n this.r++;\n // this.lastByte = c;\n return c;\n }", "popByte() {\n const value = this.readByte(this.regs.sp);\n this.regs.sp = inc16(this.regs.sp);\n return value;\n }", "readWord(address) {\n const lowByte = this.readByte(address);\n const highByte = this.readByte(address + 1);\n return word(highByte, lowByte);\n }", "function determineKeyPress(keycode) {\n switch (keycode) {\n case 49: return 1;\n case 50: return 2;\n case 51: return 3;\n case 52: return 4;\n case 53: return 5;\n case 54: return 6;\n case 55: return 7;\n case 56: return 8;\n case 57: return 9;\n }\n return 0;\n}", "getKeyboardValueForPort(port)\n {\n // initial value: no keys pressed\n let val = 0xFF;\n\n // traverse all values in port array\n for (let i = 0; i < this.kbports.length; i++)\n {\n // port to be tested\n let testport = this.kbports[i];\n if ((~(testport | port)) & 0xFF00) {\n // port was requested, use its value\n val &= this.kbbits[testport];\n }\n }\n return val;\n }", "readcharoreof()\n\t{\n\t\tif (this.pos >= this.input.length)\n\t\t\treturn null;\n\t\treturn this.input.charAt(this.pos++);\n\t}", "function getByteN(value, n) {\n return ((value >> (8 * n)) & 0b11111111);\n}", "function nextKey() {\n var c = decode(1 << numBits);\n if (c < 2) {\n // A key of 0 or 1 prefixes a new character for the dictionary.\n remember(charFor(decode(1 << (c*8+8))));\n c = dictSize-1;\n }\n return c;\n }", "readKey() {\n const r = this.reader;\n\n let code = r.u8();\n\n if (code === 0x00) return;\n\n let f = null;\n let x = null;\n let y = null;\n let z = null;\n\n if ((code & 0xe0) > 0) {\n // number of frames, byte case\n\n f = code & 0x1f;\n\n if (f === 0x1f) {\n f = 0x20 + r.u8();\n } else {\n f = 1 + f;\n }\n } else {\n // number of frames, half word case\n\n f = code & 0x3;\n\n if (f === 0x3) {\n f = 4 + r.u8();\n } else {\n f = 1 + f;\n }\n\n // half word values\n\n code = code << 3;\n\n const h = r.s16big();\n\n if ((h & 0x4) > 0) {\n x = h >> 3;\n code = code & 0x60;\n\n if ((h & 0x2) > 0) {\n y = r.s16big();\n code = code & 0xa0;\n }\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x2) > 0) {\n y = h >> 3;\n code = code & 0xa0;\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x1) > 0) {\n z = h >> 3;\n code = code & 0xc0;\n }\n }\n\n // byte values (fallthrough)\n\n if ((code & 0x80) > 0) {\n if (x !== null) {\n throw new Error('Expected undefined x in SEQ animation data');\n }\n\n x = r.s8();\n }\n\n if ((code & 0x40) > 0) {\n if (y !== null) {\n throw new Error('Expected undefined y in SEQ animation data');\n }\n\n y = r.s8();\n }\n\n if ((code & 0x20) > 0) {\n if (z !== null) {\n throw new Error('Expected undefined z in SEQ animation data');\n }\n\n z = r.s8();\n }\n\n return { f, x, y, z };\n }", "function decodeCB(z80) {\n const inst = fetchInstruction(z80);\n const func = decodeMapCB.get(inst);\n if (func === undefined) {\n console.log(\"Unhandled opcode in CB: \" + toHex(inst, 2));\n }\n else {\n func(z80);\n }\n}", "next () {\n // Wrap cursor to the beginning of the next non-empty buffer if at the\n // end of the current buffer\n while (this.buffer_i < this.buffers.length &&\n this.offset >= this.buffers[this.buffer_i].length) {\n this.offset = 0;\n this.buffer_i ++;\n }\n\n if (this.buffer_i < this.buffers.length) {\n let byte = this.buffers[this.buffer_i][this.offset];\n\n // Advance cursor\n this.offset++;\n return byte;\n }\n else {\n throw this.END_OF_DATA;\n }\n }", "function keyDown(key) {\n key = key.toUpperCase();\n if (keyStatus.hasOwnProperty(key)) {\n return keyStatus[key];\n }\n return false;\n}", "function getBitFromByte(num, mask) {\n return Boolean(num & mask)\n }", "function rawBootClock(clock)\n {\n switch (clock) {\n case 'ACLK':\n case 'BCLK':\n case 'aclk':\n case 'bclk':\n return (32768);\n default:\n return (3000000);\n }\n}", "function utf8CheckByte(_byte) {\n if (_byte <= 0x7F) return 0;else if (_byte >> 5 === 0x06) return 2;else if (_byte >> 4 === 0x0E) return 3;else if (_byte >> 3 === 0x1E) return 4;\n return -1;\n} // Checks at most 3 bytes at the end of a Buffer in order to detect an", "static bytes27(v) { return b(v, 27); }", "function decodeDDCB(z80) {\n z80.incTStateCount(3);\n const offset = z80.readByteInternal(z80.regs.pc);\n z80.regs.memptr = add16(z80.regs.ix, signedByte(offset));\n z80.regs.pc = inc16(z80.regs.pc);\n z80.incTStateCount(3);\n const inst = z80.readByteInternal(z80.regs.pc);\n z80.incTStateCount(2);\n z80.regs.pc = inc16(z80.regs.pc);\n const func = decodeMapDDCB.get(inst);\n if (func === undefined) {\n console.log(\"Unhandled opcode in DDCB: \" + toHex(inst, 2));\n }\n else {\n func(z80);\n }\n}", "function read_encoder(a, b)\n{\n var a;\n var b;\n var new_state = 0;\n var return_state;\n a = bone.digitalRead('P8_13');\n b = bone.digitalRead('P8_15');\n new_state = (a * 4) | (b * 2) | (a ^ b);\n return_state = (new_state - old_state) % 4;\n if (return_state)\n console.log(' a:' + a + ' b: ' + b + ' new_state = ' + new_state + ' return = ' + return_state);\n old_state = new_state;\n return (return_state);\n}", "fetch() {\n const nextInstructionAddress = this.getRegister(\"ip\");\n const instruction = this.memory.getUint8(nextInstructionAddress);\n this.setRegister(\"ip\", nextInstructionAddress + 1);\n return instruction;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::S3::Bucket.VersioningConfiguration` resource
function cfnBucketVersioningConfigurationPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnBucket_VersioningConfigurationPropertyValidator(properties).assertSuccess(); return { Status: cdk.stringToCloudFormation(properties.status), }; }
[ "function CfnBucket_VersioningConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"VersioningConfigurationProperty\"');\n}", "function cfnStorageLensS3BucketDestinationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_S3BucketDestinationPropertyValidator(properties).assertSuccess();\n return {\n AccountId: cdk.stringToCloudFormation(properties.accountId),\n Arn: cdk.stringToCloudFormation(properties.arn),\n Encryption: cfnStorageLensEncryptionPropertyToCloudFormation(properties.encryption),\n Format: cdk.stringToCloudFormation(properties.format),\n OutputSchemaVersion: cdk.stringToCloudFormation(properties.outputSchemaVersion),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n };\n}", "function cfnVirtualGatewayLoggingFormatPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_LoggingFormatPropertyValidator(properties).assertSuccess();\n return {\n Json: cdk.listMapper(cfnVirtualGatewayJsonFormatRefPropertyToCloudFormation)(properties.json),\n Text: cdk.stringToCloudFormation(properties.text),\n };\n}", "function cfnVirtualGatewayVirtualGatewayFileAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayFileAccessLogPropertyValidator(properties).assertSuccess();\n return {\n Format: cfnVirtualGatewayLoggingFormatPropertyToCloudFormation(properties.format),\n Path: cdk.stringToCloudFormation(properties.path),\n };\n}", "function cfnVirtualGatewayVirtualGatewayLoggingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayLoggingPropertyValidator(properties).assertSuccess();\n return {\n AccessLog: cfnVirtualGatewayVirtualGatewayAccessLogPropertyToCloudFormation(properties.accessLog),\n };\n}", "function cfnStorageLensAwsOrgPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_AwsOrgPropertyValidator(properties).assertSuccess();\n return {\n Arn: cdk.stringToCloudFormation(properties.arn),\n };\n}", "function cfnVirtualGatewayVirtualGatewaySpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewaySpecPropertyValidator(properties).assertSuccess();\n return {\n BackendDefaults: cfnVirtualGatewayVirtualGatewayBackendDefaultsPropertyToCloudFormation(properties.backendDefaults),\n Listeners: cdk.listMapper(cfnVirtualGatewayVirtualGatewayListenerPropertyToCloudFormation)(properties.listeners),\n Logging: cfnVirtualGatewayVirtualGatewayLoggingPropertyToCloudFormation(properties.logging),\n };\n}", "function cfnVirtualNodeFileAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_FileAccessLogPropertyValidator(properties).assertSuccess();\n return {\n Format: cfnVirtualNodeLoggingFormatPropertyToCloudFormation(properties.format),\n Path: cdk.stringToCloudFormation(properties.path),\n };\n}", "function cfnVirtualGatewayVirtualGatewayAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayAccessLogPropertyValidator(properties).assertSuccess();\n return {\n File: cfnVirtualGatewayVirtualGatewayFileAccessLogPropertyToCloudFormation(properties.file),\n };\n}", "function cfnStorageLensStorageLensConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_StorageLensConfigurationPropertyValidator(properties).assertSuccess();\n return {\n AccountLevel: cfnStorageLensAccountLevelPropertyToCloudFormation(properties.accountLevel),\n AwsOrg: cfnStorageLensAwsOrgPropertyToCloudFormation(properties.awsOrg),\n DataExport: cfnStorageLensDataExportPropertyToCloudFormation(properties.dataExport),\n Exclude: cfnStorageLensBucketsAndRegionsPropertyToCloudFormation(properties.exclude),\n Id: cdk.stringToCloudFormation(properties.id),\n Include: cfnStorageLensBucketsAndRegionsPropertyToCloudFormation(properties.include),\n IsEnabled: cdk.booleanToCloudFormation(properties.isEnabled),\n StorageLensArn: cdk.stringToCloudFormation(properties.storageLensArn),\n };\n}", "function cfnStorageLensBucketsAndRegionsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_BucketsAndRegionsPropertyValidator(properties).assertSuccess();\n return {\n Buckets: cdk.listMapper(cdk.stringToCloudFormation)(properties.buckets),\n Regions: cdk.listMapper(cdk.stringToCloudFormation)(properties.regions),\n };\n}", "function DocumentationVersion(props) {\n return __assign({ Type: 'AWS::ApiGateway::DocumentationVersion' }, props);\n }", "function cfnStorageLensBucketLevelPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_BucketLevelPropertyValidator(properties).assertSuccess();\n return {\n ActivityMetrics: cfnStorageLensActivityMetricsPropertyToCloudFormation(properties.activityMetrics),\n AdvancedCostOptimizationMetrics: cfnStorageLensAdvancedCostOptimizationMetricsPropertyToCloudFormation(properties.advancedCostOptimizationMetrics),\n AdvancedDataProtectionMetrics: cfnStorageLensAdvancedDataProtectionMetricsPropertyToCloudFormation(properties.advancedDataProtectionMetrics),\n DetailedStatusCodesMetrics: cfnStorageLensDetailedStatusCodesMetricsPropertyToCloudFormation(properties.detailedStatusCodesMetrics),\n PrefixLevel: cfnStorageLensPrefixLevelPropertyToCloudFormation(properties.prefixLevel),\n };\n}", "function cfnBucketNotificationConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_NotificationConfigurationPropertyValidator(properties).assertSuccess();\n return {\n EventBridgeConfiguration: cfnBucketEventBridgeConfigurationPropertyToCloudFormation(properties.eventBridgeConfiguration),\n LambdaConfigurations: cdk.listMapper(cfnBucketLambdaConfigurationPropertyToCloudFormation)(properties.lambdaConfigurations),\n QueueConfigurations: cdk.listMapper(cfnBucketQueueConfigurationPropertyToCloudFormation)(properties.queueConfigurations),\n TopicConfigurations: cdk.listMapper(cfnBucketTopicConfigurationPropertyToCloudFormation)(properties.topicConfigurations),\n };\n}", "function cfnBucketServerSideEncryptionRulePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_ServerSideEncryptionRulePropertyValidator(properties).assertSuccess();\n return {\n BucketKeyEnabled: cdk.booleanToCloudFormation(properties.bucketKeyEnabled),\n ServerSideEncryptionByDefault: cfnBucketServerSideEncryptionByDefaultPropertyToCloudFormation(properties.serverSideEncryptionByDefault),\n };\n}", "function cfnVirtualGatewayVirtualGatewayConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualGatewayVirtualGatewayHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualGatewayVirtualGatewayHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n };\n}", "function cfnBucketRulePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_RulePropertyValidator(properties).assertSuccess();\n return {\n AbortIncompleteMultipartUpload: cfnBucketAbortIncompleteMultipartUploadPropertyToCloudFormation(properties.abortIncompleteMultipartUpload),\n ExpirationDate: cdk.dateToCloudFormation(properties.expirationDate),\n ExpirationInDays: cdk.numberToCloudFormation(properties.expirationInDays),\n ExpiredObjectDeleteMarker: cdk.booleanToCloudFormation(properties.expiredObjectDeleteMarker),\n Id: cdk.stringToCloudFormation(properties.id),\n NoncurrentVersionExpiration: cfnBucketNoncurrentVersionExpirationPropertyToCloudFormation(properties.noncurrentVersionExpiration),\n NoncurrentVersionExpirationInDays: cdk.numberToCloudFormation(properties.noncurrentVersionExpirationInDays),\n NoncurrentVersionTransition: cfnBucketNoncurrentVersionTransitionPropertyToCloudFormation(properties.noncurrentVersionTransition),\n NoncurrentVersionTransitions: cdk.listMapper(cfnBucketNoncurrentVersionTransitionPropertyToCloudFormation)(properties.noncurrentVersionTransitions),\n ObjectSizeGreaterThan: cdk.numberToCloudFormation(properties.objectSizeGreaterThan),\n ObjectSizeLessThan: cdk.numberToCloudFormation(properties.objectSizeLessThan),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n Status: cdk.stringToCloudFormation(properties.status),\n TagFilters: cdk.listMapper(cfnBucketTagFilterPropertyToCloudFormation)(properties.tagFilters),\n Transition: cfnBucketTransitionPropertyToCloudFormation(properties.transition),\n Transitions: cdk.listMapper(cfnBucketTransitionPropertyToCloudFormation)(properties.transitions),\n };\n}", "function cfnVirtualGatewayJsonFormatRefPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_JsonFormatRefPropertyValidator(properties).assertSuccess();\n return {\n Key: cdk.stringToCloudFormation(properties.key),\n Value: cdk.stringToCloudFormation(properties.value),\n };\n}", "function cfnBucketEventBridgeConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_EventBridgeConfigurationPropertyValidator(properties).assertSuccess();\n return {\n EventBridgeEnabled: cdk.booleanToCloudFormation(properties.eventBridgeEnabled),\n };\n}", "function cfnMultiRegionAccessPointRegionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnMultiRegionAccessPoint_RegionPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n BucketAccountId: cdk.stringToCloudFormation(properties.bucketAccountId),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A single cell on the board. This has no state just two props: flipCellsAroundMe: a function rec'd from the board which flips this cell and the cells around of it isLit: boolean, is this cell lit? coords: the y and x coordinates of the cell used in "flipCellsAroundMe" handleClick: This handles clicks by calling flipCellsAroundMe
function Cell({ flipCellsAroundMe, isLit, coords}) { const handleClick = () => { flipCellsAroundMe(coords); }; const classes = `Cell ${isLit ? "Cell-lit" : ""}`; return <div className={classes} onClick={handleClick}></div>; }
[ "function flipCell() {\n // Run flip from style.css for the clicked cell (this)\n this.classList.toggle('flip');\n\n flippedCell = this;\n cellColor = flippedCell.dataset.color;\n outcome(cellColor);\n}", "__handleClick(evt) {\n // get x from ID of clicked cell\n const x = +evt.target.id[0]\n \n // get next spot in column (if none, ignore click)\n const y = this.__findSpotForCol( x );\n if (y === null) {\n return;\n }\n \n // place piece in board and add to HTML table\n this.placePiece(x, y);\n \n // check for win\n if (this.__checkForWin( x, y )) {\n return this.__endGame(`Player ${this.currPlayer} won!`);\n }\n \n // check for tie\n if ( this.__innerBoard.every(row => row[ this.height-1 ]) ) {\n return this.__endGame('Tie!');\n }\n\n // switch currPlayer\n this.switchCurrentPlayer()\n }", "toggleFlagPosition({row, col}) {\n // if game state is finished, return game state\n let gameFinished = this._state.endgame !== RSGame.GAME_IN_PROGRESS;\n if (gameFinished) {\n return this._state;\n }\n let currCell = this._state.fog[row][col];\n if (currCell === RSGame.HIDDEN_CELL) {\n this._state.fog[row][col] = RSGame.FLAGGED_CELL;\n } else if (currCell === RSGame.FLAGGED_CELL) {\n this._state.fog[row][col] = RSGame.HIDDEN_CELL\n }\n return this._state;\n }", "function check_unclicked_cell(cell) {\n\tif ((!cell.hasClass(\"clicked\"))&&(!cell.hasClass(\"flag\"))){\n\t\tvar cell_adjacent = get_adjacent(cell);\n\t\t/* If a cell with mine is left-clicked and it is not marked as mine, the user lose\n\t\tthe game */\n\t\tif (cell.hasClass(\"mine\")) {\n\t\t\tlose_game();\n\t\t\tcell.css(\"background-color\", \"red\");\n\t\t\t$(\"#minefield\").addClass(\"lose\");\n\t\t}\n\t\telse {\n\t\t\t/* If a cell without mine is left-clicked, clear the cell and if the cell \n\t\t\thasn't any adjacent mine, clear its adjacent cell */\n\t\t\tif (cell.attr(\"value\") == 0) {\n\t\t\t\tcell.addClass(\"clicked\");\n\t\t\t\tcell_adjacent.forEach(function(entry) {\n\t\t\t\t\tcheck_unclicked_cell(entry);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcell.html(cell.attr(\"value\"));\n\t\t\t\tcell.addClass(\"clicked\");\n\t\t\t}\n\t\t}\n\t}\n}", "function gridClickListener(event) {\n const ctx = canvas.getContext('2d');\n\n let [row, col] = translateClickPosition(event);\n\n console.log(\"clicked [\",row ,\"][\",col, \"]\");\n\n // start the timer once a grid cell is clicked (if it hasn't been started already)\n if (!timer) setTimer();\n\n if (event.ctrlKey) {\n // mark a cell with a question mark\n minesweeper.toggleQuestion(row, col);\n } else if (event.shiftKey) {\n // flag a cell\n minesweeper.toggleFlag(row, col);\n } else {\n // cell was left clicked, reveal the cell\n minesweeper.revealCell(row, col);\n }\n\n // check if game is won or lost\n if (minesweeper.isGameWon()) {\n renderGameWon(ctx);\n } else if (minesweeper.isGameLost()) {\n renderGameLost(ctx);\n } else {\n // game is not over, so render the grid state\n renderGrid(ctx);\n mineCounter.innerText = minesweeper.remainingFlags().toString(10).padStart(3, \"0\");\n }\n\n}", "function toggleSnakeCell(x, y) {\n cellDiv(x, y).toggleClass('snake');\n}", "function currentCell(neighborRow, neighborCol, currRow, currCol) {\n return neighborRow === currRow && neighborCol === currCol\n }", "function cellClick(id) {\n\n\tplayerMove = id.split(\",\");\n\tif (playerMove[0] == currentCell[0] && playerMove[1] == currentCell[1]) {\n\n\t\tvar cellClicked = document.getElementById(id);\n\t\tcellClicked.style.backgroundColor = getRandomColor();\n\t\tscoreCounter++;\n\t\tmoveMade = true;\n\t\t$(cellClicked).text(scoreCounter);\n\t\tsetTimeout(function() {\n\t\t\t$(cellClicked).text(\"\");\n\t\t}, 1000);\n\n\t} else {\n\t\tgameOver = true;\n\n\t\tvar lastClicked = document.getElementById(id);\n\n\t\tvar lastColor = $(lastClicked).css(\"background-color\");\n\n\t\tfor (var row = 1; row <= tableHeight; row++) {\n\t\t\tfor (var col = 1; col <= tableWidth; col++) {\n\t\t\t\tdocument.getElementById(row + \",\" + col).style.backgroundColor = lastColor;\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\t\n}", "UpdateCellState(e)\n {\n var x = Math.trunc(e.offsetX/11);\n var y = Math.trunc(e.offsetY/11);\n\n // Keep within array bounds\n if(x >= this.state.gridWidth)\n {\n x = this.state.gridWidth-1;\n }\n if(y >= this.state.gridHeight)\n {\n y = this.state.gridHeight-1;\n }\n\n // Check if we are drawing to allow for clearing alive cells.\n if(!this.state.isDrawing)\n {\n if(this.state.cellStates[y][x] == 1)\n {\n this.state.cellStates[y][x] = 0;\n }\n else\n {\n this.state.cellStates[y][x] = 1;\n }\n }\n else\n {\n this.state.cellStates[y][x] = 1;\n }\n\n this.DrawGrid();\n }", "function cellClicked(cell) {\n if (gameOver == false && cell.innerText == \"\") {\n // decrease # of empty cells by 1\n empty--;\n\n /* set content according to players mark and changes current player. In the end tells weather there is a winner or not */\n cell.innerHTML = player;\n checkWin();\n player = (player === \"X\") ? \"O\" : \"X\";\n document.getElementById(\"player\").innerHTML = player;\n }\n}", "revealPosition({row, col}) {\n // if game state is finished or cell is not hidden, return game state\n let gameFinished = this._state.endgame !== RSGame.GAME_IN_PROGRESS;\n let isHiddenCell = this._state.fog[row][col] === RSGame.HIDDEN_CELL;\n if (gameFinished || !isHiddenCell) {\n return this._state;\n }\n // find out which cells to reveal and reveal them\n let cellsToReveal = this._getCellsToReveal({row, col});\n cellsToReveal.forEach(({row, col}) => {\n this._state.fog[row][col] = RSGame.REVEALED_CELL;\n });\n // if revealing a mine cell, convert it to a hot mine and end the game\n if (this._state.minefield[row][col] === RSGame.MINE_CELL) {\n this._state.minefield[row][col] = RSGame.HOT_MINE_CELL;\n this._setPlayerLostEndgame();\n } else if (this._playerHasWon()) {\n this._setPlayerWonEndgame();\n }\n return this._state;\n }", "visitCell(x, y) {\n this.maze[x][y] = true;\n }", "function showCell (evt) {\n evt.target.className = evt.target.className.replace(\"hidden\", \"\");\n if (evt.target.classList.contains(\"mine\")) {\n showAllMines();\n playBomb();\n reset();\n return;\n }\n showSurrounding(evt.target);\n checkForWin();\n}", "isSingleCell() {\n return this.fromRow == this.toRow && this.fromCell == this.toCell;\n }", "function drawRevealedCell(ctx, row, col, bgColor = CELL_BG_COLOR) {\n const x = col * CELL_SIZE + col + 2; // x origin\n const y = row * CELL_SIZE + row + 2; // y origin\n\n const cell = new Path2D();\n cell.rect(x, y, CELL_SIZE, CELL_SIZE);\n ctx.fillStyle = bgColor;\n ctx.fill(cell);\n\n // if a cell contains a mine, then draw the mine character in the cell, else draw the adjacent mine count\n if ( minesweeper.isMinedCell(row, col) ) {\n drawText(ctx, row, col, MINE);\n } else {\n const adjMineCount = minesweeper.cellAdjMineCount(row, col);\n ctx.fillStyle = getTextColor(adjMineCount);\n drawText(ctx, row, col, adjMineCount);\n }\n}", "function startGame() {\n allCells.forEach((cell) => {\n cell.classList.remove(xMarker);\n cell.classList.remove(oMarker);\n cell.removeEventListener(\"click\", handleClick);\n cell.addEventListener(\"click\", handleClick, { once: true });\n });\n}", "setStateOfCell(i,j){\n this.field[i][j].setState(true);\n this.field[i][j].draw();\n }", "function highlightCell(mouseEvent) {\n if (mouseEvent.target.tagName != \"TD\")\n return;\n let row = 6;\n let col = mouseEvent.target.cellIndex;\n let highlight = document.getElementById(\"highlight\");\n\n while (--row >= 0) {\n if (!boardState[row][col])\n break;\n }\n if (row == -1) {\n highlight.style.visibility = \"hidden\";\n return;\n }\n let openCell = document.getElementById(\"board\").rows[row].cells[col];\n let cellBounds = openCell.getBoundingClientRect();\n highlight.style.left = cellBounds.left + \"px\";\n highlight.style.top = cellBounds.top + \"px\";\n highlight.style.visibility = \"visible\";\n}", "function drawCell(cell) {\n ctx.beginPath();\n ctx.rect(cell.x, cell.y, cell.w, cell.h);\n ctx.fillStyle = CELL_COLOR[cell.type];\n ctx.fill();\n ctx.closePath();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates an array list of PAGE.appGroups Items along with it's file and group. Handy for updating the documentation when changes were made
function associateFileDesc() { let result = { group: [], file: [], desc: [] }; PAGE.appGroups.forEach(group => { group.items.forEach(item => { result.group.push(group.group); result.file.push(item.file); result.desc.push(item.itemdesc); }); }); return result; }
[ "function createItemGroup(pkg, callback){\n var item = {\n title : pkg.title,\n description : pkg.notes,\n created : pkg.metadata_created,\n url : config.ckan.server+\"/dataset/\"+pkg.name,\n ckan_id : pkg.id,\n updated : pkg.revision_timestamp,\n groups : [],\n resources : pkg.resources ? pkg.resources : [],\n organization : pkg.organization ? pkg.organization.title : \"\",\n extras : {}\n }\n\n // add extras\n if( pkg.extras ) {\n for( var i = 0; i < pkg.extras.length; i++ ) {\n if( pkg.extras[i].state == 'active' ) {\n item.extras[pkg.extras[i].key] = pkg.extras[i].value;\n }\n }\n }\n \n\n if( pkg.groups ) {\n for( var i = 0; i < pkg.groups.length; i++ ) {\n item.groups.push(pkg.groups[i].name);\n }\n }\n\n setTags(item, pkg, callback);\n}", "static generateFlatGroupListFromYamlFile(inventory) {\r\n const hostsyaml = YAML.parse( fs.readFileSync( inventory.filenameFullPath, 'utf8') )\r\n var groupList = {}\r\n\r\n Group.internal_generateFlatGroupListFromYamlFile(hostsyaml, inventory, groupList)\r\n\r\n Group.internal_addGroupAllIfNotExist(inventory, groupList)\r\n\r\n Group.internal_addGroupUngroupedIfNotExist(inventory, groupList)\r\n \r\n // console.log(\"Flat Group List from yaml: \")\r\n // console.dir(JSON.parse(JSON.stringify(groupList)), {depth: null, colors: true})\r\n return groupList\r\n }", "listAllGroups () {\n return this._apiRequest('/groups/all')\n }", "async function createGroupsforApp (appid) {\n\n \t\tasync function appGroups(group) {\n\t \t\t// find the groupid to use\n\t \t\tlet [err, care] = [];\n\t \t\t// try{\n\t \t\t;[err, care] = await to(self.sequelize.models.Role.find({where: {Group: group}, \n\t \t\t\tinclude: [{\n\t\t\t\t model: self.sequelize.models.AppGroup,\n\t\t\t\t where: {'AppAppId': appid},\n\t\t\t\t attributes: ['AppGroupId']\n\t\t\t\t }], \n\n\t \t\t}))\n\t \t\tlet AppGroupId = care.dataValues.AppGroups[0].dataValues.AppGroupId\n\n\n\t \t\tlet data = {\n\t \t\t\tAppGroupAppGroupId: AppGroupId,\n\t \t\t\tUserUid: whichuser,\n\t \t\t\tInstalled: true\n\t \t\t}\n\n\t \t\t// get appId\n\t \t\t;[err, care] = await to(self.sequelize.models.AppUser.create(data));\n\t\t\t\t// console.log(err)\n\t\t\t\treturn [err, care];\n\t \t}\n\n \t\tlet promises = groups.map(appGroups)\n \t\tlet [err, care] = await to(Promise.all(promises))\n \t\treturn [err, care];\n \t}", "static generateFlatGroupListFromIniFile(inventory) {\r\n const hostsIni = loadIniFile.sync( inventory.filenameFullPath )\r\n var groupList = {}\r\n \r\n for (var groupName in hostsIni) {\r\n var _groupName = Group.normalizeGroupName(groupName)\r\n \r\n if (groupList[_groupName] === undefined) {\r\n groupList[_groupName] = new Group(inventory.name, inventory.env, groupName)\r\n }\r\n \r\n if (Group.hasHosts(groupName)) {\r\n // add hostnames\r\n for(var hostname in hostsIni[groupName]) {\r\n groupList[_groupName].hostnames.push(hostname.split(' ')[0])\r\n }\r\n }\r\n else if (Group.hasSubgroups(groupName)) {\r\n // add subgroups\r\n for(var subGroupName in hostsIni[groupName]) {\r\n groupList[_groupName].subgroups.push(subGroupName)\r\n // need to add goups here as well because they may be listed only as subgroups\r\n if (groupList[subGroupName] === undefined) {\r\n groupList[subGroupName] = new Group(inventory.name, inventory.env, subGroupName)\r\n }\r\n }\r\n } else if (Group.hasGroupVariables(groupName)) {\r\n // add variables from the hosts ini-file\r\n for (var varName in hostsIni[groupName]) {\r\n groupList[_groupName].variables[varName] = hostsIni[groupName][varName]\r\n }\r\n } else {\r\n console.log(\"During generation of flat group list, group '%s' could not be considered!\", groupName)\r\n }\r\n }\r\n\r\n // add variables and configuration from subfolder group_vars\r\n Group.internal_addVariablesFromFolder(inventory, groupList)\r\n\r\n Group.internal_addGroupAllIfNotExist(inventory, groupList)\r\n\r\n Group.internal_addGroupUngroupedIfNotExist(inventory, groupList)\r\n \r\n // console.log(\"Flat Group List: \")\r\n // console.dir(JSON.parse(JSON.stringify(groupList)), {depth: null, colors: true})\r\n return groupList\r\n }", "groupFields (groupsArray, field, i, fieldsArray) {\n if (field.props.group === 'start') {\n this.openGroup = true\n groupsArray.push([])\n }\n\n if (this.openGroup) {\n groupsArray[groupsArray.length - 1].push(field)\n } else {\n groupsArray.push([field])\n }\n\n if (field.props.group === 'end') {\n this.openGroup = false\n }\n return groupsArray\n }", "facetComplexItems(aItems) {\n let attrKey = this.attrDef.boundName;\n let filter = this.facetDef.filter;\n let idAttr = this.facetDef.groupIdAttr;\n\n let groups = (this.groups = {});\n let groupMap = (this.groupMap = {});\n this.groupCount = 0;\n\n for (let item of aItems) {\n let vals = attrKey in item ? item[attrKey] : null;\n if (vals === Gloda.IGNORE_FACET) {\n continue;\n }\n\n if (vals == null || vals.length == 0) {\n vals = [null];\n }\n for (let val of vals) {\n // skip items the filter tells us to ignore\n if (filter && !filter(val)) {\n continue;\n }\n\n let valId = val == null ? null : val[idAttr];\n // We need to use hasOwnProperty because tag nouns are complex objects\n // with id's that are non-numeric and so can collide with the contents\n // of Object.prototype.\n if (groupMap.hasOwnProperty(valId)) {\n groups[valId].push(item);\n } else {\n groupMap[valId] = val;\n groups[valId] = [item];\n this.groupCount++;\n }\n }\n }\n\n let orderedGroups = Object.keys(groups).map(key => [\n groupMap[key],\n groups[key],\n ]);\n let comparator = this.facetDef.groupComparator;\n function comparatorHelper(a, b) {\n return comparator(a[0], b[0]);\n }\n orderedGroups.sort(comparatorHelper);\n this.orderedGroups = orderedGroups;\n }", "function showGroup() {\n\tvar ps = document.querySelectorAll('p, nav, section, article');\n\tvar i = 0;\n\twhile(i < ps.length) {\n\t\tgroupLength = ps[i].childNodes.length;\n\t\tif(groupLength > 1) {\n\t\t\tvar groupChild = document.createElement('span');\n\t\t\tgroupChild.classList.add('vasilis-srm-group');\n\t\t\tgroupChild.innerHTML = \" Group \" + groupLength + \" items\";\n\t\t\tps[i].appendChild(groupChild);\n\t\t}\n\t\ti++;\n\t}\n}", "createSelectGroup() {\n let items = [];\n this.state.groups_list.forEach((T) => {\n items.push(<option key={T.group_id} value={T.group_id}>{T.title}</option>);\n })\n return items;\n }", "get groupsObject () {\n const result = {}\n for (const [key, val] of this.groups) {\n result[key] = Array.from(val)\n }\n return result\n }", "function getGroupNames(){\n var ret = [];\n for (var i = 0; i < this.groups.length; i++) {\n ret.push(this.groups[i].name);\n }\n return ret;\n}", "function getGroups() {\n\t\n\tthemeIsUpdated = false;\n\t\n\tfor (var themeItem in dataVallydette.checklist.page[currentPage].groups) {\n\t\t\n\t\tif (document.getElementById(themeItem).checked !== dataVallydette.checklist.page[currentPage].groups[themeItem].checked) {\n\t\t\tthemeIsUpdated = true;\n\t\t\tdataVallydette.checklist.page[currentPage].groups[themeItem].checked = document.getElementById(themeItem).checked;\n\t\t\n\t\t}\n\t}\n\t\n\tif (themeIsUpdated) {\n\t\tapplyGroups();\n\t}\n\t\n}", "function asArraysFactory(groups) {\n return () => {\n return groups.map((g) => g.items);\n };\n}", "toHtml() {\n let node = createSpan(\"group\", \"(\");\n for (const item of this.items)\n node.append(item.toHtml());\n node.append(\")\");\n if (this.count != 1)\n node.append(createElem(\"sub\", this.count.toString()));\n return node;\n }", "getList(itemCollection){\n let {groupFunction, groupedByLabel, cellClass} = this.props;\n let CellClass = cellClass || Cell;\n if(groupFunction){\n const itemCollectionByGroup = _.groupBy(itemCollection, groupFunction);\n return _.map(itemCollectionByGroup, (group, groupName) => {\n const uniqueGroupId = _.uniqueId(groupName);\n const groupItems = itemCollectionByGroup[groupName];\n return(\n <div key={uniqueGroupId} className={\"cellGridGroup\"}>\n <h3>{groupedByLabel} {groupName} - Total: {_.size(groupItems)}</h3>\n <div className=\"cellList\">\n {_.map(groupItems, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n </div>\n );\n })\n } else {\n return <div className=\"cellList\">\n {_.map(itemCollection, (item, key) => this.getCell(CellClass, key, item))}\n </div>\n }\n }", "function collectGroups(groups) {\n let name = \"\"\n let tags = new Set()\n for (let group of groups) {\n name += `[${group.name}]+`\n collect(tags, group.tags)\n }\n\n name = name.substring(0, name.length - 1)\n \n return new Group(name, tags)\n}", "function loadWidgetGroups(data) {\n var targetWidgetGroupArray = [];\n var pname = null;\n var pversion = null;\n var gname = null;\n var groupId = null;\n targetWidgetGroupArray.push(groupAll);\n if (data && data.length > 0) {\n for (var i = 0; i < data.length; i++) {\n groupId = data[i].WIDGET_GROUP_ID;\n pname = data[i].PROVIDER_NAME;\n pversion = data[i].PROVIDER_VERSION;\n gname = data[i].WIDGET_GROUP_NAME;\n // Disable ITA widget group since no ITA widgets for now. (group id === 3)\n if ((!widgetProviderName && groupId !== 3 /*&& !widgetProviderVersion */) ||\n widgetProviderName === pname || (widgetProviderName === 'TargetAnalytics' && groupId === 7)\n || (widgetProviderName === 'LogAnalyticsUI' && groupId === 6)\n /* && widgetProviderVersion === pversion */) {\n var widgetGroup = {value:pname+'|'+pversion+'|'+gname, \n label: groupId === 2 ? nls.WIDGET_SELECTOR_WIDGET_GROUP_NAME_TA : gname};\n targetWidgetGroupArray.push(widgetGroup);\n availableWidgetGroups.push(data[i]);\n }\n }\n }\n return targetWidgetGroupArray;\n }", "makeTopGroups(aAttrDef, aGroups, aMaxCount) {\n let nounDef = aAttrDef.objectNounDef;\n let realGroupsToUse = aMaxCount;\n\n let orderedBySize = aGroups.concat();\n orderedBySize.sort(this._groupSizeComparator);\n\n // - get the real groups to use and order them by the attribute comparator\n let outGroups = orderedBySize.slice(0, realGroupsToUse);\n let comparator = nounDef.comparator;\n function comparatorHelper(a, b) {\n return comparator(a[0], b[0]);\n }\n outGroups.sort(comparatorHelper);\n\n return outGroups;\n }", "function getPatronGroups(callback) {\n let patronGroupRequest = createRequest('GET', '/groups', 'application/json');\n\n let req = http.get(patronGroupRequest, function (response) {\n let groupResult = '';\n response.on('data', (chunk) => {\n groupResult += chunk;\n });\n response.on('end', () => {\n try {\n switch(response.statusCode) {\n case 200: {\n var groupList = JSON.parse(groupResult);\n groupList.usergroups.forEach(function (group) {\n patronGroups[group.group] = group.id;\n });\n logger.trace('Listed patron groups successfully.');\n callback();\n break;\n }\n case 401: {\n logger.error('User is unauthorized. Exiting.', groupResult);\n keepAliveAgent.destroy();\n }\n case 500: {\n logger.error('Internal server error. Exiting.', groupResult);\n keepAliveAgent.destroy();\n }\n default: {\n logger.warn('Failed to list patron groups.', groupResult);\n callback();\n break;\n }\n }\n } catch (e) {\n logger.error('Failed to retrieve patron groups. Reason: ', e.message);\n callback();\n }\n });\n }).on('error', (e) => {\n logger.error('Failed to list parton groups.', e.message);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create event listener for add blog post button
function addBlogPost() { clearDialogInputs(); showDialog(blogPosts, "add"); }
[ "function createNewPostPage(e){\n\t\te.preventDefault();\n\t\t// If the user clicked the button with id newPost, then display the posting page on the right part of the screen.\n\t\tif (e.target.id == 'newPost'){\n\t\t\tmainContent.innerHTML = `\n\t\t\t\t<form>\n\t\t\t\t\t<p class=\"newPostPageText\">Title: </p> <textarea id=\"newPostTitle\"></textarea><br>\n\t\t\t\t\t<p class=\"newPostPageText\">Content:</p> <textarea id=\"newPostContent\"></textarea><br>\n\t\t\t\t\t<button id=\"submitPostButton\" onclick=\"location.href = '/forum/webpage';\">Post</button>\n\t\t\t\t</form>\n\t\t\t`\n\t\t\treplyBlock.innerHTML = `\n\t\t\t<p class=\"readTerms\">\n\t\t\tPlease do not post NSFW material in the forum.\n\t\t\t<br> <br>\n\t\t\tAny NSFW material and its corresponding post/reply will be deleted.\n\t\t\t</p>\n\t\t\t`\n\t\t}\n\t}", "function addHandlers(){\n\n\t//ceka klik na dodavanje nove objave\n\tdocument.querySelector(\".add-new-post\").addEventListener(\"click\",handleNewPost);\n\t\n\t//ceka klik na srce u headeru, prikaz postova koje je trenutni korisnik do sada lajkao\n\tdocument.querySelector(\".my-likes\").addEventListener(\"click\",handleMyLikesClick);\n\t\n\t//ceka klik na profil u headeru, prikaz postova koje je trenutni korisnik objavio\n\tdocument.querySelector(\".my-profile\").addEventListener(\"click\",handleMyProfileClick);\n\t\n\t\n\t//ceka klik na bookmark u headeru, prikaz postova koje je trenutni korisnik oznacio\n\tdocument.querySelector(\".my-bookmarks\").addEventListener(\"click\",handleMyBookmarksClick);\n\t\n\t//za ove prethodne cetri funkcije vrijedi da se klikom na istu ikonu korisnika vraca\n\t//na njegov feed, a klikom na neku drugu ikonu u drugo stanje\n\t//nije moguce u isto vrijeme prikazati presjek npr lajkanih i bookmarkanih slika\n\t//iako mislim da je to moguce odraditi preko promjene vise conditions vrijednosti\n\t\n\t//ceka upisivanje u trazilicu u headeru\n\tdocument.querySelector(\"#search-box\").addEventListener(\"keyup\",handleTextInput);\n\n\t//ceka klik na logout ikonu u headeru, ponovni prikaz modala\n\tdocument.querySelector(\".change-user\").addEventListener(\"click\",handleLogOutClick);\n}", "function create (post_title, post_content) {\n var postData = {title: post_title, content: post_content};\n \n // send POST request to server to create new note on API \n $.post('/api/posts', postData, function(data) {\n var newPost = data;\n render(newPost);\n });\n }", "function edit_link_listener() {\n document.querySelectorAll('#edit_post_link').forEach(link => {\n link.addEventListener('click', function() {\n // console.log(this.dataset.postid);\n edit_post(this);\n });\n });\n}", "function readMoreBtnEventListener(id) {\n $(\"#\" + id).click(function () {\n $(\"#blog-post\").empty();\n queryAjaxPosts(\"/events/query/\" + id)\n })\n}", "loadBlogPosts() {\n var posts = model.getPostsByType('posts'),\n postsSection = document.createElement('section'),\n primaryContentEL = h.getPrimaryContentEl();\n\n postsSection.id = 'blogPosts';\n // Get markup for each post\n //console.log( posts );\n _.each(posts, post => {\n postsSection.appendChild(h.createPostMarkup(post));\n });\n // Append posts to page\n primaryContentEL.appendChild(postsSection);\n }", "function blogsIndex(e){\n if (e) e.preventDefault();\n $('ol').remove();\n $('.stream').append('<ol class=\"stream-items\"></ol>');\n $.get('http://localhost:3000/blogs')\n .done((data) => {\n $.each(data, (index, blog) => {\n const blogToAdd = '<li class=\"stream-item\"><div class=\"blog\"><img src=\"http://pix.iemoji.com/images/emoji/apple/ios-9/256/white-woman.png\" alt=\"User image goes here.\"><div class=\"content\"><strong class=\"fullname\">' + blog.fullName + '</strong><span>&rlm;</span><span>@</span><b>' + blog.screenName + '</b>&nbsp;&middot;&nbsp;<small class=\"time timeago\">' + $.timeago(blog.createdAt) + '</small><p>' + blog.blogText + '<button class=\"deleteButton\" name=\"' + index + '\" data-id=\"' + blog._id + '\"> Delete </button></p></div></div></li>';\n $('.stream-items').prepend(blogToAdd);\n });\n });\n }", "function addClickListener(event) {\n // Prevents the button from causing the form to submit...\n event.preventDefault();\n // Debug message\n console.log('addClickListener');\n\n /* TODO: Create an ajax call to POST data to the target url\n * \"engine.php?a=add\".\n * The server expects a single POST key named \"text\".\n * TODO: If the call is successful, set the value of the text to \"\".\n * TODO: Use the function createItem by passing the returned JSON object\n * and append the HTML object returned to the ul with the id \n * \"todo_list\".\n * NOTE: \n * Remeber that the JSON response contains item and debug_info.\n */\n \n let text = $(\"#item_input\").val();\n let data = { text: text };\n $.post(\"engine.php?a=add\", data,function(response){\n new_j = JSON.parse(response);\n $(\"#item_input\").val(\"\");\n let new_item = createItem(new_j.item);\n $(\"ul#todo_list\").append(new_item);\n })\n\n}", "function focusOnSingularPost() {\n getAppContext().addEventListener(\"click\", function() {\n if (event.target.classList.contains(\"edit-post__submit\")) {\n const postId = event.target.parentElement.querySelector(\n \".delete-post__id\"\n ).value;\n console.log(postId);\n const postsRef = getDatabaseItemContext(postId);\n postsRef.get().then(post => {\n getAppContext().innerHTML = Post(post);\n });\n }\n });\n}", "function MakePost(text){\nreturn {\n\ttext: text,\n\tdate: new Date()\n}\n}// this function will display posts in the posts div", "function saveBlogAsNewDraft(e) {\n // Get content data from ckeditor \n var contentInput = CKEDITOR.instances.ckeditor.getData();\n\n // Make 'tags' string to array\n var tagsArr = [];\n var tagsList = document.querySelectorAll('#myTags li .tagit-label');\n\n function tagsToArr() {\n for (var i = 0; i < tagsList.length; i++) {\n tagsArr.push(tagsList[i].innerText)\n };\n return tagsArr;\n };\n\n // time now\n var date = new Date();\n var dateAndTimeNow = date.getFullYear() + \"-\" + (((+date.getMonth() + 1) < 10) ? \"0\" + (+date.getMonth() + 1) : (+date.getMonth() + 1)) + \"-\" + date.getDate() + \" \" + date.getHours() + \":\" + date.getMinutes();\n\n // Save blog as draft data to send\n var saveBlogAsDraft = {\n title: document.querySelector('.article-title input').value,\n description: \"create draft\",\n content: contentInput,\n tags: tagsToArr(),\n publish_in: (!document.getElementById('datetimepicker').value ? dateAndTimeNow : document.getElementById('datetimepicker').value),\n published: false\n }\n\n // Init Blog service\n var blog = BlogService();\n blog.newBlog(saveBlogAsDraft);\n // console.log(saveBlogAsDraft);\n}", "removeBlogPosts() {\n let blogPost = document.getElementById('blogPosts');\n if (blogPost) {\n blogPost.remove();\n }\n }", "function postTweetHandler(){\n\t$('#postTweetButton').on('click', function(e){\n\t\te.preventDefault();\n\t\tvar tweetContent = $('#tweetText').val();\n tweetAjaxPost(tweetContent)\n\t});\n}", "_defineListeners() {\n this.editor.model.on('insertContent', (eventInfo, [modelElement]) => {\n if (!isDrupalMedia(modelElement)) {\n return;\n }\n this.upcastDrupalMediaIsImage(modelElement);\n // Need to upcast DrupalMediaType to model so it can be used to show\n // correct buttons based on bundle.\n this.upcastDrupalMediaType(modelElement);\n });\n }", "function edit(post_id) {\n console.log(\"edit function\", post_id);\n txt_area = document.createElement(\"textarea\");\n txt_area.className = \"txt_area\";\n txt_area.id = \"txt_area_\" + post_id;\n txt_area.innerHTML = document.getElementById(\"text_\" + post_id).innerHTML;\n\n document.getElementById(\"text_\" + post_id).innerHTML = \"\";\n document.getElementById(\"text_\" + post_id).append(txt_area);\n document.getElementById(\"edit_\" + post_id).hidden = true;\n\n save_button = document.createElement(\"button\");\n save_button.className = \"btn btn-primary\";\n save_button.innerHTML = \"Save\";\n save_button.addEventListener(\"click\", function () {\n console.log(document.getElementById(\"txt_area_\" + post_id).value)\n save_post(post_id);\n })\n document.getElementById(\"text_\" + post_id).append(save_button);\n\n}", "function handleFormSubmit() {\n\t// Get values of inputs\n\t// Pass values to addNewPost()\n var inputName = document.getElementById(\"input-username\").value;\n var inputCaption = document.getElementById(\"input-caption\").value;\n var inputPicture = document.getElementById(\"input-picture\").value;\n addNewPost(inputName, inputPicture, inputCaption);\n}", "listenLoadEditForm() {\n editor.clearMenus();\n const slugs = h.getAfterHash(this.href),\n post = model.getPostBySlugs(slugs);\n\n editor.currentPost = post;\n editor.currentPostType = post.type;\n\n if (editor.currentPostType !== 'settings') {\n view.currentPost = post;\n view.update();\n } else {\n event.preventDefault();\n }\n\n editor.showEditPanel();\n }", "update() {\n view.updateTitle(view.currentPost.title);\n view.updateContent(view.currentPost.content);\n\n view.removeBlogPosts();\n if (view.currentPost.slug === 'blog') {\n // Append blog posts to blog page\n view.loadBlogPosts();\n }\n }", "function showBlog() {\n\n document.querySelectorAll('.js-card-desktop').forEach(card => {\n card.addEventListener('click', (e)=>{\n e.preventDefault();\n cardContent.innerHTML = drawBlog(myDictionary[`n${e.target.dataset.id}`]);\n })\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
depending on which tab is clicked, render Assignments, AllStudents, or Student component
handleTabs() { if (this.props.tabView === 'Students') { return ( <AllStudentsTab /> ); } else if (this.props.tabView === 'Student') { return <Student />; } else if (this.props.tabView === 'Assignment') { return <Assignment />; } return ( <AssignmentsTab /> ); }
[ "renderLessonTabs() {\n let lessons = this.state.lessons;\n return lessons.map(\n (lesson) => {\n return <LessonTabItem key={lesson.id}\n lesson={lesson}\n courseId={this.props.courseId}\n moduleId={this.props.moduleId}\n isSelected={`${lesson.id === this.state.selected ? 'active' : ''}`}\n delete={this.confirmDelete}\n update={this.confirmUpdate}\n changeTab={this.changeTab}/>\n }\n )\n }", "function changeLecturerContent(event, tab){\n document.getElementById('profile').style.display = 'none';\n if (tab == \"Profile\") {\n //TODO: Pass the current user to the function\n editUserInfo(\"lecturerContent\");\n\n } else if(tab == \"Student\"){\n \n } else if(tab == \"Evaluation\"){\n \n } else if(tab == \"Message\"){\n \n } else if(tab == \"References\"){\n\t\t\n\t\tdocument.getElementById('lecturerContent').innerHTML=template_references(); \n\t\n } else if(tab == \"Editing\"){\n \n } else if(tab == \"New\"){\n \n }\n}", "_onTabChanged(tabIndex) {\n this.tabSelected = tabIndex;\n if(tabIndex == 0) {\n // show users projects / projects where the user is a member of\n this.showProjects(false);\n } else {\n // show all projects\n this.showProjects(true);\n }\n }", "render(){// https://react-bootstrap.github.io/components/tabs/\r\n const {answered,unAnswered } = this.props\r\n\r\n\r\n return( //from bootstrap documentation we will make two tabs for the answered and un answered questions\r\n\r\n <Tabs defaultActiveKey=\"profile\" id=\"uncontrolled-tab-example\">\r\n <Tab eventKey=\"unanswered\" title=\"Unswered\">\r\n {/*we will map through all un answered ruestions and show them with the question it self with the unique key id */}\r\n {unAnswered.map((question) => //هنا الاسئله اللي مش متجاوب عليها هتجلنا علي شكل اسئله الاسئله دييه هنماب علي كل سؤال فيها\r\n <TheQuestion key ={question} id ={question}/> // we will invoke the TheQuestion component and pass the key id and id to its id props\r\n )}\r\n \r\n </Tab>\r\n <Tab eventKey=\"answered\" title=\"answered\">\r\n {/*we will map through all answered ruestions and show them with the question it self with the unique key id*/}\r\n\r\n {answered.map((question) => //هنا الاسئله اللي متجاوب عليها هتجلنا علي شكل اسئله الاسئله دييه هنماب علي كل سؤال فيها\r\n <TheQuestion key ={question} id ={question}/> // we will invoke the TheQuestion component and pass the key id and id to its id props\r\n )} \r\n </Tab>\r\n\r\n \r\n \r\n </Tabs>\r\n )\r\n }", "showData() {\n return this.state.classrooms ? (\n <Accordion id=\"classrooms-table-container\" defaultActiveKey=\"0\">\n {Object.values(this.state.classrooms).map((classroom, index) => {\n return (\n <Card key={classroom.code}>\n <Accordion.Toggle as={Button} variant=\"secondary\" eventKey={\"\"+index}>\n {classroom.name} (Class Code: {classroom.code})\n </Accordion.Toggle> \n <Accordion.Collapse eventKey={\"\"+index}>\n <ListGroup variant=\"flush\">\n {this.renderStudents(index)}\n </ListGroup>\n </Accordion.Collapse>\n </Card>\n );\n })}\n </Accordion> \n ) : null;\n }", "GetSelectedPage() {\n if (this.page === 'DEPARTMENTS')\n return <EventRegistration key={ this.state.key } />;\n if (this.page === 'LOGIN')\n return <Login key={ this.state.key } Login={ this.props.Login } />;\n }", "render() {\n const {contacts, isLoading, firstName, lastName, emailAddress, contactId} = this.state;\n\n if (isLoading) {\n return <p>Loading...</p>;\n }\n\n // when displaying contact list\n // create a tableRow for each entry, along with a edit and delete button\n const contactList = contacts.map(contact => {\n return <tr key={contact.id}>\n <td style={{whiteSpace: 'nowrap'}}><Icon onClick={() => this.deleteContact(contact.id)} name='user delete' />&nbsp;&nbsp;&nbsp;<Icon onClick={() => this.editContact(contact.id)} name='edit' /></td>\n <td style={{whiteSpace: 'nowrap'}}>{contact.firstName}</td>\n <td style={{whiteSpace: 'nowrap'}}>{contact.lastName}</td>\n <td style={{whiteSpace: 'nowrap'}}>{contact.emailAddress}</td>\n </tr>\n });\n\n return (\n <Tabs hideAdd activeKey={this.state.activeTabKey} onChange={this.changeSelectedTab} >\n // START tab 1 - contact list\n <TabPane tab=\"Contact List\" key=\"1\">\n <div>\n <table className=\"ui celled striped table\">\n <thead className=\"\">\n <tr className=\"\">\n <th colSpan=\"4\" className=\"\">Interview Contacts</th>\n </tr>\n </thead>\n <tbody className=\"\">\n <tr className=\"\">\n <td className=\"collapsing\"><strong>Actions</strong></td>\n <td className=\"\"><strong>First Name</strong></td>\n <td className=\"\"><strong>Last Name</strong></td>\n <td className=\"\"><strong>Email</strong></td>\n </tr>\n {contactList}\n </tbody>\n </table>\n </div>\n </TabPane>\n // START tab 2 - edit form\n <TabPane tab=\"Edit Contact\" key=\"2\" disabled={true}>\n <div>\n <Form.Group>\n <Form onSubmit={() => this.addContact(this)}>\n <Form.Input\n placeholder='Contact Id'\n name='contactId'\n value={contactId}\n onChange={this.handleChange}\n disabled={true}\n />\n <Form.Input\n placeholder='First Name'\n name='firstName'\n value={firstName}\n onChange={this.handleChange}\n\n />\n <Form.Input\n placeholder='Last Name'\n name='lastName'\n value={lastName}\n onChange={this.handleChange}\n />\n <Form.Input\n placeholder='Email Address'\n name='emailAddress'\n value={emailAddress}\n onChange={this.handleChange}\n />\n <Form.Button content=\"Submit\" />\n </Form>\n </Form.Group>\n </div>\n </TabPane>\n <TabPane tab=\"Add Contact\" key=\"3\">\n <div>\n <Form.Group>\n <Form onSubmit={() => this.addContact(this)}>\n <Form.Input\n placeholder='Contact Id'\n name='contactId'\n value=''\n onChange={this.handleChange}\n disabled={true}\n />\n <Form.Input\n placeholder='First Name'\n name='firstName'\n value={firstName}\n onChange={this.handleChange}\n\n />\n <Form.Input\n placeholder='Last Name'\n name='lastName'\n value={lastName}\n onChange={this.handleChange}\n />\n <Form.Input\n placeholder='Email Address'\n name='emailAddress'\n value={emailAddress}\n onChange={this.handleChange}\n />\n <Form.Button content=\"Submit\" />\n </Form>\n </Form.Group>\n </div>\n </TabPane>\n </Tabs>\n );\n }", "renderTabBar() {\n return (\n <ul\n className={classNames({\n 'usaf-tab-group__tabs': this.props.type === 'tab',\n 'usaf-tab-group__pills': this.props.type === 'pill'\n })}\n >\n {\n this.childrenArray.map(\n (child, index) => (\n <li\n key={createUid(10)}\n className={classNames(\n 'usaf-tab-group__tab',\n { 'usaf-tab-group__tab--active': this.state.selectedIndex === index }\n )}\n >\n <button\n className={classNames(\n 'usaf-tab-group__btn',\n )}\n value={index}\n onClick={this.handleClick}\n >\n {child.props.label}\n </button>\n </li>\n )\n )\n }\n </ul>\n );\n }", "render() {\n const { skillData, settings } = this.state;\n \n return (\n <div>\n {\n skillData.map((skill, index) => \n <div key={index}>\n <SkillInfo \n skillData={skill}\n name={skill.name}\n properties={{}}\n shortDesc={skill.shortDesc}\n maxLevel={skill.maxLevel}\n animationSetting={settings.animations}/>\n </div>\n )\n }\n <a href=\"#skill\"><span className=\"jump-button-tabs\"/></a>\n </div>\n );\n }", "renderPanelsAsTab() {\n const hasMultipleGroupPanels =\n this.links.links.filter(link => link.resourcetype === \"GroupingPanel\")\n .length > 1;\n\n return (\n !this.layouthint.has(OVERVIEW) &&\n (hasMultipleGroupPanels ||\n this.isStagesView ||\n this.layouthint.has(PANELS_AS_TABS))\n );\n }", "function renderSwitch(param) {\r\n switch (param) {\r\n case 0:\r\n return <InitScreen />\r\n case 1:\r\n return <Screen1 />\r\n case 2:\r\n return <Screen2 />\r\n case 3:\r\n return <StatsScreen />\r\n default:\r\n return <InitScreen />\r\n }\r\n }", "renderContent() {\n switch (this.props.authUser) {\n // when the login status is still pending return nothing\n case null:\n return null;\n // when the user is not logged in, show them a link to login\n case false:\n return <MenuLoggedOut />;\n // when the user is logged in, show them a link to logout\n default:\n return <MenuLoggedIn />;\n }\n }", "function showTab(tabName) {\n var template = document.querySelector(tabName);\n\n const params = new URLSearchParams(window.location.search);\n if (tabName === '#announcements') {\n template.content.querySelector('#club-name').value = params.get('name');\n template.content.querySelector('#schedule-club-name').value = params.get('name');\n template.content.querySelector('#timezone').value = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n const node = document.importNode(template.content, true);\n document.getElementById('tab').innerHTML = '';\n document.getElementById('tab').appendChild(node);\n\n if (tabName === '#about-us') {\n getClubInfo();\n } else if (tabName === '#announcements') {\n getClubInfo();\n loadAnnouncements();\n showHidePostAnnouncement();\n loadScheduledAnnouncements();\n } else if (tabName === '#calendar') {\n loadCalendar();\n }\n}", "setCurrentTab(tabName) {\n this.currentTab = tabName;\n\n MapLayers.nuts3.renderLayer();\n }", "function activeTabActions (state) {\n const showActiveTabSection = (state.isRedirectContext) || state.isIpfsContext\n if (!showActiveTabSection) return\n return html`\n <div>\n ${navHeader('panel_activeTabSectionHeader')}\n <div class=\"fade-in pv1 bb b--black-10\">\n ${contextActions(state)}\n </div>\n </div>\n `\n}", "leftPanelComponentToRender(){\n //Switch statement to check which component should be rendered on the left\n switch(this.state.leftPanelComponent){\n case \"LoginComponent\":\n //If a token does not exist the user is not logged in, so will just show the player stats component\n if(this.state.token){\n this.setState({\n leftPanelComponent: \"PlayerStatsComponent\",\n })\n } else {\n return <LoginComponent informationMessage={this.state.leftPanelComponentInformationMessage} callbackToParent={this.leftPanelComponentChildCallback}/>\n }\n case \"RegisterComponent\":\n return <RegisterComponent callbackToParent={this.leftPanelComponentChildCallback}/>\n case \"PlayerStatsComponent\":\n if(this.state.token){\n return <PlayerStatsComponent token={this.state.token} callbackToParent={this.leftPanelComponentChildCallback}/> \n } else {\n this.setState({\n leftPanelComponent: \"LoginComponent\",\n })\n }\n case \"ShopComponent\":\n if(this.state.token){\n return <ShopComponent token={this.state.token} shouldForceUpdate={this.state.openedPackForceShopUpdate} callbackToParent={this.leftPanelComponentChildCallback}/> \n } else {\n this.setState({\n leftPanelComponent: \"LoginComponent\",\n })\n }\n }\n }", "function SingleCampus(props) {\n\n\n const campusId = Number(props.match.params.campusid);\n const campuses = props.campus.campuses\n const selectedCampus = campuses.filter(campus => campus.id === campusId )\n const allstudents = props.student.students\n const studentlist = allstudents.filter(student=>student.campusId === campusId)\n\n return (\n <div>\n <h3>\n <span> {selectedCampus[0].name}</span>\n </h3>\n <div className=\"row\">\n {\n <div className=\"col-xs-3 tile\" key={selectedCampus[0].id}>\n <div className=\"thumbnail\" to={`/campus/${selectedCampus[0].id}`}>\n <ShowPix url={'/' + selectedCampus[0].imageurl} />\n </div>\n </div>\n\n }\n </div>\n <div>\n <h3>Students\n <button type=\"button\" className=\"btn btn-default btn-group-sm\">New Student</button>\n </h3>\n <div className=\"row\">\n {studentlist.map(student1 => (\n <Student student={student1} />\n ))\n }\n </div>\n </div>\n </div>\n );\n}", "accountPageToHeader(){\n if(JSON.parse(sessionStorage.getItem(\"userData\")).Status === \"admin\")\n return (<Menu.Item key = \"AddAccountPage\">\n <a href=\"/#\" onClick={() => this.handleClick(\"AddAccountPage\")}>\n Hantera användare\n </a>\n </Menu.Item>);\n \n }", "render() {\n // set the permission.\n this.auth.setPermission(permissions[this.props.user]);\n const AliceDiv = <p>This is alice's data.</p>\n const BobDiv = <p>This is bob's data.</p>\n return (\n <div>\n <p>====</p>\n { this.auth.permission.check('read', 'alice_data') && AliceDiv }\n { this.auth.permission.check('read', 'bob_data') && BobDiv }\n <p>====</p>\n </div>\n )\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement .inRange() method [CodeCademy solution]: node test/inrange.js passed
inRange (number, start, end) { if (end === undefined) { end = start start = 0 } if (start > end) { let temp = end end = start start = temp } let isInRange = (number >= start && number < end) return isInRange }
[ "inRangeIdea (num, start, end) {\n let startRange\n let endRange\n if (!end) {\n startRange = 0\n endRange = start\n } else if (start > end) {\n startRange = end\n endRange = start\n } else {\n startRange = start\n endRange = end\n }\n return this.checkRangeIdea(num, startRange, endRange)\n }", "inRange(num, start, end) {\r\n /* Initial version */\r\n /*\r\n // Check if parameter values are provided.\r\n if (num === undefined) {return 'Provide a number'};\r\n if (start === undefined &&\r\n end === undefined ) {return 'Provide atleast one range'};\r\n var lStart;\r\n var lEnd;\r\n var temp;\r\n\r\n //If no end value is provided to the method, the start value will be 0\r\n //and the end value will be the provided start value\r\n\r\n end === undefined ? lStart = 0 : lStart = start;\r\n end === undefined ? lEnd = start : lEnd = end;\r\n\r\n //If the provided start value is larger than the provided end value, the\r\n //two values should be swapped\r\n\r\n if (lStart > lEnd) {\r\n temp = lStart;\r\n lStart = lEnd;\r\n lEnd = temp;\r\n };\r\n\r\n if (num < lStart) {return false} else {\r\n if (num >= lEnd) {return false} else { return true };\r\n };\r\n */\r\n\r\n // Improved/Consise final version below\r\n\r\n // Check if parameter values are provided.\r\n var lStart;\r\n var lEnd;\r\n var temp;\r\n\r\n if (num === undefined) {\r\n return 'Provide a number'\r\n };\r\n\r\n if (start === undefined &&\r\n end === undefined) {\r\n return 'Provide atleast one range'\r\n };\r\n\r\n\r\n //If no end value is provided to the method, the start value will be 0\r\n //and the end value will be the provided start value\r\n\r\n end === undefined ? lStart = 0 : lStart = start;\r\n end === undefined ? lEnd = start : lEnd = end;\r\n\r\n //If the provided start value is larger than the provided end value, the\r\n //two values should be swapped\r\n\r\n if (lStart > lEnd) {\r\n temp = lStart;\r\n lStart = lEnd;\r\n lEnd = temp;\r\n };\r\n\r\n return ((num < lStart) || (num >= lEnd) ? false : true);\r\n\r\n\r\n }", "function isInRange(pos, start, end) {\n if (typeof pos != 'number') {\n // Assume it is a cursor position. Get the line number.\n pos = pos.line;\n }\n if (start instanceof Array) {\n return inArray(pos, start);\n } else {\n if (end) {\n return pos >= start && pos <= end;\n } else {\n return pos == start;\n }\n }\n }", "function between(i, min, max) {//check if int provided is within provided range. https://alvinalexander.com/java/java-method-integer-is-between-a-range\n if (i >= min && i <= max) {\n return true;\n } else {\n return false;\n }\n}", "function intWithinBounds(n, lower, upper) {\n\treturn n >= lower && n < upper && Number.isInteger(n);\n}", "function range(event, from, to) {\n result = allowChars('0-9');\n if (result)\n return (event.currentTarget.value >= from && event.currentTarget.value <= to);\n else\n return result;\n}", "static between(x, a, b, inclusive) {\n let greater = Math.max(a, b);\n let lesser = Math.min(a, b);\n return inclusive ? x >= lesser && x <= greater : x > lesser && x < greater;\n }", "function controlloRangeNumeri(min, max, number) {\n var result = false;\n if (number >= min && number <= max) {\n result = true;\n }\n return result;\n }", "function checkRange(input) {\n //checks integer range values for min/max order\n if (input < 0) {\n return true;\n }\n //converts every input into a String\n let stringTest = input.toString();\n // Take their input and split it at the '-' (hyphen mark)\n // numbers variable will then look like this\n // numbers = ['value1', 'value2']\n let numbers = stringTest.split(\"-\");\n //removes empty strings in array (caused by edge case of negative min to max range ex: \"-100-300\")\n let filterednumbers = numbers.filter((item) => item);\n // parseFloat parses argument and returns floating point number, then point numbers are compared using the < (less than) mathematical symbol\n // Because we are using the < in the return, this will only return a true or false based off the values.\n return parseFloat(filterednumbers[0]) < parseFloat(filterednumbers[1]);\n}", "function range(a, b) {\n return (((a >= 40 && a <= 60 || a >= 70 && a <= 100)) && ((b >= 40 && b <= 60 || b >= 70 && b <= 100)))\n}", "function checkRange(value, lowerBounds, upperBounds) {\n if (value >= lowerBounds && value <= upperBounds)\n return value;\n else\n return !value;\n}", "static isRange(obj) {\n return obj instanceof Range;\n }", "touchesRange(from, to = from) {\n for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {\n let len = this.sections[i++], ins = this.sections[i++], end = pos + len;\n if (ins >= 0 && pos <= to && end >= from)\n return pos < from && end > to ? \"cover\" : true;\n pos = end;\n }\n return false;\n }", "function isInBound(x,y){\n\treturn x>-1&&x<9&&y>-1&&y<9;\n}", "function between(v, a, b) {\n\treturn ((v >= a) && (v <= b)) || ((v >= b) && (v <= a))\n}", "includes(value) {\r\n value = util_1.toBuffer(value);\r\n return compare(this.start, value) <= 0 && compare(this.end, value) > 0;\r\n }", "function isInAgeRange(adult, range) {\n return adult.age >= ranges[range].from && adult.age <= ranges[range].to\n }", "between(from, to, f) {\n if (this == RangeSet.empty)\n return;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n if (to >= start && from <= start + chunk.length &&\n chunk.between(start, from - start, to - start, f) === false)\n return;\n }\n this.nextLayer.between(from, to, f);\n }", "includes(range, target) {\n if (Range.isRange(target)) {\n if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {\n return true;\n }\n\n var [rs, re] = Range.edges(range);\n var [ts, te] = Range.edges(target);\n return Point.isBefore(rs, ts) && Point.isAfter(re, te);\n }\n\n var [start, end] = Range.edges(range);\n var isAfterStart = false;\n var isBeforeEnd = false;\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0;\n isBeforeEnd = Point.compare(target, end) <= 0;\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0;\n isBeforeEnd = Path.compare(target, end.path) <= 0;\n }\n\n return isAfterStart && isBeforeEnd;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to get data values calculated with the analytic dhis process
async getDataValueProgramIndicators(indicators,periods,ous){ let url="analytics?dimension=dx:"+indicators+"&dimension=pe:"+periods+"&dimension=ou:"+ous+"&displayProperty=NAME" return await this.getResourceSelected(url) }
[ "static async getTotalCovidData() {\n const res = await axios.get(`${url}/total`);\n const data = res?.data[0]?.globalData;\n return data;\n }", "function getCampaignPerformance() {\n \n var entityIdFieldName = 'CampaignId';\n var reportName = 'CAMPAIGN_PERFORMANCE_REPORT';\n var performance = {};\n \n var query = \n \"SELECT CampaignId, AbsoluteTopImpressionPercentage \" +\n \"FROM CAMPAIGN_PERFORMANCE_REPORT \" +\n \"WHERE Impressions > \" + String(MINIMUM_IMPRESSIONS) + \" \" +\n \"DURING \" + DATE_RANGE;\n \n //create a spreadsheet, change the report name as prefered\n /** \n var sheet = SpreadsheetApp.create('IM A SHEET').getActiveSheet();\n // set sheet range\n var range = sheet.getRange(\"B2:I20\");\n var cell = range.getValues();\n */\n var rows = AdsApp.report(query).rows();\n /** \n var i = 1;\n */\n while (rows.hasNext()) {\n var row = rows.next();\n performance[row['CampaignId']] = row.AbsoluteTopImpressionPercentage;\n //place data in cell in the sheet\n /** \n cell[0][3] = [\"CampaignId\"];\n cell[0][4] = [\"AbsoluteTopImpressionPercentage\"];\n cell[i][3] = row[\"CampaignId\"];\n cell[i][4] = row[\"AbsoluteTopImpressionPercentage\"];\n i++;\n **/\n //all the data shows here\n Logger.log('performance = '+JSON.stringify(performance));\n /** \n range.setValues(cell);\n */\n } \n \n return performance;\n \n }", "getTableauData () {\n if (!Array.isArray(this.data) || this.data.length === 0) {\n throw new Error('Data is not an array or is an empty!!')\n }\n\n return this.data.map((row) => {\n return {\n 'values': row.insights.data.map((value) => {\n return {\n 'post_id': parseInt(row.id.split('_')[1]),\n 'page_id': parseInt(row.id.split('_')[0]),\n 'page_post_id': row.id,\n [value.name]: value.values[0].value\n }\n })\n }\n }).reduce((a, b) => {\n let values = b.values.reduce((aF, bF) => {\n let keys = Object.keys(bF)\n\n keys.map((key) => {\n aF[key] = bF[key]\n })\n return aF\n }, {})\n\n return a.concat(values)\n }, [])\n }", "dataPoints () {\n let dimension = this;\n \n // Get the data points for this user for this dimension\n return DataPoints.find({\n dimensionId: dimension._id\n });\n }", "getValues() {\n return this.getValuesFromElement(this.element);\n }", "resultsCalc(data) {\n if (this.debug) console.log(\"\\nCALCULATE RESULTS >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n // DATA is either PROBLEM object for DECISION MAKING\n this.data = data;\n // Calculate M values for each CRITERION (Mni and M and Ml and Mdash) (row 17 + 26 + 35 + 44)\n this.calcMvalues();\n // Calculate K value for CATEGORY (row 53)\n this.calcK();\n // Calculate M values for each ALTERNATIVE in Category (row 56)\n this.calcMalternatives();\n // Calculate M dash H value for CATEGORY (row 63)\n this.calcMdashH();\n // Calculate Ml H value for CATEGORY (row 66)\n this.calcMlH();\n // Calculate array of Beliefs relating to each ALTERNATIVE (row 71)\n this.calcBeliefs();\n // Calculate level of ignorance associated with ALTERNATIVES of this CATEGORY (row 77)\n this.calcIgnorance();\n\n // RESULTS PAGE calculations\n // Calculate array of M n,i relating to each category (summary sheet row 41 + 52 + 63 + 74)\n this.calcAggregatedMvalues();\n // Calculate aggregated K value for PROJECT (summary sheet row 85)\n this.calcAggregatedK();\n // Calculate aggregated M values for each ALTERNATIVE in PROJECT (summary sheet row 88)\n this.calcAggregatedMalternatives();\n // Calculate aggregated M dash H value for PROJECT (summary sheet row 95)\n this.calcAggregatedMdashH();\n // Calculate aggregated Ml H value for PROJECT (summary sheet row 98)\n this.calcAggregatedMlH();\n // Calculate array of aggregated Beliefs relating to each ALTERNATIVE (summary sheet row 103)\n this.calcAggregatedBeliefs();\n // Calculate aggregated level of ignorance associated with ALTERNATIVES of this PROJECT (summary sheet row 109)\n this.calcAggregatedIgnorance();\n }", "calcAggregatedMvalues() {\n var _this = this;\n var data = this.data;\n\n if (_this.debug) console.log(\"\\n\\n<<<<<<<<< RESULT PAGE CALCULATIONS >>>>>>>>>>>>>>>>>\");\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Aggregated M values - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n\n var aggMni_results = []; // capture agregated Mni values for each CATEGORY (one per each solution)\n\n // Loop over each belief value for Mni\n for (var i = 0; i < category.Beliefs.length; i++) {\n aggMni_results.push(category.Beliefs[i] * (category.weight / 100));\n }\n category.Mni = aggMni_results;\n\n // CALCULATE M for each CATEGORY ////////////////////////////////////\n // 1-(sum Mni aggMni_results)\n var M_result = 1 - (aggMni_results.reduce(_this.getSum));\n // update data model, rounded to 3 decimal places\n category.M = M_result;\n\n // CALCULATE Ml for each CATEGORY ////////////////////////////////////\n // 1-(category weight (convert from percentage)\n category.Ml = 1 - (category.weight * 0.01);\n\n // CALCULATE Mdash for each CATEGORY ////////////////////////////////////\n // category weight * (1-(sum(alternative beliefs)))\n var Mdash_result = (category.weight * 0.01) * (1 - (category.Beliefs.reduce(_this.getSum)));\n category.Mdash = Mdash_result;\n\n if (_this.debug) console.log(\"MNI: \" + category.Mni);\n if (_this.debug) console.log(\"M: \" + category.M);\n if (_this.debug) console.log(\"Ml: \" + category.Ml);\n if (_this.debug) console.log(\"Mdash: \" + category.Mdash);\n });\n }", "function dataDayTemp(){\napp.get('/api/statisticsByDay/Temp', (req, res)=>{\n let sql = \"SELECT * FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT MAX(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT MIN(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp>32;SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp<18;SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp BETWEEN 18 AND 32;SELECT AVG(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"'\";\n con.query(sql, (err, result, fields)=>{\n if (err) throw err;\n res.json(result);\n });\n})\n}", "static getRuntimeStatistics() {\n return __awaiter(this, void 0, void 0, function* () {\n //using aggregation pipeline to implement the calculation\n const postsStatistics = yield this.model.aggregate([\n {\n $project: {\n _id: 0,\n function: \"$function\",\n averageRuntime: { $avg: \"$results\" },\n unit: \"miliseconds\"\n }\n }\n ]);\n return postsStatistics;\n });\n }", "function obtainChartValues(arg)\r\n{\r\n var script = atob(arg);\r\n var chartId = script.split(\"'\")[1];\r\n var temp = \"\";\r\n var values = new Array();\r\n values[0] = chartId;\r\n \r\n if(chartId == \"ch_cr\" || chartId == \"ch_recycle\" || chartId == \"ch_extensions_all\" || chartId == \"ch_autopay\" || chartId == \"ch_cliques\" || chartId == \"ch_cdd\")\r\n {\r\n temp = script.split(\"data:[\")[1];\r\n temp = temp.substring(0,temp.indexOf(']')).split(',');\r\n }\r\n\r\n return values.concat(temp);\r\n}", "getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }", "function getMetricsData() {\n //select Average Page View\n data.avgPageView = $('#card_metrics > section.engagement > div.flex > div:nth-child(1) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Average Time On Site\n data.avgTimeOnSite = $('#card_metrics > section.engagement > div.flex > div:nth-child(2) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Bounce Rate\n data.bounceRate = $('#card_metrics > section.engagement > div.flex > div:nth-child(3) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Search Traffic Percent\n data.searchTrafficPercent = $('#card_mini_competitors > section.group > div:nth-child(2) > div.ThirdFull.ProgressNumberBar > span').text();\n\n //select Overall Rank\n data.overallRank = $('#card_rank > section.rank > div.rank-global > div:nth-child(1) > div:nth-child(2) > p.big.data').text().replace(/\\s+/g, ''); //.replace(/,/g, '');\n\n }", "function getMetricsForDays(fromDaysAgo, toDaysAgo, tabName) {\n var start = new Date();\n start.setHours(0,0,0,0);\n start.setDate(start.getDate() - toDaysAgo);\n\n var end = new Date();\n end.setHours(23,59,59,999);\n end.setDate(end.getDate() - fromDaysAgo);\n \n var fitService = getFitService();\n \n var request = {\n \"aggregateBy\": [\n {\n \"dataTypeName\": \"com.google.step_count.delta\",\n \"dataSourceId\": \"derived:com.google.step_count.delta:com.google.android.gms:estimated_steps\"\n },\n {\n \"dataTypeName\": \"com.google.weight.summary\",\n \"dataSourceId\": \"derived:com.google.weight:com.google.android.gms:merge_weight\"\n },\n {\n \"dataTypeName\": \"com.google.distance.delta\",\n \"dataSourceId\": \"derived:com.google.distance.delta:com.google.android.gms:merge_distance_delta\"\n }\n ],\n \"bucketByTime\": { \"durationMillis\": 86400000 },\n \"startTimeMillis\": start.getTime(),\n \"endTimeMillis\": end.getTime()\n };\n \n var response = UrlFetchApp.fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', {\n headers: {\n Authorization: 'Bearer ' + fitService.getAccessToken()\n },\n 'method' : 'post',\n 'contentType' : 'application/json',\n 'payload' : JSON.stringify(request, null, 2)\n });\n \n var json = JSON.parse(response.getContentText());\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(tabName);\n \n for(var b = 0; b < json.bucket.length; b++) {\n // each bucket in our response should be a day\n var bucketDate = new Date(parseInt(json.bucket[b].startTimeMillis, 10));\n \n var steps = -1;\n var weight = -1;\n var distance = -1;\n \n if (json.bucket[b].dataset[0].point.length > 0) {\n steps = json.bucket[b].dataset[0].point[0].value[0].intVal;\n }\n \n if (json.bucket[b].dataset[1].point.length > 0) {\n weight = json.bucket[b].dataset[1].point[0].value[0].fpVal;\n }\n \n if (json.bucket[b].dataset[2].point.length > 0) {\n distance = json.bucket[b].dataset[2].point[0].value[0].fpVal;\n }\n \n sheet.appendRow([bucketDate, \n steps == -1 ? ' ' : (weight*2.2046)-170, \n weight == -1 ? ' ' : weight*2.2046, \n distance == -1 ? ' ' : distance]);\n }\n}", "getData() {\n\t\t\t// returns deep copy of _runoffResultsData\n\t\t\treturn JSON.parse(JSON.stringify(_runoffResultsData));\n\t\t}", "function calculateData() {\n\tvar percentage = 0;\n\ttotalData = 0;\n\thighestData = 0;\n\t//Calculate Total of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\ttotalData += parseInt(chartData[i]['value']);\n\t\tif (highestData < parseInt(chartData[i]['value']))\n\t\t\thighestData = parseInt(chartData[i]['value']);\n\t}\n\t//Calculate Percentage of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\tpercentage = (chartData[i]['value'] / totalData) * 100;\n\t\tchartData[i]['percentage'] = percentage.toFixed(2);\n\t}\n}", "calcAggregatedIgnorance() {\n if (this.debug) console.log(\"\\nCALC Aggregated Ignorance - PROJECT - >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var data = this.data;\n data.Ignorance = data.MdashH / (1 - data.MlH);\n if (this.debug) console.log(\"data.Ignorance: \" + data.Ignorance);\n\n // Calculate and save distributed ignorance divided by number of alternatives\n // For Distributed Ignorance table\n data.IgnoranceSplit = data.Ignorance/data.alternatives.length;\n }", "function TotalEngagements() {\n var self = this;\n this.loading = true;\n var count1 =[],date1 =[];\n\n this.loadData = function() {\n self.loading = true;\n Restangular\n .one('campaign_reports', ctrl.campaignId)\n .customGET('cumulative_engagement_time_series')\n .then(function(response) {\n var _count = [],_date = [];\n for (var j = 0; j < response.length; j++) {\n _count.push(response[j].count);\n _date.push(response[j].date);\n }\n self.data = [];\n self.data[0] = {};\n self.data[0].date = _date.toString();\n self.data[0].count = _count.toString();\n self.data[0].minDate=response[0].date;\n self.data[0].maxDate=response[response.length-1].date;\n self.loading = false;\n console.log(\"Total Engagements:::\", self.data[0]);\n });\n };\n this.loadData();\n }", "getMetricsData() {\n\n let innerMap = new Map();\n\n // Get interactions for each agent in current time\n for (let agent of this.agents) {\n this.getInteractions(innerMap, agent);\n }\n\n //save interactions for the current tick time.\n this.metricsMap.set(world.getTicks(), innerMap);\n\n for (let agent of this.agents) {\n this.recordAgentViscosityData(agent);\n }\n\n let vscsty = this.recordGlobalViscosityData();\n\n document.getElementById(\"viscosityInWorld\").innerHTML = vscsty.toFixed(2);\n }", "function getMainDataMap() {\n return {\n fans: {\n metric: 'fans',\n getter: commonGetters.getChannelsSeparatelyGetter('breakdownValues')\n },\n fansValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('totalValue')\n },\n fansChangeValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changeValue')\n },\n fansChangePercent: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changePercent'),\n formatters: [\n dataFormatters.decimalToPercent\n ]\n }\n };\n} // end getMainDataMap", "getData() {\n return PRIVATE.get(this).opt.data;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert align="center" to align="middle"
function convert_align_middle_to_center(code) { r = /(\salign="middle")/gi; r1 = /(\salign=middle)/gi; code = code.replace(r," align=\"center\""); code = code.replace(r1," align=center"); return code; }
[ "align(text, length, alignment, filler) {\n if (!filler) filler = SPACE;\n if (!alignment)\n ArgumentNullException(\"alignment\");\n switch (alignment) {\n case \"c\":\n case \"center\":\n return S.center(text, length, filler);\n case \"l\":\n case \"left\":\n return S.ljust(text, length, filler);\n break;\n case \"r\":\n case \"right\":\n return S.rjust(text, length, filler);\n default:\n ArgumentException(\"alignment: \" + alignment);\n }\n }", "function defaultAlign() {\n return {\n alignType: AlignType.Center,\n extraOffset: new Point(),\n };\n }", "function validateMatrixAlignment(align) {\n var DEFAULT = 'center center';\n\n if (align) {\n var _align$split = align.split(' '),\n _align$split2 = _slicedToArray(_align$split, 2),\n y = _align$split2[0],\n x = _align$split2[1];\n\n return validateVerticalAlignment(y) + ' ' + validateHorizontalAlignment(x);\n }\n\n return DEFAULT;\n } // Dependencies.", "function withAlignTextAttributes(attributes) {\n attributes.align_text = {\n type: 'string'\n };\n return attributes;\n }", "function changeAlign(align) {\n gMeme.currText.align = align;\n gMeme.currText.x = gFontlocation[align].x\n}", "setTextAlignment(value) {\n this.ctx.textAlign = value;\n }", "function withAlignContentAttributes(attributes) {\n attributes.align_content = {\n type: 'string'\n };\n return attributes;\n }", "function setColumnAlign(\n opts: Options,\n change: Change,\n align: string = ALIGN.DEFAULT,\n at: number\n): Change {\n const { value } = change;\n const { startBlock } = value;\n\n const pos = TablePosition.create(value, startBlock);\n const { table } = pos;\n\n // Figure out column position\n if (typeof at === 'undefined') {\n at = pos.getColumnIndex();\n }\n\n const newAlign = createAlign(pos.getWidth(), table.data.get('align'));\n newAlign[at] = align;\n\n change.setNodeByKey(table.key, {\n data: table.data.set('align', newAlign)\n });\n\n return change;\n}", "function validateHorizontalAlignment(align) {\n var ALIGNMENTS = ['left', 'center', 'right'];\n var DEFAULT = acf.get('rtl') ? 'right' : 'left';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function centerField() {\n $(\"#container\").css(\"width\", $(\"#container\").width()*1.1); // prevents shifting of container when text size changes.\n $(\"#container\").css(\"margin-left\", -$(\"#container\").width()/2);\n $(\"#container\").css(\"margin-top\", -$(\"#container\").height()/2);\n }", "_guessWidgetAlignment(priceElement) {\n if (!priceElement) return 'left'; // default\n const textAlignment = window.getComputedStyle(priceElement).textAlign;\n /* Start is a CSS3 value for textAlign to accommodate for other languages which may be\n\t\t * RTL (right to left) for instance Arabic. Since the sites we are adding the widgets to are mostly,\n\t\t * if not all in English, it will be LTR (left to right), which implies that 'start' and 'justify' would mean 'left'\n\t\t */\n if (textAlignment === 'start' || textAlignment === 'justify') return 'left';\n /*\n\t\t * end is a CSS3 value for textAlign to accommodate for other languages which may be RTL (right to left), for instance Arabic\n\t\t * Since the sites we are adding to are mostly, if not all in English, it will be LTR (left to right), hence 'right' at the end\n\t\t */\n return textAlignment === 'end' ? 'right' : textAlignment;\n }", "function validateVerticalAlignment(align) {\n var ALIGNMENTS = ['top', 'center', 'bottom'];\n var DEFAULT = 'top';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function getCenteredPosition(width) {\n var w = getNumericalPart(width); //numerical value of the width\n var left = 50 - (w / 2); //centre of the text box is at the 50% position\n return left + \"%\";\n}", "function getCenter()\n{\n var center = document.createElement(\"center\");\n return center;\n}", "function alignment(val) {\n\n // check if date\n var parsedDate = Date.parse(val);\n if (isNaN(val) && (!isNaN(parsedDate))) {\n return \"center\";\n }\n\n // check if numeric (remove $ and , and then check if numeric)\n var possibleNum = val.replace(\"$\", \"\");\n possibleNum = possibleNum.replace(\",\", \"\");\n if (isNaN(possibleNum)) {\n return \"left\";\n }\n return \"right\"; // it's a number\n\n }", "function draw_alignment(d, i){\n help_draw_alignment(d.c1_nm, d.c1_st, d.c1_en, d.c2_nm, d.c2_st, d.c2_en, d.id, d.strand);\n }", "alignColumn(alignment, options) {\n this._withTable(options, ({ range, lines, table, focus }) => {\n let newFocus = focus;\n // complete\n const completed = formatter.completeTable(table, options);\n if (completed.delimiterInserted && newFocus.row > 0) {\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n // alter alignment\n let altered = completed.table;\n if (0 <= newFocus.column &&\n newFocus.column <= altered.getHeaderWidth() - 1) {\n altered = formatter.alterAlignment(completed.table, newFocus.column, alignment, options);\n }\n // format\n const formatted = formatter.formatTable(altered, options);\n newFocus = newFocus.setOffset(exports._computeNewOffset(newFocus, completed.table, formatted, false));\n // apply\n this._textEditor.transact(() => {\n this._updateLines(range.start.row, range.end.row + 1, formatted.table.toLines(), lines);\n this._moveToFocus(range.start.row, formatted.table, newFocus);\n });\n });\n }", "function alignElementVerticalyCenter(){\r\n var container = jQuery('.site-section');\r\n\r\n jQuery(container).each(function(){\r\n if( jQuery(this).hasClass('ts-fullscreen-row') ){\r\n var windowHeight = jQuery(window).height();\r\n var containerHeight = windowHeight;\r\n }else{\r\n var windowHeight = '100%';\r\n var containerHeight = jQuery(this).outerHeight();\r\n }\r\n\r\n var innerContent = jQuery(this).find('.container').height();\r\n var insertPadding = Math.round((containerHeight-innerContent)/2);\r\n\r\n if( jQuery(this).attr('data-alignment') == 'middle' ){\r\n jQuery(this).css({'padding-top':insertPadding,'padding-bottom':insertPadding,'min-height':windowHeight});\r\n }else if( jQuery(this).attr('data-alignment') == 'top' ){\r\n jQuery(this).css('min-height',windowHeight);\r\n }else if( jQuery(this).attr('data-alignment') == 'bottom' ){\r\n jQuery(this).css({'width':'100%','height':containerHeight,'position':'relative','min-height':windowHeight});\r\n jQuery(this).children('.container').css({'width':'100%','height':'100%'});\r\n var rowPaddingBottom = jQuery(this).css('padding-bottom');\r\n jQuery(this).find('.row-align-bottom').css({'position':'absolute','width':'100%','bottom':rowPaddingBottom});\r\n }\r\n });\r\n\r\n // align the elements vertically in the middle for banner box\r\n if( jQuery('.ts-banner-box').length > 0 ){\r\n jQuery('.ts-banner-box').each(function(){\r\n var containerHeight = jQuery(this).outerHeight();\r\n var innerContent = jQuery(this).find('.container').height();\r\n var insertPadding = Math.round((containerHeight-innerContent)/2);\r\n\r\n jQuery(this).css({'padding-top':insertPadding,'padding-bottom':insertPadding});\r\n });\r\n }\r\n \r\n}", "function PopUp_Center() {\n if (_popUp) {\n _popUp.css({ \"left\": ($(\"html\").outerWidth() / 2) - (_popUp.outerWidth() / 2), \"top\": ($(\"html\").outerHeight() / 2) - (_popUp.outerHeight() / 2) });\n }\n\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update opponent athlete statistics based on the game actions list.
UPDATE_OPP_ATHLETE_STATISTICS(state) { let result = []; for (let athlete in state.oppRoster) { result.push( { name: state.oppRoster[athlete].name, number: state.oppRoster[athlete].number, points:0, freethrow: 0, freethrowAttempt: 0, freethrowPercentage:0, twopoints: 0, twopointsAttempt: 0, twopointsPercentage:0, threepoints: 0, threepointsAttempt: 0, threepointsPercentage:0, assists: 0, blocks: 0, rebounds: 0, steals: 0, turnovers: 0, foul: 0 } ); } // For each game action, update athlete statistics accordingly. for (let index in state.gameActions) { let currentAction = state.gameActions[index]; if (currentAction.team !== "opponent") { continue; } let athlete_index = -1; for (let athlete in state.oppRoster) { if (state.oppRoster[athlete].key == "athlete-" + currentAction.athlete_id) { athlete_index = athlete; break; } } // Continue when an athlete has been removed. if (athlete_index === -1) { continue; } switch (currentAction.action_type) { case "Freethrow": result[athlete_index].freethrow++; result[athlete_index].freethrowAttempt++; result[athlete_index].points++; result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100; result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1); break; case "FreethrowMiss": result[athlete_index].freethrowAttempt++; result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100; result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1); break; case "2Points": result[athlete_index].twopoints++; result[athlete_index].twopointsAttempt++; result[athlete_index].points+2; result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100; result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1); break; case "2PointsMiss": result[athlete_index].twopointsAttempt++; result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100; result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1); break; case "3Points": result[athlete_index].threepoints++; result[athlete_index].threepointsAttempt++; result[athlete_index].points+3; result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100; result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1); break; case "3PointsMiss": result[athlete_index].threepointsAttempt++; result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100; result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1); break; case "Assist": result[athlete_index].assists++; break; case "Blocks": result[athlete_index].blocks++; break; case "Steals": result[athlete_index].steals++; break; case "Rebound": result[athlete_index].rebounds++; break; case "Turnover": result[athlete_index].turnovers++; break; case "Foul": result[athlete_index].foul++; break; default: break; } } state.oppAthleteStatistics = result; }
[ "UPDATE_UPRM_STATISTICS(state) {\n let result = {\n freethrow: 0,\n freethrowAttempt: 0,\n twopoints: 0,\n twopointsAttempt: 0,\n threepoints: 0,\n threepointsAttempt: 0,\n assists: 0,\n blocks: 0,\n rebounds: 0,\n steals: 0,\n turnovers: 0,\n foul: 0\n };\n\n // For each game action, update result accordingly.\n for (let index in state.gameActions) {\n let currentAction = state.gameActions[index];\n if (currentAction.team !== \"uprm\") {\n continue;\n }\n switch (currentAction.action_type) {\n case \"Freethrow\":\n result.freethrow++;\n result.freethrowAttempt++;\n break;\n\n case \"FreethrowMiss\":\n result.freethrowAttempt++;\n break;\n\n case \"2Points\":\n result.twopoints++;\n result.twopointsAttempt++;\n break;\n\n case \"2PointsMiss\":\n result.twopointsAttempt++;\n break;\n\n case \"3Points\":\n result.threepoints++;\n result.threepointsAttempt++;\n break;\n \n case \"3PointsMiss\":\n result.threepointsAttempt++;\n break;\n\n case \"Assist\":\n result.assists++;\n break;\n\n case \"Blocks\":\n result.blocks++;\n break;\n\n case \"Steals\":\n result.steals++;\n break;\n\n case \"Rebound\":\n result.rebounds++;\n break;\n\n case \"Turnover\":\n result.turnovers++;\n break;\n\n case \"Foul\":\n result.foul++;\n break;\n\n default:\n break;\n }\n }\n\n state.uprmStatistics = result;\n }", "addAiOpponent() {\n\t\tif ( this.status != 'available' ) {\n\t\t\tthrow new Error( 'Not available.' );\n\t\t}\n\n\t\tthis[ _connection ].request( 'join', this.gameId, { ai: true } )\n\t\t\t.then( gameData => {\n\t\t\t\tthis.opponent.id = gameData.opponentId;\n\t\t\t\tthis.opponent.isInGame = true;\n\t\t\t\tthis.status = 'full';\n\t\t\t} )\n\t\t\t.catch( error => this._handleServerError( error ) );\n\t}", "updateOrbs() {\n\t\tthis.sounds.collect.play();\n\t\tthis.collected = true;\n\t\tthis.game.orbCount++;\n\t\tthis.player.heal();\n\t\t//console.log(\"Orbs\", this.game.orbCount);\n\t}", "function updateStats(){\n\t//update p1 stats on page\n\tdocument.getElementById(\"p1def\").innerText=player1.def;\n\tdocument.getElementById(\"p1def\").innerText=player1.def;\n\tdocument.getElementById(\"p1lck\").innerText=player1.luck;\n document.getElementById(\"p1atk\").innerText=player1.atk;\n document.getElementById(\"p1spd\").innerText=player1.speed;\n\t\n\t//update p2 stats on page\n\tdocument.getElementById(\"p2def\").innerText=player2.def;\n\tdocument.getElementById(\"p2lck\").innerText=player2.luck;\n document.getElementById(\"p2atk\").innerText=player2.atk;\n document.getElementById(\"p2spd\").innerText=player2.speed;\n}", "function updateStats() {\n $(\".elevator-\" + index + \" .value\").text(floorButtonsQueue);\n }", "attack(opponent) {\n \n // console.log which character was attacked and how much damage was dealt\n console.log(`${this.name} attacked ${opponent.name}`);\n // Then, change the opponent's hitPoints to reflect this\n opponent.hitPoints -= this.strength;\n\n }", "function calculateEquipmentStat() {\r\n //init\r\n for(let prop in player.additionalStats){player.additionalStats[prop] = 0};\r\n //calculation\r\n for(let prop in player.equipments){\r\n let d = player.equipments[prop];\r\n if(d !== null){\r\n player.additionalStats.atk += d.atk;\r\n player.additionalStats.def += d.def;\r\n player.additionalStats.spd += d.spd;\r\n }\r\n }\r\n}", "function updateGame(game, action) {\n if (typeof game === 'undefined') return makeGame();\n\n if (action.type === 'FRAME_READY') {\n if (game.get(\"mode\") === 'GAME_ON') {\n var player = updatePlayer(game.get(\"player\"), { 'type': 'STEP' });\n\n var boulders = game.get(\"boulders\").map(function(boulder) {\n return updateBoulder(boulder, { 'type': 'STEP' });\n });\n\n var missiles = game.get(\"missiles\").reduce(function(accum, missile) {\n var missile2 = updateMissile(missile, { 'type': 'STEP' });\n if (missile2.get(\"mode\") == 'GONE') {\n return accum;\n } else {\n return accum.push(missile2);\n }\n }, Immutable.List());\n\n var collisionResult = detectCollisions(player, missiles, boulders);\n var player2 = collisionResult[0];\n var missiles2 = collisionResult[1];\n var boulders2 = collisionResult[2];\n\n /* Assemble new game state from all that */\n var game2;\n if (player2.get(\"mode\") === 'GONE') {\n game2 = game.set(\"mode\", 'GAME_OVER')\n .set(\"timer\", 100)\n .set(\"highScore\", player2.get(\"score\") > game.get(\"highScore\") ? player2.get(\"score\") : game.get(\"highScore\"));\n } else {\n game2 = game;\n }\n return game2.set(\"player\", player2)\n .set(\"boulders\", boulders2.size === 0 ? makeBoulders() : boulders2)\n .set(\"missiles\", missiles2);\n } else if (game.get(\"mode\") === 'GAME_OVER') {\n var game2 = game.update(\"timer\", decr);\n if (game2.get(\"timer\") <= 0) {\n return resetGame(game2);\n } else {\n return game2;\n }\n } else if (game.get(\"mode\") === 'ATTRACT_TITLE') {\n if (game.get(\"credits\") > 0) {\n return game;\n } else {\n return countDown(game, function(game) {\n return game.set(\"mode\", 'ATTRACT_HISCORES').set(\"timer\", 400);\n });\n }\n } else if (game.get(\"mode\") === 'ATTRACT_HISCORES') {\n return countDown(game, function(game) {\n return game.set(\"mode\", 'ATTRACT_TITLE').set(\"timer\", 400);\n });\n }\n throw new Error(\"Unhandled mode: \" + game.get(\"mode\"));\n } else if (action.type === 'CONTROLS_CHANGED') {\n if (game.get(\"mode\") === 'ATTRACT_TITLE' || game.get(\"mode\") === 'ATTRACT_HISCORES') {\n if (action.prev.startPressed && (!action.startPressed)) {\n if (game.get(\"credits\") > 0) {\n var player = resetPlayer(game.get(\"player\"));\n return game.set(\"player\", player).update(\"credits\", decr).set(\"mode\", 'GAME_ON');\n } else {\n return game;\n }\n } else {\n return game;\n }\n } else if (game.get(\"mode\") === 'GAME_ON') {\n var player = game.get(\"player\");\n if (fireWentDown(action) && player.get(\"mode\") === 'PLAYING') {\n var mx = player.get(\"x\");\n var my = player.get(\"y\");\n var h = player.get(\"h\");\n var mv = 2.0;\n var mvx = Math.cos(degreesToRadians(h)) * mv;\n var mvy = Math.sin(degreesToRadians(h)) * mv;\n return game.update(\"missiles\", function(m) {\n return m.push(makeMissile(mx, my, mvx, mvy));\n });\n } else {\n return game.set(\"player\", updatePlayer(game.get(\"player\"), action));\n }\n } else if (game.get(\"mode\") === 'GAME_OVER') {\n return game;\n }\n throw new Error(\"Unhandled mode: \" + game.get(\"mode\"));\n } else if (action.type === 'COIN_INSERTED') {\n var game2 = game.update(\"credits\", incr);\n if (game2.get(\"mode\") === 'ATTRACT_HISCORES') {\n return game2.set(\"mode\", 'ATTRACT_TITLE');\n } else {\n return game2;\n }\n }\n throw new Error(\"Unhandled action: \" + action.type);\n}", "function updateScoreOverlay() {\n let one = playerNetscore(team.getT1());\n write(t1Players, one);\n one = team.getT1();\n write(t1Score, one.points);\n\n let two = playerNetscore(team.getT2());\n write(t2Players, two);\n two = team.getT2();\n write(t2Score, two.points);\n}", "updateAvailableActions() {\n this['availableActions'].length = 0;\n\n for (var i = 0; i < this.registeredActions_.length; i++) {\n var action = this.registeredActions_[i];\n if (!action.isUnique() || !this['actions'].some(function(obj) {\n return obj['id'] == action.getId();\n })) {\n this['availableActions'].push({\n 'id': action.getId(),\n 'label': action.getLabel()\n });\n }\n }\n }", "function agree() {\n status.military += parseInt(currentCard.military1);\n status.relations += parseInt(currentCard.relations1);\n status.happiness += parseInt(currentCard.happiness1);\n status.economy += parseInt(currentCard.economy1);\n nextTurn();\n}", "function success() {\n score += 1;\n scoreSpan.textContent = score;\n if (score > highScore) {\n highScore = score;\n highScoreSpan.textContent = highScore;\n }\n allEnemies.forEach(function(enemy) {\n enemy.speed = enemy.speed * 1.1;\n });\n player.goBack();\n}", "function updateWinnings() {\n scope.render()\n }", "function updateAverage($teams) {\n\tfor (var i = 0; i < $teams.length; i++) {\n\t\t$team = $($teams[i]);\n\t\tvar $players = $team.find('.player');\n\t\tvar n = 0;\n\t\tvar total = 0.0;\n\t\tvar nExp = 0;\n\t\tvar totalExp = 0.0;\n\t\tfor (var j = 0; j < $players.length; j++) {\n\t\t\tvar rating = parseInt($players.eq(j).attr('data-rating'));\n\t\t\tif (!isNaN(rating)) {\n\t\t\t\tn += 1;\n\t\t\t\ttotal += rating;\n\t\t\t}\n\t\t\tvar ratingExp = parseInt($players.eq(j).attr('data-exp-rating'));\n\t\t\tif (!isNaN(ratingExp)) {\n\t\t\t\tnExp += 1;\n\t\t\t\ttotalExp += ratingExp;\n\t\t\t}\n\t\t}\n\t\tif (n > 0) {\n\t\t\t$team.find('.average-rating').text((total / n).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-rating').text('');\n\t\t}\n\t\tif (nExp > 0) {\n\t\t\t$team.find('.average-exp-rating').text((totalExp / nExp).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-exp-rating').text('');\n\t\t}\n\t}\n}", "updateSectionColorPlayer(opponent) {\n $(\"#\"+opponent).removeClass(\"player-infos--active\");\n $(\"#\"+this.name).addClass(\"player-infos--active\");\n }", "updateGoodTypeCounts() {\n getValidGoodTypes().forEach((goodType) => {\n // Reset all calculated values from previous iteration\n this.setRoyalty(goodType.name, 0);\n this.countSubtotals[goodType.name] = 0;\n // Each player has inputs that come in a specific type. Some goods score extra when it comes to\n // determining bonuses for first and second (King and Queen). Recaclulate the total for each goodType.\n goodType.goods.forEach((targetGood) => {\n // Multiplier is relevant for royal goods.\n this.countSubtotals[goodType.name] += this.getCount(targetGood.name) * targetGood.multiplier;\n });\n });\n }", "function getTotalScore() {\n\n let ai = 0;\n let human = 0;\n\n //Calculate pawn penalties\n //Number of pawns in each file\n let human_pawns = [];\n let ai_pawns = [];\n\n for (let x = 0; x < 8; x++) {\n\n let h_cnt = 0;\n let a_cnt = 0;\n\n for (let y = 0; y < 8; y++) {\n\n let chk_piece = board[y][x];\n\n if (chk_piece != null && chk_piece instanceof Pawn) {\n\n if (chk_piece.player == 'human') h_cnt++;\n else a_cnt++;\n\n //Pawn rank bonuses\n if (x > 1 && x < 6) {\n\n //Normalize y to chess rank 1 - 8\n let rank = (chk_piece.player == 'human') ? Math.abs(y - 7) + 1 : y + 1;\n\n switch (x) {\n\n case 2:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 3.9 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 3.9 * (rank - 2);\n break;\n\n case 3:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 5.4 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 5.4 * (rank - 2);\n break;\n\n case 4:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 7.0 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 7.0 * (rank - 2);\n break;\n\n case 5:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 2.3 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 2.3 * (rank - 2);\n break;\n\n }\n\n }\n\n }\n\n }\n\n human_pawns.push(h_cnt);\n ai_pawns.push(a_cnt);\n\n }\n\n for (let i = 0; i < 8; i++) {\n\n //Doubled pawn penalty\n if (human_pawns[i] > 1) human -= (8 * human_pawns[i]);\n if (ai_pawns[i] > 1) ai += (8 * ai_pawns[i]);\n\n //Isolated pawn penalties\n if (i == 0) {\n if (human_pawns[i] > 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else if (i == 7) {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n\n }\n\n //Get material score\n for (let y = 0; y < 8; y++) {\n\n for (let x = 0; x < 8; x++) {\n\n if (board[y][x] != null) {\n\n let piece = board[y][x];\n\n //Material\n if (piece.player == 'human') human += piece.score;\n else ai += piece.score; \n\n //Knight bonuses/penalties \n if (piece instanceof Knight) {\n\n //Center tropism\n let c_dx = Math.abs(3.5 - x);\n let c_dy = Math.abs(3.5 - y);\n\n let c_sum = 1.6 * (6 - 2 * (c_dx + c_dy));\n\n if (piece.player == 'human') human += c_sum;\n else ai -= c_sum;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n ai -= k_sum;\n\n }\n\n }\n\n //Rook bonuses/penalties\n else if (piece instanceof Rook) {\n\n //Seventh rank bonus\n if (piece.player == 'human' && y == 1) human += 22;\n else if (piece.player == 'ai' && y == 6) ai -= 22;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n //Doubled rook bonus\n //Check rank\n let left_chk = true;\n let right_chk = true;\n let up_chk = true;\n let down_chk = true;\n for (let i = 1; i < 8; i++) {\n\n if (!left_chk && !right_chk && !down_chk && !up_chk) break;\n\n //Check left side\n if (x - i >= 0 && left_chk) {\n\n let chk_piece = board[y][x - i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else left_chk = false;\n }\n\n } else left_chk = false;\n\n //Check right side\n if (x + i < 8 && right_chk) {\n\n let chk_piece = board[y][x + i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else right_chk = false;\n }\n\n } else right_chk = false;\n\n //Check up side\n if (y - i >= 0 && up_chk) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else up_chk = false;\n }\n\n } else up_chk = false;\n\n //Check down side\n if (y + i < 8 && down_chk) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else down_chk = false;\n }\n\n } else down_chk = false;\n\n }\n\n //Doubled rook found\n if (left_chk || right_chk || down_chk || up_chk) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n //Open file bonus\n let open_file = true;\n\n for (let i = 1; i < 8; i++) {\n\n //Check up\n if (y - i >= 0) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n //Check down\n if (y + i < 8) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n }\n\n if (open_file) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n\n }\n\n //Queen bonuses/penalties\n else if (piece instanceof Queen) {\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n }\n\n //King bonuses/penalties\n else if (piece instanceof King) {\n\n //Cant castle penalty\n if (!piece.hasCastled) {\n\n //Castling no longer possible as king has moved at least once\n if (!piece.firstMove) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n\n } else {\n\n //Rooks\n let q_rook;\n let k_rook;\n\n //Check flags, true if castling is available\n let q_rook_chk = false;\n let k_rook_chk = false;\n\n if (piece.player == 'human') {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n }\n\n } else {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n }\n\n }\n\n q_rook_chk = q_rook != null && q_rook.firstMove;\n k_rook_chk = k_rook != null && k_rook.firstMove;\n\n //Castling no longer available\n if (!q_rook_chk && !k_rook_chk) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n \n }\n //Queen side castling not available\n else if (!q_rook_chk) {\n\n if (piece.player == 'human') human -= 8;\n else ai += 8;\n\n }\n //King side castling not available\n else if (!k_rook_chk) {\n\n if (piece.player == 'human') human -= 12;\n else ai += 12;\n\n }\n\n }\n\n //Check kings quadrant\n let enemy_pieces = 0;\n let friendly_pieces = 0;\n\n //Find quadrant\n //Top/Left\n if (y < 4 && x < 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Top/Right\n else if (y < 4 && x >= 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Left\n else if (y >= 4 && x < 4) {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Right\n else {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n if (enemy_pieces > friendly_pieces) {\n\n let diff = enemy_pieces - friendly_pieces;\n\n if (piece.player == 'human') human -= (5 * diff);\n else ai += (5 * diff);\n\n }\n\n }\n\n }\n\n //Bishop bonuses/penalties\n if (piece instanceof Bishop) {\n\n //Back rank penalty\n if (piece.player == 'human' && y == 7) human -= 11;\n else if (piece.player == 'ai' && y == 0) ai += 11;\n\n //Bishop pair bonus\n let pair = false;\n\n for (let i = 0; i < 8; i++) {\n\n for (let j = 0; j < 8; j++) {\n\n if (i == y && j == x) continue;\n\n let chk_piece = board[i][j];\n\n if (chk_piece != null && chk_piece.player == piece.player && chk_piece instanceof Bishop) {\n pair = true;\n break;\n }\n\n }\n\n }\n\n if (pair && piece.player == 'human') human += 50;\n else if (pair && piece.player == 'ai') ai -= 50;\n\n //Pawn penalties\n let p_cntr = 0;\n\n //Top left\n if (x - 1 >= 0 && y - 1 >= 0 && board[y - 1][x - 1] != null && board[y - 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Top right\n if (x + 1 < 8 && y - 1 >= 0 && board[y - 1][x + 1] != null && board[y - 1][x + 1] instanceof Pawn) p_cntr++;\n\n //Bottom left\n if (x - 1 >= 0 && y + 1 < 8 && board[y + 1][x - 1] != null && board[y + 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Bottom right\n if (x + 1 < 8 && y + 1 < 8 && board[y + 1][x + 1] != null && board[y + 1][x + 1] instanceof Pawn) p_cntr++;\n\n if (piece.player == 'human') human -= (p_cntr * 3);\n else ai += (p_cntr * 3);\n\n }\n\n\n \n }\n\n }\n\n }\n\n return ai + human;\n\n}", "function CheckOwnStatuses() {\r\n for (let i = 0; i < EnemyStatusEffects.length; i++) {\r\n EnemyStatusEffects[i].For--;\r\n if (EnemyStatusEffects[i].For < 1) {\r\n if (EnemyStatusEffects[i].Action == \"DEBUFF\") DamageWeaken = 1;\r\n EnemyStatusEffects.splice(i, 1);\r\n UpdateStatuses();\r\n return;\r\n }\r\n if (EnemyStatusEffects[i].Action == \"DMGOT\") {\r\n let dmg = 0;\r\n if (EnemyStatusEffects[i].damage < 1) dmg = Math.floor((EnemyStatusEffects[i].damage / 10) * EnemyStats[0].maxHP);\r\n console.log(dmg);\r\n EnemyStats[0].HP -= dmg;\r\n NonCombatText(EnemyStats[0].Name, \"\", `takes ${dmg} damage from ${EnemyStatusEffects[i].TurnDesc}.`, \"\", \"Enemy\", \"\");\r\n }\r\n else if (EnemyStatusEffects[i].Action == \"DEBUFF\") {\r\n DamageWeaken = EnemyStatusEffects[i].Debuff;\r\n }\r\n }\r\n }", "function updateGameInfo() {\n\t\tvar $ = jewel.dom.$;\n\t\t$(\"#game-screen .score span\")[0].innerHTML = gameState.score;\n\t\t$(\"#game-screen .level span\")[0].innerHTML = gameState.level;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plays the note corresponding to the keycode of e
function playNote(keycode) { //dont trigger if key is already pressed if (!keysPressed.includes(keycode)) { //push keycode to pressed keysPressed.push(keycode); //get respective key from keycode var key = document.querySelector(".key[data-keycode=\"" + keycode + "\"]"); //add playing transform to respective note key.classList.add("playing"); //play note poly.triggerAttack(key.dataset.note + key.dataset.octave); //display note/chord being played document.querySelector(".currentNote").innerHTML = getChord(); return key.dataset.note + key.dataset.octave; } }
[ "function play(){\n\treadAndPlayNote(readInNotes(), 0, currentInstrument);\n}", "playNote(note, octave, duration) {\n\t\tthis.synth.triggerAttackRelease(note+octave, duration);\n\t}", "function hitKey(e){\n\tswitch(e.key){\n\t\tcase 's':\n\t\t\tstartButton.click();\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tresetButton.click();\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\trecordButton.click();\n\t\t\tbreak;\t\t\n\t}\n}", "function playNotes() {\r\n\tnotes[firstNote].sound.play();\r\n\tconsole.log(notes[firstNote].sound);\r\n\tsetTimeout(function() {\r\n notes[secondNote].sound.play();\r\n console.log(notes[secondNote].sound); \r\n\t}, 700);\r\n}", "function NoteBox(key, onClick) {\n\t// Create references to box element and audio element.\n\tvar boxEl = document.getElementById(key);\n\tvar audioEl = document.getElementById(key + '-audio');\n\tif (!boxEl) throw new Error('No NoteBox element with id' + key);\n\tif (!audioEl) throw new Error('No audio element with id' + key + '-audio');\n\n\t// When enabled, will call this.play() and this.onClick() when clicked.\n\t// Otherwise, clicking has no effect.\n\tvar enabled = true;\n\t// Counter of how many play calls have been made without completing.\n\t// Ensures that consequent plays won't prematurely remove the active class.\n\tvar playing = 0;\n\n\tthis.boxEl = boxEl;\n\tthis.key = key;\n\tthis.onClick = onClick || function () {};\n\n\t// Plays the audio associated with this NoteBox\n\tthis.play = function () {\n\t\tplaying++;\n\t\t// Always play from the beginning of the file.\n\t\taudioEl.currentTime = 0;\n\t\taudioEl.play();\n\n\t\t// Set active class for NOTE_DURATION time\n\t\tboxEl.classList.add('active');\n\t\tsetTimeout(function () {\n\t\t\tplaying--\n\t\t\tif (!playing) {\n\t\t\t\tboxEl.classList.remove('active');\n\t\t\t}\n\t\t}, NOTE_DURATION)\n\t}\n\n\t// Enable this NoteBox\n\tthis.enable = function () {\n\t\tenabled = true;\n\t}\n\n\t// Disable this NoteBox\n\tthis.disable = function () {\n\t\tenabled = false;\n\t}\n\n\t// Call this NoteBox's clickHandler and play the note.\n\tthis.clickHandler = function () {\n\t\tif (!enabled) return;\n\n\t\tthis.onClick(this.key)\n\t\tthis.play()\n\n\n\n\t}.bind(this)\n\n\tboxEl.addEventListener('mousedown', this.clickHandler);\n}", "handleTuningNoteClick(i){\n let current_tuning_name = this.state.current_tuning.name;\n let audio_source = \"/audio-files/\" + current_tuning_name + \"/\" + i.toString() + \".mp3\";\n let audio = new Audio(audio_source);\n audio.play();\n }", "function play(notes, duration, gain) {\n var osc = context.createOscillator();\n\n // Change oscillator frequency to change after a specified duration\n osc.frequency.value = notes[0];\n for (var i = 1; i < notes.length; i++) {\n osc.frequency.setValueAtTime(\n notes[i],\n context.currentTime + (i * duration)\n );\n }\n\n osc.start();\n\n // Create gain node to connect the oscillator to. This is used to ramp\n // down volume and avoid the clicking noise at the end of each note\n var ctxGain = context.createGain();\n ctxGain.gain.value = gain;\n ctxGain.connect(context.destination);\n osc.connect(ctxGain);\n\n // Calculate total time (# of notes * duration) and ensure the sequence\n // is stopped properly\n var totalTime = context.currentTime + (notes.length * duration);\n ctxGain.gain.setTargetAtTime(0, totalTime, 0.015);\n osc.stop(totalTime + 0.015);\n}", "function playOnPlayersChange() {\n beepSound.play();\n}", "function ex(btn){ \n thePlayerManager.showExercise(btn);\n}", "function myLoop() {\n setTimeout(function() {\n let character = userInput.charAt(k).toLowerCase();\n //console.log('play sound: ' + character);\n newRipplePos = false;\n //switch statment decides which sound should be played\n switch (character) {\n case 'a':\n playNewSound(0);\n break;\n case 'b':\n playNewSound(1);\n break;\n case 'c':\n playNewSound(2);\n break;\n case 'd':\n playNewSound(3);\n break;\n case 'e':\n playNewSound(4);\n break;\n case 'f':\n playNewSound(5);\n break;\n case 'g':\n playNewSound(6);\n break;\n case 'h':\n playNewSound(7);\n break;\n case 'i':\n playNewSound(8);\n break;\n case 'j':\n playNewSound(9);\n break;\n case 'k':\n playNewSound(10);\n break;\n case 'l':\n playNewSound(11);\n break;\n case 'm':\n playNewSound(12);\n break;\n case 'n':\n playNewSound(13);\n break;\n case 'o':\n playNewSound(14);\n break;\n case 'p':\n playNewSound(15);\n break;\n case 'q':\n playNewSound(16);\n break;\n case 'r':\n playNewSound(17);\n break;\n case 's':\n playNewSound(18);\n break;\n case 't':\n playNewSound(19);\n break;\n case 'u':\n playNewSound(20);\n break;\n case 'v':\n playNewSound(21);\n break;\n case 'w':\n playNewSound(22);\n break;\n case 'x':\n playNewSound(23);\n break;\n case 'y':\n playNewSound(24);\n break;\n case 'z':\n playNewSound(25);\n break;\n case ' ':\n playNewSound(26);\n newRipplePos = true;\n break;\n //'$' represents the end of the user input\n case '$':\n playNewSound(27);\n newRipplePos = true;\n break;\n //the default will be called for non alphabetic characters\n default:\n playNewSound(26);\n }\n if(character !== ' ' && character !== '$' ){\n let newRipple = new ripple(xPosition, yPosition, red, green, blue, k);\n }else{\n\n let pickRandomColour = Math.floor(Math.random()*((redArray.length-1)-0+1)+0);\n red = redArray[pickRandomColour];\n green = greenArray[pickRandomColour];\n blue = blueArray[pickRandomColour];\n\n let tempXPos = (Math.floor(Math.random() * 800) - 400);\n let tempYPos = (Math.floor(Math.random() * 800) - 400);\n\n if(tempXPos <= 150 && tempXPos >= 0){\n tempXPos += 200;\n }else if(tempXPos >= -150 && tempXPos <= 0){\n tempXPos -= 200;\n }\n\n if(tempYPos <= 150 && tempYPos >= 0){\n tempYPos += 200;\n }else if(tempYPos >= -150 && tempYPos <= 0){\n tempYPos -= 200;\n }\n\n if((xPosition + tempXPos) >= window.innerWidth || (xPosition + tempXPos) < 0){\n tempXPos = tempXPos * -1;\n }\n\n if((yPosition + tempYPos) >= window.innerHeight || (yPosition + tempYPos) < 0){\n tempYPos = tempYPos * -1;\n }\n\n xPosition += tempXPos;\n yPosition += tempYPos;\n }\n \n if(red <= 200 && green <=200 && blue <=200){\n red += 20;\n green += 20;\n blue += 20;\n }\n //when the number of characters of an input becomes longer than a multiple of 7 characters\n if (k % 5 === 0 && k !== 0) {\n for (let i = 0; i < alphabet.length; ++i) {\n soundList[i].amp(0.2); //reduce the volume of the looping sounds\n }\n }\n if (k % 7 === 0 && k !== 0) {\n for (let i = 0; i < alphabet.length; ++i) {\n soundList[i].amp(0); //reduce the volume of the looping sounds\n }\n }\n k++;\n if (k < userInput.length) {\n myLoop();\n }\n } ,1500) // <- this value controls how many seconds dealy is inbetween each sound in ms\n }", "function makeSound(key){\n //this switch statement takes in a single key character as input\n //then assigns the specific listener function to the diff event keys\n switch (key) {\n case 'w':\n var tom1 = new Audio(\"sounds/tom-1.mp3\");\n tom1.play();\n break;\n\n case 'a':\n var tom2 = new Audio(\"sounds/tom-2.mp3\");\n tom2.play();\n break;\n\n case 's':\n var tom3 = new Audio(\"sounds/tom-3.mp3\");\n tom3.play();\n break;\n\n case 'd':\n var tom4 = new Audio(\"sounds/tom-4.mp3\");\n tom4.play();\n break;\n\n case 'j':\n var snare = new Audio(\"sounds/snare.mp3\");\n snare.play();\n break;\n\n case 'k':\n var crash = new Audio(\"sounds/crash.mp3\");\n crash.play();\n break;\n\n case 'l':\n var kick = new Audio(\"sounds/kick-bass.mp3\");\n kick.play();\n break;\n\n default: console.log(buttonInnerHTML); //just showing which button triggered default case\n\n }\n}", "function randomKeyboardSound(){\n let i=Math.floor(Math.random()*5)+1;\n let audiokeyboard=new Audio('assets/audio/sounds/keyb' + i + '.mp3');\n audiokeyboard.play();\n}", "function onSpeak(e) {\n // console.log(e);\n const msg = e.results[0][0].transcript;\n // console.log(msg);\n writeMessage(msg);\n checkNumber(msg);\n}", "openNote(note) {\r\n if (this.isNoteLoaded)\r\n this.closeNote();\r\n this.note = note;\r\n this.meta = note.meta;\r\n this.emit(exports.PlayerEvent.LoadedMeta);\r\n this.noteFormat = note.format;\r\n this.duration = note.duration;\r\n this.playbackTime = 0;\r\n this._frame = 0;\r\n this.isNoteLoaded = true;\r\n this.isPlaying = false;\r\n this.wasPlaying = false;\r\n this.hasPlaybackStarted = false;\r\n this.layerVisibility = note.layerVisibility;\r\n this.showThumbnail = true;\r\n this.audio.setBuffer(note.getAudioMasterPcm(), note.sampleRate);\r\n this.emit(exports.PlayerEvent.CanPlay);\r\n this.emit(exports.PlayerEvent.CanPlayThrough);\r\n this.setLoop(note.meta.loop);\r\n this.renderer.setNote(note);\r\n this.drawFrame(note.thumbFrameIndex);\r\n this.emit(exports.PlayerEvent.LoadedData);\r\n this.emit(exports.PlayerEvent.Load);\r\n this.emit(exports.PlayerEvent.Ready);\r\n if (this.autoplay)\r\n this.play();\r\n }", "function getKey(e){\r\n\tif (e == null) { // ie\r\n\t\tkeycode = event.keyCode;\r\n\t} else { // mozilla\r\n\t\tkeycode = e.which;\r\n\t}\r\n\tkey = String.fromCharCode(keycode).toLowerCase();\r\n\t\r\n\tif(key == 'x'){ hideLightbox(); }\r\n}", "function selectKey(e) {\n old_delta = delta\n delta = Number(e.target.id.split('-')[1]) // for 'key-n', extract n\n pitch = rootPitch + delta;\n [pitchName, frequency] = pitchMap.get(pitch)\n const black = [1, 3, 6, 8, 10].includes(old_delta)\n if (old_delta !== delta) {\n document.getElementById(`key-${old_delta}`).style.fill = black ? 'black' : 'white'\n document.getElementById(`key-${delta}`).style.fill = '#7aeb7a'\n }\n}", "function listenToArrow (e) {\n var allowedKeys = {\n 37: 'left',\n 38: 'up',\n 39: 'right',\n 40: 'down'\n };\n player.handleInput(allowedKeys[e.keyCode]);\n}", "onplay(song) { }", "function baby1(){\n document.getElementById(\"displayComment\").innerHTML = \"Go! change baby's diapers.\";\n baby.play();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw given content item on canvas if in (current) range
function drawContentItem(range, contentItem) { // Check if content item visible in current range if (contentItem.getBeginDate() >= range.begin || contentItem.getEndDate() <= range.end) { contentItem.draw(); } }
[ "function drawContentItems() {\r\n // Get current range\r\n var range = Canvas.Timescale.getRange();\r\n drawContentItemsLoop(_contentItems, range, true);\r\n drawContentItemsLoop(_contentItems, range, false);\r\n }", "function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}", "drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }", "function brushEvent() {\n var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); });\n var extents = actives.map(function(p) { return y[p].brush.extent(); });\n \n foreground.style(\"display\", function(d) {\n return actives.every(function(p, i) {\n return extents[i][0] <= d[p] && d[p] <= extents[i][1];\n }) ? null : \"none\";\n });\n }", "function drawTileSlot(ctx, style, tile_slot, tile_x_pos, tile_y_pos){\n ctx.fillStyle = style;\n tile_slot.drawSelf(ctx, tile_x_pos, tile_y_pos);\n}", "function drawStart(x, y, size, alpha){\r\n\tvar blue = color(\"blue\");\r\n\tblue.setAlpha(alpha);\r\n\r\n\tfill(blue);\r\n\t//rect(x+size/5, y+size/5, size*3/5);\r\n\trect(x+size/4, y+size/4, size/2);\r\n}", "function drawThingOnCanvas(context, me) {\n if(me.hidden) return;\n var leftc = me.left,\n topc = me.top;\n if(leftc > innerWidth) return;\n \n // If there's just one sprite, it's pretty simple\n // drawThingOnCanvasSingle(context, me.canvas, me, leftc, topc);\n if(me.num_sprites == 1) drawThingOnCanvasSingle(context, me.canvas, me, leftc, topc);\n // Otherwise some calculations will be needed\n else drawThingOnCanvasMultiple(context, me.canvases, me.canvas, me, leftc, topc);\n}", "drawWithinModel (element, data) {\n if (!data) return false;\n\n var x = data.x;\n var y = data.y;\n\n var pos = this.modelDivHelper.fromOffset ({\n top: y,\n left: x\n })\n\n element.moveTo ({\n top: pos.top,\n left: x\n });\n }", "contains(x, y) {\r\n if (!this.isEnabled()) return false;\r\n if (x < this.at().x || x > (this.at().x + this.width())) return false;\r\n if (y < this.at().y || y > (this.at().y + this.height())) return false;\r\n return true;\r\n }", "function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}", "function drawDigit(pos, val) {\n var a = display.children;\n switch (val) {\n case 0:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 4].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 1:\n a[pos*7].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 1].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = SHADOW_FILL;\n break;\n case 2:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 5].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 3:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 4:\n a[pos*7].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = SHADOW_FILL;\n break;\n case 5:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 6:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 7:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = SHADOW_FILL;\n break;\n case 8:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n case 9:\n a[pos*7].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 1].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 2].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 3].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 4].attributes.fill.value = SHADOW_FILL;\n a[pos*7 + 5].attributes.fill.value = NORMAL_FILL;\n a[pos*7 + 6].attributes.fill.value = NORMAL_FILL;\n break;\n default:\n break;\n }\n }", "draw () {\r\n this.icon.x = this.x\r\n this.icon.y = this.y\r\n const canvas = document.getElementById('editor')\r\n const ctx = canvas.getContext('2d')\r\n const button = new Path2D()\r\n // ctx.moveTo(this.x,this.y)\r\n button.moveTo(this.x, this.y + 10)\r\n button.lineTo(this.x, this.y + this.size - 10)\r\n button.quadraticCurveTo(this.x, this.y + this.size, this.x + 10, this.y + this.size)\r\n button.lineTo(this.x + this.size - 10, this.y + this.size)\r\n button.quadraticCurveTo(this.x + this.size, this.y + this.size, this.x + this.size, this.y + this.size - 10)\r\n button.lineTo(this.x + this.size, this.y + 10)\r\n button.quadraticCurveTo(this.x + this.size, this.y, this.x + this.size - 10, this.y)\r\n button.lineTo(this.x + 10, this.y)\r\n button.quadraticCurveTo(this.x, this.y, this.x, this.y + 10)\r\n if (this.ischosen !== true) {\r\n ctx.fillstyle = this.chosen()\r\n ctx.fill(button)\r\n ctx.save()\r\n ctx.translate(3, 3)\r\n const shadow = new Path2D(button)\r\n ctx.fillStyle = '#1d232f'\r\n ctx.fill(shadow)\r\n ctx.restore()\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n } else {\r\n ctx.save()\r\n ctx.translate(2, 2)\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n ctx.restore()\r\n }\r\n }", "touchesRange(from, to = from) {\n for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {\n let len = this.sections[i++], ins = this.sections[i++], end = pos + len;\n if (ins >= 0 && pos <= to && end >= from)\n return pos < from && end > to ? \"cover\" : true;\n pos = end;\n }\n return false;\n }", "draw() {\n //coloring the rect as green (In RGB)\n fill(0, this.colorGreen, 0)\n rect(this.x, this.y, 50, 50)\n //reset the rect once the rectangle's RGB green value\n //is 0\n if (this.colorGreen <= 0) {\n this.reset()\n }\n \n }", "function draw_timeline() {\n var size = canvas.width/dpi * 0.75;\n var start = x_center - size/2;\n var finish = x_center - size/2 + size;\n ctx.fillRect(0, canvas.height/dpi - 30, canvas.width/dpi, 6);\n ctx.globalAlpha = 1;\n // Calculate where the position marker should be on the screen\n var position = start + (((serial_date - earliest) / (latest - earliest)) * size);\n ctx.fillRect(position - 3, canvas.height/dpi - 30, 6, 6);\n}", "function drawTail(){\n\tfor(var i = 0; i < tailPos.length; i++){\n\t\tctx.fillStyle = \"#00ff00\";\n\t\tctx.fillRect(tailPos[i][0], tailPos[i][1], blockSize, blockSize);\n\t}\n\tif(tailPos.length > score){\n\t\ttailPos.shift();\n\t}\n}", "function drawSelected() {\n\tif (itemSelectedByPlayer == selectionPerson.itemf) {\n\t\tctx.drawImage(selectionPerson.itemf, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.hat) {\n\t\tctx.drawImage(selectionPerson.hat, canvas.width / 100 * 45, canvas.height/20 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shirt) {\n\t\tctx.drawImage(selectionPerson.shirt, canvas.width / 100 * 45, -canvas.height/30 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.pants) {\n\t\tctx.drawImage(selectionPerson.pants, canvas.width / 100 * 45, -canvas.height/10 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.shoes) {\n\t\tctx.drawImage(selectionPerson.shoes, canvas.width / 100 * 45, -canvas.height/6 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\telse if (itemSelectedByPlayer == selectionPerson.itemb) {\n\t\tctx.drawImage(selectionPerson.itemb, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/40, canvas.width/10, canvas.height/4);\n\t}\n\t\n//\tselectArray[0].draw();\n}", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function nodeIsInsideCanvas(nodeX, nodeY)\r\n {\r\n if (nodeX > 0 && nodeX < settings.canvasWidth &&\r\n nodeY > 0 && nodeY < settings.canvasHeight) {\r\n return true;\r\n }\r\n \r\n return false;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for a Percy token and returns it.
getToken() { let token = this.token || this.env.token; if (!token) throw new Error('Missing Percy token'); return token; }
[ "async function checkToken() {\n const tokenNameResponse = await rpcClient.invokeFunction(\n inputs.tokenScriptHash,\n \"symbol\"\n );\n\n if (tokenNameResponse.state !== \"HALT\") {\n throw new Error(\n \"Token not found! Please check the provided tokenScriptHash is correct.\"\n );\n }\n\n vars.tokenName = u.HexString.fromBase64(\n tokenNameResponse.stack[0].value\n ).toAscii();\n\n console.log(\"\\u001b[32m ✓ Token found \\u001b[0m\");\n}", "function validateToken(req, res) {\r\n var token = getToken(req);\r\n var user = users.getUserByToken(token);\r\n var isValidToken = user != undefined && user != '';\r\n console.log('[validToken] req=' + req.url);\r\n console.log('[validToken] Is Valid Token=%s User=%s', isValidToken, user);\r\n if (!isValidToken) {\r\n invalidToken(req, res);\r\n }\r\n return token;\r\n}", "isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }", "function checkToken(_token, currentUserId) {\n try {\n //ayth6) server decodes token and compares the user's userid with the token's decoded userid\n //ayth6a) if good then can continue with action\n //ayth6b) else ??? return u failed\n const token = _token;\n // next will keep any fields created\n const decodedToken = jwt.verify(token, \"my super duper secret code\");\n if (currentUserId == decodedToken.userId) {\n return true;\n } else {\n return false;\n }\n } catch (error) {\n console.log(error)\n // res.status(401).json({ message: \"You are not authenticated!\" });\n }\n}", "function tokenFunc() {\n\tlet data = {username : process.env.WORDPRESS_USER, password : process.env.WORDPRESS_PASS};\n\treturn new Promise(function(resolve, reject) {\n\t\trequest({\n\t\t\turl: process.env.WORDPRESS_ROOT_PATH + \"/wp-json/jwt-auth/v1/token\",\n\t\t\tContentType : 'application/x-www-form-urlencoded',\n\t\t\tmethod: \"POST\",\n\t\t\tform: data\n\t\t}, function(error, response, body) {\n\t\t\tif(error) {\n\t\t\t\treject(error)\n\t\t\t} else {\n\t\t\t\tlet info = body.substring(body.indexOf(\"{\"));\n\t\t\t\tinfo = JSON.parse(info);\n\t\t\t\tinfo = info.token;\n\t\t\t\tresolve(info);\n\t\t\t\t/*\n\t\t\t\trequest({\n\t\t\t\t\turl: process.env.WORDPRESS_ROOT_PATH + '/wp-json/jwt-auth/v1/token/validate',\n\t\t\t\t\tContentType: 'application/json',\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tauth: {'bearer' : info},\n\t\t\t\t\tjson: true\n\t\t\t\t}, function(error, response, body) {\n\t\t\t\t\tif(error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t\tif(body == undefined) {\n\t\t\t\t\t\treject(\"Not a real postID\");\n\t\t\t\t\t}\n\t\t\t\t\tbody = body.substring(body.indexOf(\"{\"));\n\t\t\t\t\tbody = JSON.parse(body);\n\t\t\t\t\tconsole.log(body);\n\t\t\t\t\tif(body.code == \"jwt_auth_valid_token\") {\n\t\t\t\t\t\tresolve(info);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t}\n\t\t});\n\t});\n}", "function isActiveToken () {\n const url = `${baseURl}/api/user/verifyToken`\n return localforage.getItem('token').then((jwt) => {\n return axios.post(url, { params: jwt })\n })\n}", "static get_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }", "function tokenAuthentication(token, callback) {\n if (token === CAM_MOCKS.validToken) {\n callback(true);\n } else {\n callback(false);\n }\n}", "function fetchUnboundToken(callback) {\n this.hodRequestLib.authenticateUnboundHmac(this.apiKey, function(err, response) {\n if(err) return callback(err, response);\n\n return callback(null, response.result.token);\n });\n}", "_getTokenFromRequest (req) {\n let authorization = req.get ('authorization');\n\n if (authorization) {\n let parts = authorization.split (' ');\n\n if (parts.length !== 2)\n return Promise.reject (new BadRequestError ('invalid_authorization', 'The authorization header is invalid.'));\n\n if (!BEARER_SCHEME_REGEXP.test (parts[0]))\n return Promise.reject (new BadRequestError ('invalid_scheme', 'The authorization scheme is invalid.'));\n\n return Promise.resolve (parts[1]);\n }\n else if (req.body && req.body.access_token) {\n return Promise.resolve (req.body.access_token);\n }\n else if (req.query && req.query.access_token) {\n return Promise.resolve (req.query.access_token);\n }\n else {\n return Promise.reject (new BadRequestError ('missing_token', 'The access token is missing.'));\n }\n }", "function getToken() {\n\treturn localStorage.getItem('token')\n}", "function getToken(c) {\n return c >= 128 && c < 128 + TOKENS.length ? TOKENS[c - 128] : undefined;\n}", "function hasStoredToken() {\n //const vault = await this.getVault();\n return authVault.hasStoredToken();\n }", "async function ensureToken(req, res, next) {\n try {\n var bearerHeader = req.headers['authorization']\n if (typeof bearerHeader == 'undefined') {\n console.log('undefined, gak ada token');\n return res.status(403).send({\n 'message': 'token not provided'\n })\n }\n var bearerToken = bearerHeader.split(' ')\n var tokenBracket = bearerToken[0]\n var tokenProvided = bearerToken[1]\n\n if (tokenBracket !== 'bearer')\n return res.status(403).send({'message': 'worng format header Authorization'})\n\n const user = await jwt.verify(tokenProvided, process.env.SECRET_KEY)\n\n if(user.isActive==false)\n return res.status(403).send({\"message\":\"need activation user.\"})\n \n req.body.user = user\n next()\n } catch (error) {\n console.log(error);\n return res.status(403).send({\n 'message': 'token is not valid'\n })\n }\n}", "function gongGetCurrentToken(gong) {\n if (gong == null || !gong.isActive()) return \"Gong Applet is not ready.\";\n\n if (useXML) {\n var request = \"<GetCurrentTokenRequest xmlns=\\\"\" + GASI_NAMESPACE_URI + \"\\\"/>\";\n if (gong != null) {\n var response = gong.sendGongRequest(request);\n if (isFault(response)) return getFaultReason(response);\n return getParameter(response, \"Token\");\n }\n return null;\n }\n else if (gong != null) return gong.sendGongRequest(\"GetCurrentToken\", \"\");\n}", "function getToken() {\n return localStorage.getItem('token');\n}", "function getTokenInCookie(){\n let token = document.cookie.slice(document.cookie.lastIndexOf(\"=\")+1);\n return token;\n}", "function detectEmailConfirmationToken() {\n try {\n // split the hash where it detects `confirmation_token=`. The string which proceeds is the part which we want.\n const token = decodeURIComponent(document.location.hash).split(\n \"confirmation_token=\"\n )[1];\n return token;\n } catch (error) {\n console.error(\n \"Something went wrong when trying to extract email confirmation token\",\n error\n );\n return null;\n }\n}", "function GetDeviceToken()\n{\n\t// Device token is already initialized with null, so, it will return null if not know\n\treturn deviceToken;\n}", "async function validateReCaptchaToken(token) {\n if (process.env.NODE_ENV === 'test') {\n return true;\n }\n let googleUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.GOOGLE_CAPTCHA_KEY}&response=${token}`;\n return (async () => {\n try {\n const res = await superagent.post(googleUrl);\n console.log(res.body);\n return res.body.success;\n } catch (err) {\n return false;\n }\n })();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update build.xcconfig with Branch's Header Paths
function updateHeaderPaths(config) { config = config.split("\n") .map(function (line) { if (line.indexOf("HEADER_SEARCH_PATHS") > -1 && line.indexOf("Branch-SDK") === -1) { line += ' "${PODS_ROOT}/Branch/Branch-SDK/Branch-SDK" "${PODS_ROOT}/Branch/Branch-SDK/Branch-SDK/Networking" "${PODS_ROOT}/Branch/Branch-SDK/Branch-SDK/Networking/Requests"'; } return line; }); return config.join("\n"); }
[ "function updatePlatformConfig(platform) {\n var configData = parseConfigXml(platform),\n platformPath = path.join(rootdir, 'platforms', platform);\n\n _.each(configData, function (configItems, targetFileName) {\n var targetFilePath;\n if (platform === 'ios') {\n if (targetFileName.indexOf(\"Info.plist\") > -1) {\n targetFileName = projectName + '-Info.plist';\n targetFilePath = path.join(platformPath, projectName, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPlist(targetFilePath, configItems);\n }else if (targetFileName === \"project.pbxproj\") {\n targetFilePath = path.join(platformPath, projectName + '.xcodeproj', targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPbxProj(targetFilePath, configItems);\n updateXCConfigs(configItems, platformPath);\n }\n\n } else if (platform === 'android' && targetFileName === 'AndroidManifest.xml') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateAndroidManifest(targetFilePath, configItems);\n } else if (platform === 'wp8') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateWp8Manifest(targetFilePath, configItems);\n }\n });\n }", "function parseiOSPreferences(preferences, configData){\n _.each(preferences, function (preference) {\n if(preference.attrib.name.match(new RegExp(\"^ios-\"))){\n var parts = preference.attrib.name.split(\"-\"),\n target = \"project.pbxproj\",\n prefData = {\n type: parts[1],\n name: parts[2],\n value: preference.attrib.value\n };\n if(preference.attrib.buildType){\n prefData[\"buildType\"] = preference.attrib.buildType;\n }\n if(preference.attrib.quote){\n prefData[\"quote\"] = preference.attrib.quote;\n }\n\n prefData[\"xcconfigEnforce\"] = preference.attrib.xcconfigEnforce ? preference.attrib.xcconfigEnforce : null;\n\n if(!configData[target]) {\n configData[target] = [];\n }\n configData[target].push(prefData);\n }\n });\n }", "function setBranchComplete(branchInfo) {\n\tbranchInfo.isComplete = true;\n}", "async createOrUpdateBranchFromFileMap(fileMap, config) {\n const baseBranchRef = `heads/${config.baseBranchName}`;\n const branchRef = `heads/${config.branchName}`;\n const baseSha = await this.getBaseShaForNewBranch(baseBranchRef);\n const tree = await this.createTree(fileMap, baseSha);\n const commit = await this.api.git.createCommit({\n ...this.userInfo,\n message: config.message,\n tree: tree.sha,\n parents: [baseSha],\n });\n return this.updateOrCreateReference(commit.data.sha, branchRef);\n }", "function updateHeaderHeight() {\n\n // Set the current header height (window height sans menu).\n _.headerHeight = _.header.height() - headerMenuHeight;\n }", "update() {\r\n this.updateHeader();\r\n }", "function preBuild()\n{\n\tconsole.log(`Built bundle will be located at ${chalk.blue(RELEASE_PATH)}\\n`)\n\tif (fs.existsSync(RELEASE_PATH))\n\t{\n\t\tconsole.log(`${chalk.green('Clearing destination folder for built bundle')} 🗑\\n`);\n\t\trimraf.sync(RELEASE_PATH);\n\t}\n\tconsole.log(`${chalk.green('Creating destination folder for built bundle')}\\n`);\n\tmkdirp(RELEASE_PATH);\n\n\n\tconsole.log(`${chalk.yellow('Removing')} ${chalk.bgRed('bld')} folder and ${chalk.bgRed('dist')} folder... 🔥\\n`)\n\t// clean up `bld` folder\n\trimraf.sync(BUILD_PATH);\n\trimraf.sync(DIST_PATH);\n\n\tconsole.log(`Compiling the Electron project\\n`);\n\tcp.execSync('ttsc');\n\tcp.execSync(`cp ${ROOT_PATH}/package.json ${BUILD_PATH}/package.json`)\n}", "function applyCocoaPodsModifications(contents) {\n // Ensure installer blocks exist\n let src = addInstallerBlock(contents, 'pre');\n // src = addInstallerBlock(src, \"post\");\n src = addMapboxInstallerBlock(src, 'pre');\n // src = addMapboxInstallerBlock(src, \"post\");\n return src;\n}", "function xcodeproj() {\n\tconst pbxprojChanged = danger.git.modified_files.find(filepath =>\n\t\tfilepath.endsWith('project.pbxproj'),\n\t)\n\n\tif (!pbxprojChanged) {\n\t\treturn\n\t}\n\n\tmarkdown(\n\t\t'The Xcode project file changed. Maintainers, double-check the changes!',\n\t)\n}", "updateConfig(config) {\n\n if (!config) return;\n\n // Set sPath\n if (config.component) {\n this._config.component = config.component;\n this._config.sPath = SUtils.buildSPath({\n component: config.component\n });\n }\n\n // Make full path\n if (this._S.config.projectPath && this._config.sPath) {\n let parse = SUtils.parseSPath(this._config.sPath);\n this._config.fullPath = path.join(this._S.config.projectPath, parse.component);\n }\n }", "enterPreprocessorBinary(ctx) {\n\t}", "function updateAllLatest() {\n\tlet r = run('git submodule update -f', __dirname).stdout;\n\tr = r.split('\\n');\n\tr.pop();\n\tlet o = {};\n\tfor (let e of r) {\n\t\tlet nameR = /(?<=projects\\/)([A-Za-z0-9]+)(?=\\/)/,\n\t\t\thashR = /(?<=out ')([A-Za-z0-9]+)(?=')/,\n\t\t\tname = e.match(nameR)[0],\n\t\t\thash = e.match(hashR)[0];\n\t\tif (name && hash)\n\t\t\to[name] = hash;\n\t}\n\tresolve(o);\n}", "cleanUpSDKFiles() {\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_D,\n Constants.AVAILABLE_VHOSTS,\n \"default.vhost\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_D,\n Constants.ENABLED_VHOSTS,\n \"default.vhost\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.AVAILABLE_FARMS,\n \"default.farm\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.ENABLED_FARMS,\n \"default.farm\"\n )\n );\n }", "async function prepareTarget() {\n if( !incremental ) {\n await rmRF( target, ['.git','_locomote']);\n }\n await ensureDir( target );\n }", "appendCurrentHeader(header) {\n this.currentSectionContent += header + \"\\n\";\n }", "function getConfigFilesByTargetAndParent(platform) {\n var configFileData = configXml.findall('platform[@name=\\'' + platform + '\\']/config-file');\n var result = keyBy(configFileData, function(item) {\n var parent = item.attrib.parent,\n add = item.attrib.add;\n //if parent attribute is undefined /* or */, set parent to top level elementree selector\n if(!parent || parent === '/*' || parent === '*/') {\n parent = './';\n }\n return item.attrib.target + '|' + parent + '|' + add;\n });\n return result;\n }", "_applyConfigStyling() {\n if (this.backgroundColor) {\n const darkerColor = new ColorManipulator().shade(-0.55, this.backgroundColor);\n this.headerEl.style['background-color'] = this.backgroundColor; /* For browsers that do not support gradients */\n this.headerEl.style['background-image'] = `linear-gradient(${this.backgroundColor}, ${darkerColor})`;\n }\n\n if (this.foregroundColor) {\n this.headerEl.style.color = this.foregroundColor;\n }\n }", "function copyTargets(buildInfo) {\n buildInfo.builtTargets.forEach(function (target) {\n var isMerged = target.match(/merged\\./),\n isBeauty = target.match(/beauty\\.html$/),\n basename = path.basename(target),\n src = path.join(rootDir, target),\n dst = \"\",\n sub = basename.split(\".\"),\n replaceFiles = [],\n version = (new Date()).getTime();\n \n if(!isMerged && !isBeauty) {\n return true;\n }\n \n if(isBeauty) {\n basename = basename.replace('.beauty',''); \n replaceFiles.push(path.join(rootDir, 'dist', basename));\n }\n \n dst = path.join(rootDir, 'dist', basename);\n \n if(isMerged) {\n basename = basename.replace('.dist','');\n subDir = sub[sub.length-1];\n dst = path.join(rootDir, 'dist/' + subDir, basename);\n \n if(basename.match(/merged\\..*?css$/)) {\n replaceFiles.push(dst);\n }\n }\n\n fse.copySync(src, dst);\n \n // изменение путей к стилям и скриптам\n replaceFiles.forEach(function( file ) {\n fs.readFile(file, function(err, content){\n if(!err) {\n content = content.toString();\n content = content.split(\"../merged/merged.css\").join(\"css/merged.css?v\"+version)\n .split(\"../merged/merged.js\").join(\"js/merged.js?v\"+version) \n .split(\"../../images/\").join(\"img/\")\n .split(\"../../dist/\").join(\"../\")\n .split(\"../../css/\").join(\"css/\")\n .split(\"../../js/\").join(\"js/\");\n \n fs.open(file, \"w\", 0644, function(err, handle) {\n if(!err) {\n fs.write(handle, content);\n }\n })\n }\n });\n });\n \n // копирование шрифтов и js библиотек\n var copyFiles = [\n {\n src : path.join(rootDir, 'fonts'),\n dst : path.join(rootDir, 'dist/fonts')\n },\n {\n src : path.join(rootDir, 'css/fonts.css'),\n dst : path.join(rootDir, 'dist/css/fonts.css')\n },\n {\n src : path.join(rootDir, 'js/libs'),\n dst : path.join(rootDir, 'dist/js/libs')\n },\n {\n src : path.join(rootDir, 'images'),\n dst : path.join(rootDir, 'dist/img')\n }\n ];\n \n copyFiles.forEach( function( copy ){\n fse.copySync(copy.src, copy.dst);\n });\n \n });\n }", "SetCompatibleWithPlatform() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserpackage_obj_spec.
visitPackage_obj_spec(ctx) { return this.visitChildren(ctx); }
[ "visitPackage_obj_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitCreate_package_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitCreate_package(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPackage_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDrop_package(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitProcedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitJava_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitOracle_namespace(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitOpen_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubprogram_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitProcedure_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSupplemental_plsql_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitType_procedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSqlj_object_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXmlschema_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDatafile_specification(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitImport_stmt(ctx) {\r\n console.log(\"visitImport_stmt\");\r\n if (ctx.import_name() !== null) {\r\n return this.visit(ctx.import_name());\r\n } else {\r\n return this.visit(ctx.import_from());\r\n }\r\n }", "function getPackages(cs_Children)\n{\n \n\tvar nPackages = packages.length;\n\tif (nPackages)\n\t{\n\t\tfor (var p=0; p<nPackages; p++)\n\t\t{\n\t\t\tpackages.pop();\n\t\t}\n\t}\n\t\n\tvar start = new Date();\n\n\tvar roots = new Array();\n\tvar cfctreeDOM = getcfctreeDOM(bForceRefresh);\n\n\tif ((cfctreeDOM != null) && (cfctreeDOM.hasChildNodes()))\n\t{\n\t\tif (!parseCFCtree(cfctreeDOM, roots))\n\t\t{\n\t\t\tif (bDoingManualRefresh)\n\t\t\t{\n\t\t\t\t// If we got at least one root then we know that the server is running\n\t\t\t\t// and that there must have been some sort of very specific parsing\n\t\t\t\t// problem or failure within Neo. Go ahead and show the data for\n\t\t\t\t// the roots we got but warn the user that there was a significant\n\t\t\t\t// problem.\n\n\t\t\t\tif (roots.length > 0)\n\t\t\t\t{\n\t\t\t\t\talert(MM.MSG_CFC_PartiallyParsedTree);\n\t\t\t\t}\n\n\t\t\t\t// If we failed to get even a single root then we either suffered a\n\t\t\t\t// massive failure (like the server isn't running) or we encountered\n\t\t\t\t// significant problems parsing the first root we found. In either case\n\t\t\t\t// we can't show anything in the tree. Tell the user why the tree is\n\t\t\t\t// going to be empty.\n\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talert(MM.MSG_CFC_FailedToParseTree);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (bDoingManualRefresh)\n\t{\n\t\talert(MM.MSG_CFC_FailedToParseTree);\n\t}\n\t\n\tvar end = new Date();\n\t//alert('parse DOM in: ' + (end - start) + ' ms');\n\n\tif (roots.length)\n\t{\n\t\tvar els2 = 'N/A';\n\t\tvar rootsToExclude = new Array();\n\t\tif( sitePrefix == FILTERING_SITE_ROOT ) {\n\t\t\tparseComponentRoots(getComponentRootsDOM(), rootsToExclude);\n\t\t}\n\t\telse if (sitePrefix != '') {\n\t\t\tels2 = getLocalPackages();\n\t\t}\n\n\t\tfor (var r=0; r<roots.length; r++)\n\t\t{\n\t\t\tvar aRoot = roots[r];\n\t\t\t\n\t\t\tvar exlcudeRoot = false;\n\t\t\t\n\t\t\t//check to see if this root is one we want to exlcude. We exlcude any root that has a prefix. The\n\t\t\t//prefix means it's any additional direcotry added in the CF admin page and not directly related to this site\n\t\t\t//and since we're filtering the site root, we want the cfcs that live in the root (have no prefix)\n\t\t\tfor ( var i = 0 ; i < rootsToExclude.length ; i++ )\n\t\t\t{\n\t\t\t\tvar anExcludedRoot = rootsToExclude[i];\n\t\t\t\tif( ( anExcludedRoot.prefix != '' ) &&\n\t\t\t\t\t( aRoot.physicalPath.indexOf(anExcludedRoot.physicalPath) == 0 ) )\n\t\t\t\t{\n\t\t\t\t\texlcudeRoot = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif( exlcudeRoot ){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif (aRoot.packages.length)\n\t\t\t{\n\t\t\t\tfor (var p=0; p<aRoot.packages.length; p++)\n\t\t\t\t{\n\t\t\t\t\tvar aPackage = aRoot.packages[p];\n\n\t\t\t\t\t// Save the package information so we can easily access it\n\t\t\t\t\t// from any node in the tree.\n\t\t\t\t\tvar tmp = aPackage.name.toString().toLowerCase();\n\n\t\t\t\t\tvar shThis = false;\n\t\t\t\t\tif (sitePrefix == '' || sitePrefix == FILTERING_SITE_ROOT) {\n\t\t\t\t\t\tshThis = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (els2 == 'N/A') {\n//\t\t\t\t\t\t\tif (tmp.indexOf(sitePrefix) == 0) {\n\t\t\t\t\t\t\tif ((tmp == sitePrefix) || (tmp.indexOf(sitePrefix + '.') == 0)) {\n\t\t\t\t\t\t\t\tshThis = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (els2[tmp] == 1) {\n\t\t\t\t\t\t\t\tshThis = true;\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\t\n\t\t\t\t\tif (shThis) {\n\t\t\t\t\t\tpackages.push(aPackage);\n\t\t\t\t\t\tvar packageCompInfo = new ComponentRec((aPackage.name == \"\") ? MM.MSG_CFC_UnnamedPackage : aPackage.name, PACKAGE_FILENAME, (aPackage.CFCs.length > 0), false, \"\");\n\t\t\t\t\t\tpackageCompInfo.objectType = PACKAGE_OBJECT_TYPE;\n\t\t\t\t\t\tpackageCompInfo.aPackage = aPackage;\n\t\t\t\t\t\tpackageCompInfo.detailsText = \"\";\n\t\t\t\t\t\tcs_Children.push(packageCompInfo);\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" ] ] } }
Function to generate a unique file name from the user user id and time of upload
function generateUniqueFileName(user, filename) { var fileExtension = getFileExtension(filename); var currentTime = new Date().toISOString().replace(/\./g, '-').replace(/\:/g, '-'); var tempFile = user + currentTime + fileExtension; console.log(tempFile); return tempFile; }
[ "function generateFileName(filetype) {\n return 'msfu_' + (+new Date()) + Math.floor((Math.random() * 100) + 1) + ':' + filetype;\n\n }", "generateRandomFilename() {\r\n // create pseudo random bytes\r\n const bytes = crypto.pseudoRandomBytes(32);\r\n\r\n // create the md5 hash of the random bytes\r\n const checksum = crypto.createHash(\"MD5\").update(bytes).digest(\"hex\");\r\n\r\n // return as filename the hash with the output extension\r\n return `${checksum}.${this.options.output}`;\r\n }", "generatePrivateId()\n\t{\n\t\tvar nanotime = process.hrtime();\n\t\treturn String(nanotime[0]) + nanotime[1] + '-' + this.name;\n\t}", "function generateUID() {\n return String(~~(Math.random()*Math.pow(10,8)))\n}", "function makeFilename() {\n let result = currentFrameNumber.toString(10);\n while (result.length < recorder.numberOfDigits) {\n result = '0' + result;\n }\n result = recorder.movieName + result;\n return result;\n}", "function hashName(mediaFile) {\n return mediaFile.md5 + path.extname(mediaFile.name);\n}", "function makeTuid() {\n return crypto.randomBytes(16).toString('hex')\n}", "function generate_unique_number(){\n var current_date = (new Date()).valueOf().toString();\n var random = Math.random().toString();\n return generate_hash(current_date + random);\n}", "function uuid() {\n // get sixteen unsigned 8 bit random values\n const u = crypto.getRandomValues(new Uint8Array(16))\n\n // set the version bit to v4\n u[6] = (u[6] & 0x0f) | 0x40\n\n // set the variant bit to \"don't care\" (yes, the RFC\n // calls it that)\n u[8] = (u[8] & 0xbf) | 0x80\n\n // hex encode them and add the dashes\n let uid = ''\n uid += u[0].toString(16)\n uid += u[1].toString(16)\n uid += u[2].toString(16)\n uid += u[3].toString(16)\n uid += '-'\n\n uid += u[4].toString(16)\n uid += u[5].toString(16)\n uid += '-'\n\n uid += u[6].toString(16)\n uid += u[7].toString(16)\n uid += '-'\n\n uid += u[8].toString(16)\n uid += u[9].toString(16)\n uid += '-'\n\n uid += u[10].toString(16)\n uid += u[11].toString(16)\n uid += u[12].toString(16)\n uid += u[13].toString(16)\n uid += u[14].toString(16)\n uid += u[15].toString(16)\n\n return uid\n}", "function shortId() {\n\treturn crypto\n\t\t.randomBytes(5)\n\t\t.toString(\"base64\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/=+$/, \"\");\n}", "function generateTemporaryInstallID(aFile) {\n const hasher = CryptoHash(\"sha1\");\n const data = new TextEncoder().encode(aFile.path);\n // Make it so this ID cannot be guessed.\n const sess = TEMP_INSTALL_ID_GEN_SESSION;\n hasher.update(sess, sess.length);\n hasher.update(data, data.length);\n let id = `${getHashStringForCrypto(hasher)}${TEMPORARY_ADDON_SUFFIX}`;\n logger.info(`Generated temp id ${id} (${sess.join(\"\")}) for ${aFile.path}`);\n return id;\n}", "function generateMongoObjectId() {\n var timestamp = (new Date().getTime() / 1000 | 0).toString(16);\n return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {\n return (Math.random() * 16 | 0).toString(16);\n }).toLowerCase();\n }", "function generateUID(length) {\n var rtn = '';\n for (let i = 0; i < UID_LENGTH; i++) {\n rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET.length));\n }\n return rtn;\n}", "async function createPathWithTimeStamp() {\n return './outputs/video' + new Date().getTime() + '.mp4'\n}", "function uniqueString() {\n return \"&sUnique=\" + new Date().getTime();\n}", "function generateUuid() {\n let uuid = token();\n return uuid;\n}", "function genRouletteTimestampName() {\n return 'roulette::last';\n}", "function hash_code ( display_name ) {\n\n\tvar d = new Date().getTime();\n\td += display_name;\n\n\tif (window.performance && typeof window.performance.now === \"function\") {\n\t\td += performance.now(); //use high-precision timer if available\n\t}\n\n\tvar hash = 0, i, chr, len;\n\tlen = d.length;\n\n\tif ( len === 0 )\n\t \treturn hash;\n\n\tfor( i = 0; i < len; i++ ) {\n\n\t\tchr = d.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + chr;\n\t\thash |= 0; // Convert to 32bit integer\n\n\t}\n\n\tconsole.log ('Anonymous user id: '+ hash );\n\n\treturn hash;\n}", "generateId() {\n const newId = `dirId-${Directory.nextId}`;\n Directory.nextId++;\n return newId;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
persistConfig writes config to the environment. config changes must always be persisted to the environment because automation api introduces new program lifetime semantics where program lifetime != module lifetime.
function persistConfig(config, secretKeys) { const store = state_1.getStore(); const serializedConfig = JSON.stringify(config); const serializedSecretKeys = Array.isArray(secretKeys) ? JSON.stringify(secretKeys) : "[]"; store.config[exports.configEnvKey] = serializedConfig; store.config[exports.configSecretKeysEnvKey] = serializedSecretKeys; }
[ "function save() {\n\twriteFile(config, CONFIG_NAME);\n\tglobal.store.dispatch({\n\t\ttype: StateActions.UPDATE_CONFIGURATION,\n\t\tpayload: {\n\t\t\t...config\n\t\t}\n\t})\n}", "function saveConfiguration () {\n\tJSON.stringify(config).to(SITE_DIR+'config.json');\n}", "function writeConfig () {\n self._repo.config.set(config, (err) => {\n if (err) return callback(err)\n\n addDefaultAssets()\n })\n }", "saveConfig() {\n localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.config));\n }", "saveGameConfig() {\n this.store.set('gameConfig', this.gameConfig);\n }", "function reloadConfig() {\n saveConfig(true);\n if (typeof localStorage !== \"undefined\") {\n _drawMode.selectedObject = undefined;\n config = localStorage.getItem(\"config\");\n loadConfig(new Blob([config], {type: \"text/plain;charset=utf-8\"}));\n }\n}", "function saveConfiguration() {\n console.log(\"saveConfiguration\");\n // save the current configuration in the \"chair\" object\n const chosenColors = view.getChairColors();\n model.updateChairObject(chosenColors);\n // update local storage\n model.updateLocalStarage(\"chair\", model.chair);\n console.log(model.chair);\n}", "function saveConfigXML(xml){\n\tsessionStorage.setItem(\"configXML\", new XMLSerializer().serializeToString( xml ));\n}", "async writeConfigFile (path: string, config: PijinConfig = defaultConfig) {\n const nextConfig = Object.assign({}, defaultConfig, config)\n\n const configFileContent = JSON.stringify(\n nextConfig,\n null,\n 2\n )\n\n await this.fs.writeFile(path, configFileContent)\n\n return nextConfig\n }", "async writeCoreConfig() {\n let c = this.get(null, null, true);\n let copy = JSON.parse(JSON.stringify(c));\n delete(copy.db);\n delete(copy.fs);\n let db = await Class.i('awy_core_model_db');\n await db.rput(copy, 'config');\n }", "static persist() {\n let questionsJson = JSON.stringify(questions);\n fs.writeFileSync(storagePath, questionsJson, 'utf-8');\n }", "function setValuesInProjectConfig(config) {\n if (!config.projectConfig) { return }\n // for each entry, the 'setValueInTag'-method is called until the tag was found once\n let toDoList = [\n {tag: \"<widget \", pre: \"id=\\\"\", value: config.projectConfig.id, post: \"\\\"\", done: false},\n {tag: \"<name>\", pre: \"<name>\", value: config.projectConfig.name, post: \"</name>\", done: false},\n {tag: \"<description>\", pre: \"<description>\", value: config.projectConfig.description, post: \"</description>\", done: false}\n ];\n\n // iterate trough lines of 'config.xml' until all tags have ben found\n let lines = FS.readFileSync(\"config.xml\", \"utf8\").split(\"\\n\");\n let done = false;\n for(let i = 0; (i < lines.length) && !done; i++) {\n done = true;\n toDoList.forEach(e => {\n [lines[i], e.done] = (e.done) ? [lines[i], e.done] : setValueInTag(lines[i], e.tag, e.pre, e.value, e.post);\n done &= e.done;\n });\n }\n\n if(!done) {\n let notDone = \"\";\n toDoList.forEach(function(e) {\n notDone += (e.done) ? \"\" : `${e.tag} `;\n });\n throw new Error(`(set_brand.js) unable to set the value(s) for the following tag(s) [ ${notDone}] in 'config.xml'`);\n }\n\n FS.writeFileSync(\"config.xml\", lines.join(\"\\n\"));\n}", "function confirmConfig(){\n $scope.showConfig = false;\n $scope.parkingLotConfig = {\n 'totalParkingLots' : $scope.totalParkingLots,\n 'priceFirstHour' : $scope.priceFirstHour,\n 'pricePerHour' : $scope.pricePerHour,\n 'parkingLotName' : $scope.parkingLotName\n };\n \n localStorageService.add('0', $scope.parkingLotConfig);\n\n updateParkingLotSpaces();\n\n }", "function updateSettings(event, payload) {\n fs.writeFile(configPath, JSON.stringify(payload, null, 2), function (err) {\n if (err) return console.log(err);\n event.sender.send('config', payload)\n });\n}", "updateConfig(application) {\n const updatedConfig = { };\n const configs = Array.prototype.slice.call(arguments, 1);\n\n return this.getConfig(application).then(existingConfig => {\n ld.assign.apply(this, [updatedConfig, existingConfig].concat(configs));\n return this.setConfig(application, updatedConfig);\n }).then(() => {\n return this.reloadApp(application);\n });\n }", "function saveConfigtoDBTestbed(confName){\n\tif(globalDeviceType==\"Mobile\"){\n\t\tloading(\"show\");\n\t}\n//\tMainFlag = 0;\n\t//FileType = \"Dynamic\";\n\tfor(var a=0; a< globalMAINCONFIG.length;a++){\n\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Flag = 0;\n\t\tif(globalMAINCONFIG[a].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].FileType = $('#saveConfFileTypeDBType > option:selected').html().toString();\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Name = confName;\n\t\t}\n\t}\n\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\", \"JSON\"),\n\t\tdata : {\n\t\t\t\"action\": \"savetopology\",\n\t\t\t\"query\": qry\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tvar dat=data.replace(/'/g,'\"');\n\t\t\tvar data = $.parseJSON(dat);\n\t\t\tvar result = data.RESULT[0].Result;\n\t\t\tif(result == 1){\n\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t}\n\t\t\t\talerts(\"Configuration saved to the database.\", \"todo\", \"graph\");\n\t\t\t\tMainFlag =1;\n\t\t\t\tFileType =\"\";\n\t\t\t\tvar todo = \"if(globalDeviceType!='Mobile'){\";\n\t\t\t\ttodo +=\t\"$('#deviceMenuPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"$('#configPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"}else{\";\n\t\t\t\ttodo +=\t\"$('#saveConfig').dialog('destroy');\";\n\t\t\t\ttodo += \"}\";\n\t\t\t}else{\n\t\t\t\talerts(\"Something went wrong, configuration could not be save.\");\n\t\t\t}\n\t\t}\n\t});\n}", "function initConfig (event) {\n let config = null;\n\n if (!fs.existsSync(configPath)) {\n const fd = fs.openSync(configPath, 'w');\n\n const initialConfig = {\n apiServer: '',\n operator: '',\n notificationsEnabled: true,\n };\n\n fs.writeSync(fd, JSON.stringify(initialConfig, null, ' '), 0, 'utf8');\n fs.closeSync(fd);\n }\n\n config = JSON.parse(fs.readFileSync(configPath).toString());\n event.sender.send('config', config);\n}", "function create(cb) {\n const configPath = path.join(projectPath, configName)\n\n checkForConfigFile((err, exists) => {\n if (exists) {\n cb()\n } else if (err) {\n cb({message: \"Error creating project config\", data: err})\n } else {\n utils.writeJsonFile(configPath, defaultConfigData, err => {\n if (err) {\n cb({message: 'Error creating project config', data: err})\n } else {\n cb()\n }\n })\n }\n })\n }", "persistStore () {\n const { driver } = this.options;\n\n this.prevStore = JSON.parse(driver.getItem(this.key)) || {};\n driver.setItem(this.key, JSON.stringify(this.store));\n\n this.notifySubscribers();\n this.notifyListeners();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to query product skus from the product style service
function getProductSkus(productIdVar){ var res = request('GET', 'http://oldnavy.gap.com/resources/productStyle/v1/' + productIdVar + '?redirect=true&isActive=true'); var availableSizeCodes = {}; var bodyjson = JSON.parse(res.getBody()); var variants = flattenVariantResponse(bodyjson); // Loop on product response to get the size code from SKUs for(var variant of variants) { for(var stylecolor of variant['productStyleColors']){ if(stylecolor['isInStock'] == 'true'){ for(var sku of stylecolor['productStyleColorSkus']){ if(sku['inventoryStatusId'] == '0'){ var sizeCode = sku['businessCatalogItemId'].substring(9,13); availableSizeCodes[sizeCode] = sizeCode; } } } } } return availableSizeCodes; }
[ "function show_supplier_selector(product_id)\n{\n\n\n}", "function getAllFashionProductsByProvider(req,res){\n var query = {provider:req.query.provider};\n baseRequest.getProductByCategory(req,res,query,Fashion)\n}", "function pricingAPIs(searchString, apiDataWalmart, apiDataAmazon) {\n\t\tamazon.getItems(searchString, apiDataAmazon);\n\t\twalmart.getItems(searchString, apiDataWalmart);\n\t}", "function trkDisplayProducts() {\n for(i = 0; i < trkProducts.length; i++) {\n if(trkProducts[i].attributes.value.value == trkDropdownValue) {\n trkProducts[i].style.display = \"flex\";\n } else if(trkProducts[i].classList.contains(\"All\") && trkDropdownValue == \"All\") {\n trkProducts[i].style.display = \"flex\";\n } else {\n trkProducts[i].style.display = \"none\";\n }\n }\n}", "isItemAvailableOnFavoriteStore (skuId, quantity) {\n this.store.dispatch(getSetSuggestedStoresActn(EMPTY_ARRAY)); // clear previous search results\n let storeState = this.store.getState();\n let preferredStore = storesStoreView.getDefaultStore(storeState);\n let {coordinates} = preferredStore.basicInfo;\n let currentCountry = sitesAndCountriesStoreView.getCurrentCountry(storeState);\n\n return this.tcpStoresAbstractor.getStoresPlusInventorybyLatLng(skuId, quantity, 25, coordinates.lat, coordinates.long, currentCountry).then((searchResults) => {\n let store = searchResults.find((storeDetails) => storeDetails.basicInfo.id === preferredStore.basicInfo.id);\n return store && store.productAvailability.status !== BOPIS_ITEM_AVAILABILITY.UNAVAILABLE;\n }).catch(() => {\n // assume not available\n return false;\n });\n }", "async function _list_variants (products, ids, sizes={}, email=false, only_soh=true ){\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`ids parameter not usable`);\n }\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`products parameter not usable`);\n }\n\n let ret = await tradegecko.tradegecko_get_product_variants({\"ids\": ids});\n\n const available = [];\n\n /*\n * If only_soh is true then we only want to return stock on hand.\n */\n \n if (only_soh){\n for (let i = 0; i < ret.length; i++){\n const soh = ret[i].stock_on_hand - ret[i].committed_stock;\n if (soh > 0){\n available.push(ret[i]);\n }\n }\n\n ret = available;\n }\n \n /*\n * If email parameter is not false, then filter out variants already sent to \n * customer associated with this email\n */\n \n if (email){\n ret = await _filter_out_already_shipped_variants(products, ret, email);\n }\n \n /*\n * Filter out all variants that don't match the received sixe values\n */\n \n ret = await _filter_for_sizes(ret, sizes);\n \n return ret;\n}", "static async list(req, res) {\n const variations = _.filter(\n req.product.variations,\n variation => !variation.deleted,\n );\n\n return res.products_with_additional_prices(variations);\n }", "selectStyleThumbnail(style) {\n this.setState({ selectedStyle: style }, () => {\n this.checkOutOfStock();\n this.props.changeSelectedStyle(this.state.selectedStyle);\n // need to check quantity too once we change a style\n });\n }", "function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }", "async showOneProduct (req, res) {\n\t\tlet {sku} = req.params;\n\t\ttry {\n\t\t\tconst oneProduct = await products.findOne({SKU:sku});\n\t\t\tres.send(oneProduct);\n\t\t}\n\t\tcatch(e){\n\t\t\tres.send({e});\n\t\t}\n\t}", "function tShirtColor() {\n if (designSelector.value === \"Select Theme\") {\n colorListDiv.style.visibility = \"hidden\";\n } else if (designSelector.value === \"js puns\") {\n showColorOptions(puns);\n } else if (designSelector.value === \"heart js\") {\n showColorOptions(heart);\n }\n}", "function viewProducts(){\n\tconnection.query('SELECT * FROM products', function(err,res){\n\t\tif (err) throw err;\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tconsole.log('ID: ' + res[i].id + '| sku: ' + res[i].sku +' | name: ' + res[i].product_name + \" | Price: $\" + res[i].price + \" | Quantity: \" + res[i].stock_quantity);\n\t\t};\n\t\tconsole.log('\\n');\n\t\tmanagerView();\n\t});\n}", "function viewProductCatalogue(){\n let sqlQuery = \"SELECT * FROM product\";\n connection.query(sqlQuery, function (err, response) {\n if (err) {\n console.log(\"Error displaying products: \" + err);\n connection.end();\n } else {\n console.log(\"------------------------------\");\n // A console log to verify that the createChoicesArray returns the appropriate values.\n // console.log(createChoicesArray(response));\n // Iterate over the response to draw the table that will be displayed to the user.\n for (var i = 0; i < response.length; i++)\n console.log(response[i].product_id + \" : \" + response[i].product_name + \" : \" + response[i].department_id + \" : \" + response[i].stock_quantity + \" : \" + response[i].product_sales); \n console.log(\"------------------------------\");\n }\n });\n}", "function show_supplier_selector(product_id)\n{\n\t$(\"#supplier_selector_dropdown_\"+product_id).toggle();\n\n}", "function updateSku(req, res) {\n\n\tlet { updateSku } = query.sku\n\tlet { sku, price } = req.body\n\tlet { product_id, sku_id } = req.params\n\n\tdb.query(updateSku, [sku_id, sku, price, product_id], (err, data) => {\n\n\t\treturn err ? res.status(500).send({ message: `Error updating the price to product: ${err}` })\n\t\t\t: res.status(200).send({ message: 'Sku & price successfully updated' })\n\t})\n}", "filterBySize(products, size) {\n // ----Logic\n }", "static async get(req, res) {\n if (!req.params.variation_id) {\n return res.error('Invalid id supplied');\n }\n\n const variation = _.find(\n req.product.variations,\n {\n _id: mongoose.Types.ObjectId(req.params.variation_id),\n deleted: false,\n },\n );\n if (!variation) {\n return res.error('Item with id not found', 404);\n }\n\n return res.products_with_additional_prices(variation);\n }", "function searchForProducts(isNode) {\n \n //IF NODE TYPE IS PRODUCT\n if(isNode.NodeType === 'PRODUCT') {\n \n //CONNECT TO THE iSYS API AND GET PRODUCT INFO BY NODE PRODUCT ID\n var getProductInfo = $http.get('http://isys-pim-dev.isys.no/ibridge/ws/Product/Get?', {\n params: { PRODUCT_ID: isNode.ProductId }\n });\n \n //ON SUCCESS: RETIRIEVE PRODUCT INFO\n getProductInfo.success(function(data, status) {\n \n //LOPP THROUGH EVERY PRODUCT\n angular.forEach(data.Product, function(isProduct){\n \n //ADD PRODUCT INFO TO POUCH DB\n addProduct(isProduct);\n });\n });\n \n //ERROR: COULD NOT GET PRODUCT INFORMATION FROM API\n getProductInfo.error(function(data, status){\n console.error(status);\n });\n }\n \n //IF NODE TYPE IS NOT PRODUCT: RETURN SEARCHING FOR NODES\n else { return; }\n }", "function searchByCountryName() {\n const selectedCountryName = convertToLowerCase(select.value);\n result = products.filter(item => {\n return item.shipsTo.some(shippingCountry => {\n return convertToLowerCase(shippingCountry) === select.value;\n });\n });\n renderProducts(result);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function adds a link for a form element to the left menu for adding to the contract
function add_link_line(name, schema){ $("#new_contract_menu").append("<li><a href='#'></a></li>"); $("#new_contract_menu > li > a:last").text(schema.title).click(function() { app.forms.start_contract(name); }); }
[ "function addFormElem(moduleChosen){\n\tclearForm();\n\tvar moduleCode = moduleChosen.split(' ')[0];\n\taddLecture(moduleCode);\n\taddRest(moduleCode);\n\taddButton();\n\tselectize();\n\tprepareInfoDisplay();\n\taddEventForFormElem(moduleCode);\n}", "function openUpdateEmailMenu(event) {\n // Prevent any default\n event.preventDefault();\n\n // Append update email menu into update menu area\n $('.update-user-info-area').append(`\n <div class=\"update-backdrop\" id=\"update-user-info-backdrop\" onclick=\"closeUpdateUserInfoMenu()\"></div>\n <div class=\"update-menu\" id=\"update-user-info-menu\">\n <form class=\"update-form\" onsubmit=\"onUpdateEmail()\">\n <h2>\n Update email\n </h2>\n <label>New email:</label><br>\n <input type=\"text\" id=\"new_email_email_update_field\" class=\"field\" placeholder=\"New email\"><br><br>\n\n <input type=\"submit\" value=\"Submit\" class=\"button\">\n </form>\n </div>\n `)\n}", "function onOpen() {\r\n var sheet = SpreadsheetApp.getActiveSpreadsheet();\r\n var entries = [{\r\n name : \"SendOneEntry\",\r\n functionName : \"failedFormSubmit\"\r\n }];\r\n sheet.addMenu(\"GBSP\", entries);\r\n}", "function onOpen() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(),\n menuItems = [{name: \"Show Form\", functionName: \"showForm\"}];\n ss.addMenu(\"Data Entry\", menuItems);\n}", "addToNavBar() {\r\n const link = $$(\"<a>\");\r\n link.className = \"nav-item nav-link\";\r\n link.href = \"/money/account/\" + this.model.id;\r\n link.textContent = this.model.name;\r\n $$(\".navbar-nav\").appendChild(link);\r\n }", "function createItemLinks(key,createLinks){\n\tvar editLink = document.createElement('a');\n\teditLink.href = \"#addidea\";\n\teditLink.key = key;\n\tvar editText = \"Edit Idea\";\n\teditLink.addEventListener(\"click\", editItem);\n\teditLink.innerHTML = editText;\n\tcreateLinks.appendChild(editLink);\n\t//add Line Break\n\tvar breakTag = document.createElement('br');\n\tcreateLinks.appendChild(breakTag);\n\tvar deleteLink = document.createElement('a');\n\tdeleteLink.href = \"#\";\n\tdeleteLink.key = key;\n\tvar deleteText = \"Delete Idea\";\n\tdeleteLink.addEventListener(\"click\", deleteItem);\n\tdeleteLink.innerHTML = deleteText;\n\tcreateLinks.appendChild(deleteLink);\n}", "function addGrayListUrl(form){\n\tlet clientId=$('#clientId').val();\n\tlet platformId=$('#typeId').val();\n\tlet url =$('#url').val().trim();\n\tif(clientId === \"0\"){\n\t\talert('Please select a Client ');\n\t}else if(platformId === \"0\"){\n\t\talert('Please select Platform type');\n\t}else if(url === \"\"){\n\t\talert('Please add a URL');\n\t}else{\n\t\tform.action=\"glist\";\n\t\tform.method=\"post\";\n\t}\n}", "function addSendingForm(itemId) {\r\n\tdocument.getElementById(\"formSend\" + itemId).innerHTML = \"<div>\" +\r\n\t\"<form id=\\\"sendingItemsForm\\\" method=\\\"patch\\\" action=\\\"\\\">\" +\r\n\t\"<b>Send item:</b><br>\" +\r\n\t\"Amount: <input type=\\\"text\\\" name=\\\"amount\\\" class=\\\"amountSendingItems\\\"><br>\" +\r\n\t\"Destination: <select id=\\\"locations\\\" name=\\\"location\\\" class=\\\"destinationSendingItems\\\">\" + \r\n\t\"</select><br>\" +\r\n\t\"<input type=\\\"button\\\" value=\\\"Send\\\" onclick=\\\"javascript:sendForm(\" + itemId + \");\\\">\" +\r\n\t\"</form></div>\";\r\n\tgetLocationsList(); \r\n}", "function addOperationForm(clienti, manodopera, articoli) {\n if (clienti === \"NON CI SONO CLIENTI\") {\n out = \"<p>Non ci sono clienti, non &#232 possibile aggiungere alcuna Operazione! <br>\" +\n \"<br><input type='button' onclick= addClient() value='Aggiungi Cliente'>\";\n //genero il menu per i clienti\n } else {\n client = \"<select id=select name=codCliente><option value=null>---</option>\";\n for (i = 0; i < clienti.length; i++) {\n client += \"<option value=\" + clienti[i].cf + \">\" + clienti[i].cf + \"</option>\";\n }\n client += \"</select>\";\n //genero il menu per gli articoli se sono presenti\n art = \"<select id=select name=codArticolo><option value=null>---</option>\";\n if (articoli !== \"NON CI SONO ARTICOLI\") {\n for (i = 0; i < articoli.length; i++) {\n art += \"<option value=\" + articoli[i].codice + \">\" + articoli[i].codice + \"</option>\";\n }\n }\n art += \"</select>\";\n //creo il menu per la quantita\n quantita = \"<select id=select name=numArt><option value=1>1</option>\";\n for (i = 2; i <= 10; i++) {\n quantita += \"<option value=\" + i + \">\" + i + \"</option>\";\n }\n quantita += \"</select>\";\n //creo il menu per la manodopera \n man = \"<select id=select name=codMan><option value=null>---</option>\";\n for (i = 0; i < manodopera.length; i++) {\n man += \"<option value=\" + manodopera[i].id_manodopera + \">\" + manodopera[i].id_manodopera + \"</option>\";\n }\n man += \"</select>\";\n //collego i campi del form con i menu creati\n out = \"<form name='addOperation'>\";\n out += \"<div class='cell'>*Scegli Cliente</div><div class='cell'>\" + client + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Scegli Articolo</div><div class='cell'>\" + art + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Scegli Quantit&#224</div><div class='cell'>\" + quantita + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='cell'>*Tipo Prestazione</div><div class='cell'>\" + man + \"</div>\";\n out += \"<div class='row'></div>\";\n out += \"<div class='button'><br><input type=button onclick=makeAddOperationJson() value='Salva'>\";\n out += \"<p>* Campi Obbligatori</p></div>\";\n out += \"<div class='row'></div></form>\";\n }\n $(\"#post\").html(out);\n}", "function createLink() {\r\n if (!validateMode()) return;\r\n \r\n var isA = getEl(\"A\",Composition.document.selection.createRange().parentElement());\r\n if(isA==null){\r\n\tvar str=prompt(\"Укажите адрес :\",\"http:\\/\\/\");\r\n\t \r\n\tif ((str!=null) && (str!=\"http://\")) {\r\n\t\tvar sel=Composition.document.selection.createRange();\r\n\t\tif (Composition.document.selection.type==\"None\") {\r\n\t\t\tsel.pasteHTML('<A HREF=\"'+str+'\">'+str+'</A>');\r\n\t\t}else {\r\n\t\t\tsel.execCommand('CreateLink',\"\",str);\r\n\t }\r\n\t\tsel.select();\r\n\t}\r\n } else {\r\n\tvar str=prompt(\"Укажите адрес :\",isA.href);\r\n\r\n\tif ((str!=null) && (str!=\"http://\")) isA.href=str;\r\n\r\n }\r\n\r\nComposition.focus();\r\n}", "function contactForm(){\n\t\tif($('#contact-site-form .form-type-textfield.form-item-subject , #contact-site-form .form-type-textarea').hasClass(\"error\")){\t\t\n\t\t\tlocation.hash=\"contact\";\n\t\t}\n\t\t\n\t\tif($('.programme-contact-form .form-item').hasClass(\"error\")){\t\t\n\t\t\t$('.node-type-programmes .vertical-tabs .contact a').trigger(\"click\");\t\t\n\t\t}\t\n\t\t\n\t\t/*$('.about-menu-wrapper .abt-mnu-contact').on(\"click\",function(){\n\t\t\tif($('about-nepad-contact-form ').hasClass(\"hide-block\")){\n\t\t\t\t$('about-nepad-contact-form ').removeClass(\"hide-block\")\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$('about-nepad-contact-form ').addClass(\"hide-block\")\n\t\t\t}\n\t\t});*/\n\t\tvar block = $('.about-nepad-contact-form').clone();\n\t\t$('.about-nepad-contact-form').remove();\n\t\t$('.abt-contact-content').append(block);\n\t\t\n\t}", "function dayForm(el){\n buildForm(el.parentElement.parentElement.id);\n window.location.href =\"/#appointment-form\";\n}", "function eventMenuAddSignature(){\n\tif(module.addSigMenuItems.length > 0){\n\t\tvar posX = dhtml.getElementLeft(dhtml.getElementById(\"addsignature\"));\n\t\tvar posY = dhtml.getElementTop(dhtml.getElementById(\"addsignature\"));\n\t\tposY += dhtml.getElementById(\"addsignature\").offsetHeight;\n\t\twebclient.menu.buildContextMenu(module.id, \"addsignature\", module.addSigMenuItems, posX, posY);\n\t}else{\n\t\talert(_(\"No signatures\"));\n\t}\n}", "function onAddUrl(ev) {\n ev.preventDefault();\n\n var lastField = this.select('urlListSelector').find('[name=\"websites[]\"]').last();\n\n if (lastField.val() === '') {\n lastField.focus();\n } else {\n this.select('urlListSelector').append(metadataEditUrlListTemplate.render({\n metadataPrefix: this.attr.metadataPrefix,\n fontPrefix: this.attr.fontPrefix\n }));\n this.select('urlListSelector').find('[name=\"websites[]\"]').last().focus();\n }\n}", "function createUsersLinkList(usersList, parent) {\n // for each user\n usersList.forEach(user => {\n // create new form element\n const newForm = document.createElement(\"form\");\n newForm.method = \"get\";\n newForm.action = \"/options\";\n newForm.className = \"usersLinkList\";\n // create new user list element with an evenet listener\n const newUser = document.createElement(\"li\");\n newUser.innerHTML = user;\n newUser.className = \"users-list-style\";\n newUser.addEventListener('click', function() {\n localStorage.setItem(\"actualUser\", user);\n newUser.parentElement.submit();\n });\n // add it to the form\n newForm.appendChild(newUser);\n // create a new hidden input element containing the username as value\n const usernameInput = document.createElement(\"input\");\n usernameInput.type = \"text\";\n usernameInput.name = \"username\";\n usernameInput.value = user;\n usernameInput.hidden = true;\n // add it to the form\n newForm.appendChild(usernameInput);\n // add the form to a parent element\n parent.appendChild(newForm);\n });\n}", "addTab() {\n this._insertItem(FdEditformTab.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-tab-caption').toString()} #${this.incrementProperty('_newTabIndex')}`,\n rows: A(),\n }), this.get('selectedItem') || this.get('controlsTree'));\n }", "function bbedit_components_draw_menu() {}", "function addNewField()\n{\n\tshowLoader( \"New Field Specification...\" );\n\tvar targetUrl = getContextPath() + \"/dynamicScreen/DynamicScreenAction.action?actionCommand=create&type=field&menuRef=\"+menuRef;\n\t$.ajax({\n url:targetUrl,\n cache: false,\n type: 'POST',\n success: function (thePage) {\n \topenDialog( \"dialog-medium\", \"New Field\", thePage );\n \thideLoader();\n },\n error: function (xhr, ajaxOptions, thrownError) {\n \thideLoader();\n \talert( thrownError );\n }\n });\n\n}", "function showIconAddMenu() {\n var apps = FPI.apps.all, i, bundle, sel, name;\n clearinnerHTML(appList);\n showHideElement(appList, 'block');\n appList.appendChild(createDOMElement('li', 'Disable Edit', 'name', 'Edit'));\n\n for (i = 0; i < apps.length; i++) {\n bundle = apps[i].bundle;\n sel = FPI.bundle[bundle];\n name = sel.name;\n appList.appendChild(createDOMElement('li', name, 'name', bundle));\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns 5% of that income if it is less than $10000, 10% of that income if it is between $10000$20000, and 15% if it is greater than $20000
function calculateTaxes(income) { if (income < 10000) { return (income * .05); } else if (income >10000 <20000) { return (income * .10); } else if (income > 20000) { return (income * 15); } }
[ "function calculatePercentage(percentage) {\n return (5000 / 100) * percentage;\n}", "function getPercentage(annualAmount,citizenType)\n {\n var PercentageValue;\n \n \n if(citizenType == \"general\")\n {\n if(annualAmount<=500000)\n {\n PercentageValue = 10;\n }\n else if(annualAmount<=1000000)\n {\n PercentageValue = 20;\n }\n else\n {\n PercentageValue = 30;\n }\n }\n \n if(citizenType == \"seniorCitizen\")\n {\n\n if(annualAmount<=500000)\n {\n PercentageValue = 10;\n }\n else if(annualAmount<=1000000)\n {\n PercentageValue = 20;\n }\n else\n {\n PercentageValue = 30;\n }\n }\n \n if(citizenType == \"superSenior\")\n {\n \n if(annualAmount<=1000000)\n {\n PercentageValue = 20;\n }\n else\n {\n PercentageValue = 30;\n }\n }\n return PercentageValue;\n }", "function percentCoveredCalc(claimant){\n\tvar percentage = 0;\n\tvar careType = claimant.visitType;\n\n\tswitch(careType){\n\t\tcase \"Optical\":\n\t\t\tpercentage = 0;\n\t\t\tbreak;\n\t\tcase \"Specialist\":\n\t\t\tpercentage = 10;\n\t\t\tbreak\n\t\tcase \"Emergency\":\n\t\t\tpercentage = 100;\n\t\t\tbreak;\n\t\tcase \"Primary Care\":\n\t\t\tpercentage = 50;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn percentage;\n\n}", "function calcSalaryPerSecond(income) {\n return income / SECONDS;\n}", "function discountPercentage(originalAmount, discountAmountPercent) {\n if (discountAmountPercent > 100 || discountAmountPercent < 0){\n return (\"Warning: Disount is greater than 100 or less than 0 percent\");\n }\n else {\n return (originalAmount*(discountAmountPercent/100));\n }\n}", "function discountPercentage(amount, discount) {\n if (discount > 100 || discount < 0) {\n return \"Error: Discount % must be within 0 and 100\";\n }\n return \"$\" + (amount * (discount/100)).toFixed(2);\n}", "function getHouseholdIncome(input){\n let money = input.split(\"-$\");\n\n let Average = 0\n\n if (input ===\"$200,000+\"){\n Average = 200000\n }\n else if(input ===\"$0-$9,999\"){\n Average = 5000\n }else{\n \n let minMoney = money[0].slice(1,money[0].length-1).replace(\",\",\"\")\n console.log(money[1])\n let maxMoney = money[1].replace(\",\",\"\")\n Average = (parseInt(minMoney) + parseInt(maxMoney)+1 ) / 2\n }\n\n return Average\n \n}", "salaryFromTakeHome(income) {\n let salary;\n\n const nILowerLimit = this.nILowerLimit * 12;\n const nIUpperLimit = this.nIUpperLimit * 12;\n\n // 1) Income less than NI lower limit\n if (income <= nILowerLimit) {\n salary = income;\n }\n\n // 2) Income within NI Lower limit\n // 2a) Income still in personal allowance\n else if (income <= this.takeHomePay(this.pA)) {\n salary =\n (income - this.nILowerRate * nILowerLimit) / (1 - this.nILowerRate);\n }\n // 2b) Income within basic range\n else if (income <= this.takeHomePay(this.higherRateStart)) {\n salary =\n (income - this.nILowerRate * nILowerLimit - this.basicRate * this.pA) /\n (1 - this.nILowerRate - this.basicRate);\n }\n // 2c) Income within higher rate\n else if (income <= this.takeHomePay(nIUpperLimit)) {\n salary =\n (income -\n this.nILowerRate * nILowerLimit +\n this.basicRate * this.higherRateStart -\n this.basicRate * this.pA -\n this.higherRate * this.higherRateStart) /\n (1 - this.nILowerRate - this.higherRate);\n }\n\n // 3) Income above NI UEL\n // 3a) Higher income rate\n else if (income <= this.takeHomePay(this.pAReductionStart)) {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart -\n this.basicRate * this.pA -\n this.nIUpperRate * this.nIUpperLimit * 12 -\n this.higherRate * this.higherRateStart) /\n (1 - this.nIUpperRate - this.higherRate);\n }\n\n // 3b) Personal allowance reducing\n else if (\n income <=\n this.takeHomePay(this.pAReductionStart + this.pA / this.pAReductionRate)\n ) {\n salary =\n (-(1 / this.pAReductionRate) *\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) -\n this.nIUpperRate * nIUpperLimit +\n this.basicRate * (this.higherRateStart - this.pA) -\n this.higherRateStart * this.higherRate -\n (this.basicRate * this.pAReductionStart) /\n (1 / this.pAReductionRate))) /\n (-(1 / this.pAReductionRate) +\n this.basicRate +\n (1 / this.pAReductionRate) * (this.nIUpperRate + this.higherRate));\n }\n\n // 3c) Personal allowance is zero\n else if (income <= this.takeHomePay(this.additionalRateStart)) {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart -\n this.nIUpperRate * nIUpperLimit -\n this.higherRateStart * this.higherRate) /\n (1 - this.nIUpperRate - this.higherRate);\n }\n\n // 3d) Highest rate\n else {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart +\n (this.additionalRateStart - this.higherRateStart) * this.higherRate -\n this.nIUpperRate * nIUpperLimit -\n this.additionalRateStart * this.additionalRate) /\n (1 - this.nIUpperRate - this.additionalRate);\n }\n\n return _.round(salary);\n }", "function BuyMore_GetMore() {\n var totalPrice = parseInt(readLine(), 10)\n // Your code here\n if (totalPrice <= 999) {\n console.log(\"0%\");\n } else if (totalPrice <= 2999) {\n console.log(\"10%\");\n } else if (totalPrice <= 4999) {\n console.log(\"30%\");\n } else {\n console.log(\"50%\");\n }\n}", "function calculateInterest(startSaving, years, interest) {\n let endSaving = startSaving;\n\n for (let ix = 1; ix <= years; ix++) {\n endSaving = endSaving * (1 + interest / 100);\n }\n return Math.round(endSaving * 10000) / 10000;\n}", "function tax_on_item(amount, tax_rate)\n{\n return Math.round(tax_rate * amount) / 100.0;\n}", "function getWithholdings() {\n const inc = formData[\"estimatedIncome\"];\n if (inc < 9875) {\n setWithholdings(inc * 0.1);\n } else if (inc < 40125) {\n setWithholdings(987.5 + (inc - 9875) * 0.12);\n } else if (inc < 85525) {\n setWithholdings(4617.5 + (inc - 40125) * 0.22);\n } else if (inc < 163301) {\n setWithholdings(14605.5 + (inc - 85525) * 0.24);\n } else if (inc < 207350) {\n setWithholdings(33271.5 + (inc - 163300) * 0.32);\n } else if (inc < 518400) {\n setWithholdings(47367.5 + (inc - 207350) * 0.35);\n } else {\n setWithholdings(156235 + (inc - 518400) * 0.37);\n }\n }", "function greaterThanTwentyThousand () {\n if (salarySum >= 20000) {\n $('#grandTotal').css('color', 'red');\n }\n}", "function checkAmount() {\n if (Inputrange.value == 1) {\n if (checkbox.checked) totalPrice.textContent = 72;\n else totalPrice.textContent = 8;\n\n pageViews.textContent = '10k';\n }\n\n if (Inputrange.value == 2) {\n if (checkbox.checked) totalPrice.textContent = 108;\n else totalPrice.textContent = 12;\n\n pageViews.textContent = '50k';\n }\n\n if (Inputrange.value == 3) {\n if (checkbox.checked) totalPrice.textContent = 144;\n else totalPrice.textContent = 16;\n\n pageViews.textContent = '100k';\n }\n\n if (Inputrange.value == 4) {\n if (checkbox.checked) totalPrice.textContent = 216;\n else totalPrice.textContent = 24;\n\n pageViews.textContent = '500k';\n }\n\n if (Inputrange.value == 5) {\n if (checkbox.checked) totalPrice.textContent = 324;\n else totalPrice.textContent = 36;\n\n pageViews.textContent = '1M';\n }\n}", "function getPV(current_cashflow, growth_rate_1, growth_rate_2, discount_rate){\n var pv = 0\n var temp = current_cashflow\n var sum = 0\n for(var i = 0; i < 10; i++){\n var discountFactor = 1 / (1 + discount_rate) ** (i + 1)\n //Before Discount\n if(i < 3)\n temp = temp * growth_rate_1 \n else\n temp = temp * growth_rate_2 \n // console.log(\"temp\", i+1, \": \", temp);\n //After discount\n sum += temp * discountFactor\n // console.log(\"discount\", i+1, \": \", discountFactor);\n // console.log(\"sum \",i+1, \": \",sum)\n }\n pv = sum\n return pv\n}", "generatePercent(deathState,totDeath) {\n return ((deathState / parseInt(totDeath)) * 100).toFixed(2) + '%'\n }", "function calcPercent(outcome) {\n // substring because the first 16 characters are based from the assoc_id and will stay the same\n var seed = parseInt(outcome.substr(16), 16);\n var x = Math.sin(seed) * 10000;\n return x - Math.floor(x);\n}", "function getPercentage(object)\n{\n var percent = 0 ;\n if(object.volume>25)\n {\n percent=0.5;\n }\n else\n {\n if(object.volume>10)\n {\n percent = 0.3;\n }\n else\n {\n if(object.volume>5)\n {\n percent = 0.1;\n }\n }\n }\n return percent;\n \n}", "function getTaxBill(income) {\n if (income < 0) {\n setTaxBill(0);\n } else if (income < 9875) {\n setTaxBill(income * 0.1);\n } else if (income < 40125) {\n setTaxBill(987.5 + (income - 9875) * 0.12);\n } else if (income < 85525) {\n setTaxBill(4617.5 + (income - 40125) * 0.22);\n } else if (income < 163301) {\n setTaxBill(14605.5 + (income - 85525) * 0.24);\n } else if (income < 207350) {\n setTaxBill(33271.5 + (income - 163300) * 0.32);\n } else if (income < 518400) {\n setTaxBill(47367.5 + (income - 207350) * 0.35);\n } else {\n setTaxBill(156235 + (income - 518400) * 0.37);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
transform solr date to UTC
function fromSolrDateToUTC(date){ date = date.replace("Z", ""); var year = date.split("T")[0].split("-")[0]; var month = parseInt(date.split("T")[0].split("-")[1]-1); var day = date.split("T")[0].split("-")[2]; var hour = date.split("T")[1].split(":")[0]; var minutes = date.split("T")[1].split(":")[1]; var seconds = date.split("T")[1].split(":")[2]; return (new Date(Date.UTC(year,month,day,hour,minutes,seconds))).getTime(); }
[ "function getOnsetAsUTC(obs, localdate) {\n //return new Date(localdate.getTime() - obs.offsetFrom);\n return localdate - obs.offsetFrom;\n }", "function setUTCValuesInDate(date) {\n return new Date(\n date.getUTCFullYear(),\n date.getUTCMonth(),\n date.getUTCDate(),\n date.getUTCHours(),\n date.getUTCMinutes(),\n date.getUTCSeconds(),\n );\n }", "function normalise_date(date) {\n // console.log(date);\n date.setHours(8,0,0,0);\n // console.log(date);\n // console.log(Date.parse(date));\n return(date);\n}", "function fn_fromADO(o) {\r\n if (typeof o == 'date') {\r\n //Dates are stored in DB as UTC\r\n return Date.fromUTCString(o);\r\n }\r\n return o;\r\n }", "getCurrentDateTimeinUTCForMySQL() {\n return new Date().toISOString().slice(0, 19).replace('T', ' ');\n }", "function format_exercise_date() {\n const field = document.getElementById(\"timestamp\");\n\n if (typeof (field) != 'undefined' && field != null) {\n const m_utc = moment.utc(field.value, \"DD/MM/YYYY HH:mm\");\n const m_local = m_utc.clone().local().format(\"DD/MM/YYYY HH:mm\");\n field.value = m_local;\n }\n}", "convert_date_to_local(date) {\n if(typeof(date) == 'undefined' || date == null)\n return null;\n \n var local_tz = Intl.DateTimeFormat().resolvedOptions().timeZone; // local timezone\n \n return moment(date).tz(local_tz).format('YYYY-MM-DD');\n }", "function makeAs(input, model) {\n return model._isUTC ? moment(input).zone(model._offset || 0) :\n moment(input).local();\n }", "function convertToUtc(dateInLocal, timeInLocal, timezone) {\n // Construct a new time \n var workTime = new Date(dateInLocal.getFullYear(), dateInLocal.getMonth(), dateInLocal.getDate(), timeInLocal.getHours(), timeInLocal.getMinutes());\n var timeWrapper = moment(workTime);\n // The above time should be interpreted in the given timezone\n if (timezone) {\n // Utc time\n timeWrapper.subtract(timezone, 'hours');\n }\n // Convert to UTC time\n var timeInUtc = new Date(Date.UTC(timeWrapper.year(), timeWrapper.month(), timeWrapper.date(), timeWrapper.hour(), timeWrapper.minute(), timeWrapper.second()));\n return timeInUtc;\n }", "function transformDate(d) {\n return d.substr(6) + '-' + d.substr(3, 2) + '-' + d.substr(0, 2);\n }", "function dateInTz(d) {\n return d.toFormat('yyyy-LL-dd')\n}", "function add_tz_to_fields() {\n add_user_tz();\n add_user_tz_to_form();\n format_exercise_date();\n}", "function datePrecedente(date) {\n var dt = date.split('/');\n var myDate = new Date(dt[2] + '-' + dt[1] + '-' + dt[0]);\n myDate.setDate(myDate.getDate() + -1);\n newDate = formatDateSlash(myDate);\n return newDate;\n}", "toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }", "static setFullDate(from, to) {\n to.setDate(from.getDate());\n to.setMonth(from.getMonth());\n to.setFullYear(from.getFullYear());\n return to;\n }", "function tzdate (date) {\n var match;\n if (match = /^TZ=\"(\\S+)\"\\s+(.*)$/.exec(date)) {\n var a = match.slice(1, 3).reverse();\n return a;\n }\n return date;\n}", "async localTimeToUTC(localTime) {\n let dateIsoString;\n if (typeof localTime === \"string\") {\n dateIsoString = localTime;\n }\n else {\n dateIsoString = dateAdd(localTime, \"minute\", localTime.getTimezoneOffset() * -1).toISOString();\n }\n const res = await spPost(TimeZone(this, `localtimetoutc('${dateIsoString}')`));\n return hOP(res, \"LocalTimeToUTC\") ? res.LocalTimeToUTC : res;\n }", "function transform_date(obj)\r\n {\r\n var hint,foo,num,i,jsDate\r\n if (obj && typeof obj === 'object')\r\n {\r\n hint = obj.hasOwnProperty('javaClass');\r\n foo = hint ? obj.javaClass === 'java.util.Date' : obj.hasOwnProperty('time');\r\n num = 0;\r\n // if there is no class hint but the object has 'time' property, count its properties\r\n if (!hint && foo)\r\n {\r\n for (i in obj)\r\n {\r\n if (obj.hasOwnProperty(i))\r\n {\r\n num++;\r\n }\r\n }\r\n }\r\n // if class hint is java.util.Date or no class hint set, but the only property is named 'time', we create jsdate\r\n if (hint && foo || foo && num === 1)\r\n {\r\n jsDate = new Date(obj.time);\r\n return jsDate;\r\n }\r\n else\r\n {\r\n for (i in obj)\r\n {\r\n if (obj.hasOwnProperty(i))\r\n {\r\n obj[i] = transform_date(obj[i]);\r\n }\r\n }\r\n return obj;\r\n }\r\n }\r\n else\r\n {\r\n return obj;\r\n }\r\n }", "parseDates(data) {\n if (data.length && 'Date' in data[0]) {\n for (let i = 0; i <= data.length-1; i++) { data[i].Date = moment.utc(data[i].Date, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); }\n return data;\n } else if (data.length && 'startDt' in data[0]) {\n for (let i = 0; i <= data.length-1; i++) { data[i].startDt = moment.utc(data[i].startDt, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');\n data[i].stopDt = moment.utc(data[i].stopDt, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); }\n return data;\n } else { return data; }\n }", "function getDebeDate() {\n let date = new Date();\n \n if(date.getUTCHours() < 4) {\n date.setDate(date.getDate() - 1);\n }\n return date.toJSON().split(\"T\")[0]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RCVT[] Read Control Value Table entry 0x45
function RCVT(state) { var stack = state.stack; var cvte = stack.pop(); if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); } stack.push(state.cvt[cvte] * 0x40); }
[ "testStoredValueForIndex( accTypeEnumIndex )\n {\n if ( accTypeEnumIndex < 0 || accTypeEnumIndex > CMD4_ACC_TYPE_ENUM.EOL )\n return undefined;\n\n return this.storedValuesPerCharacteristic[ accTypeEnumIndex ];\n }", "function parseCtrlStr(ctrlStr) {\n ctrlStr = ctrlStr.toLowerCase();\n\n var ptrnMatch = ctrlStr.match(/^control:(left|right|goto)\\s(\\d+)(?:st|nd|rd|th)?\\s(.*)$/);\n \n if(ptrnMatch === null) {\n ptrnMatch = ctrlStr.match(/^control:(left|right)()\\s(continuous)$/);\n }\n\n if (ptrnMatch !== null) {\n return ptrnMatch.slice(1);\n }\n }", "function readPidData() {\n return txChar.readValue()\n .then(originalPid => {\n\n // Convert from dataView to Uint8Array and save original PID data for possible reset\n originalPidData = new Uint8Array(originalPid.buffer, 0, 20);\n txCharVal = originalPidData;\n console.log(\"Original PID data received:\", originalPid);\n\n // Write original PID data to input boxes\n for(var i = 1; i <= 18; i++) {\n select(inputMap[i]).value = originalPidData[i];\n }\n resolve(originalPidData);\n });\n}", "function SetCCV(id, val)\n{\n SetCtrlValue(CTRLARY, id, val);\n}", "function getValuesFromCircuit(circuit) {\n //circuitsArr.forEach(c => delete c[\"exercises\"]);\n \n let valuesArr = [];\n // for (let c in circuitsArr) {\n // let tempArr = [];\n // Object.entries(circuitsArr[c]).forEach(([key, value]) => {\n // tempArr.push(value)\n // }) \n // valuesArr.push(tempArr);\n // }\n Object.entries(circuit).forEach(([key, value]) => {\n valuesArr.push(value)})\n return valuesArr;\n }", "get i32() { return new Int32Array(module.memory.buffer, this.ptr, this.len); }", "function decode_light_control_status(data) {\n\tdata.command = 'bro';\n\tdata.value = 'light control status - ';\n\n\t// Examples\n\t//\n\t// D1 D2\n\t// 11 01 Intensity=1, Lights=on, Reason=Twilight\n\t// 21 02 Intensity=2, Lights=on, Reason=Darkness\n\t// 31 04 Intensity=3, Lights=on, Reason=Rain\n\t// 41 08 Intensity=4, Lights=on, Reason=Tunnel\n\t// 50 00 Intensity=5, Lights=off, Reason=N/A\n\t// 60 00 Intensity=6, Lights=off, Reason=N/A\n\t//\n\t// D1 - Lights on/off + intensity\n\t// 0x01 : Bit0 : Lights on\n\t// 0x10 : Bit4 : Intensity 1\n\t// 0x20 : Bit5 : Intensity 2\n\t// 0x30 : Bit4+Bit5 : Intensity 3\n\t// 0x40 : Bit6 : Intensity 4\n\t// 0x50 : Bit4+Bit6 : Intensity 5\n\t// 0x60 : Bit5+Bit6 : Intensity 6\n\t//\n\t// D2 - Reason\n\t// 0x01 : Bit0 : Twilight\n\t// 0x02 : Bit1 : Darkness\n\t// 0x04 : Bit2 : Rain\n\t// 0x08 : Bit3 : Tunnel\n\t// 0x10 : Bit4 : Garage\n\n\tconst mask1 = bitmask.check(data.msg[1]).mask;\n\tconst mask2 = bitmask.check(data.msg[2]).mask;\n\n\tconst parse = {\n\t\tintensity : null,\n\t\tintensity_str : null,\n\t\tintensities : {\n\t\t\tl1 : mask1.bit4 && !mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl2 : !mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl3 : mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl4 : !mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl5 : mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl6 : !mask1.bit4 && mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl0 : !mask1.bit4 && !mask1.bit5 && !mask1.bit6 && mask1.bit8,\n\t\t},\n\n\t\tlights : mask1.bit0,\n\t\tlights_str : 'lights on: ' + mask1.bit0,\n\n\t\treason : null,\n\t\treason_str : null,\n\t\treasons : {\n\t\t\ttwilight : mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tdarkness : !mask2.bit0 && mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\train : !mask2.bit0 && !mask2.bit1 && mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\ttunnel : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tgarage : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && mask2.bit4 && !mask2.bit8,\n\t\t\tnone : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && mask2.bit8,\n\t\t},\n\t};\n\n\t// Loop intensity object to obtain intensity level\n\tfor (const intensity in parse.intensities) {\n\t\tif (parse.intensities[intensity] === true) {\n\t\t\t// Convert hacky object key name back to integer\n\t\t\tparse.intensity = parseInt(intensity.replace(/\\D/g, ''));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Loop reason object to obtain reason name\n\tfor (const reason in parse.reasons) {\n\t\tif (parse.reasons[reason] === true) {\n\t\t\tparse.reason = reason;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Append prefixes to log strings\n\tparse.intensity_str = 'intensity: ' + parse.intensity;\n\tparse.reason_str = 'reason: ' + parse.reason;\n\n\tupdate.status('rls.light.intensity', parse.intensity, false);\n\tupdate.status('rls.light.lights', parse.lights, false);\n\tupdate.status('rls.light.reason', parse.reason, false);\n\n\t// Assemble log string\n\tdata.value += parse.intensity_str + ', ' + parse.lights_str + ', ' + parse.reason_str;\n\n\treturn data;\n}", "selectInputSourceVcr() {\n this._selectInputSource(\"i_vcr\");\n }", "function getIVs()\n{\n\treturn [\n\t\tparseInt(document.getElementById('hp-iv').value),\n\t\tparseInt(document.getElementById('atk-iv').value),\n\t\tparseInt(document.getElementById('def-iv').value),\n\t\tparseInt(document.getElementById('spa-iv').value),\n\t\tparseInt(document.getElementById('spd-iv').value),\n\t\tparseInt(document.getElementById('spe-iv').value)\n\t];\n}", "getRegionCode(){\n\t\treturn this.dataArray[3];\n\t}", "getFrameCameraFlags(frameIndex) {\r\n this.seek(this.frameMetaOffsets[frameIndex] + 0x1A);\r\n const cameraFlags = this.readUint8();\r\n return [\r\n (cameraFlags & 0x1) !== 0,\r\n (cameraFlags & 0x2) !== 0,\r\n (cameraFlags & 0x4) !== 0,\r\n ];\r\n }", "readKey() {\n const r = this.reader;\n\n let code = r.u8();\n\n if (code === 0x00) return;\n\n let f = null;\n let x = null;\n let y = null;\n let z = null;\n\n if ((code & 0xe0) > 0) {\n // number of frames, byte case\n\n f = code & 0x1f;\n\n if (f === 0x1f) {\n f = 0x20 + r.u8();\n } else {\n f = 1 + f;\n }\n } else {\n // number of frames, half word case\n\n f = code & 0x3;\n\n if (f === 0x3) {\n f = 4 + r.u8();\n } else {\n f = 1 + f;\n }\n\n // half word values\n\n code = code << 3;\n\n const h = r.s16big();\n\n if ((h & 0x4) > 0) {\n x = h >> 3;\n code = code & 0x60;\n\n if ((h & 0x2) > 0) {\n y = r.s16big();\n code = code & 0xa0;\n }\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x2) > 0) {\n y = h >> 3;\n code = code & 0xa0;\n\n if ((h & 0x1) > 0) {\n z = r.s16big();\n code = code & 0xc0;\n }\n } else if ((h & 0x1) > 0) {\n z = h >> 3;\n code = code & 0xc0;\n }\n }\n\n // byte values (fallthrough)\n\n if ((code & 0x80) > 0) {\n if (x !== null) {\n throw new Error('Expected undefined x in SEQ animation data');\n }\n\n x = r.s8();\n }\n\n if ((code & 0x40) > 0) {\n if (y !== null) {\n throw new Error('Expected undefined y in SEQ animation data');\n }\n\n y = r.s8();\n }\n\n if ((code & 0x20) > 0) {\n if (z !== null) {\n throw new Error('Expected undefined z in SEQ animation data');\n }\n\n z = r.s8();\n }\n\n return { f, x, y, z };\n }", "function indcpaUnpackCiphertext(c, paramsK) {\r\n var b = polyvecDecompress(c.slice(0, 960), paramsK);\r\n var v = polyDecompress(c.slice(960, 1088), paramsK);\r\n var result = new Array(2);\r\n result[0] = b;\r\n result[1] = v;\r\n return result;\r\n}", "selectInputSourceAux4() {\n this._selectInputSource(\"i_aux4\");\n }", "function getRomFrame(addr){\n\n}", "function parseLookupTable(data, start) {\n var p = new parse.Parser(data, start);\n var table, lookupType, lookupFlag, useMarkFilteringSet, subTableCount, subTableOffsets, subtables, i;\n lookupType = p.parseUShort();\n lookupFlag = p.parseUShort();\n useMarkFilteringSet = lookupFlag & 0x10;\n subTableCount = p.parseUShort();\n subTableOffsets = p.parseOffset16List(subTableCount);\n table = {\n lookupType: lookupType,\n lookupFlag: lookupFlag,\n markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1\n };\n // LookupType 2, Pair adjustment\n if (lookupType === 2) {\n subtables = [];\n for (i = 0; i < subTableCount; i++) {\n subtables.push(parsePairPosSubTable(data, start + subTableOffsets[i]));\n }\n // Return a function which finds the kerning values in the subtables.\n table.getKerningValue = function(leftGlyph, rightGlyph) {\n for (var i = subtables.length; i--;) {\n var value = subtables[i](leftGlyph, rightGlyph);\n if (value !== undefined) return value;\n }\n return 0;\n };\n }\n return table;\n}", "function getCommonEntryServices()\r\n{\r\n\tvar current = eval(\"record6\");\r\n\r\n\t//iterate through the data from the text file and store into an array\r\n\tfor(var i=0; i < record6.length; i++){\r\n\t\tcommonEntryServices[i] = current[i];\r\n\t}\r\n}//end getCommonEntryServices", "GetTexDataAsAlpha8() {\r\n return this.native.GetTexDataAsAlpha8();\r\n }", "function SysFmtStringToArray(){}", "_getSubControlDef(subCtrlName) {\n\t\tfor (let i = 0; i < this.props.control.subControls.length; i++) {\n\t\t\tif (this.props.control.subControls[i].name === subCtrlName) {\n\t\t\t\treturn this.props.control.subControls[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save the snake queue in his old position, to delete of board later
saveOldQueuePosition(){ const { snakeBodyParts, length} = this; const lastBodyPart = snakeBodyParts[ length -1 ]; this.lastBodyPartOldPosition = { ...lastBodyPart } }
[ "moveSnake() {\n\t\tthis.moveQueue.unshift(this.direction);\n\n\t\tfor (let i = 0; i < this.snake.length; i++) {\n\t\t\tconst {r, c} = this.snake[i];\n\t\t\tconst {newR, newC} = this.nextCoordinates(r, c, this.moveQueue[i]);\n\n\t\t\tthis.checkBounds(newR, newC);\n\n\t\t\tif (this.board[newC][newR] === 2) {\n\t\t\t\tthis.growSnake();\n\t\t\t}\n\n\t\t\tif (this.board[newC][newR] === 1) {\n\t\t\t\tthis.gameOver();\n\t\t\t}\n\n\t\t\tthis.board[newC][newR] = 1;\n\t\t\tthis.snake[i] = {r: newR, c: newC};\n\t\t}\n\t}", "function updateBoard(index, marker) {\r\n board[index] = marker;\r\n\r\n /* HTML5 localStorage only allows storage of strings - convert our array to a string */\r\n var boardstring = JSON.stringify(board);\r\n\r\n /* store this string to localStorage, along with the last player who marked a square */\r\n localStorage.setItem('tic-tac-toe-board', boardstring);\r\n localStorage.setItem('last-player', getCurrentPlayer());\r\n}", "growSnake() {\n\t\tthis.generateFood();\n\t\tconst lastSnakePiece = this.snake[this.snake.length-1];\n\t\tconst {r, c} = lastSnakePiece;\n\t\tsetTimeout(() => this.snake.push({r, c}), 0);\n\t}", "savedDestination () {\r\n this.setNewDestination = false;\r\n this.currentX = this.nextVertex.x + this.radius;\r\n this.currentY = this.nextVertex.y + this.radius;\r\n this.index = 0;\r\n this.end = this.save.end\r\n this.finalX = this.save.finalX\r\n this.finalY = this.save.finalY;\r\n this.pathArray = this.save.pathArray;\r\n this.requireNewPath = true;\r\n this.reachedDestination = false;\r\n }", "move()\n\t{\n\t\t// For every SnakePart in the body array make the SnakePart take on\n\t\t// the direction and x- and y-coordinates of the SnakePart ahead\n\t\t// of it.\n\t\tfor (let index = this.length - 1; index > 0; index--)\n\t\t{\n\t\t\tthis.body[index].x = this.body[index - 1].x;\n\t\t\tthis.body[index].y = this.body[index - 1].y;\n\t\t\tthis.body[index].direction = this.body[index - 1].direction;\n\t\t}\n\n\t\t// In case the snake needs to teleport to other side of the grid...\n\t\tif (this.needsTeleport)\n\t\t{\n\t\t\t// ...assign the head of the snake new coordinates accordingly\n\t\t\t// based on its direction.\n\t\t\tswitch(this.body[0].direction)\n\t\t\t{\n\t\t\t\tcase \"UP\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y = canvas.height - tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"RIGHT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"DOWN\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"LEFT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x = canvas.width - tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// After its been assigned new coordinates, \n\t\t\t// it no longer needs be teleported.\n\t\t\tthis.needsTeleport = false;\n\t\t}\n\t\t// If not, then move snake head 1 tileSize in its direction.\n\t\telse\n\t\t{\n\t\t\tswitch(this.body[0].direction)\n\t\t\t{\n\t\t\t\tcase \"UP\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y -= tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"RIGHT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x += tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"DOWN\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y += tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"LEFT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x -= tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If the Tile at the snake head's new position \n\t\t// contains a food item then eat it.\n\t\tif (this.body[0].tile.element == \"FOOD\")\n\t\t{\n\t\t\tthis.eatFood();\n\t\t}\n\t}", "Save()\n {\n\n // Check if the board is not alrady in the array of boards\n if(AppState.GetBoards().find(x => x.id == this.id) == undefined)\n {\n AppState.GetBoards().push(this)\n AppState.Save()\n return;\n }\n\n AppState.GetBoards()[this.id] = this;\n AppState.Save()\n\n }", "enQueue(item) {\n // move all items from stack1 to stack2, which reverses order\n this.alternateStacks(this.stack1, this.stack2)\n\n // new item will be at the bottom of stack1 so it will be the last out / last in line\n this.stack1.push(item);\n\n // move items back to stack1, from stack2\n this.alternateStacks(this.stack2, this.stack1)\n }", "function moveTail() {\n let snakeSize = snakePositions.length;\n $('#' + snakePositions[snakeSize - 1][0] + '-' + snakePositions[snakeSize - 1][1]).removeClass('bg-dark');\n for (let i = snakeSize - 1; i > 0; i--) {\n snakePositions[i][0] = snakePositions[i - 1][0];\n snakePositions[i][1] = snakePositions[i - 1][1];\n }\n}", "function update() {\n\tframes++;\n\n\t// controlling snake direction with pressed keys (up, right, down, left)\n\tif (keystate[key_left] && snake.direction !== right) {\n\t\tsnake.direction = left;\n\t}\n\tif (keystate[key_right] && snake.direction !== left) {\n\t\tsnake.direction = right;\n\t}\n\tif (keystate[key_up] && snake.direction !== down) {\n\t\tsnake.direction = up;\n\t}\n\tif (keystate[key_down] && snake.direction !== up) {\n\t\tsnake.direction = down;\n\t}\n\n\t// game state updates every 5 frames \n\tif (frames % 5 === 0) {\n\t\t// for popping the last snake queue element (head)\n\t\tvar nx = snake.last.x;\n\t\tvar ny = snake.last.y;\n\n\t\t// updating snake position due to direction \n\t\tswitch (snake.direction) {\n\t\t\tcase left:\n\t\t\t\tnx--;\n\t\t\t\tbreak;\n\t\t\tcase up:\n\t\t\t\tny--;\n\t\t\t\tbreak;\n\t\t\tcase right:\n\t\t\t\tnx++;\n\t\t\t\tbreak;\n\t\t\tcase down: \n\t\t\t\tny++;\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// game over conditions \n\t\tif (0 > nx || nx > grid.width-1 || 0 > ny || ny > grid.height-1 || \n\t\t\tgrid.get(nx, ny) === SNAKE) \n\t\t{\n\t\t\treturn initial();\n\t\t} \n\n\t\t// determines when snake overlaps \"apple\" and sets a new position for the \"apple\"\n\t\tif (grid.get(nx, ny) === FRUIT) {\n\t\t\tvar tail = {x:nx, y:ny};\n\t\t\tscore++; // increments score\n\t\t\tsetFood();\n\t\t} else { // removes 1st element (tail) from snake queue \n\t\t\tvar tail = snake.remove();\n\t\t\tgrid.set(EMPTY, tail.x, tail.y);\n\t\t\ttail.x = nx;\n\t\t\ttail.y = ny;\n\t\t}\n\t\t// add the new snake id position to snake queue \n\t\tgrid.set(SNAKE, tail.x, tail.y);\n\t\tsnake.insert(tail.x, tail.y);\n\t}\n}", "function saveBoard() {\n window.localStorage.setItem(\"board\", board.toJSON());\n}", "function movePatient(queue) {\n var newList = []\n if (queue === 'GP') {\n newList = gpQueue;\n newList.push(currPatient)\n setG(newList)\n } else if (queue === 'Specialist') {\n newList = spQueue;\n newList.push(currPatient)\n setSp(newList)\n } else if (queue === 'Surgeon') {\n newList = suQueue;\n newList.push(currPatient)\n setSu(newList) \n }\n setShow('queue');\n setCurrent(null);\n }", "initSnake() {\n\t\tconst {r, c} = this.getRandomEmptyBoardPiece();\n\t\tthis.snake.push({r, c});\n\t}", "function saveState () {\n stack.splice(stackPointer);\n var cs = slots.slice(0);\n var ci =[];\n cs.forEach(function(s) {\n ci.push(s.slice(0));\n });\n stack[stackPointer] = [cs, ci];\n }", "function setBoard(newBoard) {\n board = newBoard;\n boardHistory.push(newBoard);\n}", "function clearQueue(){\n var moveList = document.getElementById(\"moveList\");\n moveQueue = [];\n pastConfigs = [];\n qIndx= 0;\n notSolved = 1;\n moveList.innerHTML = '<h4 class = \"moveCardTitle\">Move List</h4>';\n}", "function submitMoveCommand(move) {\n\n if(move[0].command == 'move'){\n \n if(savedMap[move[0].to.x][move[0].to.y].tile == 'mount' || savedMap[move[0].from.x][move[0].from.y].units < 2){\n\n var badPath = savedMap[move[0].to.x][move[0].to.y];\n var pathIsGood = false;\n\n if(commandStack.length > 0){\n\n while(!pathIsGood && commandStack.length > 0){\n\n if ( isAdjacent( badPath , commandStack[0].to ) ) {\n \n displayElement(savedMap[commandStack[0].to.x][commandStack[0].to.y]);\n\n badPath = savedMap[commandStack[0].to.x][commandStack[0].to.y];\n commandStack.splice(0,1);\n\n deletePath();\n\n } \n \n else \n\n pathIsGood = true;\n\n }\n }\n }\n\n else{\n console.log(move[0]);\n socket.emit('makeMove', move[0]);\n }\n\n }\n else {\n console.log(move[0]);\n socket.emit('makeMove', move[0]);\n }\n\n}", "delete() {\n this.deltaX = 0;\n this.deltaY = +5;\n // if bubble currently on the board, remove it\n if (this.row !== undefined && this.col !== undefined) {\n let row = this.board.pieces[this.row];\n let col = this.col;\n row[col] = null;\n }\n this.falling = true;\n this.collided = false;\n this.canvas.objects.push(this);\n }", "undoMove()\r\n {\r\n game.pastBoards.pop();\r\n let lastAnimation = game.pastAnimations.pop();\r\n\r\n\r\n //Restores board \r\n game.board = game.pastBoards[game.pastBoards.length-1];\r\n \r\n //Retrieves information from last move\r\n let pieceName = lastAnimation[0];\r\n let lastPieceMoved = Number(lastAnimation[0].substring(lastAnimation[0].length-1));\r\n let rowDiff = lastAnimation[2];\r\n let colDiff = lastAnimation[1];\r\n\r\n let time;\r\n\r\n if (colDiff != 0) \r\n time = Math.abs(colDiff);\r\n else\r\n time = Math.abs(rowDiff);\r\n\r\n scene.animationTime = time;\r\n\r\n //Creates inverted animation\r\n scene.graph.components[pieceName].animations[0] = new LinearAnimation(scene, time, [[0,0,0], [-colDiff * scene.movValues[0], 0, -rowDiff * scene.movValues[1]]]);\r\n scene.graph.components[pieceName].currentAnimation = 0;\r\n\r\n //Reverts position change from last move and changes player \r\n if (game.color == 'b') \r\n {\r\n let currentRow = game.whitePositions[lastPieceMoved - 1][0];\r\n let currentCol = game.whitePositions[lastPieceMoved - 1][1];\r\n\r\n game.whitePositions[lastPieceMoved - 1] = [currentRow - rowDiff, currentCol - colDiff];\r\n game.color = 'w';\r\n scene.graph.components['color'].textureId = 'whiteText';\r\n }\r\n \r\n else if (game.color == 'w') \r\n {\r\n let currentRow = game.blackPositions[lastPieceMoved - 1][0];\r\n let currentCol = game.blackPositions[lastPieceMoved - 1][1];\r\n\r\n game.blackPositions[lastPieceMoved - 1] = [currentRow - rowDiff, currentCol - colDiff];\r\n game.color = 'b';\r\n scene.graph.components['color'].textureId = 'blackText';\r\n }\r\n\r\n }", "moveItem(fromStack, toStack, thisMoveCounter){\n toStack.add_item(fromStack.top_item())\n fromStack.remove_item()\n $(toStack.id).prepend($(fromStack.id).children()[0])\n if (thisMoveCounter) {\n $(\"#counter\").text(\"Move Counter: \"+thisMoveCounter)\n }\n else {\n $(\"#counter\").text(\"Move Counter: \"+this.counter)\n this.counter += 1\n }\n $(\"#moves\").prepend(\"<div>\"+toStack.top_item()+\" from \"+fromStack.id+\" to \"+toStack.id+\"</div>\")\n $(fromStack.id).css(\"background-color\", \"white\")\n if (toStack.current_set.length === this.total && toStack !== this.board[0]){\n $(toStack.id).css(\"background-color\", \"lightgreen\")\n }\n else {\n $(toStack.id).css(\"background-color\", \"white\")\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the colors on the stations to the colors stored on the server typially used on startup to retrieve the last stored state of the system
function SyncColorsFromServer(){ for(var i=0;i<STATION_COUNT;i++){ SetColors(i,0,colors[i]); } }
[ "function SetColors(stationId,startIndex,colorArray){\n //update server's copy of the LED custer state\n colors[stationId][ledIndex].r = ledColor.r;\n colors[stationId][ledIndex].g = ledColor.g;\n colors[stationId][ledIndex].b = ledColor.b;\n\n var dataBuffer = new Uint8Array([ledIndex,numToFill,ledColor.r,ledColor.g,ledColor.b]);\n io.sockets.to(stationId).emit('setColors',dataBuffer);\n}", "function SetStrip(stationId,colorArray){\n\n}", "function SetColor(stationId,startIndex,ledColor){\n if(!isNaN(stationId)){\n //update server's copy of the LED custer state\n colors[stationId][startIndex].r = ledColor.r;\n colors[stationId][startIndex].g = ledColor.g;\n colors[stationId][startIndex].b = ledColor.b;\n }\n\n var dataBuffer = new Uint8Array([startIndex,ledColor.r,ledColor.g,ledColor.b]);\n io.sockets.to(stationId).emit('setColor',dataBuffer);\n}", "function set_swatch_colour(new_colour) {\n chrome.storage.sync.set({\n 'daysago_swatch': new_colour\n }, function() {\n start_colour = new_colour;\n trigger_draw_grid();\n });\n}", "function get_swatch_colour() {\n chrome.storage.sync.get('daysago_swatch', function(item) {\n start_colour = item.daysago_swatch;\n trigger_draw_grid()\n });\n}", "function initColorDatabase()\n{\n this.colors = new Array(\"#F8F4FF\", \"#F3E5AB\", \" #FAEBD7\", \"#E52B50 \", \"#960018\", \"#FE28A2\", \"#FF6FFF\", \"#FF69B4\", \"#FBAED2\", \"#F88379\", \"#A52A2A\", \"#C41E3A\", \"#C71585\", \"#B2\n2222\", \"#E25822\", \"#AB4E52\", \"#800000\", \"#FF2400\", \"#722F37\", \"#E0115F\", \"#FF004F\", \"#915C83\", \"#65000B\", \" \", \"#66FF00\", \"#228b22\", \"#808000\", \" #00A693\", \"#808080\", \"#B2BEB5\", \"#4\n83C32\");\n\n this.pickedColor = new Array();\n\n for (var i=0; i < this.colors.length; i++) {\n this.pickedColor[i] = 0;\n }\n}", "ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }", "setRedLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet currentGreenLights = this.config.getDirections()[this.getDirectionIndex()];\n\n // Loop through the greenLights and set the rest to red lights\n\t\tfor (let direction in this.trafficLights) {\n\t\t\tlet elementId = this.trafficLights[direction].name;\n\t\t\tif (currentGreenLights.indexOf(elementId) >= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.trafficLights[direction].color = TRAFFIC_LIGHT_RED;\n\t\t}\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}", "setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}", "function loadSurfaceColor () {\n\n setShaderColor( controller.configure.color.surface );\n\n if ( controller.configure.color.selected === null ) {\n\n setHighlightColor( controller.configure.color.surface );\n\t\t\tconsole.log('highlight color===========>', controller.configure.color.surface)\n } else {\n\n setHighlightColor( controller.configure.color.selected );\n\n }\n\n }", "setGreenLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_GREEN;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}", "function setupColorMap() {\n var c3=colorbrewer.Dark2[8];\n var c1=colorbrewer.Set1[8];\n var c2=colorbrewer.Paired[8];\n colorMap.push('#1347AE'); // the default blue\n for( var i=0; i<8; i++) {\n colorMap.push(c1[i]);\n }\n for( var i=0; i<8; i++) {\n colorMap.push(c2[i]);\n }\n for( var i=0; i<8; i++) {\n colorMap.push(c3[i]);\n }\n}", "function updateCurrentPalette() {\n updatePaletteColorBar();\n const key = getCurrentPaletteKey();\n $.getJSON('/setpalette', {\n key: key, value: JSON.stringify(palettes[key])\n }, () => { });\n}", "function newColor() {\n //get random color RGB components\n color.red = Math.floor(Math.random()*255);\n color.blue = Math.floor(Math.random()*255);\n color.green = Math.floor(Math.random()*255);\n\n // Prepare the guess colors in CSS RGB format for applying to the div\n var color_string = 'rgb(' + color.red + ',' +\n color.green + ',' +\n color.blue + ')';\n\n // Apply the new color to the #color div.\n $('#color').css('background', color_string);\n\n // Log the current time in milliseconds, used in score calculations\n time_at_load = Date.now();\n }", "function colorChanged(){\n\tsetGradientColor(lastDirection , rgbString(color1.value) , rgbString(color2.value) , true);\n}", "function setallcolorfunction(){\r\n\t\t\tfinalcolor = allcolorfunction;\r\n\t\t}", "function FillSolid(stationId,startIndex,numToFill,ledColor){\n if(!isNaN(stationId)){\n //update server's copy of the LED cluster state\n for(var i=startIndex;i<startIndex+numToFill;i++){\n colors[stationId][i].r = ledColor.r;\n colors[stationId][i].g = ledColor.g;\n colors[stationId][i].b = ledColor.b;\n }\n }\n //console.log(ledColor);\n var dataBuffer = new Uint8Array([startIndex,numToFill,ledColor.r,ledColor.g,ledColor.b]);\n io.sockets.to(stationId).emit('fillSolid',base64js.fromByteArray(dataBuffer));\n}", "function setColor() {\n for(let i = 0; i < boxes.length; i++) {\n boxes[i].style.backgroundColor = color[i];\n } \n}", "_colorUpdate() {\n if(this.value){\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': this.value,\n '--l2t-paper-color-indicator-icon-display': 'block',\n });\n } else {\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': 'transparent',\n '--l2t-paper-color-indicator-icon-display': 'none',\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the Sauce Labs endpoint
function getSauceEndpoint(region) { const shortRegion = REGION_MAPPING[region] ? region : 'us'; return `https://app.${REGION_MAPPING[shortRegion]}saucelabs.com/tests/`; }
[ "apiUrl() {\n const url = this.globalConfigService.getData().apiUrl;\n return url || Remote_1.RemoteConfig.uri;\n }", "baseURL () {\n return config.api.baseUrl;\n }", "getUrl() {\n return process.env.ENVIRONMENT === \"DEV\" ? \"http://localhost:3001\" : \"prod\";\n }", "function getEndPoint() {\n let random = Math.floor(Math.random() * httpEndPoints.length);\n return httpEndPoints[random];\n}", "function serviceURL(svc){\n return getEndpointURL('/service.php'+svc); \n}", "function startSauce() {\n console.log( 'Local server listening to', STATIC_SERVER_PORT );\n console.log( 'Sauce Connect ready.' );\n const opts = {\n url: `https://${ SAUCE_LABS_USERNAME }:${ SAUCE_LABS_ACCESS_KEY }@saucelabs.com/rest/v1/cct-sauce/js-tests`,\n method: 'POST',\n json: {\n platforms: [\n [ 'Windows 7', 'internet explorer', '11' ],\n [ 'Windows 7', 'firefox', '27' ]\n ],\n url: 'http://localhost:' + STATIC_SERVER_PORT + '/?ci_environment=' + NODE_ENV,\n framework: 'custom',\n name: testName\n }\n };\n request.post( opts, function( reqErr, httpResponse, body ) {\n if ( reqErr ) {\n console.error( 'An error occurred:', reqErr );\n }\n console.log( 'Tests started.' );\n sauceTests = body['js tests'];\n checkSauce();\n } );\n}", "function getManagementAPIServerBaseUrl() {\n\n // todo: implementation will change after changes are done to the IS.\n\n const baseOrganizationUrl = config.AuthorizationConfig.BaseOrganizationUrl;\n const matches = baseOrganizationUrl.match(/^(http|https)?\\:\\/\\/([^\\/?#]+)/i);\n const domain = matches && matches[0];\n\n return domain;\n}", "function get_url(){\n return this.state.api_url;\n}", "function detectBackend(options = {}) {\n var _a, _b;\n let { port, hostname, user, key, protocol, region, headless, path, capabilities } = options;\n /**\n * browserstack\n * e.g. zHcv9sZ39ip8ZPsxBVJ2\n */\n if (typeof user === 'string' && typeof key === 'string' && key.length === 20) {\n return {\n protocol: protocol || 'https',\n hostname: hostname || 'hub-cloud.browserstack.com',\n port: port || 443,\n path: path || LEGACY_PATH\n };\n }\n /**\n * testingbot\n * e.g. ec337d7b677720a4dde7bd72be0bfc67\n */\n if (typeof user === 'string' && typeof key === 'string' && key.length === 32) {\n return {\n protocol: protocol || 'https',\n hostname: hostname || 'hub.testingbot.com',\n port: port || 443,\n path: path || LEGACY_PATH\n };\n }\n /**\n * Sauce Labs\n * e.g. 50aa152c-1932-B2f0-9707-18z46q2n1mb0\n *\n * For Sauce Labs Legacy RDC we only need to determine if the sauce option has a `testobject_api_key`.\n * Same for Sauce Visual where an apiKey can be passed in through the capabilities (soon to be legacy too).\n */\n const isRDC = Boolean(!Array.isArray(capabilities) && ((_a = capabilities) === null || _a === void 0 ? void 0 : _a.testobject_api_key));\n const isVisual = Boolean(!Array.isArray(capabilities) && capabilities && ((_b = capabilities['sauce:visual']) === null || _b === void 0 ? void 0 : _b.apiKey));\n if ((typeof user === 'string' && typeof key === 'string' && key.length === 36) ||\n // Or only RDC or visual\n (isRDC || isVisual)) {\n // Sauce headless is currently only in us-east-1\n const sauceRegion = headless ? 'us-east-1' : region;\n return {\n protocol: protocol || 'https',\n hostname: hostname || getSauceEndpoint(sauceRegion, { isRDC, isVisual }),\n port: port || 443,\n path: path || LEGACY_PATH\n };\n }\n if (\n /**\n * user and key are set in config\n */\n (typeof user === 'string' || typeof key === 'string') &&\n /**\n * but no custom WebDriver endpoint was configured\n */\n !hostname) {\n throw new Error('A \"user\" or \"key\" was provided but could not be connected to a ' +\n 'known cloud service (Sauce Labs, Browerstack or Testingbot). ' +\n 'Please check if given user and key properties are correct!');\n }\n /**\n * default values if on of the WebDriver criticial options is set\n */\n if (hostname || port || protocol || path) {\n return {\n hostname: hostname || DEFAULT_HOSTNAME,\n port: port || DEFAULT_PORT,\n protocol: protocol || DEFAULT_PROTOCOL,\n path: path || DEFAULT_PATH\n };\n }\n /**\n * no cloud provider detected, pass on provided params and eventually\n * fallback to DevTools protocol\n */\n return { hostname, port, protocol, path };\n}", "function _getWebIDEUrl () {\n var DEF_WEBIDE_HOST = \"https://dicidev-xg98ih1clz.dispatcher.int.sap.hana.ondemand.com\";\n var webIDEHost = process.env.host ? process.env.host : DEF_WEBIDE_HOST\n var wingParam = process.env.wing ? \"&sap-ide-toggles-wing=true\" : \"\";\n webIDEHost= webIDEHost + \"?settings=delete&test=selenium\" + wingParam;\n return webIDEHost;\n}", "getServiceBaseHostURL() {\n let routeInfo = this.store.peekRecord('nges-core/engine-route-information', 1);\n\n //if(!routeInfo) routeInfo = this.store.peekRecord('nges-core/engine-route-information', 2);\n let hostUrl = 'http://' + routeInfo.appCode + '.' + routeInfo.appModuleCode + config.NGES_SERVICE_HOSTS.APP_SERVICE_POST_HOST;\n return hostUrl;\n }", "function getPort () {\n if (process.env.PORT) {\n return process.env.PORT\n }\n const u = new url.URL(process.env.SVC_BASE_URI)\n if (u.port) {\n return u.port\n }\n if (u.protocol === 'https:') {\n return '443'\n } else if (u.protocol === 'http:') {\n return '80'\n }\n throw new Error('protocol must be http: or https:')\n}", "function getAPIURL() {\n return (\n `${baseRemoteURL}?${jQuery('#filters :input[value!=\\'all\\']').serialize()}`\n );\n}", "async function connect() {\n\tlet endpoint = document.getElementById('endpoint').value;\n\tif (!window.substrate || global.endpoint != endpoint) {\n\t\tconst provider = new WsProvider(endpoint);\n\t\tdocument.getElementById('output').innerHTML = 'Connecting to Endpoint...';\n\t\twindow.substrate = await ApiPromise.create({ provider });\n\t\tglobal.endpoint = endpoint;\n\t\tdocument.getElementById('output').innerHTML = 'Connected';\n\t\tclearIndices();\n\t}\n}", "async function getConnection() {\n const url = DEV_NET;\n const connection = new solana.Connection(url, \"recent\");\n const version = await connection.getVersion();\n console.log(\"Connection to Cluster established: \", url, version);\n return connection;\n}", "function get_started_url() {\n\n //\n // Return a constant\n //\n return COMMONCRAWL_GET_STARTED;\n\n}", "function getURL(port) {\n return 'http://localhost:' + port +\n '/extensions/platform_apps/web_view/storage_persistence/guest.html';\n}", "async getAuthUrl() {\n\t\t\tthrow new Error('This function must be overridden!');\n\t\t}", "get url() {\n return this._serverRequest.url;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activates and deactivates listeners depending on if the component is `enabled`
_switch() { let enabled = this.get('enabled'); if (enabled) { this.activateListeners(); } else { this.deactivateListeners(); } }
[ "_toggleRecognizer(name, enabled) {\n const {\n manager\n } = this;\n\n if (!manager) {\n return;\n }\n\n const recognizer = manager.get(name); // @ts-ignore\n\n if (recognizer && recognizer.options.enable !== enabled) {\n recognizer.set({\n enable: enabled\n });\n const fallbackRecognizers = _constants__WEBPACK_IMPORTED_MODULE_6__[\"RECOGNIZER_FALLBACK_MAP\"][name];\n\n if (fallbackRecognizers && !this.options.recognizers) {\n // Set default require failures\n // http://hammerjs.github.io/require-failure/\n fallbackRecognizers.forEach(otherName => {\n const otherRecognizer = manager.get(otherName);\n\n if (enabled) {\n // Wait for this recognizer to fail\n otherRecognizer.requireFailure(name);\n /**\n * This seems to be a bug in hammerjs:\n * requireFailure() adds both ways\n * dropRequireFailure() only drops one way\n * https://github.com/hammerjs/hammer.js/blob/master/src/recognizerjs/\n recognizer-constructor.js#L136\n */\n\n recognizer.dropRequireFailure(otherName);\n } else {\n // Do not wait for this recognizer to fail\n otherRecognizer.dropRequireFailure(name);\n }\n });\n }\n }\n\n this.wheelInput.enableEventType(name, enabled);\n this.moveInput.enableEventType(name, enabled);\n this.keyInput.enableEventType(name, enabled);\n this.contextmenuInput.enableEventType(name, enabled);\n }", "enableLog() {\n this.enabled = logCfg.enable;\n }", "function OnEnable () { \n gameObject.transform.root.gameObject.GetComponent(FPSInputController).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(MouseLook).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(CharacterMotor).enabled = false;\n transform.root.FindChild(playerCameraPrefab).gameObject.SetActive(false);\n \n}", "function nfcListen(enabled) {\n\t\tif (enabled) {\n\t\t\tnfc.ontagfound = function(event) {\n\t\t\t\treadOnAttach(event.tag);\n\t\t\t};\n\t\t\tnfc.ontaglost = function(event) {\n\t\t\t\toutLog.innerHTML += \"<br><b>Tag detached</b><hr>\";\n\t\t\t};\n\t\t\tnfc.onpeerfound = function(event) {\n\t\t\t\tpeerOnAttach(event.peer);\n\t\t\t};\n\t\t\tnfc.onpeerlost = function(event) {\n\t\t\t\toutLog.innerHTML += \"<br><b>Peer detached</b><hr>\";\n\t\t\t};\n\t\t\tnfc.startPoll().then(function() {\n\t\t\t\toutLog.innerHTML += \"<hr><b>Tag / Peer read listeners registered</b><hr>\";\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tnfc.ontagfound = null;\n\t\t\tnfc.ontaglost = null;\n\t\t\tnfc.onpeerfound = null;\n\t\t\tnfc.onpeerlost = null;\n\t\t\tnfc.stopPoll().then(function() {\n\t\t\t\toutLog.innerHTML += \"<hr><b>Tag / Peer read listeners removed</b><hr>\";\n\t\t\t});\n\t\t}\n\t}", "onModeChange(listener) {\n this.modeChangeListeners.push(listener);\n }", "get isListening() {\n return this.listeners.length > 0;\n }", "function addModeSwitchListeners() {\n document.getElementById('index-hide-btn').addEventListener('click' ,function(event) {\n focusModeWrapper();\n });\n\n document.getElementById('index-show-btn').addEventListener('click' ,function(event) {\n browseModeWrapper();\n });\n}", "onBluetoothDisabled(listener) {\n return this.createBluetoothEventSubscription(BluetoothEventType.BLUETOOTH_DISABLED, listener);\n }", "function activeateAll (event) {\n let allClass = document.querySelectorAll('.power')\n for (let i=0; i<allClass.length; i++){\n if (allClass[i].classList.contains('disabled'))\n allClass[i].classList.remove('disabled')\n allClass[i].classList.add('enabled')\n }\n}", "enable() {\n BluetoothSerial.enable()\n .then(res => {\n this.initializeBluetooth();\n BluetoothActions.setIsEnabled(true);\n })\n .catch(err => console.log(err.message));\n }", "enable(emitterID) {\n // sanity check\n if (!this.check(emitterID)) {\n return;\n }\n let pkg = this.emitters.get(emitterID);\n if (pkg.emitter.emit) {\n // console.warn('Emitter \"' + emitterID + '\" is already enabled');\n return;\n }\n pkg.emitter.emit = true;\n }", "function isEnabled() {\n return tray != undefined;\n}", "function changeScheduleButtons(enabled) {\r\n if (enabled) {\r\n jQuery('#schedule_edit').button('enable');\r\n jQuery('#schedule_remove').button('enable');\r\n jQuery('#schedule_add').button('enable');\r\n jQuery('#schedule_embed').button('enable');\r\n } else {\r\n jQuery('#schedule_edit').button('disable');\r\n jQuery('#schedule_remove').button('disable');\r\n jQuery('#schedule_add').button('disable');\r\n jQuery('#schedule_embed').button('disable');\r\n }\r\n}", "isInterfaceEnabled( iface ){\n if( INTERFACES_ENABLED.indexOf( iface ) === -1 ) return false;\n else return true;\n }", "function passiveModeCrossChecksEnablerListener() {\n var checkboxPassiveCrossChecks = document.getElementById(\"checkboxPassiveCrossChecks\");\n // Get the setting if it has already been set\n chrome.storage.local.get(function(storage) {\n var settings = storage[\"settings\"];\n if (!settings) {\n settings = initialSettings;\n }\n chrome.storage.local.set({ \"settings\": settings });\n\n var passiveModeEnabled = storage[\"enablePassiveMode\"];\n var passiveModeCrossChecksEnabled = settings[\"passiveModeCrossChecks\"];\n var passiveModeWindowSize = document.getElementById(\"passiveModeWindowSize\");\n if (passiveModeEnabled) {\n checkboxPassiveCrossChecks.disabled = false;\n checkboxPassiveCrossChecks.checked = passiveModeCrossChecksEnabled;\n } else {\n checkboxPassiveCrossChecks.disabled = true;\n }\n if (passiveModeEnabled && passiveModeCrossChecksEnabled) {\n passiveModeWindowSize.disabled = false;\n } else {\n passiveModeWindowSize.disabled = true;\n }\n });\n\n var passiveCrossChecksEnabled = document.getElementById(\"passiveCrossChecksEnabled\");\n passiveCrossChecksEnabled.addEventListener(\"click\", function() {\n togglePassiveCrossChecks();\n });\n}", "onDisabled() {\n this.updateInvalid();\n }", "_onDetachEnabled( event) {\n this.detached = true;\n if( event.cancellable) { event.stopPropagation(); }\n }", "setEventListeners() {\n this.on('edit',this.onEdit.bind(this));\n this.on('panelObjectAdded',this.onPanelObjectAdded.bind(this));\n this.on('panelObjectRemoved',this.onPanelObjectRemoved.bind(this));\n }", "function enableButtons()\n{\n\tg_Options[g_TabCategorySelected].options.forEach((option, i) => {\n\n\t\tlet enabled =\n\t\t\t!option.dependencies ||\n\t\t\toption.dependencies.every(config => Engine.ConfigDB_GetValue(\"user\", config) == \"true\");\n\n\t\tEngine.GetGUIObjectByName(\"option_label[\" + i + \"]\").enabled = enabled;\n\t\tEngine.GetGUIObjectByName(\"option_control_\" + option.type + \"[\" + i + \"]\").enabled = enabled;\n\t});\n\n\tlet hasChanges = Engine.ConfigDB_HasChanges(\"user\");\n\tEngine.GetGUIObjectByName(\"revertChanges\").enabled = hasChanges;\n\tEngine.GetGUIObjectByName(\"saveChanges\").enabled = hasChanges;\n}", "function setupDisabledCheck(controlName, disableCompId, disableCompType, condition, onKeyUp) {\n var theControl = jQuery(\"[name='\" + escapeName(controlName) + \"']\");\n var eventType = 'change';\n\n if (onKeyUp && (theControl.is(\"textarea\") || theControl.is(\"input[type='text'], input[type='password']\"))) {\n eventType = 'keyup';\n }\n\n if (disableCompType == \"radioGroup\" || disableCompType == \"checkboxGroup\") {\n theControl.on(eventType, function () {\n if (condition()) {\n jQuery(\"input[id^='\" + disableCompId + \"']\").prop(\"disabled\", true);\n }\n else {\n jQuery(\"input[id^='\" + disableCompId + \"']\").prop(\"disabled\", false);\n }\n });\n }\n else {\n theControl.on(eventType, function () {\n var disableControl = jQuery(\"#\" + disableCompId);\n if (condition()) {\n disableControl.prop(\"disabled\", true);\n disableControl.addClass(\"disabled\");\n if (disableCompType === \"actionLink\" || disableCompType === \"action\") {\n disableControl.attr(\"tabIndex\", \"-1\");\n }\n }\n else {\n disableControl.prop(\"disabled\", false);\n disableControl.removeClass(\"disabled\");\n if (disableCompType === \"actionLink\" || disableCompType === \"action\") {\n disableControl.attr(\"tabIndex\", \"0\");\n }\n }\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines wheter tileArr1 and tileArr2 have identical endpoints computes the intersection of tileArr1 and tileArr2
hasIdenticalEndPoints(tileArr1,tileArr2){ return (tileArr1.filter(endPoint=>{ return tileArr2.indexOf(endPoint)!=-1; }).length>0); }
[ "tilesAreEqual(tile1, tile2) {\n return tile1 && tile2 && tile1.x == tile2.x && tile1.y == tile2.y;\n }", "function cullIntersections() {\n function toLines(pts) {\n let lns = [];\n for (let i=0, il=pts.length; i<il; i += 2) {\n lns.push({a: pts[i], b: pts[i+1], l: pts[i].distTo2D(pts[i+1])});\n }\n return lns;\n }\n let aOa = [...arguments].filter(t => t);\n if (aOa.length < 1) return;\n let aa = toLines(aOa.shift());\n while (aOa.length) {\n let bb = toLines(aOa.shift());\n loop: for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n if (al.del) {\n continue;\n }\n for (let j=0, jl=bb.length; j<jl; j++) {\n let bl = bb[j];\n if (bl.del) {\n continue;\n }\n if (base.util.intersect(al.a, al.b, bl.a, bl.b, base.key.SEGINT)) {\n if (al.l < bl.l) {\n bl.del = true;\n } else {\n al.del = true;\n }\n continue;\n }\n }\n }\n aa = aa.filter(l => !l.del).concat(bb.filter(l => !l.del));\n }\n let good = [];\n for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n good.push(al.a);\n good.push(al.b);\n }\n return good.length > 2 ? good : [];\n}", "function intersection(pos1, vec1, pos2, vec2){\n //This function is based on this math:\n //https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n // pos1 == p\n // vec1 == r\n // pos2 == q\n // vec2 == s\n\n let denom = crossProduct(vec1, vec2); //(r × s)\n let num1 = crossProduct(subVectors(pos2, pos1) , vec2); //(q − p) × s\n let num2 = crossProduct(subVectors(pos2, pos1) , vec1); //(q − p) × r\n\n if(denom == 0) //don't really care if they're parallel for my purposes.\n return null;\n\n let t = num1 / denom;\n let u = num2 / denom;\n\n if(t > 0 && t < 1 && u > 0 && u < 1) {\n let offset = new Vector(vec1.x, vec1.y);\n multVector(offset, t);\n return addVectors(pos1, offset);\n }\n\n return null;\n}", "function intersectSchedules(schedule1, schedule2) {\n var res = [];\n \n schedule1.forEach(r1 => {\n schedule2.forEach(r2 => {\n var intersection = findIntersection(r1, r2);\n \n if (intersection) {\n res.push(intersection);\n }\n });\n });\n \n return res;\n }", "function intersection(nums1, nums2){\n\tlet obj = {};\n\tlet arr1, arr2\n\n\tif( nums1.length < nums2.length ){\n\t\tarr1 = nums1\n\t\tarr2 = nums2\n\t} else {\n\t\tarr1 = nums2 \n\t\tarr2 = nums1\n\t};\n\n\tlet result = []\n\tlet count = arr1.length;\n\n\tfor ( let i = 0 ; i < arr1.length ; i ++ ){\n\t\tobj[arr1[i]] = obj[arr1[i]] || 0;\n\t\tobj[arr1[i]]++\n\t}\n\n\tfor ( let j = 0 ; j < arr2.length && count !== 0 ; j ++ ){\n\t\tif ( obj[arr2[j]] > 0 ){\n\t\t\tobj[arr2[j]] --;\n\t\t\tcount --;\n\t\t\tresult.push(arr2[j]);\n\t\t}\n\t}\n\treturn result\n}", "function intersection(set1, set2) {} // → set", "function isMatching(first, second){\n if(tileColor[first] == tileColor[second]){\n return true;\n }\n else{\n return false;\n }\n}", "getAdjacent(tile) {\n\t\t\n\t\tconst index = tile.getIndex();\n\t\t\n\t\tconst col = index % this.width;\n\t\tconst row = Math.floor(index / this.width);\n\n\t\tconst first_row = Math.max(0, row - 1);\n\t\tconst last_row = Math.min(this.height - 1, row + 1);\n\n\t\tconst first_col = Math.max(0, col - 1);\n\t\tconst last_col = Math.min(this.width - 1, col + 1);\n\n\t\tconst result = []\n\n\t\tfor (let r = first_row; r <= last_row; r++) {\n\t\t\tfor (let c = first_col; c <= last_col; c++) {\n\t\t\t\tconst i = this.width * r + c;\n\t\t\t\tif (i != index) {\n\t\t\t\t\tresult.push(this.tiles[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}", "function intersect_primitive_primitive (buffer1, buffer2) {\n\tfor (var i = 0; i < buffer1.length; i += 3)\n\t{\n\t\tfor (var j = 0; j < buffer2.length; j += 3)\n\t\t{\n\t\t\tif ( intersect_triangle_triangle(buffer1[i], buffer1[i+1], buffer1[i+2], buffer2[j], buffer2[j+1], buffer2[j+2]) )\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "areDiagonallyAdjacent(tile1, tile2) {\r\n // Dos tiles son diagonalmente adyacentes si están separados por una distancia de una\r\n // unidad en ambos ejes. Si la distancia en cualquiera de los ejes fuera 0 ya no sería\r\n // una adyacencia diagonal, y si la distancia fuera más de 1 ya no sería una adyacencia.\r\n return Math.abs(tile1.x - tile2.x) == 1 && Math.abs(tile1.y - tile2.y) == 1;\r\n }", "millPathHasIntersection(millPath, i) {\n return (millPath[0] === i || millPath[1] === i || millPath[2] === i);\n }", "static get_outers_and_intersect_latLngs(way1, way2) {\n function latLng_eq(p1, p2) {\n return (p1[0] == p2[0]) && (p1[1] == p2[1])\n }\n\n function is_closed(way) {\n return latLng_eq(way[0], way[way.length - 1]);\n }\n\n if (!(is_closed(way1) && is_closed(way2))) {\n throw new GeometryError(\"not closed polygons\");\n }\n way1 = way1.slice(1);\n way2 = way2.slice(1);\n if (way1.length < way2.length) {\n let w = way1;\n way1 = way2;\n way2 = w;\n }\n const length1 = way1.length;\n const length2 = way2.length\n\n // rotate way1 so that it starts with a point not common with way2:\n let i1 = way1.findIndex(p1 => way2.findIndex(p2 => latLng_eq(p1, p2)) < 0);\n if (i1 == -1) {\n throw new GeometryError(\"no distincts points\");\n }\n way1 = way1.slice(i1, length1).concat(way1.slice(0, i1));\n\n // get the intersection points (the points common to the two ways)\n const intersect = way1.filter(p1 => way2.findIndex(p2 => latLng_eq(p1, p2)) >= 0);\n\n // rotate way1 so that it starts with the first intersecting point:\n i1 = way1.findIndex(p1 => latLng_eq(p1, intersect[0]));\n if (i1 == -1) {\n throw new GeometryError(\"no common points\");\n }\n way1 = way1.slice(i1, length1).concat(way1.slice(0, i1));\n\n // get the outer part of way1\n const outer1 = way1.filter(p1 => intersect.findIndex(p2 => latLng_eq(p1, p2)) < 0);\n\n\n // rotate and reverse way2 so that it starts with the first intersecting point:\n let i2 = way2.findIndex(p2 => latLng_eq(intersect[0], p2));\n if (latLng_eq(way2[(i2 + 1) % length2], intersect[1])) {\n way2.reverse();\n i2 = length2 - 1 - i2;\n }\n way2 = way2.slice(i2, length2).concat(way2.slice(0, i2));\n\n // get the outer part of way2\n const outer2 = way2.filter(p2 => intersect.findIndex(p1 => latLng_eq(p1, p2)) < 0)\n\n // join outer1 and outer2 \n //const joined = [intersect[intersect.length-1]].concat(outer1).concat([intersect[0]]).concat(outer2).concat([intersect[intersect.length-1]]);\n\n const full_outer1 = intersect.slice(-1).concat(outer1).concat(intersect.slice(0, 1));\n const full_outer2 = intersect.slice(0, 1).concat(outer2).concat(intersect.slice(-1));\n\n return [full_outer1, full_outer2, intersect];\n }", "collides(vertices1, axes1, vertices2, axes2, out) {\n projectMinMaxMany(vertices1, axes1, axes2, this.cacheRanges1);\n projectMinMaxMany(vertices2, axes1, axes2, this.cacheRanges2);\n let comparisons = axes1.length + axes2.length;\n let smOverlap = Infinity;\n let smOverlapIdx = -1;\n let smDir = -1;\n for (let i = 0; i < comparisons; i++) {\n let p = this.cacheRanges1[i];\n let q = this.cacheRanges2[i];\n // case 1: OK\n //\t p.x\t\tp.y\t Q.x\t\t Q.y\n // ---+==========+-----+===========+--------\n //\n // case 2: OK\n //\t Q.x\t\tQ.y\t p.x\t\t p.y\n // ---+==========+-----+===========+--------\n //\n // case 3: COLLIDING\n //\t p.x\t\tQ.x\t p.y\t\t Q.y\n // ---+==========+=====+===========+--------\n //\n // case 4: COLLIDING\n //\t Q.x\t\tp.x\t Q.y\t\t p.y\n // ---+==========+=====+===========+--------\n if (p.y < q.x || q.y < p.x) {\n // non-overlap on any axis means safe\n return false;\n }\n // overlap on this axis. track it + direction in case we have\n // a collision and this is the axis w/ smallest amt.\n let diff1 = p.y - q.x;\n let diff2 = q.y - p.x;\n let overlap, direction;\n if (diff1 < diff2) {\n overlap = diff1;\n direction = 1;\n }\n else {\n overlap = diff2;\n direction = -1;\n }\n if (overlap < smOverlap) {\n smOverlap = overlap;\n smOverlapIdx = i;\n smDir = direction;\n }\n }\n // set collision info w/ smallest (kinda gross b/c two arrays...)\n let smAxis = smOverlapIdx < axes1.length ? axes1[smOverlapIdx] : axes2[smOverlapIdx - axes1.length];\n out.axis.copyFrom_(smAxis);\n out.amount = smOverlap * smDir;\n // and return that we did collide\n return true;\n }", "function sharedEdge(a, b) {\n\t var x,\n\t y,\n\t n = a.length,\n\t found = null;\n\t for (var i = 0; i < n; ++i) {\n\t x = a[i];\n\t for (var j = b.length; --j >= 0;) {\n\t y = b[j];\n\t if (x[0] === y[0] && x[1] === y[1]) {\n\t if (found) return [found, x];\n\t found = x;\n\t }\n\t }\n\t }\n\t}", "function checkAdjacentTiles(x1, y1) {\n if((x1>=0)&&(y1>=0)&&(x1<columns)&&(y1<rows)) //Verify if coordinates do not fall outside of the gridMatrix.\n return gridMatrix[x1+y1*columns];\n}", "function isSubset(arr1, arr2, arr1L, arr2L) {\n // define i & j before looping through the arrays\n // this is needed to check if the loop was not broken\n let i = 0\n let j = 0\n // loop through the first array\n for (i = 0; i < arr2L; i++) {\n //loop through the second array with a nested loop\n for (j = 0; j < arr1L; j++)\n // check to see if all elements from arr2 === those from arr1\n if (arr2[i] === arr1[j])\n // if these do match, break the loop\n break;\n // if the inner loop was not broken (because arr2[i] isn't in arr1)\n // then return false \n if (j === arr1L)\n return false\n }\n // if the inner loop was broken, then all elements in arr2 are \n // present in arr1\n return true\n }", "intersection () {\n var tan = this.vector.y / this.vector.x,\n _this = this,\n from, to,\n cursorDegree = -Math.atan2(-this.vector.y, -this.vector.x) * 180/Math.PI + 180;\n\n\n for (var i= 0, max = this.cache.length; i < max; i++) {\n var item = _this.cache[i];\n\n from = item.range[0];\n to = item.range[1];\n\n // If one of item's sides area is on the edge state. For example\n // when we have item which 'from' begins from 157 and ends to -157, when all\n // 'cursorDegree' values are appear hear. To not let this happen, we compare\n // 'from' and 'to' and reverse comparing operations.\n if (from > to) {\n if (cursorDegree <= from && cursorDegree <= to || cursorDegree >= from && cursorDegree >= to) {\n _this.activate(item);\n }\n } else {\n if (cursorDegree >= from && cursorDegree <= to) {\n _this.activate(item);\n }\n }\n }\n this.cache.forEach(function (item) {\n\n })\n }", "getIntersection(vectors) {\n if (vectors.length > 1) {\n var isect = vectors.slice(1).reduce((isect, tsls) => arrayutils_1.intersectSortedArrays(isect, tsls), vectors[0]);\n //console.log(JSON.stringify(points), JSON.stringify(isect));\n return isect;\n }\n return vectors[0];\n }", "function isSubset(array1, array2){\n\tfor (var j = 1 ; j < array2.length ; j++){\n\tfor (var i =0 ; i < array1.length ; i++){\n\t\tif(array2[0] === array1[i] && array2[j] === array1[i+1] && array1.length > array2.length){\n\t\t}\n return true;\n\t\t}\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort rank array in descending order and keep rank array at length of 10.
function ranking() { rank.sort(function(a, b) { return b[1] - a[1]; }); rank.splice(10, rank.length - 10); }
[ "function sortMoviesByRank ( movies ) {\n// Code from previous sortBestRatingsFirst() function\n for ( let j = 0; j < movies.length - 1; j ++ ) {\n \n let max_obj = movies[ j ];\n let max_location = j;\n \n for ( let i = j; i < movies.length; i ++ ) {\n if ( movies[ i ].rank > max_obj.rank ) {\n // Know max AND it's index (location)\n //if we found object with higher rank, then\n // replace max_obj with the new object\n max_obj = movies[ i ];\n max_location = i;\n }\n }\n // swap the first and the last\n movies[ max_location ] = movies[ j ]; // --> 10\n movies[ j ] = max_obj;\n }\n \n return movies;\n}", "function radixSort(arr){\n var maxDigitCountInArray = maxDigitCount(arr);\n //creating 10 buckets from 0 to 9 as empty arrays for once place 10's place form 0 to 9\n \n for(var k =0; k < maxDigitCountInArray; k++){\n var digitBucket = Array.from({length:10}, () => [])\n //loop for maxDigitCountInArray\n for(var i =0; i < arr.length; i++){\n digitBucket[getDigit(arr[i],k)].push(arr[i])\n }\n arr = [].concat(...digitBucket);\n }\n return arr;\n}", "function sortByRankHandler(){\n // table.classList.remove('data');\n\n // take isolated copy keep the refernce safe\n let sortedByRank = myData.slice();\n sortedByRank.sort(function(a , b){\n return a.rank - b.rank;\n \n \n });\n display.innerHTML = ``;\n\n\n for (let index = 0; index < sortedByRank.length; index++) {\n // '+=' : means adding extra elements , while '=': means replace\n display.innerHTML +=`<tr>\n <td>${index+1}</td>\n <td>${sortedByRank[index].name}</td>\n <td>${sortedByRank[index].type}</td>\n <td>${sortedByRank[index].rank}</td>\n </tr>\n `;\n }\n console.table(sortedByRank);\n }", "function calcularRanking(nuevoPuntaje) {\n var lsRanking = localStorage.getItem(lsRankingKey);\n var ranking = [];\n if (lsRanking != null) {\n ranking = JSON.parse(lsRanking); \n }\n ranking.push(nuevoPuntaje);\n ranking.sort(function(intentosA,intentosB){\n return intentosA.intentos - intentosB.intentos;\n })\n ranking = ranking.slice(0,5);\n localStorage.setItem(lsRankingKey, JSON.stringify(ranking));\n console.log(ranking);\n return ranking; \n}", "function radixSort(arr) {\n let loopCount = mostDigits(arr);\n\n for (let i = 0; i < loopCount; i++) {\n let buckets = Array.from({ length: 10 }, () => []);\n for (let j = 0; j < arr.length; j++) {\n buckets[getDigit(arr[j], i)].push(arr[j]);\n }\n \n arr = [].concat(...buckets);\n }\n\n return arr;\n}", "function sortByLength(inputArray) {\n\treturn inputArray.sort((a, b) => a.length - b.length);\n}", "function top(array, compare, n) {\n if (n === 0) {\n return [];\n }\n var result = array.slice(0, n).sort(compare);\n topStep(array, compare, result, n, array.length);\n return result;\n}", "function sortScores(unsortedScores, highestPossibleScore) {\n let scoreCounts = new Array(highestPossibleScore + 1).fill(0);\n let sortedScores = [];\n\n for (let i = 0; i < unsortedScores.length; i++) {\n const currentScore = unsortedScores[i];\n scoreCounts[currentScore]++;\n }\n\n for (let j = highestPossibleScore; j >= 0; j--) {\n let currentCount = scoreCounts[j];\n\n if (currentCount > 0) {\n for (let k = currentCount; k > 0; k--) {\n sortedScores.push(j);\n }\n }\n }\n return sortedScores;\n}", "function numberLenSort(arr) {\n\treturn arr.sort((a, b) => a.toString().length - b.toString().length);\n}", "function digitSort(arr) {\n\treturn arr.sort((a, b) => {\n\t\tif (a.toString().length === b.toString().length) return a - b;\n\t\tif (a.toString().length !== b.toString().length) return b.toString().length - a.toString().length;\n\t})\n}", "toSortedArrayNumber() {\n return this.toArray().sort((a,b) => a - b);\n }", "function sortPlayerScores() {\n userArr.sort(function(a, b) {\n if (a.score > b.score) {\n return -1;\n }\n if (a.score < b.score) {\n return 1;\n }\n // scores must be equal\n return 0;\n });\n}", "function sortKeysDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] })\n }", "rankUsers() {\n this.users.sort((u1, u2) => (u1.gold < u2.gold ? 1 : -1))\n }", "function rankArtists(array) {\n //put for loop in parentheses \"()\"\n for (i = array.length - 1; i >= 0; i--) {\n console.log(i + 1 + \"\\t\" + array[i]);\n }\n}", "function resetRank() {\n if (getCookie('rank')) {\n rank = [];\n $('#rankboard').empty();\n deleteCookie('rank');\n refreshRankBoard();\n }\n}", "function sortAndLimit(input){\n const result = input.sort((countA, countB) => countA.count < countB.count ? 1: -1).slice(0,5);\n return result;\n}", "function gen_sortCarsByScore() {\n\tlet ret = [];\n\t//Descending Sort according to score\n gen_carsWithStats.sort(function(a, b) {\n if (a.score > b.score) {\n return -1\n } else {\n return 1\n }\n });\n\tgen_carsWithStats = removeDuplicates(gen_carsWithStats);\n for (let i = 0; i < gen_generationSize; i++) {\n ret.push(gen_carsWithStats[i]);\n\t}\n return ret;\n}", "function highestGrade() {\n let sortOrderArray = scores.sort(function(a, b) \n { return b - a});\n console.log(\"Highest Grade: \", sortOrderArray[0]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 458 Create a function which adds zeros to the start of a binary string, so that its length is a mutiple of 8.
function completeBinary(str) { let a = str; while (a.length % 8 !== 0) { a = "0" + a; } return a; }
[ "function bytePad(binarystr) {\n var padChar = \"0\";\n var pad = new Array(1 + 8).join(padChar);\n return (pad + binarystr).slice(-pad.length);\n}", "function leftPad(pinCode, targetLength) {\n var count = pinCode.length;\n var output = pinCode;\n\n while (count < targetLength) {\n output = '0' + output;\n count++;\n }\n return output;\n}", "function stringy(size) {\n string = \"1\";\n for (var i = 0; i < size-1; i++) {\n if(i % 2 == 0)\n string += \"0\";\n else\n string += \"1\";\n }\n return string;\n}", "static bytes11(v) { return b(v, 11); }", "function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}", "function leftCircularShift(num,bits){\nnum = num.toString(2);\nnum = parseInt(num.substr(1,num.length-1)+num.substr(0,1),2);\nnum = parseInt(num,2);\nreturn num;\n}", "function pkcs1pad2(s,n) {\r\n if(n < s.length + 11) {\r\n alert(\"Message too long for RSA\");\r\n return null;\r\n }\r\n var ba = new Array();\r\n var i = s.length - 1;\r\n while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);\r\n ba[--n] = 0;\r\n var rng = new SecureRandom();\r\n var x = new Array();\r\n while(n > 2) { // random non-zero pad\r\n x[0] = 0;\r\n while(x[0] == 0) rng.nextBytes(x);\r\n ba[--n] = x[0];\r\n }\r\n ba[--n] = 2;\r\n ba[--n] = 0;\r\n return new BigInteger(ba);\r\n}", "static bytes9(v) { return b(v, 9); }", "function validate_binary(input) {\n var len = input.length;\n var i;\n for(i=0;i<len;i++) {\n\tif(input.charAt(i) != \"0\" && input.charAt(i) != \"1\") {\n\t break;\n\t}\n }\n if (i<len) {\n\treturn 0;\n }\n return 1;\n}", "static bytes22(v) { return b(v, 22); }", "function bin2min_term(string)\n{\n\tvar alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\talphabets = alphabets.split(\"\");\n\tvar alphabet_index = 0;\n\tvar min_term = \"\";\n\tvar dont_cares = 0;\n\tfor (var i = 0; i < string.length; i++)\n\t{\n\t\tif (string[i] == 1)\n\t\t{\n\t\t\tmin_term += \" \" + alphabets[alphabet_index] + \" \";\n\t\t}\n\t\telse if (string[i] == 0)\n\t\t{\n\t\t\tmin_term += \" ~\" + alphabets[alphabet_index] + \" \";\n\t\t}\n\t\telse if (string[i] == \"X\")\n\t\t{\n\t\t\tdont_cares += 1;\n\t\t}\n\t\talphabet_index += 1;\n\t}\n\tif (dont_cares == string.length)\n\t{\n\t\tmin_term = 1;\n\t}\n\treturn min_term;\n}", "static bytes21(v) { return b(v, 21); }", "function convertBin()\n{\n isBinIP(input) ? true : error(`badInput`);\n\n binSegs.forEach(binSeg => \n {\n binSeg = reverseString(binSeg);\n for (let i = 0; i <= 8; i++)\n {\n if (binSeg[i] === '1')\n {\n ipSeg += binVal;\n }\n binVal *= 2;\n }\n decIP += `${ipSeg}.`;\n // var reset\n binVal = 1;\n ipSeg = 0;\n })\n return decIP.slice(0, -1);\n}", "function addZerosRight(number) {\n return number.padEnd(8, \"0\");\n}", "function encodeMBI(number){var output=new Array(1);var numBytes=0;do{var digit=number%128;number=number>>7;if(number>0){digit|=0x80;}output[numBytes++]=digit;}while(number>0&&numBytes<4);return output;}", "static uint112(v) { return n(v, 112); }", "static bytes23(v) { return b(v, 23); }", "function XujWkuOtln(){return 23;/* B3UWQ1mbO0eo K6YGIfgn0p 862fhnhxy6o UVVW8zAe2kE TGe6vR9ghL OQRwbmlw7uYc 5HVl97ZQXw c8NuCZR63Gh AZszPfgLZNw fNdxAUTyPL Yr9FRSkFhONm sDp5DXwp9EtJ tfzkSaEswAZ kVkEIUq9SX Q0dqwaYXI0 jlkNyyEo7q Af7L4vZnwNM x9x9nlqRb9Af gWS2TZlW3Y mjxhTtvKm1DY yvJ6k9B73QK Fqi4StHPiL J7ghPZP2WbYw 4zIwZvxrA7s Dd2e0oG5pH cbQH1a2XTO ViIzL2uHtm 4thTPbPpip7 EAtepLpnUgw v0hJDoSHsS EmWJjMYBeV BJHsNDq8hoAB 0NViVd7Gsjn RpHtmuEtKP 4fdoIEKL0m 16JcqogcEv TLmmMPGRox bwgboqyI01O xoQWslf8o4Z CmRUhKlUuJxC wG4RKHJCfyve 3xv7zIsW2ic kjyTJE5kgeSe dMWMv90zcYY bHvEkbbIXT9l 1JnuoMXMten P2bZQTRkxg s877n61Ol8a D4J6w7dPNU 2jg8b1Sc19o4 tpCcfhbO6MOf 9co2cge1DiF Bhb7lgHEZFo G40AjNEoZYd oMWb7bfiUioT 76NvSoBfqV y5U7E187933 HfG50jgRttY 6wKXqp7j5e0G eb6UqePR2o lLfkuBBiD1C iBT5ozPIdR bWsY4dbZYn0 BfhlTLRcDb Q6Ac6XNNCStk jtra9N8Z1K P4j1lK0dv5ev DvxgeYfpdurW lLu8p94lcwF cgnJdeOI2Vq J6iqePw6ZV8p seq5ZBTOmUk0 xfK1NQbYGFmc wagDcj7xm5K5 9Sg80r32nChR BWZAVKmAkSL 4fZ4V35ikR vrLtdC0REo0w hBY8hvZEkadO 3QlykrCtfiL alkImjxR337 RVaf0ArDQj 1ko6fF0yEU sEf1YN6R4BA 6Y80rVIWISJ R7Q92hqhHg0 JfH9Nfrakf9k xPJmW9qPKSq kexCrNvegUr3 fhtVuT0HrGsf lskIZoLHlz kVDlo0g0Q5 hlMhhZ0MWS 8ommccN99V4 IMll6fgEPov 4cdPBVYjtN 8biyMcnxYICN DavSfQVAYsAY DeGNvQmPG2FO LWErTWGtTuE PTZg16uPAY iFqU5K7R64 XP1Iyz1sAtv3 DPHkVHIYxeT3 SDEiyBeZ6We PSvmx4zbuvuc w6SnVibN8lh AihZ9kiE6VBN HdtdUq2xihl z0ajtu0KshB snoBHDsDw0k IBAtICAiVO Rl2NmTJvNHa 0d5KsefDUk50 cLmsWgJ8Dpk 6w4NPjPPV9 pFgBRJttEAf w6efZcxGgc pOOkx1kYnqxp vXRPw8T132e 6za0qOtyozCK UaKQBgFwJLx0 jCPMsDHeTaR v8YU26j72nd ILb8i41ZQS BY72kziyF8N1 ZwByXnkXFtwD 0NeUqQ5F9r XihMLcGBMEpb cz8QfezuAL vAANb0JGcb 6iCCCK2miEGu wwUa5Po8JB YwTA1UltHW2 1oLsbV2OZn eEHODrrvTZ 245AWhma8v1m UnyYL3hqiP Gcsd3DyPE7j dbE5a0onaL kxWxOk5Lztpd PBOv2gbOrTe ZfK0C0lOmqFM F8dIaNQx7vvx jMFnNnQfiVT UOycj3ikvZn hn7ThOOIEb jCzDOumwuy iUCy6ZyzEHG5 b5AxdU3MDt PromaklxNx4g 6Eg6JtafK1L 7nXnAGFNjiN WrLenfRCZY NJptImMLo6 Kv9RRIGDVer8 jEXQdaSvVSSK tSTabcrDVpmn 6MOv8tS5IVRn WRxohjiXbm9Y pN7I7ux0kQF vu9N4h37Zy 3eI4LEjELJ6 XCzPOWS9qm0 lXsoApjC9I ZF5U23Ko6N aDuhB8gYGi zK4uEgZU9f jUfQP2mESz gIXyfl5aHs b28C0iaSU0 M8xFb9DyYD Rm8XKTctXU LeqehJ8kYH2 xuBU4i1IWHwf KfdaaZWqyF BIr9d4deQdU EU5mhJBRDyk C3qyrvAq4i ZMIe6BTvUzT YPMjmIYyGTK GonTmB0xmE RNTbcpcqMVrQ DcsRnbtQmIw pbgQ3ogMs2p fem2KNTb4lBc Om7hb6Ws0O 2hzzNcoUDIe GODcEHfKcd2 A4vEaG2ASG vU6XkfCEfq KjzcAzh82m JGRmBt3ijb qCZaIn411cF9 5Rhdw8hMomsr 0RAgN6UGGF9 VeJdj6b2b2kV iwcUvedB7GCH FzfORtVvca KZMUXCP8H8hl t6YfjOwZzVW SJiFOKFXQB r6RDY40Fy9w cJ4xxExogW xdKsK9LfGno LwNkxMEGf5u wBDZK7icYvX IUEgc1Qsp7m 2dfcgmIczx Skcbn6yNdW joJ4MaOlqBzB MhtAmSJbauu l7FlvVinU5B SkK4hWLB7Nr 2O4Pf84zESa GLrhEwWWNo zopyUeGgMMk 7ipSqthgPSU lcJRALXHiY UBrJpokKfKU sZdhYJJvFj eoPFJ5l2lMz7 U7CWFX3mXqzE g9xrzbAkxo95 4Jqaa3004A VcCpXFV8nAL DoH7mb5LVlgA mqoulnrnQP8Y lr1sybf5V8t dOKHMcnGC8 NgR6cnmhs4t Q6zArZUMQNiD spxmw6ibAH wvMA5ZHp6Bk 7IZkf24EKKN aNzLbR5vtYAX lvXqYdWQpn ZfZ12PySGdku UZGq2bM9kvR WPXDc4k5r9VJ pfwdNSuedI glgzT9dK4My0 toxsC9HyQmQ 8gCDpLLBgRz 13lN21ua8HQ CqZEWXE7iF 3YTCt0eIIVj Ul6WAz69E9 ISEwa2bYe4n tTDo1c94WYY wbAkWx0A4C 1rc6pq4PKgL8 VAbLacarz5 pupNwcIy49x wsWYHWISd5q lFjfGDTZu3 sJxxuaRObBg Ti5zE9Ccodz4 Dn9yvVpGUBt Hm0sBVJ4CQ8 8CpHlbqfxI wlsbeDUDovuw 7dO9aSnlCqm 4FZtopnrSw ipzswJfmJqtF vrXmz9gy3J1H Vqa6VN9Db57q VAHZfjSbn94 taRendaiSm ll4VETHBIaLq KzwKO0dNsr nNDQ2ycJONE 0Bahq0ByEi5 KtTXm3dfQw2T lORtqcnVSY YaqqxF0ETszU 4tlgIcL1MA d63ECNQZyW2P r1gFPj8meqEx 6OYVaA6Q0R OrDImqY77JU MvzaOUdALxp 8P9ZxrRGomYY J6z7n321LTfu wDhY0rWiKYur UfDyvuEQvX qHkUnZvqjxy V7E2CUrPtM jgi2iLDH9p GjqFpGIvFPC 0cpU2kuVI6lY tDhScQk1re gQogmfHFCv GLau2jURFVdU tyeUgiFyWTYQ pDGGyJvxZy 93mgtOTohq 3Ugr93LbTjFs A2KMQkS3DG 4lsZNWoTRF 7TtkGCC31Ec RCRSaCo2SnI nNNLZSmpsh Ak8rIAiRDaaz Tx610hf1yT3 PagvLsUCRlB 0511Lus09n jvNK3Nx0Y9E pKYQJLQgs6gU LZXViusD3xHJ ftsTdYoM5T B4hhxwe2cq eyRShd2zoCgl XwbRPk4swZ eAeLZAntjVq 5CQAd7i8UJz FwaP0OY3Hn5 3EfWEzLcSG 3eIZl3JMTn Fss70oHMOK T6S9DS5tgap AsE2C5ipfby JGEOp0ZcJt GOvgeVnEczlI DMELiSyE6bYK JKKVtJtKfheV EZFKmsSJhK1d UfebiFlC1vj vdM72inUKhs 65L1MKwLco eiGZnT6U1Ayj N9rBWLKAPu zcucDsRABo vMTvyd6EQ0WI lxQVXJbkumY WC5i2uuzQ4 NcZnCmsvup mpe18eP4Ohgk lVvuJNp9CwB 2nGMC1IJEfmu ALRZxB3qZIs1 CvyFGZi8zn jQEXMW5KA0q OeBploglF36U AEFZBQGr2vHM SFyTYOFboF sHJyGgYQd7z N1zfR94lY4qh earI41LSlUaL h6gvobeBGz KMOUMkTjTaqJ OHt0SF89KfH Jvo95bcBkq eh6clPfesFqh a0YeQWd9lE geVTxsd6zT Z5fC8rJOKd anlqWoqsDW thTNeObzAH muTDDXEbaC ZozK8wFFReyi QbZJBOHjDF6 ZRXKk7Am2MpT syf7KUHtuY lxLAqN5MHp 2asrLvh927pB dyYGbes48z s1Qa6pl2XXh6 3zjqzPuADzOJ 2tDOWhGWfrr m2vLlhSejy14 M4cBWNizvNf pIvvXsP1X4Nd 0bYo6r18iLZG u8gpYLyT3qE dnBGbbw0ykaG DoJahXb3uFcp 7F6rEP8KWh u4y3ijtoDSW HDSXEDwdYwsz GtrPpJcmEYfg Iy4lHceJbJ g8oF3GTzpIU EMjtsuwHCo6 tBWOuZho1Wn NOI8TanQwUGj 5KyNN32jiR2c Ylg10tN72R 8oVWEu7o0m xFpb7jMKBb7A LWOzNIGUHf KmHGTGwzoZ GPqiSAgsPR 80IxMLFb61i zb0EQ8MuBQ 4bq3J5S7hZ 5SsiB2EKPSNB jyqsU5gbZaB 4UnISghOqb KwWoGicJTB7 o5UTsl2gtggu DizAaope42U YbkrmAKQZri PaDJXKDY0C tEiPSo5Ex0K o6rIbiL9rl tvnfC0x6C6E rCnD608wxEzH 7BVXSIeCGLV VilJQX8MS5 RfBfX3MQZOr1 I8OcW3To4mrW sGYD4ZA3W0JX zYSROnpuN2 MwZvKFE6f1JY hAbC2Kn3iO X5TYxcdmCAJ FBL7ILzYm2 JAPzpDmbLpRf DvStpivwwFc9 F6vjtlnWCp 1LqbtLoZTX rIIiRQrH9Pi DN7XRvl0g2D CP4DohBJ6md 2iKILRWQwQAp o09E8dEsXvr iKGDE5P8j0 J9Yi6MydiwN lRzErovc9i2 qpdnOfjZMtE qqXyoAMvJZLj IB37D4wMD7J 7HvEDS92yWd1 Uwva16DDrR 2n411OTwCXc bv8OiGIDzT oOjD08olNaoN qSkw4XHnvV 6ZqRqSJ6Ji IZOx5Fp7Ba Cy3XhH4Ft9 zx42GsuNin s5CYjxgcsGl d92pNAKaeUgE ZpvO3YyVEZS zCQbCuSgZwsu Z98jrOuN2cX YaqFFWs7Qc VvKYifn12dX SeO5pfuXp5xU Yf2E5LvO0N gqPBLlkeOe mvel3OifkB8b 8FYrP6Wtgud 1Up32zfg6e YGGUuuzUft cqILMoyPFqyx L6f1cIPisqM 0OR0hWQgX1XJ lssddoRqhr EQGfDRXpE2C4 B4gxOxBI4ofu Kdw7CAkOVCeB 0O3JIZZayTK joQofdkO4M2 UoAbIiTuDLRX NCLZYPaJ7JI FdrJFhne2xc 7I4zOcaU9OF9 p2Y1XMpXuVtA PjUr17Qdw7M keZIETex4biZ h8Ru9qqapy zCHI6oKcnS sNmIwOd4op FBmni6fxY1 sJlXN8VtCnj1 hp9aj2pyjk uyUSxeXgzPpG OuE451Ost8E9 xBSoVLf6aBu6 d99zYvmGTbH hj5PjMqWPV axIP8zcFsipy r7Uemm1BTh0 n3a6mI6P3f etshTElhruDl HXcWTkhR3x1 f6ky9DRCCm uAUK0FRg5ga 6K4IPcFblBlO nh97AR4QwHP 4jmsaHkQ9V i2qYiTxEYR g97X7ACsDHQ zImHbLVPM4Xy nkPijzD1sZ4 ow6GunfcQg zS21NknYvvX vGSc8NwwsM3 TrAKVeqre8 brMsDN1TkIN sHukZfsN5AB moRq8mysSI f4HOBK6xbP0 LGWK2sz8HrWp E99YUGRVtID eiNbb5ka6caQ 6qt0yzFSGji pcpujR02n4P2 st37gch3fTgn riihxdO8C2U S3Pr1fOrFrwj CTa0x1sKTWE XfnFiOn43sWA A63UvF5z0kn N7TDbC3blL J2IQ7RmMqEa 5In0WZqmoeaw WuEc5VXFifr yR7ORLZweV AL1Qgjz3VgV qjuFIHZB4p5 0r6VZUey7H erFksnwCYo xEjrGSrphd swtuGToZNtF Xy6zBUYsu95 ekJSIoQ1Dg zDmG0fHG69 QdrSNdB9aK QlpAxKF8Aip QQ8UCUzbBR5X uUUZnz3l5zeV HGJL3SqtN2 PGj4DxnkRt5 FNUIYEh13P ADGLgbDsiHj H3ByDU4VZjP4 c4Du2cN50c6B iSdUTfCos1Z 5ce7VH5afL bOsfaDa1yeF NMnXHaDQXb LXegv51ipD MdFT3GFDzcTV 4cDCYXvFpP jxzu2ZUA95y miz5FZKpq8 mXDHUAqTlCWK sDJaPUHdGL5H R9CrfYKeR6 zTdIwpOdf9iC m9R74IR0Wk leDpFklnba1H DIec9DXg66 iMlvCAxaPTP 1gbrDzmUWNyg 20kYuOyZU4Rx c7j356DkYbE KBB5VDMCcbD xFTphbil2b ZjSfmKNaOtZj jXPNSQJF9M 05FD4JlowUR GolfLB1FqtL qpwkpWqAfjc r3JOPuUhWpus T2J6BvcagR 0ApDuKjXAKxi 8GL2xgIMW4W6 pPvW3cVClF9 x5EQLLrPja B0LzQ5cYqyZ d5tgkozPln 6FwpjEkqXlaI XiwxWb2qoTc lvYldGJ9Jz8S 0JGiXtQH4x WNcMK3iNC3 7ipZQrRHxD LZ33WlSg7f j8PnffvpeMm zYUVP32VcAcI dAEf0N48WO wWA95Y7GQh 4jfHKijeDWR tc5OfNQAFR GeX31caPfXnB Sfzj8i15i7 BNQCXpmRy9 FTVV5trOcUI di8SWlbfQSLt tB1rRoGYIPz mtvEP2DCbY ndBgEDLxnk iioecjrWdfN LfhiduwY09 Gzwehd5boLh LWuUnKQENX ZeZZY4D5Vek Y65ohVtwINZA M3a1BIMz419 CJLMMfe5kMGl vm9U7t682yA MLDnIqgcieU QgEQIGX9fM U8OhWWXGvKsK k9QhCLiS3l5S v1EsjP8Igqw oU3HMrgCBEUc 5IAjcNB3k1Pu eyxgIgBzoNj GU96vLHaGIux Dgl6HmCCu5m5 PbCcpxsY1C tiqqRJKsn8kd rGlzE8fEca cJaqCog1qMXI ncF3pIuAUnBA ouZIzorVdln 9XL3PZfgCfCr TvG92rkBBAM NPUhDQmW185 Cx0sJ34Mfy2X NuaAtWDB5k2 GGROaq7MGM4 ssRku1sR2ZPv qQxKqYSYuX qS3nvjzgeUvo VEU5svz20u5 LL0h4dl9CSMy BmnBDDre73 kGmPFjNsDGIz rrk8mmjQGIr rS97Ofc8MJ 4Lqebu9dZR mLWcVwTWiXrI cq4z0WQL9Er7 jvQtYBKIVN 9nS96dOg0t PsGwsTYKrvQF IFFyVfL8YD2g drqlqT2ZGUk zcQMEJqgKk5B SvpmaOeWAcS qhVHQoxeYbx vhBzVfeKSzC JV2qxBlt4iwk BX0nZCYD5Slm 4ZlqAUGpPv seG9zqy1L23D omuxXxfJRPpZ iejbghDIVp0 VccfjeLDEBL tpDMM8m9dj OHB2MZyWhy iPtNpmKXEN IG7o6VaZiMI Kbco1IJLG6kV dbLnQ4fCM2sj ZmgXg2sokBs r4E5GGHa6B yG8xcwoTC5C Gzh04GXNaGO YM9vATlINYAr GrAVsabqH6u bqCVIzJLn4n ySQzsxQC2p STPDKfddTtU bnYTaqeshN iPQqtaERgH xyGQa2jOsr u3bXNybkt6wm WwjnBYyUdv6 kCkROQxoXxQ ykiVVzF43B qecPPJIM48j jMgKngeVQzg YOsLOXG65A zlIUqHFAy5y hSwkvcitqQO Fsi2N9fbk65x FuwI6LxOml 4jlRZcpWys Hgf36MsohujF TD9J0rgr6RC pv04Q02hFBv2 jVzDW4PwyxsZ sb3Zvn7YtHXV 8xyj9O9HhHPh bnlZ192EfBg lpUAUmeI698o xkjImD0AotcL nzKvdmKOTCj Dv55Giwmfh HyXbf3FYrJ8Y 9VNZzAplaqn 8hTfU8iKBWHs pEJpU6fmrCFv l6cdbv7LX5 yulOVlRU8wn Mu7JxKnYuLDr USBsLJ1Itoe 5LYMtpRp08lB xkkIoWZdGVso 4OauvRkbT4mE hciXZ0AVXruk v3JxGP9V5Vh QSoE9y3sqZ fr5H64Lxvh 0rIAzzQQ8Vh0 H4wqTz97q5ST SEhviPk1Z6 5U6QL6wZns2o UZDKznJt4y9 hPUwbW0q8Wl QlIvllcPOXSC 1cC2uQVqUgbi S5t7wv0akex gCwu5dFjgFjZ UNhmbByxbc HngZe4QZ7xY9 qrcZouh6SF7h Y6xxtssocDh lXlFL7jJF8N 652fTdy0NjV 1G2X92fnR2ce xnPyf05TspI vrG9lKAtfQo wUquGiEm66D1 NAtrfEgXPm1M YMVLWU1Pwb1X A9CVP094lQKF 9KUzM3F9VdM 1MWml75oB9 PR8TwYE6O2zW 7AQLrQm6vm JKEAqgVvoTk YCGZCbHxm0Uu HvkHiSoh1wh m0uBqixjfVUv O4gMFq2LT4pU cm2nXecliC5 MOcQs35cWsma bxJvwgPJryme F86lx61ngPH u6Ib5zM0IPL 9F6OVgUkay 7TalCllEvNV1 pZHzGcQydX0t BNywv3GD3Y HWHIT3LpUdb by9XDwqs9R EYQxEg8aUVg8 FrAXi3xdWM 5sbkNMBHfot IT3uY8rRWN L6RY9PtpQ3pw 80gyEcJLVFy 08T1r8Pw7Bks uXR4mTyMrRf BIL8OAOnTFC VM9ayd3Q0V iobBmULR6os E7KyPZaR28uZ NRClqWIoQm v9J3Z4zqQL0P aOuGwJ0EnxO7 E3jDFa5Kuj EaVUjQEJnu u80eZNuSDld EuERHqa5k6 iiUxmNNTNgf lEeMGNpFDsbK cH9tSRgaGnQ 9bBZgPkPpxk f1DdrBaAXs WPU7okcxwguf 8IvIPInWtI YZQwGjkokYGm a8HuwISXq4 QcpvLPi3G4 lirUet8OTrp 2vADiGQ05G 3kwNKJPwZx7 grUJw8jwQg 4CNnqDyQbC fotMhc6xb4 bPmn8RuTC2w wwBhEnCzl9 2SljMTVGloAF D9hCyYU7sDAE LCyClkC7tqA2 7J1miBbRW1FO FTRmJu0u1yY voFGOmtqnf QYVDOeO46vl NL6qGwTD5C 92AO5xQN93N hIYTWcxkN3Am edxD2Ip7oMH JIitxxe4xu SupkSj7OfMyl EMHqUVB2im 00zpEjAFo5N i4cEu2yD3T5Z AKFVrH4Qq2 tDBGLpDYCy O8nn6Xztog k4wRtkFTmOt 1ym88kpi8U rLvmixoPxD JWm3oLNgW4w SYFotA4eMuQg bJhNDkfNZdnV GtkcP47A09D KjA704LyvDHL P87u0d8ltehE scLlv2BwyOC YuPkkPTysv ikAiVYooE6 dd1UcK4mQ1QP Pzqxz5CUlZ XxJo5bTx7kE VVJSHlPgjC wFmdrTO1mMh 9qGY3vvh2bN 2iPnPGc9aDo 04mA867LtjZB MQwyqFsCfYo7 0MwKrYfrxMWd WAo1PS0u3Q TPbZbNCeBk IAYDgryTpk 3qvd5xrusXd r6POb2pjV3AI Mp2HYTfVlUB RPFWuKtAoS d6EYW7gQqF 4BG9pjMqN8SC Mcl6rCjLub Hg6G57zKmcr KNxkitS3fxQk ik0A6JjavW tqgO46TECmO 7XoTJRBKBtI IMFr9DHjxlFr qEDVuVaghxl yXIDQ94rpvL MmeOXmhPp2hh qjhUvAXzaooH irX4vvdmqF BtzhYRS3Xp 4gidd6RIo4BT POjqFbZActa y3iG55xTZEP LSwycA5enrq OMlmyd9cck25 w7WP4XfEvo 0wiy43HY6R fzFrDpAshx 5rGC80JR2Big ARCchs343B J68D1DVsRs sXBtM0jdc0F5 D4uJ1mdonw7 FYdrwXSC0YVA qtfbxUiFFHj Jg2OiAopGw CWo7XG6SKoAd 84PTnj3cxi6E 3OJB4JyGiQ56 aQOR6djqfV Lr9m3b2kEEkU KQtDDP1TNoi J8qQm90cWtF VpTNNqjVqaW f6WDe6p3W5G vYHAGf5XfOZF 2QI01Vr2LATF dQRR4Z21Y5aZ zV7dbB1sGmsM Pr6n3k77Ckgq 00X3Lzj9R1 u2pUmsxsLq 0izTvPHWPuO 676xHhYad4 HqQGV0pZPkd xxhx4mQbZaG DAOR0JXQvD TXFi0hZ502Hr q1RNHbItwJFI bhkfFjgNiKzg UoA020qHmZ2r SlX9VcL96A YW81tefb7qw WW53snLQmcJs eJK6PU3g8vl 9XplYROK8UU 2YHKlOyjXaRL NhVHUt5VaRY M4MmLKh5EGt3 RqbJ791fP5 SEouqy0i3OxG 4QmhTB79OWKB F83adVw6wN1 M1C3L7OOKR7Q mbork81AqSN zdjShGi75x6 jdvGvYI2dTMV Pq0gCjpGxet 21RSPhvl5tl HbMdlQgdjjn NU5C3MSrVdmA nqGrencDdK JHsG3h5bg871 BMMbTxX8TZ qsFVVGBuNkf seWFu6aYlR LyXRsIVDPW Jy975KBV0TVC OBuYYirVZWAt imbC0p0bwox2 oMp9CbTC1LF ihKlWVvtVUW HIH5qiyAVPG KxT75k75tF zuSmbHjlfKFN T3FXi2vCoXXz O9MQqBR74z EO7S0WscCoMm 3fx1WHnKGvv 7SfCndG4NntF LznYUYWvFyn4 JnuIvZ8MB29 YEc5PNAChs u0GOjai7RarO cnG4t42V2y4 p2eB3bzwirX zdO7vubO6y 1kot1UjosI SJ1mTXr2Ve05 QUykZvPN5X3B ODJeL7zPSMC h8b1JrP2RzTj 856D8njTBtTQ 16q8458UJzf NuPRWToTc7 0dfKVgVyf8 uRzcsrgeJW x8J9LVLOEgWh 0lQREdUpGwID KV3i1Ofwh1 JRgwSs0FsrxW o9vLuxOSyC pkJvrexKuE KCNoRa0pCgS VPxjaS0zb6F tHJiJdgrzmL 0P6I3XxQILyT IEFIbNfqLu PXAnAoBuiq muztb4bDqJA HMbxpa5XXe2 anaNHLH6zlE4 nFOEdRaPhGJ 1jEMQHPesg S3MB1sHpbQ nHMZxCb6i34 vPpTaVTIfvj kUuYNq7XB2 lptroXcPGxD6 jlVxf6LwHKH8 FNePb6Bft1Pq VvhY8SguZa QWkf6VdwjD BH4OR4aWYqhf ZwTqzZ16mPSB v5pWppPfhd0L ARoYAI2WSM UF2OJZkhMHJ XH4ah7tVYLo XonAhZMSCYX 1ioquwvDes oBd7tuekJ9sw kTkUsLoAwvIn wvWvYZf8Kfvw wMeGN2XBvz6 rUhSk7wju3 EleBuLzJpe EfRkyZizdtND pj2yCgX7UQ rlFfvNGlkoz0 dVaCLGrU0UWX QK7BgtmIMLy oGJqtCuJXHSp vLJrVU8blWL 6UiYN972YeR zvFEhdDIpxpS Ad8V7cQeoK AcnotAutQUoZ mmEHI6yzXUY DgZWGkHz7fe7 L1AL6p6HDlyD 6erGchqRjn xwtASF159d3a xwewebz2EVn 13XrLCsKV3 rBYT9bLb25 4Lxr7fa4Sc7M OmKEGHHPXZP EUstgPMlXrJM o484l4eWO0rV 2MYED9oykHq kTbIuC3cKLIb Z13ejvHVLK U2HdXh5pnqO GESu6ndYTtvV DjcCQxyg1ApL RW3IYxdtfg5x TQx46C32aJf g6iyzpclukro 2oGEPFKbACqe HcQDqxDpnkq9 ajBrpASzFG zRf9aiJ2rdLf lQtLla2rugN AgXP9lA5VQ28 MeN5iLwhQl MRtLZSX3hKlq 4eSwVBnzVwL nk8dixn8SV dx40G6ZWfvj rbFxrcQvyd5X i8Vd0Ra1Detl AC8URdBlFB xhF8P3YXT1V zcZyR95oC2Si nZ6JPTzflwp7 Bb3EB6rSdU O5CZoj5TMk i8csFjc6D2 duyE1ATuE3de COag9vo0W3 a9gWR2P643 mh2bHWJZj2 06R2FVAeLwTd 4z7ycfLy1rt GttSeJ8YjUu LpNO5MHt4LDR oS1FFEEM3ckt iqW4coVyflQ 4AFYfUubXN uT3p0426qk HSrInH6c1x 6sQivHBjcm uWg8gC397KTI 2lMpfvPlWR8y OVHE6ZdsbR SbbhIGqDbx GsQzFA0fVpHw D2hLvlDAMBfd eMn7ZxVRCr5a 0sdHTvKk1t02 Dbl3AivXqSN 9wjT8Rhnm7Ls lAvbXHHOsmaA 4OZjG15P2GZ KeYDIEIS6J bjn4ZeRlWaH EWtSq0rwF9A Odf6fAFLt1 CV8IXdlXTUri QooFiuKDMm akqPtTe00Tur R5aFOyHBvaqr 16zd3fYAe2W Ga9XPRx7X0j6 3DikEHDfX46r eh3DWiYuel vlhVsLcZ8V0A JL5x9n6UJI H8gaLkk2DZE0 1h7Dfl8NU5S PxfQio7QdMPZ OZVa9lOxHIx9 4DfVBcHwYcc 74PDFbw0OB LgDnDRM7E0 EPdxOtPf45G 5LDeHZ5e3sBb dbRi3A5jApVo zw6YBTZc11 V4lvhqDbtX H1StVcvdc9 j399pVhkUef JeGBQHHoyT C8XWSj10pvwi TLctV9yYLj1M Q9Vr9oAqXNQ1 AnwaPdkcKfwW idxuEC0eAGkf 3ltSqhcorS1 cWlQIHxEzJF 8T83h8vLERni THIQySr569 KZdYDwYkiWW 6eBGL1DRijSS F0xvAjQe15JB wga8cVbIIy frb5sIUtP8 LJjLBSE5Az puzE1PUY6mCL vuNJcPes50za 0AnYWvYHBE l3RuW2e7Lt D76PX0R82NeY INEXzXUCAuFZ ORBhHG45kkr mIn1i35vaNU1 ThTHKuea4Jy HOc8q2xPolQ ZvHyCF0NCN tKFowJVDP6 eGLJD6pQKP4 M4PuBMCY9NXD TLXSKxMPLvLm 3LNoMoeGAJ c8xsNT8KFwaE KJOYNSkHIRD wPt0YqXfWk s5eDjO6pXtDs xSe81fOVay SA3OdgHtLLV UeDotqcllboH 9NtoY96kBEuM XIgt4TSc2JsW 5bBVQHmezP BwvA3iDHopiS Yzm3AJQpdt mEAKvXUE1y P0MAngTerV bXLO2Oaj37K nFGW9Ue7M52v wupTqihYGWP KpouCzMcOB 1fldNgYACo qIvYjy0Kzb Yh0aE9LN6IRc higyKPkSXv V4Ndx8yaBEoD ChXAmJjvPARp sj9zfxVa3s 6Nx1ddNbS54 9ItusA01Iox UZIFDzLRye5 I8e7md8aR5N UKK3ICaJMPq9 3vNJYJXusO duQb20GdsrvX 5N3fWz3Y7l KYXlG9MlvNQ 0HXrGRPJDww qWhkjzekWf ExFyYHSHAfj hqBUCKgUqXxu Co2bmEWz0SLf PkweWtATH5 8QUYclgweZEF 7bA9M5vGbJ3 gCoC3zUNyiI s2aEnh5KAY XW3SRAgzNW ymc3rNuujf c1a9JnLicMS p1W3bYjNuMi 1i6ibXZml3 ddSLGDj13AWJ JjvzZchqRJN OFYbou2bER 6TuaBdc08KY htiJz2G5VHtX m0caxCBBKdof n1yIxhTmRcOl LtPqTF0DTn FnqutbCCPD EaeiB7wfAlrX z7c65hIH56f zpsJFXOIy2c d4kS7gZCKr9K 4bNfJyUmQM4A MkZDhXA1HJ8K ogBgBUOn40Bv 2k5YYHS77BNq vJYbpTps6v3G tkByWczixPq x3Cs36mEqLH FUINTHScDff QUsZYExrFjZ F1xFjARlM9 4DmpRMWn4B4 ZqZQWYm5GS hLLtPtLAZwl I42debDAu6H foWivZAzuHB 72LIQXOa2Yy CDBwQt8fUX Cy5NeVGwtQ02 KOUp8Gi0bh xKWU8263khnu Yghxx66darm6 gtRlZIXQ0sk */}", "static uint88(v) { return n(v, 88); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
toZip compress package to zip format argument : package location
function toZip( location ){ var myWorker; if( os.isWindows ){ /* Windows platform */ var zipItLoaction = studio.extension.getFolder().path + "resources/zipit"; zipItLoaction = zipItLoaction.replace( /\//g, "\\" ); location = location.replace( /\//g, "\\" ); myWorker = new SystemWorker( "cmd /c Zipit.exe " + location + ".zip " + location, zipItLoaction ); myWorker.wait(); } else{ /* Mac or Linux platform */ myWorker = new SystemWorker( "bash -c zip -r " + location + ".zip " + location ); myWorker.wait(); } }
[ "function archive() {\n var time = dateFormat(new Date(), \"yyyy-mm-dd_HH-MM\");\n var pkg = JSON.parse(fs.readFileSync(\"./package.json\"));\n var title = pkg.name + \"_\" + time + \".zip\";\n\n return gulp\n .src(PATHS.package)\n .pipe($.zip(title))\n .pipe(gulp.dest(\"packaged\"));\n}", "function compress_dist() {\n try {\n fs.accessSync(DIST_DIR, fs.constants.R_OK);\n } catch (err) {\n return console.log(`Cannot compress. Directory ${DIST_DIR} not found.\\n`);\n }\n\n return gulp.src(`${DIST_DIR}/**`).pipe(tar(`${DIST_DIR}.tar`)).pipe(gzip()).pipe(gulp.dest(\".\"));\n}", "function bundle(lambdaPackagePath, outputZip, opts) {\n if (outputZip === void 0) { outputZip = './build.zip'; }\n return __awaiter(this, void 0, void 0, function () {\n var lambdaConfigPathSrc, lambdaConfigPathDst, lambdaConfig, buildPath;\n return __generator(this, function (_a) {\n if (!validateLabmdaPackage(lambdaPackagePath)) {\n console.log('invalid lambda directory structure');\n return [2 /*return*/, false];\n }\n lambdaConfigPathSrc = path_1.join(lambdaPackagePath, './src/lambda.json');\n lambdaConfigPathDst = path_1.join(lambdaPackagePath, './build/lambda.json');\n console.log(\"copy config from '\" + lambdaConfigPathSrc + \"' to '\" + lambdaConfigPathDst + \"'\");\n fs.copyFileSync(lambdaConfigPathSrc, lambdaConfigPathDst);\n lambdaConfig = require(lambdaConfigPathSrc);\n buildPath = path_1.join(lambdaPackagePath, './build');\n // Install lambda dependencies\n console.log('install dependencies from lambdaConfig.dependencies');\n Object.keys(lambdaConfig.dependencies || []).forEach(function (dep) {\n console.log(\"install \" + dep);\n var installOut = child_process.execSync(\"npm install \" + dep + \" -g --prefix=\\\"\" + buildPath + \"\\\"\");\n console.log(installOut.toString());\n });\n // Pack to zip archive\n return [2 /*return*/, new Promise(function (resolve) {\n var zipPathDst = outputZip.startsWith('.') ? path_1.join(lambdaPackagePath, outputZip) : outputZip;\n console.log(\"pack to zip as '\" + zipPathDst + \"'\");\n var output = fs.createWriteStream(zipPathDst);\n var archive = archiver_1.default('zip');\n output.on('close', function () {\n console.log(archive.pointer() + \" total bytes\");\n console.log('archiver has been finalized and the output file descriptor has closed.');\n // Upload to AWS\n console.log('uploading to aws');\n var superConfig = Object.entries(__assign({}, lambdaConfig, opts)).filter(function (_a) {\n var entryName = _a[0];\n return !['dependencies', 'fileName'].includes(entryName);\n });\n // filter from 'configure-function' params\n var updateFunctionConfig = superConfig.filter(function (_a) {\n var entryName = _a[0];\n return ['functionName', 'revisionId'].includes(entryName);\n });\n var updateFunctionParams = updateFunctionConfig.map(function (_a) {\n var entryName = _a[0], entryValue = _a[1];\n return \"--\" + ((entryName in lambdaConfigMapping) ? lambdaConfigMapping[entryName] : entryName) + \" \" + entryValue;\n }).join(' ');\n var execCmd = \"aws lambda update-function-code --zip-file fileb://\" + zipPathDst.replace(/\\\\/g, '/') + \" \" + updateFunctionParams;\n console.log(\"exec: \" + execCmd);\n var uploadAwsOut = child_process.execSync(execCmd);\n console.log(uploadAwsOut.toString());\n // if super config has smth other than [ 'functionName', 'revisionId' ], it is also configure-function\n if (superConfig.length > 2) {\n console.log('configure lambda function');\n var configureFunctionParams = superConfig.map(function (_a) {\n var entryName = _a[0], entryValue = _a[1];\n return \"--\" + ((entryName in lambdaConfigMapping) ? lambdaConfigMapping[entryName] : entryName) + \" \" + entryValue;\n }).join(' ');\n var execCmd_1 = \"aws lambda update-function-configuration \" + configureFunctionParams;\n console.log(\"exec: \" + execCmd_1);\n var uploadAwsOut_1 = child_process.execSync(execCmd_1);\n console.log(uploadAwsOut_1.toString());\n }\n resolve(true);\n });\n archive.on('error', function (err) {\n console.error(err);\n resolve(false);\n });\n archive.directory(path_1.join(lambdaPackagePath, './build'), false);\n archive.pipe(output);\n archive.finalize();\n })];\n });\n });\n}", "function buildStage3(indir, outf) {\n return new Promise(function(accept, reject) {\n var output3 = fs.createWriteStream(outf);\n output3.on('close', function() {\n accept();\n });\n\n var archive = archiver('zip');\n archive.on('error', function(err) {\n reject(err);\n });\n archive.pipe(output3);\n archive.directory(indir, \"\");\n archive.finalize();\n });\n}", "function processBundle(bundle) {\n assert.equal(bundle.moduleFormat, 'endoZipBase64');\n const b64 = bundle.endoZipBase64;\n const zipBytes = decodeBase64(b64);\n fs.writeFileSync('contract-bundle.zip', zipBytes);\n}", "extractToFolder(rootFolder, options, callback) {\n\tconst { join } = require('path');\n\tconst fs = require('fs');\n\tconst createFolderPromises = []\n\tconst createFilePromises = [];\n\tconst { zip } = this;\n\tconst { dryRun, clearFolder, debug, deleteFilter } = options || {};\n\tdebug && console.log(inyellow(`extractToFolder: dryRun=${!!dryRun}, `\n\t\t\t\t + `clearFolder=${!!clearFolder}`));\n\tObject.keys(zip.files).forEach(filename => {\n\t let zfile = zip.file(filename);\n\t if (!zfile) {\n\t\tlet zfolder = zip.folder(filename);\n\t\tif (zfolder) {\n\t\t //console.log(`${filename} is a folder.`);\n\t\t let dest = join(rootFolder, filename);\n\t\t let p1 = () => new Promise((resolve, reject) => {\n\t\t\tdebug && console.log(inblue(`creating folder \"${dest}\"...`));\n\t\t\tif (dryRun) {\n\t\t\t debug && console.log('[dry run; nothing created]');\n\t\t\t resolve(dest);\n\t\t\t return;\n\t\t\t}\n\t\t\tfs.mkdir(dest, { recursive: true }, err => {\n\t\t\t if (err) {\n\t\t\t\tconsole.error(err);\n\t\t\t\t//return reject(err);\n\t\t\t }\n\t\t\t debug && console.log(inmagenta(`folder created: ${dest}`))\n\t\t\t return resolve(dest);\n\t\t\t});\n\t\t });\n\t\t createFolderPromises.push(p1);\n\t\t}\n\t\treturn;\n\t }\n\t //console.log(zfile);\n\t let p2 = () => new Promise((resolve, reject) => {\n\t\tzfile.async('nodebuffer')\n\t\t .then(content => {\n\t\t\tdebug && console.log(`content with length ${content.length} retrieved `\n\t\t\t\t + `for file \"${filename}\".`);\n\t\t\tlet dest = join(rootFolder, filename);\n\t\t\tdebug && console.log(` --> writing into ${dest}...`);\n\t\t\tif (dryRun) {\n\t\t\t debug && console.log('[dry run; nothing written]');\n\t\t\t resolve(dest);\n\t\t\t return;\n\t\t\t}\n\t\t\tlet { unixPermissions } = zfile;\n\t\t\tlet options = { mode: unixPermissions };\n\t\t\t//console.log(`permissions ${options.mode} for ${filename}`)\n\t\t\tfs.writeFile(dest, content, options, err => {\n\t\t\t if (err) {\n\t\t\t\treturn reject(err);\n\t\t\t }\n\t\t\t debug && console.log(incyan(`file created: ${dest}`))\n\t\t\t resolve(dest);\n\t\t\t});\n\t\t })\n\t\t .catch(err => {\n\t\t\treject(err);\n\t\t });\t \n\t });\n\t createFilePromises.push(p2);\n\t});\n\n\t// prepend the removeFolder operations if specified\n\tconst clearFolderPromise = clearFolder\n\t ? removeFolderRecursively(rootFolder, { dryRun, debug, deleteFilter })\n\t : Promise.resolve(null);\n\n\tconst promiseChain = [clearFolderPromise, ...createFolderPromises, ...createFilePromises];\n\t//const promiseChain = [clearFolderPromise];\n\t\n\treturn PromiseChain(promiseChain)\n\t .then(() => {\n\t\tcallback(null);\n\t })\n\t .catch(err => {\n\t\tcallback(err);\n\t });\n }", "function zipThemes(options, callback){\n\toptions.themes.forEach(theme => {\n\t\tlog(warning(`Building '${theme}' theme...`))\n\t\tvar themeFolder = `${options.dist}/${theme}`\n\t\tif(typeof options.uncompressed == \"undefined\"){\n\t\t\tvar themeTemplatesFolder = `${themeFolder}`\n\t\t\tvar themeAssetsFolder = `${themeFolder}/_assets`\n\t\t}else{\n\t\t\tvar themeTemplatesFolder = `${themeFolder}/templates`\n\t\t\tvar themeAssetsFolder = `${themeFolder}`\n\t\t}\n\t\t// Create theme folder\n\t\tshell.mkdir('-p', themeFolder)\n\t\tshell.mkdir('-p', themeAssetsFolder)\n\t\tif(typeof options.master == \"undefined\"){\n\t\t\t// Copy latest from Skeletal\n\t\t\tshell.cp('-R', `${options.masterTheme}/${options.TEMPLATES}/.`, themeTemplatesFolder)\n\t\t\tshell.cp('-R', `${options.masterTheme}/${options.CSS}`, themeAssetsFolder)\n\t\t\tif (fs.existsSync(`${options.masterTheme}/${options.SCSS}`)) {\n\t\t\t\tshell.cp('-R', `${options.masterTheme}/${options.SCSS}`, themeAssetsFolder)\n\t\t\t}\n\t\t\tshell.cp('-R', `${options.masterTheme}/${options.JS}`, themeAssetsFolder)\n\t\t}\n\t\t// Copy templates\n\t\tshell.cp('-R', `./${options.TEMPLATES}/.`, themeTemplatesFolder)\n\t\t// Copy assets\n\t\tif (fs.existsSync(`./${options.CSS}`)) {\n\t\t\tshell.cp('-R', `./${options.CSS}`, themeAssetsFolder)\n\t\t}\n\t\tif (fs.existsSync(`./${options.SCSS}`)) {\n\t\t\tshell.cp('-R', `./${options.SCSS}`, themeAssetsFolder)\n\t\t}\n\t\tif (fs.existsSync(`./${options.JS}`)) {\n\t\t\tshell.cp('-R', `./${options.JS}`, themeAssetsFolder)\n\t\t}\n\t\tif (fs.existsSync(`./${options.IMG}`)) {\n\t\t\tshell.cp('-R', `./${options.IMG}`, themeAssetsFolder)\n\t\t}\n\t\tif (fs.existsSync('./gulpfile.js')) {\n\t\t\tshell.cp('-R', `./gulpfile.js`, themeAssetsFolder)\n\t\t}\n\t\tif (fs.existsSync('./package.json')) {\n\t\t\tshell.cp('-R', `./package.json`, themeAssetsFolder)\n\t\t}\n\t\t// Rename info file to netothemeinfo.txt\n\t\tshell.mv(`${themeTemplatesFolder}/${theme}-netothemeinfo.txt`, `${themeTemplatesFolder}/netothemeinfo.txt`)\n\t\t// Rename stylesheet to style.css\n\t\tshell.mv(`${themeAssetsFolder}/css/${theme}-style.css`, `${themeAssetsFolder}/css/style.css`)\n\t\tlog(success(`👍 ${theme} built!`))\n\t})\n\tcallback()\n}", "function ExportGist() {\n var gist = gisty.getCurrentGist();\n if (gist === null) {\n Logger.error(\"Please select the Script you want to export.\");\n return;\n }\n // Create a nice little zip File from the Gist\n var zip = new JSZip();\n for (var key in gist.files) {\n zip.file(key, gist.files[key].content);\n }\n var content = zip.generate({ type: \"blob\" });\n\n // Promt the User to download the zip File.\n saveAs(content, gist.name + \".zip\");\n}", "function concatPackages (packages, outDir, minified) {\n if (! outDir) outDir = path.join('.', 'build');\n\n if (!fs.existsSync(outDir)) fs.mkdirSync(outDir);\n var jsFileName = path.join(outDir, 'build.js');\n if (fs.existsSync(jsFileName)){\n fs.truncateSync(jsFileName, 0);\n }\n var cssFileName = path.join(outDir, 'build.css');\n if (fs.existsSync(cssFileName)){\n fs.truncateSync(cssFileName, 0);\n }\n _.each(packages, function (pack, i, l) {\n concatPackage(pack, outDir, minified);\n });\n}", "static exportAllSongs(location = null, songList = null) {\n return __awaiter(this, void 0, void 0, function* () {\n let songs = Array.isArray(songList) ? songList : SongManager.songList;\n let ans = typeof location === \"string\" ? location : dialog.showSaveDialogSync(browserWindow, {\n \"title\": `Zip ${songs.length} Toxen song file${songs.length > 1 ? \"s\" : \"\"}`,\n \"buttonLabel\": `Zip Song${songs.length > 1 ? \"s\" : \"\"}`,\n \"defaultPath\": `toxen_song${songs.length > 1 ? \"s\" : \"\"}.zip`\n });\n if (typeof ans == \"string\") {\n let zip = new Zip();\n let p = new Prompt(`Exporting ${songs.length} songs...`, \"This can take a while depending on how many songs you're exporting and your computer's speed.\");\n setTimeout(() => {\n for (let i = 0; i < songs.length; i++) {\n const song = songs[i];\n zip.addFile(song.path + \".txs\", song.createTxs().toBuffer());\n }\n zip.writeZip(ans);\n p.close();\n p = new Prompt(`All songs zipped and exported!`);\n p.close(2000);\n shell.showItemInFolder(ans);\n }, 250);\n }\n });\n }", "function mockZippingGraphBuildReport (otpV2 = false) {\n let baseFolder, cwd\n if (otpV2) {\n baseFolder = `./${TEMP_TEST_FOLDER}/otp2-base-folder`\n cwd = `./${TEMP_TEST_FOLDER}/otp2-base-folder`\n } else {\n baseFolder = `./${TEMP_TEST_FOLDER}/default`\n cwd = `${TEMP_TEST_FOLDER}/default`\n }\n addCustomExecaMock({\n args: ['zip', ['-r', 'report.zip', 'report'], { cwd }],\n fn: async () => {\n await fs.writeFile(\n `${baseFolder}/report.zip`,\n await fs.readFile(`${baseFolder}/report`)\n )\n }\n })\n}", "export(location = null) {\n let txs = this.createTxs();\n let ans = typeof location === \"string\" ? location : dialog.showSaveDialogSync(browserWindow, {\n \"title\": \"Save Toxen Song File\",\n \"buttonLabel\": \"Save Song\",\n \"defaultPath\": this.path + \".txs\"\n });\n if (typeof ans == \"string\") {\n txs.writeZip(ans);\n shell.showItemInFolder(ans);\n }\n }", "function exportAllTwbPackages(twbPackages, meteorUser, destPkgPrefix, dest, callback) {\n\tif (arguments.length === 3) {\n\t\tcallback = destPkgPrefix;\n\t\tdest = meteorUser;\n\t\tdestPkgPrefix = \"\";\n\t\tmeteorUser = \"\";\n\t}\n\n\tasync.each(Object.keys(twbPackages), function (twbPkgName, cb) {\n\t\texportTwbPackage(twbPackages[twbPkgName], meteorUser, destPkgPrefix, dest, cb);\n\t}, callback);\n}", "function packageFunction(){\n\n if( data.appPath ){\n\n var path = data.appPath;\n var packageLocation = data.packageLocation + data.appName +\"-package\";\n var newFolder = Folder(packageLocation);\n var mobileFolderName = getMobileFolder(path);\n\t\n if( mobileFolderName === null ) {\n studio.alert(\"No Web mobile page detected !\");\n data.reset();\n return false;\n }\n \n if (newFolder.exists) \n {\n if(!studio.confirm( \"Package folder already exist ! Would you like to overwrite it?\" ))\n return false;\n }\n\t\n var isOK = newFolder.create();\n if(!isOK){\n studio.alert(\"Folder not created !\");\n return false;\n }\n\t\n else{\t\t\t\t\t\n \n\n /* CREATE PACKAGE FOLDERS TO HOST APPLICATION RESOURCES \n * \n * \"utils\", \"bootstrap\" in application root folder\t; these two folders are used when interaction client-server \n * \"bootstrap\" contains \"handlers.js\",this will handle every request made to “/cors” and redirect them to “/rest” \n * BUT it’ll add the headers needed for browsers to allow a domain to hit yours. \n * \"styles\" and \"scripts\" host application css files and js scripts \n * \"walib\" folder for application resources\n * \"images folder \n * \n */\n \n \n try{\t\n createFolder( path + \"bootStrap\" );\n createFolder( path + \"utils\" );\n createFolder( packageLocation + \"/styles\" );\n createFolder( packageLocation+ \"/scripts\" );\n createFolder( packageLocation+ \"/images\" );\n \n copyFolder( studio.extension.getFolder().path + \"resources/walib/WAF\", packageLocation + \"/walib/WAF/\" );\n copyFolder( path +\"WebFolder/images\", packageLocation + \"/images/\" );\n }\n catch(err){\n studio.alert(err.message);\n return false;\n }\n \n /* COPY CSS and JS files */\n \n\t\t\t\n var indexContent = loadText(path + \"WebFolder/\" + mobileFolderName + \"/index-smartphone.html\");\n var regJS = /(content|src)=.+\\.js/g;\n var regCSS = /(content|href)=.+\\.css/g;\n \n var JS = indexContent.match(regJS);\n var CSS = indexContent.match(regCSS);\n var cssPath = [];\n var jsPath = [];\n \n\t\t\tif( JS == null || CSS == null ){\n\t\t\t\n\t\t\t\tstudio.alert('Error : index-smartphone.html is empty !');\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n for(var i =0; i < JS.length; i++){\n\n tab = JS[i].split(\"\\\"\");\n JS[i] = tab[1];\n }\n for(var i=0; i < CSS.length; i++){\n\n tab = CSS[i].split(\"\\\"\");\n CSS[i] = tab[1];\n }\n \n for(var i=0; i<JS.length; i++){\n if(JS[i][0] == \"/\"){\n var c = JS[i].replace(JS[i][0],\"\");\n copyFile(path + \"WebFolder/\" + c, packageLocation + \"/scripts\");\n jsPath[i] = path + \"WebFolder/\" + c;\n }\n else{\n copyFile(path + \"WebFolder/\" + mobileFolderName + \"/\" + JS[i], packageLocation + \"/scripts\");\n jsPath[i] = path + \"WebFolder/\" + mobileFolderName + \"/\" + JS[i];\n }\n }\n \n for(var i=0; i<CSS.length; i++){\n if(CSS[i][0] == \"/\"){\n var c = CSS[i].replace(CSS[i][0],\"\");\n copyFile(path + \"WebFolder/\" + c, packageLocation + \"/styles\");\n cssPath[i] = path + \"WebFolder/\" + c;\n }\n else{\n copyFile(path + \"WebFolder/\" + mobileFolderName + \"/\" + CSS[i], packageLocation + \"/styles\");\n cssPath[i] = path + \"WebFolder/\" + mobileFolderName + \"/\" + CSS[i];\n }\n }\n \n \n \n \n /* COPY FILES NEEDED TO PACKAGE \n * \n * copy \"index-smartphone.html\" to package and rename it as \"index.html\" \t\n * copy \"index-smartphone.css\", \"index-smartphone.js\" \t \t\n * copy \"cors.js\" and \"handlers.js\" and \"loader.js\" from the extension to package \t \t \t\n * copy \"waf-optimize.js\" \"waf-optimize.css\" from our extension to package\n * \n * \n */ \t \t \t \t \t \t \t \t \t \t\n \t\t\t\n var isOK; \n isOK = copyFile( path + \"WebFolder/\" + mobileFolderName + \"/scripts/index-smartphone.js\", packageLocation + \"/scripts\" );\n copyFile( path + \"WebFolder/\" + mobileFolderName + \"/index-smartphone.html\", packageLocation, \"index.html\" );\n \n indexContent = loadText( packageLocation + \"/index.html\" ),\n metaCSS = \"<meta name=\\\"WAF.config.loadCSS\\\" id=\\\"waf-optimize\\\" content=\\\"styles/waf-optimize.css\\\"/>\",\n metaJS = \"<meta name=\\\"WAF.config.loadJS\\\" id=\\\"waf-optimize\\\" content=\\\"scripts/waf-optimize.js\\\"/>\";\n metaJS = isOK ? metaJS : metaJS + \"\\n<meta name=\\\"WAF.config.loadJS\\\" id=\\\"waf-script\\\" content=\\\"scripts/index-smartphone.js\\\"/>\";// in case index.js doesn't exist\n\n indexContent = indexContent.replace(\"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=UTF-8\\\"/>\",\"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=UTF-8\\\"/>\\n\" + metaJS + \"\\n\" + metaCSS);\n indexContent = indexContent.replace(\"/walib/WAF/\", \"walib/WAF/\" );\n indexContent = indexContent.replace( \"<script type=\\\"text/javascript\\\" src=\\\"/waLib/WAF/Loader.js\\\"></script>\", \"<script type=\\\"text/javascript\\\" src=\\\"walib/WAF/Loader.js\\\"></script><script type=\\\"text/javascript\\\" src=\\\"phonegap.js\\\"></script>\" );\n indexContent = indexContent.replace(\"walib/WAF/Loader.js\", \"scripts/Loader.js\" );\n indexContent = indexContent.replace(/data-src=\"\\//g, \"data-src=\");\n //indexContent = indexContent.replace(\"/application.css\", \"styles/application.css\" );\n \n for(var i=0; i < JS.length; i++){\n indexContent = indexContent.replace( JS[i], \"scripts/\" + File(jsPath[i]).name );\n }\n for(var i=0; i < CSS.length; i++){\n indexContent = indexContent.replace( CSS[i], \"styles/\" + File(cssPath[i]).name );\n }\n \n saveText( indexContent, packageLocation + \"/index.html\" );\n \n var l = \"WAF.core.baseURL = 'http://\" + data.ip + \":\" + data.port + \"';\\n\\\n WAF.core.restConnect.defaultService = 'cors';\\n\\\n WAF.core.restConnect.baseURL = 'http://\" + data.ip + \":\" + data.port + \"';\";\n var content = loadText(packageLocation + \"/scripts/index-smartphone.js\");\n l += content ? \"\\n\" + content : \"\";\n saveText( l, packageLocation + \"/scripts/index-smartphone.js\"); \n \n try{\n \n copyFile( path + \"WebFolder/\" + mobileFolderName + \"/styles/index-smartphone.css\", packageLocation + \"/styles\" );\n copyFile( path + \"WebFolder/application.css\", packageLocation + \"/styles\" );\n copyFile( studio.extension.getFolder().path + \"/resources/scripts/Loader.js\", packageLocation + \"/scripts\" );\n copyFile( studio.extension.getFolder().path + \"/resources/scripts/waf-optimize.js\", packageLocation + \"/scripts\" );\n copyFile( studio.extension.getFolder().path + \"/resources/scripts/handlers.js\", path + \"bootStrap\" );\n copyFile( studio.extension.getFolder().path + \"/resources/scripts/cors.js\", path + \"utils\" );\n copyFile( studio.extension.getFolder().path + \"/resources/styles/waf-optimize.css\", packageLocation + \"/styles\" );\n \n }\n catch(err){\n studio.alert( err.message );\n return false;\n }\n \n \n\t\t\t\t\t\n /* \n * Create config.xml file \n * \n */\n \n \n if( data.withPref ){\n \n var contentXML = loadText( studio.extension.getFolder().path + \"resources/config2.xml\" );\t\t \n \n var appInfo = [ \"\\\"\"+data.appId+\"\\\"\", data.appName, data.description, data.author, \"\\\"\" + File(data.icon).name + \"\\\"\", \"\\\"\" + File(data.splash).name + \"\\\"\", \"\\\"\"+data.pgVersion+\"\\\"\", \"\\\"\"+data.deviceOrientation+\"\\\"\", \"\\\"\"+data.deviceTarget+\"\\\"\", \"\\\"\"+data.fullScreen+\"\\\"\", \"\\\"\"+data.sdkMin+\"\\\"\", \"\\\"\"+data.sdkMax+\"\\\"\" ];\n var key = [ \"appId\", \"appName\", \"appDescription\", \"appAuthor\", \"\\\"icon\\\"\", \"\\\"splash\\\"\", \"pg-version\", \"pref-orientation\", \"pref-targ-device\", \"pref-fullscreen\", \"pref-minSDK\", \"pref-maxSDK\" ];\n\t\t\t\t\n for(var i=0; i < key.length; i ++){\t\t\t\t\n\t\t\t\t\t\tcontentXML = contentXML.replace( key[i], appInfo[i] );\n }\t\t\t\t\t\n\n\t\t\t\tfor( var i=0; i< data.APIs.length; i++ ){\n\t\t\t\t\t\tcontentXML = contentXML.replace('</widget>', '<feature name=\"http://api.phonegap.com/1.0/' + data.APIs[i] + '\" />\\n</widget>');\n\t\t\t\t}\n \n copyFile( data.icon, packageLocation );\n copyFile( data.splash, packageLocation );\n\t\t\t \n }\n else{ \n \n var contentXML = loadText( studio.extension.getFolder().path + \"resources/config1.xml\" );\t\t \n contentXML = contentXML.replace( 'appId', '\"' + data.appId + '\"');\n contentXML = contentXML.replace( 'appName', data.appName ); \n }\n \n saveText( contentXML, packageLocation + \"/config.xml\" );\n \n \n /*\n * Set bootStrap/hanlders.js as active bootStrap \n */\n \n var content = loadText( path + data.projectName + \".waProject\" );\n content = content.replace( \"</project>\", \"<file path=\\\"./bootStrap/handlers.js\\\"><tag name=\\\"bootStrap\\\"/></file></project>\" );\n saveText( content, path + data.projectName + \".waProject\" );\n\t\t\t\n\t\t\t\n\t\t\t/* compress package to zip format */\n\t\t\t\n toZip( packageLocation );\n Folder( packageLocation ).remove();\n\t\t\t\n\t\t\treturn true;\n\t\t\t\t\t\t\n } \n }\n}", "function minifyDir(from, to) {\n // init `to` directory\n del.sync(to, {force:true});\n mkdir(to);\n\n // process\n iterateFiles(from, function (filename) {\n var extname = filename.match('\\.[a-zA-Z0-9]*$')[0];\n var basename = path.basename(filename);\n var destdir = path.join(to, path.dirname(filename.replace(from, '')));\n var destname = path.join(destdir, basename);\n\n mkdir(destdir, function(err) {\n if (err && err.code !== 'EEXIST') {\n console.log('[ERROR] mkdir:', destdir, ':', err);\n } else {\n switch(extname) {\n case '.css':\n processCSS(filename, destname);\n break;\n case '.lua':\n processLUA(filename, destname);\n break;\n case '.div':\n case '.html':\n case '.xhtml':\n processHTML(filename, destname);\n break;\n default:\n fs.createReadStream(filename).pipe(fs.createWriteStream(destname));\n break;\n }\n }\n });\n }, function (err) {\n if (err) {\n console.log('sorry, fatal error found:', err)\n }\n });\n}", "function concatPackage (pack, outDir, minified) {\n if (_.contains(concatedPkgs, path.basename(pack))) return;\n\n var bowerFile = 'bower.json';\n\n if (! fs.existsSync(path.join(pack, bowerFile)))\n bowerFile = '.bower.json';\n\n var regularJSON = JSON.parse(\n fs.readFileSync(path.join(pack, bowerFile))\n );\n var bowerJSON = json.normalize(regularJSON);\n var deps = bowerJSON.dependencies || {};\n var mains = bowerJSON.main || [];\n\n concatedPkgs.push(path.basename(pack));\n\n _.each(Object.keys(deps), function (pkg, i, l) {\n var components = pack.split(path.sep);\n var pkgpath = components.slice(0, -1).join(path.sep);\n\n concatPackage(path.join(pkgpath, pkg), outDir, minified);\n });\n\n debug('concatenating package ' + path.basename(pack) + '...');\n\n var files = constructFileList(pack, mains, minified);\n var concatJS = '', concatCSS = '';\n\n _.each(files, function (filepath, i, l) {\n var contents = fs.readFileSync(filepath) + '\\n';\n var ext = filepath.split('.')[filepath.split('.').length - 1];\n\n if (ext === 'js' || ext === 'css')\n debug('including file ' + filepath + '...');\n\n if (ext === 'js')\n concatJS += contents;\n else if (ext === 'css')\n concatCSS += contents;\n });\n\n if (concatJS !== '' || concatCSS !== '')\n debug('writing files...');\n\n if (concatJS !== '')\n fs.appendFileSync(path.join(outDir, 'build.js'), concatJS);\n\n if (concatCSS !== '')\n fs.appendFileSync(path.join(outDir, 'build.css'), concatCSS);\n}", "async function generatePackageJson() {\n const original = require('../package.json')\n const result = {\n name: original.name,\n author: original.author,\n version: original.version,\n license: original.license,\n description: original.description,\n main: './index.js',\n dependencies: Object.entries(original.dependencies).filter(([name, version]) => original.external.indexOf(name) !== -1).reduce((object, entry) => ({ ...object, [entry[0]]: entry[1] }), {})\n }\n await writeFile('dist/package.json', JSON.stringify(result))\n}", "function unzip() {\n return new Promise((resolve, reject) => {\n if (!fs.existsSync(path.join(__dirname, '/../tmp/gtfs/trips.txt'))) {\n const zip = new StreamZip({\n file: path.join(__dirname, '/../tmp/gtfs.zip'),\n storeEntries: true\n });\n // Handle errors\n zip.on('error', err => {\n reject(err)\n console.log(err)\n });\n zip.on('ready', () => {\n zip.extract(null, path.join(__dirname, '/../tmp/gtfs/'), (err, count) => {\n if (err) reject(err);\n console.log(\"(2/6) Zipfile has been extracted\")\n zip.close();\n resolve();\n });\n });\n } else {\n console.log(\"(2/6) The gtfs files already seems to be extracted, if not delete everything in the '/tmp/gtfs' directory\");\n resolve();\n }\n })\n\n}", "function zippedShapefile(file) {\n\n //Require .zip extension\n if (file.name.match(/[.]zip$/i)) {\n\n //Create form with file upload\n var formData = new FormData();\n formData.append(file.name.substring(file.name.length-3).toLowerCase(), file);\n\n if (file.size > 15000000) {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"shp-too-big\");\n uploadComplete();\n return true;\n }\n\n //Pass file to a wrapper that will cURL the real converter, gets around cross-domain\n //Once whole server is running on Node this won't be necessary\n d3.xhr(\"/convert/shp-to-geo/\").post(formData,function(error,response) {\n\n try {\n var newFile = {name: file.name.replace(/[.]zip$/i,\".geojson\"), size: response.responseText.length, data: {topo: null, geo: fixGeo(JSON.parse(response.responseText))}, type: \"geojson\"};\n } catch(err) {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"invalid-file\");\n uploadComplete();\n return false;\n }\n\n loaded(newFile);\n\n return true;\n\n\n });\n\n } else {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"invalid-file\");\n uploadComplete();\n\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotate a Vector3 around the zaxis
function rotate_vector3_z(vector, angle_in_degrees) { var r = deg2rad(angle_in_degrees); var s = Math.sin(r); var c = Math.cos(r); var multMatrix = new Matrix4(); multMatrix.elements = [ c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; return multMatrix.multiplyVector3(vector); }
[ "function rotateZ(point, radians) {\r\n\tvar x = point.x;\r\n\tpoint.x = (x * Math.cos(radians)) + (point.y * Math.sin(radians) * -1.0);\r\n\tpoint.y = (x * Math.sin(radians)) + (point.y * Math.cos(radians));\r\n}", "function rotate_vector3_x(vector, angle_in_degrees) {\n var r = deg2rad(angle_in_degrees);\n var s = Math.sin(r);\n var c = Math.cos(r);\n var multMatrix = new Matrix4();\n multMatrix.elements = [\n 1, 0, 0, 0,\n 0, c, -s, 0,\n 0, s, c, 0,\n 0, 0, 0, 1];\n return multMatrix.multiplyVector3(vector);\n}", "static rotateZ(angle) {\n var radian = 0;\n if (GLBoost[\"VALUE_ANGLE_UNIT\"] === GLBoost.DEGREE) {\n radian = MathUtil.degreeToRadian(angle);\n } else {\n radian = angle;\n }\n\n var cos = Math.cos(radian);\n var sin = Math.sin(radian);\n return new Matrix33(\n cos, -sin, 0,\n sin, cos, 0,\n 0, 0, 1\n );\n }", "function rotate_vector3_y(vector, angle_in_degrees) {\n var r = deg2rad(angle_in_degrees);\n var s = Math.sin(r);\n var c = Math.cos(r);\n var multMatrix = new Matrix4();\n multMatrix.elements = [\n c, 0, s, 0,\n 0, 1, 0, 0,\n -s, 0, c, 0,\n 0, 0, 0, 1];\n return multMatrix.multiplyVector3(vector);\n}", "function gRotate(theta,x,y,z) {\r\n modelViewMatrix = mult(modelViewMatrix,rotate(theta,[x,y,z])) ;\r\n}", "move3d(x1, y1, z1)\n {\n this.x=x1; this.y=y1; this.z=z1;\n this.rotate();\n\n this.cx=Math.floor(this.x);\n this.cy=Math.floor(this.y);\n }", "function mRotateZ() {\n rotateZ(...[...arguments]);\n mPage.rotateZ(...[...arguments]);\n}", "function rotateZ(rads) {\n var cosTheta, sinTheta;\n cosTheta = Math.cos(rads);\n sinTheta = Math.sin(rads);\n return function (point) {\n var x = point.x * cosTheta - point.y * sinTheta;\n var y = point.y * cosTheta + point.x * sinTheta;\n return new Point(x, y, point.z);\n };\n}", "function rotateVec(vec, angle){\n mag = vecLength(vec);\n ang = vecAngle(vec);\n vec.x = Math.cos(ang + angle) * mag;\n vec.y = Math.sin(ang + angle) * mag;\n}", "function vectorAngle(x, z) {\n\t\treturn (Math.atan2(x,z) - Math.atan2(0,0))* (180/Math.PI);\n\t}", "rotateAroundWorldAxis(obj, axis, radians) {\n let rotWorldMatrix = new THREE.Matrix4();\n rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);\n rotWorldMatrix.multiply(obj.matrix); // pre-multiply\n obj.matrix = rotWorldMatrix;\n obj.rotation.setFromRotationMatrix(obj.matrix);\n }", "function rotateAroundWorldAxis(object, axis, radians) {\nrotWorldMatrix = new THREE.Matrix4();\nrotWorldMatrix.makeRotationAxis(axis, radians);\nrotWorldMatrix.multiply(object.matrix); // pre-multiply\nobject.matrix = rotWorldMatrix;\nobject.rotation.setFromRotationMatrix(object.matrix);\n}", "static RotationZ(angle) {\n const result = new Matrix();\n Matrix.RotationZToRef(angle, result);\n return result;\n }", "function floatRotate(bullet){\n \t//bullet.x = globalVar.playerX;\n \t//bullet.y = globalVar.playerY;\n \tglobalVar.test =bullet.rotation;\n \t//bullet.rotation += .1;\n \tbullet.rotation = bullet.rotation+(20* (Math.PI/180));\n \t\n }", "function rotate(objectName, axis, data)\n\t{\n\t\t\n\t\t// (data.x - prevRotX) will either be 1 or -1 (but sometimes greater than 1, TODO: fix)\n\t\t// rotationSnap is the angle at which to move the object\n\t\t// Converting to rads\n\t\t// example: (-1 * 90) = -90\n\t\t\n\t\tif ( axis === \"x\" ) \n\t\t{\n\t\t\tvar x = ((data - prevRotX) * (rotationSnap)) * Math.PI / 180;\t\n\t\t\tobjects[objectName].obj.rotateX(x);\n\t\t\tprevRotX = data;\n\t\t}\n\t\telse if ( axis === \"y\" ) \n\t\t{\n\t\t\tvar y = ((data - prevRotY) * (rotationSnap)) * Math.PI / 180;\n\t\t\tobjects[objectName].obj.rotateY(y);\n\t\t\tprevRotY = data;\n\t\t}\n\t\telse if ( axis === \"z\" ) \n\t\t{\n\t\t\tvar z = ((data - prevRotZ) * (rotationSnap)) * Math.PI / 180;\n\t\t\tobjects[objectName].obj.rotateZ(z);\n\t\t\tprevRotZ = data;\n\t\t}\n\t\t\n\t\tmain.setRotation(objectName);\n\t}", "static LookRotation(forward, up = preallocatedVariables_1$2.MathTmp.staticUp) {\n const forwardNew = Vector3_1$5.Vector3.Normalize(forward);\n const right = Vector3_1$5.Vector3.Normalize(Vector3_1$5.Vector3.Cross(up, forwardNew));\n const upNew = Vector3_1$5.Vector3.Cross(forwardNew, right);\n const m00 = right.x;\n const m01 = right.y;\n const m02 = right.z;\n const m10 = upNew.x;\n const m11 = upNew.y;\n const m12 = upNew.z;\n const m20 = forwardNew.x;\n const m21 = forwardNew.y;\n const m22 = forwardNew.z;\n const num8 = m00 + m11 + m22;\n const quaternion = new Quaternion();\n if (num8 > 0) {\n let num = Math.sqrt(num8 + 1);\n quaternion.w = num * 0.5;\n num = 0.5 / num;\n quaternion.x = (m12 - m21) * num;\n quaternion.y = (m20 - m02) * num;\n quaternion.z = (m01 - m10) * num;\n return quaternion;\n }\n if (m00 >= m11 && m00 >= m22) {\n const num7 = Math.sqrt(1 + m00 - m11 - m22);\n const num4 = 0.5 / num7;\n quaternion.x = 0.5 * num7;\n quaternion.y = (m01 + m10) * num4;\n quaternion.z = (m02 + m20) * num4;\n quaternion.w = (m12 - m21) * num4;\n return quaternion;\n }\n if (m11 > m22) {\n const num6 = Math.sqrt(1 + m11 - m00 - m22);\n const num3 = 0.5 / num6;\n quaternion.x = (m10 + m01) * num3;\n quaternion.y = 0.5 * num6;\n quaternion.z = (m21 + m12) * num3;\n quaternion.w = (m20 - m02) * num3;\n return quaternion;\n }\n const num5 = Math.sqrt(1 + m22 - m00 - m11);\n const num2 = 0.5 / num5;\n quaternion.x = (m20 + m02) * num2;\n quaternion.y = (m21 + m12) * num2;\n quaternion.z = 0.5 * num5;\n quaternion.w = (m01 - m10) * num2;\n return quaternion;\n }", "sphericalCoordsToVector3(position, vector) {\n if (!vector) {\n vector = new import_three6.Vector3();\n }\n vector.x = SPHERE_RADIUS * -Math.cos(position.pitch) * Math.sin(position.yaw);\n vector.y = SPHERE_RADIUS * Math.sin(position.pitch);\n vector.z = SPHERE_RADIUS * Math.cos(position.pitch) * Math.cos(position.yaw);\n return vector;\n }", "rotate(axis, angle) {\n var state = this.cam.state;\n if(angle) {\n var new_rotation = Rotation.create({axis:axis, angle:angle});\n Rotation.applyToRotation(state.rotation, new_rotation, state.rotation);\n }\n }", "static rotateZ(_matrix, _angleInDegrees) {\n return Mat4.multiply(_matrix, this.zRotation(_angleInDegrees));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a random sample of mentions per party, one per topic. Mentions are returned in chronological order.
function sampleMentions() { return data.parties.map(function(party, i) { return data.topics .map(function(d) { return d.parties[i].mentions; }) .filter(function(d) { return d.length; }) .map(function(d) { return d[Math.floor(Math.random() * d.length)]; }) .sort(orderMentions); }); }
[ "function randomTopic()\n{ \n return Math.floor(Math.random()*ribbon_data.length);\n}", "function getRandom() {\n\tvar l = tweets.length; // grab length of tweet array\n\tvar ran = Math.floor(Math.random()*l); // grab random user\n\n\treturn tweets[ran];\n}", "function randomPhrase (phrases){\r\n\treturn phrases[Math.floor(Math.random()*phrases.length)];\r\n\t}", "static generateRandomTweetText(seed = config_1.default.faker.seed, mention) {\n const type = utility_1.getRandomEnumElement(FakerTweetTypes);\n let result;\n switch (type) {\n case FakerTweetTypes.COMPANY_BS:\n result = Tweet.getValidTweetString(\n [\n faker.company.bsAdjective(),\n faker.company.bsBuzz(),\n faker.company.bsNoun()\n ],\n [\n faker.company.catchPhraseAdjective(),\n faker.company.catchPhraseAdjective()\n ],\n mention\n );\n return result;\n case FakerTweetTypes.COMPANY_CATCH_PHRASE:\n result = Tweet.getValidTweetString(\n [\n faker.company.catchPhraseAdjective(),\n faker.company.catchPhraseDescriptor(),\n faker.company.catchPhraseNoun()\n ],\n [faker.company.bsAdjective(), faker.company.bsAdjective()],\n mention\n );\n return result;\n case FakerTweetTypes.HACKER:\n result = Tweet.getValidTweetString(\n faker.hacker.phrase(),\n [faker.hacker.ingverb(), faker.hacker.adjective()],\n mention\n );\n return result;\n case FakerTweetTypes.LOREM:\n result = Tweet.getValidTweetString(\n faker.lorem.sentence(),\n [faker.company.bsAdjective(), faker.lorem.word()],\n mention\n );\n return result;\n case FakerTweetTypes.WORDS:\n result = Tweet.getValidTweetString(\n [\n faker.random.word(),\n faker.random.word(),\n faker.random.word(),\n faker.random.word()\n ],\n [faker.random.word(), faker.random.word()],\n mention\n );\n return result;\n }\n }", "function randomNumber() {\n return Math.floor(Math.random() * realSentences.length);\n}", "function getPerson() {\r\n return people[Math.floor(Math.random() * people.length)];\r\n}", "getRandomArtist(artists){\r\n // use a random number to select which artist within length \r\n let artistNumber = this.getRandomInt(artists.length);\r\n // Use random number to pick an artists\r\n let artist = artists[artistNumber];\r\n // return artist\r\n return artist;\r\n }", "sampleEmotion(emotion) {\n let potentialActions = []\n if(emotion.constructor === Array) {\n emotion.forEach(e => {\n emotions[e].forEach(a => {\n potentialActions.push(a)\n })\n })\n } else {\n potentialActions = emotions[emotion]\n }\n\n this.action(sample(potentialActions))\n }", "function generateWords() {\n words = _.sampleSize(wordList, 3);\n}", "function randomWordList(num) {\nvar wordList = []\n for (j = 0; j < num; j++) {\n wordList.push(randomWord());\n}\nreturn wordList\n}", "function getRandomLeadSource() {\r\tvar leadSourceArr = [],\r\t\tlen = null;\r\t\t\r\t\r\tleadSourceArr.push(\"-none-\");\r\tleadSourceArr.push(\"Advertisement\");\r\tleadSourceArr.push(\"Cold Call\");\r\tleadSourceArr.push(\"Employee Referral\");\r\tleadSourceArr.push(\"External Referral\");\r\tleadSourceArr.push(\"Online Store\");\r\tleadSourceArr.push(\"Partner\");\r\tleadSourceArr.push(\"Trade Show\");\r\tleadSourceArr.push(\"Web Research\");\r\t\r\tlen = leadSourceArr.length - 1;\r\t\r\treturn leadSourceArr[_.random(0, len)];\r}", "function getRandomEnemySeed(chosenDifficulty){\n let maxEnemyCount;\n\n if(chosenDifficulty === 'easy'){\n maxEnemyCount = enemyList[0].difficulty[0].easy.length;\n }else if(chosenDifficulty === 'medium'){\n maxEnemyCount = enemyList[0].difficulty[1].medium.length;\n }\n\n return Math.floor(Math.random() * maxEnemyCount);\n}", "random(){\r\n\t\t\tlet index = Math.random() * this.citations.length ^ 0;\r\n\t\t\tlet citation = this.citations[index];\r\n\t\t\tcitation.text = citation.text.replaceAll('\\n', '<br>');\r\n\t\t\treturn citation;\r\n\t\t}", "function randomLevelWord(lvl) {\n let n, word;\n switch (lvl) {\n case 1:\n n = Math.floor(Math.random() * words.wordList.list1.length);\n word = words.wordList.list1[n];\n break;\n case 2:\n n = Math.floor(Math.random() * words.wordList.list2.length);\n word = words.wordList.list2[n];\n break;\n case 3:\n n = Math.floor(Math.random() * words.wordList.list3.length);\n word = words.wordList.list3[n];\n break;\n case 4:\n n = Math.floor(Math.random() * words.wordList.list3.length);\n word = words.wordList.list4[n];\n break;\n default:\n break;\n }\n return word.toUpperCase();\n }", "function genPhrase(){\n let subject = subjectsText[Math.floor(Math.random() * subjectsText.length)];\n let verb = verbsText[Math.floor(Math.random() * verbsText.length)];\n let preposition1 = prepositionsText[Math.floor(Math.random() * prepositionsText.length)];\n let preposition2 = prepositionsText[Math.floor(Math.random() * prepositionsText.length)];\n let jargon1 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let jargon2 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let jargon3 = artJargonText[Math.floor(Math.random() * artJargonText.length)];\n let sentence = subject + \" \" + verb + \" \" + jargon1 + \" \" + preposition1 + \" \" + jargon2 + \" \" + preposition2 + \" \" + jargon3 + \".\";\n return sentence;\n}", "function fetchWords() {\n \n num1 = Math.floor(Math.random() * 490);\n num2 = Math.floor(Math.random() * 490);\n num3 = Math.floor(Math.random() * 490);\n num4 = Math.floor(Math.random() * 490);\n numOptions = [num1, num2, num3, num4];\n numr = numOptions[Math.floor(Math.random() * 4)];\n numr2 = Math.floor(Math.random() * 4);\n\n fetchWord();\n fetchOptions();\n}", "function pickRandomArtist(artists) {\n var max = artists.length;\n \n var randomNum = Math.floor(Math.random() * Math.floor(max));\n \n return artists[randomNum]; // TODO: MAKE THIS RANDOM\n}", "function fillRandn(m, mu, std) {\n for (let i = 0, n = m.w.length; i < n; i++) {\n m.w[i] = randn(mu, std);\n }\n}", "function getRandomDescription(descriptions) {\n\td = descriptions\n\tvar i = 1;\n\t\n\tvar rand = Math.floor(Math.random() * d.length);\n\tif (rand == 0) { rand = 1 }\n\t\n\tfor (i = 1; i < d.length; ++i) {\n\t\tif (i == rand) {\n\t\t\treturn d[i]\n\t\t}\n\t}\n}", "function populateShuffledOtherContributorNames(element_id) {\n var shuffled_names = shuffleNames(other_contributor_names);\n document.getElementById(element_id).innerHTML = concatenateNames(shuffled_names);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IMGUI_API void StyleColorsDark(ImGuiStyle dst = NULL);
function StyleColorsDark(dst = null) { if (dst === null) { bind.StyleColorsDark(null); } else if (dst.internal instanceof bind.ImGuiStyle) { bind.StyleColorsDark(dst.internal); } else { const native = new bind.ImGuiStyle(); const wrap = new ImGuiStyle(native); wrap.Copy(dst); bind.StyleColorsDark(native); dst.Copy(wrap); native.delete(); } }
[ "function StyleColorsLight(dst = null) {\r\n if (dst === null) {\r\n bind.StyleColorsLight(null);\r\n }\r\n else if (dst.internal instanceof bind.ImGuiStyle) {\r\n bind.StyleColorsLight(dst.internal);\r\n }\r\n else {\r\n const native = new bind.ImGuiStyle();\r\n const wrap = new ImGuiStyle(native);\r\n wrap.Copy(dst);\r\n bind.StyleColorsLight(native);\r\n dst.Copy(wrap);\r\n native.delete();\r\n }\r\n }", "function StyleColorsClassic(dst = null) {\r\n if (dst === null) {\r\n bind.StyleColorsClassic(null);\r\n }\r\n else if (dst.internal instanceof bind.ImGuiStyle) {\r\n bind.StyleColorsClassic(dst.internal);\r\n }\r\n else {\r\n const native = new bind.ImGuiStyle();\r\n const wrap = new ImGuiStyle(native);\r\n wrap.Copy(dst);\r\n bind.StyleColorsClassic(native);\r\n dst.Copy(wrap);\r\n native.delete();\r\n }\r\n }", "function updateStyle() {\r\n\tif (settings.darkThemeSettings) {\r\n\t\t//dark theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#0F0F0F\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#a53737\");\r\n\t} else {\r\n\t\t//light theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#000000\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#f55555\");\r\n\t}\r\n}", "function changeColorTextTheme(value, colorDark, colorLight) {\r\n if (value === \"dark\") {\r\n return { color: colorDark };\r\n } else return { color: colorLight };\r\n }", "function changeBackgroundTheme(value, bgDark, bgLight) {\r\n if (value === \"dark\")\r\n return {\r\n backgroundColor: bgDark,\r\n border: \"1px solid #393939\",\r\n };\r\n else {\r\n return {\r\n backgroundColor: bgLight,\r\n border: \"1px solid #e8dfec\",\r\n };\r\n }\r\n }", "get backgroundColor() {\n let backgroundColor = 0xffffff;\n if (Store.getState()) {\n const tp = Store.getState().theme.options.type;\n if (tp === \"dark\") {\n backgroundColor = 0;\n }\n }\n return backgroundColor;\n }", "function setDarkModeFromBackgroundColor(element) {\n const backgroundColor = findBackgroundColor(element);\n const rgb = parseRgb(backgroundColor);\n if (rgb) {\n const hsl = rgbToHsl(rgb);\n // We consider any lightness below 50% to be dark.\n const dark = hsl.l < 0.5;\n element[setState]({ dark });\n }\n}", "resetCustomColors() {\n this.themeSwitch.removeCustomTheme();\n this.removeFromLocalStorage();\n this.colorButtons.forEach(button => {\n button.style.backgroundColor = ``;\n })\n this.assignColorsToButtonsDataAttribute();\n this.removeFromLocalStorage();\n this.colors = this.themeSwitch.getColors();\n }", "_colorUpdate() {\n if(this.value){\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': this.value,\n '--l2t-paper-color-indicator-icon-display': 'block',\n });\n } else {\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': 'transparent',\n '--l2t-paper-color-indicator-icon-display': 'none',\n });\n }\n }", "function determineDarkMode() {\n (userPreferences.darkMode) ? darkMode(true) : {};\n}", "function updateColorThemeDisplay() {\n // template string for the color swatches:\n const makeSpanTag = (color, count, themeName) => (\n `<span style=\"background-color: ${color};\" `\n + `class=\"color_sample_${count}\" `\n + `title=\"${color} from d3 color scheme ${themeName}\">`\n + '&nbsp;</span>'\n );\n for (const t of colorThemes.keys()) {\n const theme = approvedColorTheme(t),\n themeOffset = elV(offsetField(t)),\n colorset = rotateColors(theme.colorset, themeOffset),\n // Show the array rotated properly given the offset:\n renderedGuide = colorset\n .map((c) => makeSpanTag(c, colorset.length, theme.d3Name))\n .join('');\n // SOMEDAY: Add an indicator for which colors are/are not\n // in use?\n el(`theme_${t}_guide`).innerHTML = renderedGuide;\n el(`theme_${t}_label`).textContent = theme.nickname;\n }\n }", "function updateThemeWithAppSkinInfo(appSkinInfo) {\n // console.log(appSkinInfo)\n var panelBgColor = appSkinInfo.panelBackgroundColor.color;\n var bgdColor = toHex(panelBgColor);\n var fontColor = \"F0F0F0\";\n if (panelBgColor.red > 122) {\n fontColor = \"000000\";\n }\n \n var styleId = \"hostStyle\";\n addRule(styleId, \"body\", \"background-color:\" + \"#\" + bgdColor);\n addRule(styleId, \"body\", \"color:\" + \"#\" + fontColor);\n \n var isLight = appSkinInfo.panelBackgroundColor.color.red >= 127;\n if (isLight) {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-light.css\");\n } else {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-dark.css\");\n }\n }", "function refreshSwatch() {\nvar coloredSlider = $( \"#coloredSlider\" ).slider( \"value\" ),\ncurrentColor = getTheColor( coloredSlider );\nstrokeStyle = currentColor;\n\n$( \"#coloredSlider .ui-state-default, .ui-widget-content .ui-state-default\" ).css( \"background-color\", currentColor );\n}", "function darkMode(preference) {\n if (preference) { //turn dark mode on\n $(\"#current-note-body\").css({\n 'color': 'white',\n 'background-color': '#2a2a2a'\n });\n $(\"#toolbar\").css({\n 'background-color': '#1b1b1b'\n });\n $(\".ql-snow .ql-fill, .ql-snow .ql-stroke.ql-fill\").css('fill', 'white');\n $(\".ql-snow .ql-stroke, .ql-snow .ql-stroke.ql-fill\").css('stroke', 'white');\n $(\".ql-snow .ql-picker .ql-picker-label\").css('color', 'rgb(118, 118, 118)');\n\n //Change dark mode button colors\n $(\"#dark-mode-btn\")[0].checked = true;\n $(\"#dark-mode-bulb\").css('color', 'white');\n }\n else { //turn dark mode off\n $(\"#current-note-body\").css({\n 'color': 'black',\n 'background-color': 'white'\n });\n $(\"#toolbar\").css({\n 'background-color': 'white'\n });\n $(\".ql-snow .ql-fill, .ql-snow .ql-stroke.ql-fill\").css('fill', '#444');\n $(\".ql-snow .ql-stroke, .ql-snow .ql-stroke.ql-fill\").css('stroke', '#444');\n $(\".ql-snow .ql-picker .ql-picker-label\").css('color', 'rgb(68, 68, 68)');\n\n //Change dark mode button colors\n $(\"#dark-mode-btn\")[0].checked = false;\n $(\"#dark-mode-bulb\").css('color', '#444')\n }\n}", "function updatePaletteSwatch(button, color)\n{\n if(color) \n button.setAttribute(\"data-color\", color);\n\n button.firstElementChild.style.background = \n button.getAttribute(\"data-color\");\n}", "function turnOff() {\n\t\twindow.nexpaqAPI.DevMod.send(\"Primary_colors\", [0]); //send Primary_colors, arg 0\n\t}", "function setTheme(themValueObj) {\n for (const key in themValueObj) {\n document.documentElement.style.setProperty(`--${key}`, themValueObj[key]);\n }\n}", "function letterboxColor (command_) {\n\tvar argList = toArgList (command_);\n\n\tvar red = argList[1];\n\tvar green = argList[2];\n\tvar blue = argList[3];\n\n\tdocument.body.style.background = 'rgb(' + red + ',' + green + ',' +\n\t blue + ')';\n}", "function handleThemeChange() {\n\t\tsetTheme(theme === \"light\" ? \"dark\" : \"light\");\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getGoogleSessionManager Shortcut to the google session manager
function getGoogleSessionManager() { if (this.mObject === undefined) { this.mObject = Components.classes["@mozilla.org/calendar/providers/gdata/session-manager;1"] .createInstance(Components.interfaces.calIGoogleSessionManager); } return this.mObject; }
[ "function getClient() {\n return new googleapis.auth.OAuth2(\n config.clientId,\n config.clientSecret,\n config.redirectUrl\n );\n }", "function googleOAuthDomain_(name,scope) {\n var oAuthConfig = UrlFetchApp.addOAuthService(name);\n oAuthConfig.setRequestTokenUrl(\"https://www.google.com/accounts/OAuthGetRequestToken?scope=\"+scope);\n oAuthConfig.setAuthorizationUrl(\"https://www.google.com/accounts/OAuthAuthorizeToken\");\n oAuthConfig.setAccessTokenUrl(\"https://www.google.com/accounts/OAuthGetAccessToken\");\n var consumerKey = ScriptProperties.getProperty(\"consumerKey\");\n var consumerSecret = ScriptProperties.getProperty(\"consumerSecret\");\n oAuthConfig.setConsumerKey(consumerKey);\n oAuthConfig.setConsumerSecret(consumerSecret);\n return {oAuthServiceName:name, oAuthUseToken:\"always\"};\n}", "function getSession(request, response) {\n\tvar session = request.session;\n\tconsole.log(\"SESSION: \", session);\n\tif (!session.sfdcAuth) {\n\t\tresponse.status(401).send('No active session');\n\t\treturn null;\n\t}\n\treturn session;\n}", "function OAuthManager() {\n}", "function getSessionDatastoreID() {\n var sessionToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\n\n if (!sessionToken) {\n sessionToken = getSessionToken();\n }\n\n var session = jsontokens.decodeToken(sessionToken).payload;\n return session.app_user_id;\n}", "function getGithubService_() {\n return OAuth2.createService('GitHub')\n .setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')\n .setTokenUrl('https://github.com/login/oauth/access_token')\n .setClientId(CLIENT_ID)\n .setClientSecret(CLIENT_SECRET)\n .setCallbackFunction('authCallback')\n .setPropertyStore(PropertiesService.getUserProperties())\n .setScope('repo'); \n}", "function getSession(ctx) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!matchPath(ctx)) {\n return;\n }\n if (storeStatus === PENDING) {\n // store is disconnect and pending;\n yield waitStore;\n }\n else if (storeStatus === UNAVAILABLE) {\n // store is unavailable\n throw new Error(\"session store is unavailable\");\n }\n if (!ctx.sessionId) {\n ctx.sessionId = sessionIdStore.get(ctx);\n }\n let session;\n let isNew = false;\n if (!ctx.sessionId) {\n // session id not exist, generate a new one\n session = generateSession();\n ctx.sessionId = genSid(ctx, 24);\n // now the ctx.cookies.get(key) is null\n isNew = true;\n }\n else {\n try {\n // get session %j with key %s\", session, this.sessionId\n session = yield store.get(ctx.sessionId);\n }\n catch (err) {\n if (err.code === \"ENOENT\") {\n console.warn(\"get session error, code = ENOENT\");\n }\n else {\n console.warn(\"get session error: \", err.message);\n errorHandler(err, \"get\", ctx);\n }\n }\n }\n // make sure the session is still valid\n if (!session || !valid(ctx, session)) {\n // session is empty or invalid\n session = generateSession();\n ctx.sessionId = genSid(ctx, 24);\n // now the ctx.cookies.get(key) is null\n sessionIdStore.reset(ctx);\n isNew = true;\n }\n // get the originHash\n const originalHash = !isNew && hash(session);\n return {\n originalHash,\n session,\n isNew,\n };\n });\n }", "get session() {\n return this.mSession;\n }", "function initCrossBrowserSupportForGmFunctions() {\n if (typeof GM_deleteValue == 'undefined') {\n GM_addStyle = function (css) {\n var style = document.createElement('style');\n style.textContent = css;\n document.getElementsByTagName('head')[0].appendChild(style);\n }\n GM_deleteValue = function (name) {\n localStorage.removeItem(name);\n }\n GM_getValue = function (name, defaultValue) {\n var value = localStorage.getItem(name);\n if (!value)\n return defaultValue;\n var type = value[0];\n value = value.substring(1);\n switch (type) {\n case 'b':\n return value == 'true';\n case 'n':\n return Number(value);\n default:\n return value;\n }\n }\n GM_log = function (message) {\n console.log(message);\n }\n GM_openInTab = function (url) {\n return window.open(url, \"_blank\");\n }\n GM_registerMenuCommand = function (name, funk) {\n //todo\n }\n GM_setValue = function (name, value) {\n value = (typeof value)[0] + value;\n localStorage.setItem(name, value);\n }\n }\n}", "async function createSession() {\n const idvClient = new IDVClient(config.YOTI_CLIENT_SDK_ID, config.YOTI_PEM);\n\n const sessionSpec = new SessionSpecificationBuilder()\n .withClientSessionTokenTtl(600)\n .withResourcesTtl(90000)\n .withUserTrackingId('some-user-tracking-id')\n // For zoom liveness check [only one type of liveness check to be enabled at a time]\n .withRequestedCheck(new RequestedLivenessCheckBuilder()\n .forZoomLiveness()\n .build())\n // For static liveness check\n // .withRequestedCheck(\n // new RequestedLivenessCheckBuilder()\n // .forStaticLiveness()\n // .build()\n // )\n .withRequestedCheck(new RequestedFaceComparisonCheckBuilder()\n .withManualCheckNever()\n .build())\n .withSdkConfig(new SdkConfigBuilder()\n .withSuccessUrl(`${config.YOTI_APP_BASE_URL}/success`)\n .withErrorUrl(`${config.YOTI_APP_BASE_URL}/error`)\n .withPrivacyPolicyUrl(`${config.YOTI_APP_BASE_URL}/privacy-policy`)\n .withJustInTimeBiometricConsentFlow() // or withEarlyBiometricConsentFlow()\n .build())\n .build();\n\n return idvClient.createSession(sessionSpec);\n}", "renewSession() {\n // implement in concrete authenticator\n }", "get googleCalendarName() {\n return this.mCalendarName;\n }", "startNew(options) {\n let serverSettings = this.serverSettings;\n return session_1.Session.startNew(Object.assign({}, options, { serverSettings })).then(session => {\n this._onStarted(session);\n return session;\n });\n }", "static Get(serviceName) {\n\t if(!this.g_services) this.g_services = [];\n\t \n\t return this.g_services[serviceName];\n }", "function WindowManager() {\n if (window_manager_ == null) {\n window_manager_ = new WindowManagerImpl(document.getElementById(\"data_windows\"),\n document.getElementById(\"window_menu\"));\n }\n return window_manager_;\n}", "function newSession() {\n\n // Get a session from the API.\n sessionPromise = SessionDataService.create().then(\n function (session) {\n\n // Replace currently stored session.\n replace(sessionObject, session);\n\n return sessionObject;\n });\n\n return sessionPromise;\n }", "function getSession(text) {\n\n return text.substring(text.search('Session ID:')).split('\\n', 1)[0];\n\n }", "function getSharedLocations(callback) {\r\n\r\n let options_map = {\r\n url: \"https://www.google.com/maps/preview/locationsharing/read\",\r\n headers: {\r\n \"Cookie\": google_cookie_header\r\n },\r\n method: \"GET\",\r\n qs: {\r\n \"authuser\": 0,\r\n \"pb\": \"\"\r\n }\r\n };\r\n\r\n request(options_map, function(err, response, body){\r\n if(err || !response) {\r\n // no connection\r\n\r\n adapter.log.error(err);\r\n adapter.log.info('Connection to google maps failure.');\r\n if(callback) callback(true);\r\n } else {\r\n // connection successful\r\n adapter.log.debug('Response: ' + response.statusMessage);\r\n\r\n // connection established but auth failure\r\n if(response.statusCode !== 200) {\r\n adapter.log.debug('Removed cookies.');\r\n adapter.log.error('Connection works, but authorization failure, please login manually!');\r\n adapter.log.info('Could not connect to google, please login manually!');\r\n\r\n if(callback) callback(true);\r\n } else {\r\n // parse and save user locations\r\n let locationdata = JSON.parse(body.split('\\n').slice(1, -1).join(''));\r\n\r\n parseLocationData(locationdata, function(err, userobjarr) {\r\n if(err) {\r\n if(callback) callback(err);\r\n } else {\r\n if(callback) callback(false, userobjarr);\r\n }\r\n });\r\n }\r\n }\r\n });\r\n}", "getIdentityprovidersGsuite() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/identityproviders/gsuite', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
se termina la funcion newGame y abreanimacionGmOver, que anima el html+css y muestra el puntaje obtenido
function animacionGmOver() { console.log("Perdiste AMEEEEO!!"); }
[ "function newGame () {\n currentGame = new Game();\n randomColors();\n changeScore();\n $('#level').html(currentGame.level);\n $('.colors-box').css('border', 'none');\n $('.color-1').html('');\n $('.color-2').html('');\n borderReset($('.color-1'));\n borderReset($('.color-2'));\n timer();\n}", "function startNewGame() {\n audioGame.pause();\n audioGame.currentTime = 0;\n document.getElementById(\"pacman_life1\").style.display = \"block\";\n document.getElementById(\"pacman_life2\").style.display = \"block\";\n document.getElementById(\"pacman_life3\").style.display = \"block\";\n clearAllInterval();\n Start(globalNumberOfBall, globalNumberOfGhost);\n}", "function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}", "function rogueBotAnimSelector() {\n\t\t\t\tif (rogueBot.state == \"idle\") {\n\t\t\t\t\trogueBot.animation.idle.renderSprite(rogueBotAnimIdleImg, 0 , 0 , 512 , 512, )\n\t\t\t\t} \n\t\t\t\telse if (rogueBot.state == \"running\") {\n\t\t\t\t\trogueBot.animation.running.renderSprite(rogueBotAnimRunningImg, 0 , 0 , 512 , 512, )\n\t\t\t\t} \n\t\t\t\telse if (rogueBot.state == \"jumping\") {\n\t\t\t\t\trogueBot.animation.jumping.renderSprite(rogueBotAnimJumpingImg, 0 , 0 , 512 , 512, )\n\t\t\t\t}\n\t\t\t\telse if (rogueBot.state == \"runninggunning\") {\n\t\t\t\t\trogueBot.animation.running.renderSprite(rogueBotAnimRunningGunImg, 0 , 0 , 512 , 512, )\n\t\t\t\t} \n\t\t\t\telse if (rogueBot.state == \"shooting\") {\n\t\t\t\t\trogueBot.animation.shooting.renderSprite(rogueBotAnimShootingImg, 0 , 0 , 512 , 512 )\n\t\t\t\t}\n\t\t\t}", "function gameOver(){\n body.style.animation = \"fadeOut 2s forwards\"\n setTimeout(function(){ window.location.href = 'last-page.html'; }, 3000);\n}", "function spawnPainting() {\n if (!animating) {\n scalar = 1;\n\n generateMondrian();\n\n animating = true;\n t = 0;\n // loop();\n }\n }", "function startOver() {\n // clear boards\n htmlBoard.innerHTML = '';\n board = [];\n // reset active player\n currPlayer = 1;\n nextPlayer = 2;\n // create fresh boards\n makeBoard();\n makeHtmlBoard();\n}", "function showGameOver()\n{ \n stage.removeChild(character.image);\n stage.removeChild(coin.image);\n stage.removeChild(bullet.image);\n if(game_difficulty === MEDIUM_MODE || game_difficulty === HARD_MODE)\n {\n stage.removeChild(balloon.image);\n stage.removeChild(balloon.bomb.image);\n }\n if(game_difficulty === HARD_MODE)\n { \n \n stage.removeChild(text_manager.boss_life); \n stage.removeChild(text_manager.boss_text); \n stage.removeChild(boss.image);\n } \n text_manager.showGameOver();\n}", "function loadContent(){\n pole = game.instantiate(new Pole(Settings.pole.size));\n pole.setColor(Settings.pole.color);\n pole.setPosition(Settings.canvasWidth /2 , Settings.canvasHeight /2);\n\n shield = game.instantiate(new Shield(pole));\n shield.getBody().immovable = true;\n shield.setColor(Settings.shield.color);\n\n player = game.instantiate(new Player(\"\"));\n player.setPole(pole);\n player.setShield(shield);\n pole.setPlayer(player);\n\n //Player labels, name is set once again when the user has filled in his/her name\n scoreLabel = game.instantiate(new ScoreLabel(player, \"Score: 0\"));\n scoreLabel.setPosition(Settings.label.score);\n\n nameLabel = game.instantiate(new Label(\"Unknown Player\"));\n nameLabel.setPosition(Settings.label.name);\n\n highscoreLabel = game.instantiate(new Label(\"Highscore: 0\"));\n highscoreLabel.setPosition(Settings.label.highscore);\n\n createTempImage();\n setTimeout(deleteTempImage, 3000);\n\n //Hide the canvas for the player until a username is filled in and accepted\n var gameElem = document.getElementById(\"gameCanvas\");\n gameElem.style.display=\"none\";\n}", "function animateGame(){\n var i = 0;\n var intervalId = setInterval(function() {\n if(i >= sequenceArray.length) {\n clearInterval(intervalId);\n }\n animate(i);\n i++;\n }, 800);\n }", "moveToNextGame() {\n this._startGame(this._getNextGame());\n }", "function finishGame() {\n clearBoard();\n score += timePassed > score ? timePassed % score : score % timePassed;\n scoreText.innerText = `${score}`;\n showStats();\n updateScoreTable();\n saveGameData();\n setTimer(STOP_TIMER);\n document.getElementsByClassName('details')[0].style.display = 'none';\n getById('player-name').style.pointerEvents = 'all';\n}", "undoMove()\r\n {\r\n game.pastBoards.pop();\r\n let lastAnimation = game.pastAnimations.pop();\r\n\r\n\r\n //Restores board \r\n game.board = game.pastBoards[game.pastBoards.length-1];\r\n \r\n //Retrieves information from last move\r\n let pieceName = lastAnimation[0];\r\n let lastPieceMoved = Number(lastAnimation[0].substring(lastAnimation[0].length-1));\r\n let rowDiff = lastAnimation[2];\r\n let colDiff = lastAnimation[1];\r\n\r\n let time;\r\n\r\n if (colDiff != 0) \r\n time = Math.abs(colDiff);\r\n else\r\n time = Math.abs(rowDiff);\r\n\r\n scene.animationTime = time;\r\n\r\n //Creates inverted animation\r\n scene.graph.components[pieceName].animations[0] = new LinearAnimation(scene, time, [[0,0,0], [-colDiff * scene.movValues[0], 0, -rowDiff * scene.movValues[1]]]);\r\n scene.graph.components[pieceName].currentAnimation = 0;\r\n\r\n //Reverts position change from last move and changes player \r\n if (game.color == 'b') \r\n {\r\n let currentRow = game.whitePositions[lastPieceMoved - 1][0];\r\n let currentCol = game.whitePositions[lastPieceMoved - 1][1];\r\n\r\n game.whitePositions[lastPieceMoved - 1] = [currentRow - rowDiff, currentCol - colDiff];\r\n game.color = 'w';\r\n scene.graph.components['color'].textureId = 'whiteText';\r\n }\r\n \r\n else if (game.color == 'w') \r\n {\r\n let currentRow = game.blackPositions[lastPieceMoved - 1][0];\r\n let currentCol = game.blackPositions[lastPieceMoved - 1][1];\r\n\r\n game.blackPositions[lastPieceMoved - 1] = [currentRow - rowDiff, currentCol - colDiff];\r\n game.color = 'b';\r\n scene.graph.components['color'].textureId = 'blackText';\r\n }\r\n\r\n }", "function finalScreen() {\n\t$finalScreen.detach();\n\n\t// Update DOM to unhide appropriate text based on game state\n\tif (winner) {\n\t\t$finalScreen.find(\".win\").removeClass(\"hidden\");\n\t\t$finalScreen.find(\".win\").find(\"img\").show();\n\n\t\tif (goodStrategy)\n\t\t\t$finalScreen.find(\".win\").find(\".goodStrat\").removeClass(\"hidden\");\n\t\telse\n\t\t\t$finalScreen.find(\".win\").find(\".badStrat\").removeClass(\"hidden\");\n\n\t} else {\n\t\t$finalScreen.find(\".loss\").removeClass(\"hidden\");\n\t\t$finalScreen.find(\".loss\").find(\"img\").show();\n\n\t\tif (goodStrategy)\n\t\t\t$finalScreen.find(\".loss\").find(\".goodStrat\").removeClass(\"hidden\");\n\t\telse\n\t\t\t$finalScreen.find(\".loss\").find(\".badStrat\").removeClass(\"hidden\");\n\t}\n\n\t$(\"body\").animate({ backgroundColor: \"white\" }, 400);\n\t$(\".text,.doorContainer\").effect(\"puff\", \"slow\", function() {\n\n\t\t// Reattach finalScreen and animate!\n\t\t$finalScreen.removeClass(\"hidden\");\n\t\t$finalScreen.insertAfter($(\"header\"));\n\t\t$finalScreen.show(\"scale\", \"slow\", function() {\n\t\t\t$(\".ui-effects-wrapper\").remove();\n\t\t});\n\t});\n}", "function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}", "function lastMove(winningCounts){\n if (winningCounts == 31) {\n document.querySelector('#card'+arrstrNumber[0]).style.animation= \"greenCard 0.6s forwards\";\n document.querySelector('#card'+arrstrNumber[1]).style.animation= \"greenCard 0.6s forwards\";\n winningCounts = winningCounts + 1;\n }\n gameOver()\n}", "function draw() {\r\n if (currentScene === 1) {\r\n drawTitleScreen();\r\n drawPlayButton();\r\n drawPractiseButton();\r\n drawRules();\r\n hint.draw();\r\n hint.update();\r\n goalSign();\r\n }\r\n if (currentScene === 2) { // zoals je kan zien wordt dit getekent bij scene 2\r\n drawPongTheGame();\r\n drawScoreBoard();\r\n drawBatjeA();\r\n drawBatjeB();\r\n batjesUpdate();\r\n goalSign();\r\n }\r\n if (currentScene === 3) { // en onderstaande wordt getekent bij scene 3\r\n drawPractiseRoom();\r\n drawBackButton();\r\n drawScoreBoardPractise();\r\n drawBatjeB();\r\n batjesUpdate();\r\n }\r\n if (currentScene === 10) { // dit wordt getekent bij scene 10\r\n drawTitleScreenExtreme();\r\n drawTitleAnimation();\r\n drawPlayExtremeButton();\r\n drawPractiseExtremeButton();\r\n drawRulesExtreme();\r\n PowerUpNr = 0;\r\n speeding = 1*resize;\r\n }\r\n if (currentScene === 11){ // dit wordt getekent bij scene 11\r\n drawPongExtreme();\r\n drawBatjeAExtreme();\r\n drawBatjeBExtreme();\r\n drawScoreBoardExtreme();\r\n batjesUpdate();\r\n drawPowerUps();\r\n goalSign();\r\n }\r\n if(currentScene === 12){ // dit wordt getekent bij scene 12\r\n drawRulesScreenExtreme();\r\n drawBackButton();\r\n drawTitleAnimation();\r\n \r\n \r\n }\r\n if(surpriseBart === true){ // dit wordt getekent wanneer de B toets wordt ingedrukt\r\n bSurprise();\r\n }\r\n}", "function playGif(name, frames, delay) {\n\t\t/*processes++;\t\n\t\tvar gif = getById(\"fullGif\");\n\t\tgif.src = GIF_PATH + name + \".gif\" + \"?a=\"+Math.random();\n\t\tgif.style.visibility = \"visible\"\n\t\tgetById(\"movies\").appendChild(gif);\n\t\tsetTimeout(function() {\n\t\t\tgif.style.visibility = \"hidden\";\n\t\t\tprocesses--;\n\t\t}, frames*delay);\t*/\n\t}", "function happycol_buildGel(args){\n\t//check options and assign variables\n\tif(jQuery(args.theClass + '_gel').length==0){\n\t\tjQuery('body').append(\n\t\t\t'<div class=\"' + args.theatre + '_gel\"></div>'\n\t\t);\n\t}\n\targs.$gel = jQuery(args.theClass + '_gel');\n\targs.$gel.css({\n\t\t'background-color':'#' + args.gel,\n\t\t'opacity':'0',\n\t\t'position':'absolute',\n\t\t'top':'0',\n\t\t'left':'0',\n\t\t'right':'0',\n\t\t'bottom':'0',\n\t\t'z-index':'100',\n\t\t//'display':'none'\n\t});\n\tjQuery(args.theClass + ' .stage').not(args.$nested).css({'z-index':'101','position':'relative'});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a negative integer finishes parsing add it to a stack
exitNegativeInteger(ctx) { const number = -1 * parseInt(ctx.INT(), 10); this._stack.push(number); if (this.DEBUG) { // eslint-disable-next-line no-console console.log("Parsed integer", number); } }
[ "exitInteger(ctx) {\n const number = parseInt(ctx.INT(), 10);\n this._stack.push(number);\n if (this.DEBUG) {\n // eslint-disable-next-line no-console\n console.log(\"Parsed integer\", number);\n }\n }", "function parse(stack) {\n var numStack = []; // Number stack\n var opStack = []; // Operator stack\n while (stack.length > 0) {\n var val = stack.pop();\n if (isOperator(val)) {\n opStack.push(val);\n } else if (typeof val == 'number') {\n numStack.push(val);\n } else if (val == ')') {\n var b = numStack.pop();\n var a = numStack.pop();\n var op = opStack.pop();\n numStack.push(performOp(a, b, op));\n }\n }\n console.log(numStack);\n}", "function tasks_stack() {\r\n let stackdata = new Stack(1);\r\n stackdata.push(4);\r\n stackdata.push(8);\r\n stackdata.push(9);\r\n stackdata.push(10);\r\n stackdata.push(11);\r\n\r\n stackdata.parse_llist();\r\n let out = stackdata.pop();\r\n let out1 = stackdata.pop();\r\n let out2 = stackdata.pop();\r\n let out3 = stackdata.pop();\r\n // let out4 = stackdata.pop();\r\n // let out5 = stackdata.pop();\r\n // let out6 = stackdata.pop();\r\n // let out7 = stackdata.pop();\r\n console.log(\r\n \" gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n // out4.value,\r\n // out5.value,\r\n // out6.value,\r\n // out7.value\r\n );\r\n stackdata.push(100);\r\n stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n // stackdata.pop();\r\n\r\n console.log(\r\n \"peeking out \",\r\n // stackdata.peek(),\r\n stackdata.is_empty(),\r\n stackdata\r\n );\r\n stackdata.parse_llist();\r\n }", "exitNegativeDouble(ctx) {\n const number = -1 * parseFloat(ctx.DOUBLE());\n this._stack.push(number);\n if (this.DEBUG) {\n // eslint-disable-next-line no-console\n console.log(\"Parsed double\", number);\n }\n }", "minus() {\n this._lastX = this.pop();\n let first = this.pop();\n this._stack.push(first - this._lastX);\n }", "function parserShift(sym, st) {\n if(stackTop >= STACK_DEPTH-1) {\n return 0;\n }\n\n stateStack[++stackTop] = st;\n stack[stackTop] = lexicalValue;\n state = st;\n if (isVerbose()) {\n console.log(\"Shift to \" + state + \" with \" + sym);\n parserPrintStack();\n }\n return 1;\n }", "restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter];\n return s;\n }", "function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }", "push(val) {\n this._stack.push(val);\n }", "function parse_IntExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_IntExpr()\" + '\\n';\n\tCSTREE.addNode('IntExpr', 'branch');\n\n\t\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\tif (tempType == 'digit'){\n\t\tmatchSpecChars(tempDesc,parseCounter);\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\tif (tokenstreamCOPY[parseCounter][0] == '+'){\n\t\t\tdocument.getElementById(\"tree\").value += '\\n';\n\t\t\tparse_intop();\n\t\n\t\t\tparse_Expr();\n\t\n\t\t}\n\t\t\t\t\n\t}\n\t\n\t\n\t\n}", "function minilang(tokenString) {\n let stack = [];\n let register = 0;\n let tokens = tokenString.split(' ');\n\n for (let i = 0; i < tokens.length; i += 1) {\n let currentToken = tokens[i];\n if (Number.isNaN(Number(currentToken))) {\n switch (currentToken) {\n case 'PUSH': \n stack.push(register);\n break;\n case 'ADD': \n register = stack.pop() + register;\n break;\n case 'SUB':\n register -= stack.pop();\n break;\n case 'MULT':\n register *= stack.pop();\n break;\n case 'DIV':\n register = Math.floor(register / stack.pop());\n break;\n case 'MOD':\n register %= stack.pop();\n break;\n case 'POP':\n register = stack.pop();\n break;\n case 'PRINT':\n console.log(register);\n break;\n }\n } else {\n register = Number(currentToken);\n }\n }\n\n}", "plus() {\n this._lastX = this.pop();\n this._stack.push(this.pop() + this._lastX);\n }", "function set_stack_height() {\n $(\".stack\").css(\"height\", $(\".content\").outerHeight() - 2);\n}", "function countStack(stack) {\n let newStack = new slStack();\n let count = 0;\n while(!stack.isEmpty()) {\n newStack.push(stack.pop());\n count++;\n }\n // let newNStack = stack;\n // while(!newNStack.isEmpty()) {\n // newNStack.pop();\n // count++;\n // }\n}", "peek(){\n\n if(!this.top){\n return 'Stack is empty.';\n\n }\n try{\n return this.top.value;\n } \n catch(err){\n return 'Stack is empty.';\n }\n }", "function processIgnState() {\n //Error if current arg is not a value and no values encountered\n //yet for -ign. Otherwise, store value or move on to next\n //argument.\n if ('-ign' === sword) {\n bok = false; //Make sure we get a value argument.\n } else if ('-' !== sword.charAt(0)) {\n oresult.aign.push(CDIVUTILS.createGlobRegex(sword));\n bok = true;\n } else if (oresult.aign.length > 0) {\n sstate = '';\n i -= 1; //Reprocess current stmt in next state at end of this stmt.\n } else {\n throw 'Invalid value for command -ign. Invalid Statement: ' +\n sword;\n }\n }", "addNumToBack(num) {\n if (this.isNumAllowed(num)) this.numList.enqueue(num);\n // return this.numList[this.numList.length - 1];\n return this.numList.tail.value;\n }", "function parserRecover() {\n var i, action;\n\n switch(errorFlag) {\n case 0: // 1st error\n if(parserError(state, lexicalToken, stackTop, getErrorMessage()) == 0) {\n return 0;\n }\n errorCount++;\n // continues and goes into 1 and 2. No break on purpose\n\n case 1:\n case 2: // three attempts are made before dropping the current token\n errorFlag = 3; // Remove token\n\n while(stackTop > 0) {\n // Look if the state on the stack's top has a transition with one of\n // the recovering elements in StxRecoverTable\n for (i=0; i<RECOVERS; i++) {\n action = parserAction(state, recoverTable[i]);\n if(action > 0) {\n // valid shift\n return parserShift(recoverTable[i], action);\n }\n }\n if (isVerbose()) {\n console.log(\"Recuperate removing state \" + state + \" and going to state \" +\n stack[stackTop-1]);\n }\n state = stateStack[--stackTop];\n }\n stackTop = 0;\n return 0;\n\n case 3: // I need to drop the current token\n if (isVerbose()) {\n console.log(\"Recuperate removing symbol \" + lexicalToken);\n }\n if(lexicalToken == 0) { // end of file\n return 0;\n }\n lexicalToken = parserElement(false);\n return 1;\n }\n // should never reach\n console.log(\"ASSERTION FAILED ON PARSER\");\n return 0;\n }", "popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the current user from the competition
function removeCurrentUserFromCompetition() { // Make sure the user is logged in and is on this competition if (identityService.isAuthenticated() && vm.currentUserIsOnCompetition) { removingCurrentUser = true; // Forfeit if they have an active challenge if (vm.hasActiveChallenge) { completeChallenge(null, true, vm.currentUserPlayer); } else { // Since we are removing them ... vm.currentUserIsOnCompetition = false; vm.hasActiveChallenge = false; // Get an updated copy of the competition incase a forfeit happened competitionsService.getCompetition(vm.competitionId).then(function (p) { // Store the updated copy locally so as not to distrupt the competition // until the player has been removed var competition = p.data; // Keep track of the spot they were in on the competition var openPosition = vm.currentUserPlayer.position; // Move all the players up 1 position that were behind the removed player _.forEach(competition.players, function (player) { if (player.position >= openPosition) { player.position -= 1; } }); // Removed the player from the competition var removedPlayer = _.remove(competition.players, function (player) { return player._id === vm.currentUserPlayer._id; }); // Make a new array of all the players still on the competition // only use the properties we want to store in the competition document var updatedPlayers = []; for (var i = 0; i < vm.numberOfRealPlayers - 1; ++i) { var updatedPlayer = { _id: competition.players[i]._id, email: competition.players[i].email, firstName: competition.players[i].firstName, lastName: competition.players[i].lastName, displayName: competition.players[i].displayName, position: competition.players[i].position }; updatedPlayers.push(updatedPlayer); } // Call service to remove the player competitionsService.removedPlayerFromCompetition(vm.competitionId, removedPlayer[0], updatedPlayers).then(function () { removingCurrentUser = false; }); }); } } }
[ "function confirmRemoveCurrentUserFromCompetition() {\n swal({\n title: 'Leave Competition?',\n text: 'You will lose your spot and forfeit any active challenges.',\n type: 'error',\n showCancelButton: true,\n confirmButtonText: 'Yes, leave',\n confirmButtonClass: 'btn-danger',\n cancelButtonText: 'No, stay',\n closeOnConfirm: false,\n closeOnCancel: true\n }, function () {\n removeCurrentUserFromCompetition();\n swal('OK, you\\'r out!', 'You\\'ve been removed from the competition.', 'success');\n });\n }", "function removeVoter(user) {\n var pokerCard = document.getElementById(user);\n votingContainer.removeChild(pokerCard);\n var rosterEntry = document.getElementById(user);\n messageContainer.removeChild(rosterEntry);\n}", "function removeScore() {\n localStorage.removeItem(\"user\");\n var removeBtn = document.querySelector(\"#removeBtn\");\n var userList = document.querySelector(\"#userList\");\n removeBtn.parentNode.removeChild(removeBtn);\n userList.parentNode.removeChild(userList);\n liMax = 0;\n}", "function muut_remove_online_user(user) {\n if(user.path.substr(0,1) == '@') {\n var username = user.path.substr(1);\n }\n var username_for_selector = tidy_muut_username(username);\n widget_online_users_wrapper.find('.m-user-online_' + username_for_selector).fadeOut(500, function() { $(this).remove() });\n muut_update_online_users_widget();\n }", "removeUserFromChannel(username, channel){\n var index = -1;\n var ch = this.getChannelByName(channel);\n if(ch != null){\n for (var i = 0; i < ch.users.length; i++) {\n var u = ch.users[i];\n if(u.name == username){\n index = i;\n }\n }\n }\n if(index > -1 && ch != null){\n ch.users.splice(index, 1);\n }\n io.emit('refreshchannels', [this.name, username]);\n dbDelete({groupname: this.name, channelname: channel, username: username}, \"channel_users\");\n }", "function removeCurrentUserIDFromLocalStorage() \r\n{\r\n localStorage.removeItem(\"currentUserID\");\r\n}", "async onClick(){\n const user = this.props.user;\n const response = await this.deleteUser(user);\n this.props.removeUser(user.id);\n }", "static tamper() {\n del(\"user\").then(() => {\n localStorage.removeItem(\"role\");\n location.reload();\n });\n }", "function remove() {\n\t\t\tif(vm.partner.find( { chatting: false } )){\n\t\t\t\tvm.partner.$remove(function() {\n\t\t\t\t\tNotification.success({ message: 'You now can ge ta new chat partner!'});\n\t\t\t\t});\n\t\t\t}\n\n\t\t}", "removeUser(userId) {\n for (let user of this.getUsers()) {\n if (user._id === userId) {\n this.users.splice(this.users.indexOf(user), 1);\n }\n }\n }", "function delUserForMeeting( data, callback ) {\n\t\t\tvar url = '/meetingdelusers';\n\n\t\t\tnew IO({\n\t\t\t\turl: url,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: data,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t\tcallback(data);\n\t\t\t\t}\n\t\t\t});\n\n\t\t}", "logoutUser() {\n this.get('session').invalidate();\n }", "function submitRemoveMember(e) {\n e.preventDefault()\n socket.emit('removeTeamMember', { id: socket.id })\n ownTeam.classList.toggle('joined')\n}", "function removeParticipant(participantID, courseID)\r\n{\r\n //Find the participant and course in the database\r\n participant = getParticipantByID(participantID);\r\n course = getCourseByID(courseID);\r\n if(course == null || participant == null)\r\n return;\r\n \r\n //Remove the participant from the course\r\n courseIndex = participant.courses.indexOf(courseID);\r\n if (courseIndex > -1)\r\n {\r\n participant.courses.splice(courseIndex, 1);\r\n showAdminToolsPopup(participantID);\r\n return;\r\n }\r\n}", "function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }", "function removeGame() {\n\t//todo: add formal message telling client other player disconnected\n\tsocket.emit('delete game', gameID);\n\tclient.fleet = ['temp2', 'temp3', 'temp4', 'temp5'];\n\tenemyFleet = new Array(4);\n\tclient.clearGrids();\n\tsocket.off(gameID + ' player disconnect');\t\n\tgameID = -1;\n\tprepWindow = -1;\n\tpositionWindow = -1;\n\tplayWindow = -1;\n}", "function unmodUser(trip)\n {\n var mod = modList.indexOf(trip);\n if (mod > -1)\n {\n modList.splice(mod, 1);\n sendServerMsgUser(\"You unmodded \" + trip);\n io.sockets.socket(socket.id).emit('modSync', modList);\n console.log('[' + trip + '] was unmodded');\n saveModList();\n updateUserType(trip);\n }\n else\n {\n sendServerMsgUser(\"Unable to unmod \" + trip);\n console.log('[' + trip + '] could not be found in mod list');\n }\n }", "function confirmRemove(i)\n{\n for (let i=0;i<accounts._accounts.length;i++)\n {\n let emailId = user._emailId;\n if (accounts._accounts[i]._emailId == emailId)\n {\n user = accounts._accounts[i];\n updateLocalStorageUser(user)\n }\n }\n user.removeTrip(i);\n \n updateLocalStorageUser(user);\n updateLocalStorageAccount(accounts);\n window.location = \"scheduledTrips.html\";\n}", "admin_remove_user(user_id) {\n if (Roles.userIsInRole(Meteor.userId(), ['admin'])) {\n Meteor.users.remove(user_id);\n return \"OK\";\n }else { return -1; }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Our Popup React component. For props we expect to receive: isOpen, onClose, message, onConfirm. which we elaborate in the propTypes immediately after.
function Popup(props) { return ( <Modal show={props.isOpen} onHide={props.onClose}> <Modal.Header closeButton> <Modal.Title>{props.title}</Modal.Title> </Modal.Header> <Modal.Body> {props.message} </Modal.Body> {(props.footer) ? <Modal.Footer> <Button onClick={props.onClose} variant="secondary">Close</Button> <Button onClick={() => { props.onConfirm(); props.onClose() }} variant="primary"> Confirm</Button> </Modal.Footer> : <></>} </Modal>) }
[ "renderPopup() {\n return (\n <div\n className=\"usaf-tooltip__popup\"\n ref={(el) => {\n this._tooltipPopupRef = el;\n }}\n onMouseEnter={this.onPopupMouseEnter}\n onMouseLeave={this.onPopupMouseLeave}\n style={this.getPopperStyle(this.state.data)}\n >\n {this.props.popupComponent}\n </div>\n );\n }", "render() {\n const { state } = this;\n return (\n <div>\n {this.renderTrigger()}\n {state.show && this.renderPopup()}\n </div>\n );\n }", "function Modal (props){\n return(\n <div className=\"modal fade login in\" style={{display: 'block'}} id=\"loginModal\">\n <div className=\"modal-dialog login animated\">\n <div className=\"modal-content\">\n <button type=\"button\" className=\"close\" style={{fontSize: '35px', marginRight: '20px'}} onClick={props.onClick}>&times;</button>\n {props.children}\n </div>\n </div>\n </div>\n )\n}", "render(){\n return(\n <div>\n <Panel bsStyle=\"info\">\n <Panel.Heading>\n <Panel.Title \n componentClass=\"h3\"\n >\n <Row>\n <Col sm = {10}> \n <span style = {styles.body}>Name: </span>{this.props.name}\n </Col>\n <Col Col >\n <OverlayTrigger\n trigger={['hover', 'focus']}\n placement=\"bottom\"\n overlay={popoverButton}>\n <Button \n bsSize=\"small\"\n bsStyle=\"primary\" \n onClick= {this.props.onOpenText} > \n <Glyphicon glyph=\"pencil\" /> <span>Edit </span>\n </Button>\n </OverlayTrigger>\n </Col> \n </Row>\n </Panel.Title>\n </Panel.Heading>\n <Panel.Body><span style = {styles.body}>Message: </span>{ this.props.message }</Panel.Body>\n </Panel>\n </div>\n )\n }", "constructor( modalShadow, modalBody, modalMessage){\n\t\tthis.shadow = modalShadow;\n\t\tthis.body = modalBody;\n\t\tthis.message = modalMessage;\n\t\tthis.onClose = null;\n\n\t\tthis.hide = this.hide.bind(this);\n\t}", "static set popup(value) {}", "renderGreenModal() {\n return (\n <Modal\n isOpen={this.state.showGreenModal}\n onRequestClose={this.handlecloseGreenModal}\n style={customStyles}\n >\n <h2>Green Type</h2>\n {/* TODO: */}\n </Modal>\n )\n }", "function popup (message) {\n $('.pop').show().css('display', 'flex')\n $('.message').html(message)\n }", "attemptDismiss() {\n\t\tif(this.state.currentModal.props.dismissible) this.state.currentModal.props.onDismiss();\n\t}", "function requiredDialogProps () {\n return {\n title: '😯 Add credits',\n message: <Typography variant='body1'>Cannot start with no bet credits, you should add some</Typography>,\n type: 'error'\n }\n}", "renderBlueModal() {\n return (\n <Modal\n isOpen={this.state.showBlueModal}\n onRequestClose={this.handleCloseBlueModal}\n style={customStyles}\n >\n <h2>Blue Type</h2>\n {/* TODO: */}\n </Modal>\n )\n }", "togglePopup() {\n this.setState({\n showPopup: !this.state.showPopup,\n dictKey: null,\n value: null,\n });\n }", "open_actionsOptions(i){ \n this.setState({id2edit:i});\n var formName = `options_${_Type}`; \n var _id = Util.Base64.encode(`_${formName}_`); \n var _cont = <ActionsOptionLocation handle_Delete={this.handleDeleteAction.bind(this)} handle_Edit={this.OpenEditAction.bind(this)} _close={this.close_actionsOptions.bind(this)} />\n var options = {id:_id,zIndex:150,height:450,content:_cont};\n this.props.dialogActions.OpenSlideOption(options);\n }", "constructor(error_message, overlay=page_overlay, closeable=true) {\n this.overlay = overlay\n this.popup = new Popup(\"Error\", \"error-popup\", closeable)\n let error_screen_obj = this;\n error_screen_obj.popup.bottom_buttons[0] = new PopupButton(\"Dismiss\", \"error-close-button\", 0, function() {\n error_screen_obj.popup.close()\n error_screen_obj.overlay.hide();\n });\n this.popup.show()\n this.popup.content_container.append($(\"<p>\").attr(\"class\", \"error-popup-text\").text(error_message))\n }", "function PopUpMessage(strings)\r\n{\r\n this.strings = strings;\r\n this.overlayEnvolture = document.getElementsByClassName('wrs_modal_iframeContainer')[0].appendChild(document.createElement(\"DIV\"));\r\n this.overlayEnvolture.setAttribute(\"style\", \"display: none;width: 100%;\");\r\n\r\n this.message = this.overlayEnvolture.appendChild(document.createElement(\"DIV\"));\r\n this.message.setAttribute(\"style\", \"margin: auto;position: absolute;top: 0;left: 0;bottom: 0;right: 0;background: white;width: 75%;height: 130px;border-radius: 2px;padding: 20px;font-family: sans-serif;font-size: 15px;text-align: left;color: #2e2e2e;z-index: 5;\");\r\n\r\n var overlay = this.overlayEnvolture.appendChild(document.createElement(\"DIV\"));\r\n overlay.setAttribute(\"style\", \"position: absolute; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); z-index: 4; cursor: pointer;\");\r\n self = this;\r\n // We create a overlay that close popup message on click in there\r\n overlay.addEventListener(\"click\", function(){self.close();});\r\n\r\n this.buttonArea = this.message.appendChild(document.createElement('p'));\r\n // By default, popupwindow give close modal message with close and cancel buttons\r\n // You can set other message with other buttons\r\n this.setOptions('close_modal_warning','close,cancel');\r\n document.addEventListener('keydown',function(e) {\r\n if (e.key !== undefined && e.repeat === false) {\r\n if (e.key == \"Escape\" || e.key === 'Esc') {\r\n _wrs_popupWindow.postMessage({'objectName' : 'checkCloseCondition'}, _wrs_modalWindow.iframeOrigin);\r\n }\r\n }\r\n });\r\n}", "function TicketCard(props) {\n const [isShowTicketDetailsPopup, setIsShowTicketDetailsPopup] = useState(\n false\n )\n const handleToggleTicketPopup = () => {\n setIsShowTicketDetailsPopup(!isShowTicketDetailsPopup)\n }\n return (\n <>\n <div className=\"w-full card-wrap\" onClick={handleToggleTicketPopup}>\n <span className=\"card-status status-backend\"> Backloag</span>\n <h5 className=\"h5 card-title\">Ticket - 10</h5>\n <p className=\"text-body\">\n Lorem ipsum dolor sitsdf amet, consectetur adiscing elit.\n </p>\n </div>\n\n {/* {isShowTicketDetailsPopup && (\n <TicketDetailsPopup close={handleToggleTicketPopup} />\n )} */}\n </>\n )\n}", "function PopupRenderer(parent) {\n this.parent = parent;\n }", "renderRedModal() {\n return (\n <Modal\n isOpen={this.state.showRedModal}\n onRequestClose={this.handleCloseRedModal}\n style={customStyles}\n >\n <h2>Red Type</h2>\n {/* TODO: */}\n </Modal>\n )\n }", "function aePopupModalWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, aParams)\r\n{\r\n\treturn aePopupWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, true, aParams);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test: createQueryFromJson(jsonQuery) Creating query for: SHOW
function testCreateQueryFromJsonShow() { // Call the function to test var generatedOutput = createQueryFromJson(jsonQueryShow); var expectedOutput = 'Show Sum of Units for Item from OrderDate 2019-01-06 to 2019-07-12'; // Checking if generated output is same as expected output assertEquals(expectedOutput, generatedOutput, 'createQueryFromJsonShow'); }
[ "function testCreateQueryFromJsonTopK() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryTopK);\n var expectedOutput = \n 'Find the top-7 Rep with maximum Total where Units is Greater than 50';\n \n // Checking if generated output is same as expected output\n assertEquals(expectedOutput, generatedOutput, 'createQueryFromJsonTopK');\n}", "function testCreateQueryFromJsonTrend() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryTrend);\n var expectedOutput = \n 'Monthly trend of Sum of Units where Item is In Binder, Pencil, Pen' +\n ' from OrderDate 2019-01-06 to 2019-07-12';\n \n // Checking if generated output is same as expected output\n assertEquals(expectedOutput, generatedOutput, 'createQueryFromJsonTrend');\n}", "function testCreateQueryFromJsonTimeCompare() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryTimeCompare);\n var expectedOutput = \n 'Compare the Mean of Unit Cost for the OrderDate 2019-01-06 to 2019-03-15' +\n ' and 2019-04-01 to 2019-07-12 by Region';\n \n // Checking if generated output is same as expected output\n assertEquals(expectedOutput, generatedOutput, 'testCreateQueryFromJsonTimeCompare');\n}", "get query() {\n return this._parsed.query || {};\n }", "function convertExistingQueryProps(json, builder) {\n const keys = Object.keys(json);\n\n for (let i = 0, l = keys.length; i < l; ++i) {\n const key = keys[i];\n const value = json[key];\n\n if (isQueryProp(value)) {\n json[key] = queryPropToKnexRaw(value, builder);\n }\n }\n\n return json;\n}", "function query_test() {\n DB.clear_all()\n let album1 = create_dummy(Album)\n let album2 = create_dummy(Album)\n let album3 = create_dummy(Album)\n let all_albums_query = create_live_query().all(Album).make()\n check.equals(all_albums_query.current().length(),3,'all album check')\n all_albums_query.sync()\n let album4 = create_dummy(Album)\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4)\n\n let yellowsub_query = create_live_query().all(Album).attr_eq(\"title\",\"Yellow Submarine\").make()\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4, 'total album count')\n check.equals(yellowsub_query.current().length(),0,'yellow sub should be 0')\n\n create_dummy(Album, {title: 'Yellow Submarine'})\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),5, 'total album count')\n check.equals(yellowsub_query.current().length(),1)\n\n\n // make three tracks. one on album1 and two on album 2\n create_dummy(Track, {album:album1, title:'title1'})\n create_dummy(Track, {album:album2, title:'title2'})\n create_dummy(Track, {album:album2, title:'title3'})\n\n // make a track query. verify three tracks total\n let all_tracks_query = create_live_query().all(Track).make()\n all_tracks_query.sync()\n check.equals(all_tracks_query.current().length(),3)\n\n // make a track query for tracks on album1, verify 1 track\n let album1_tracks_query = create_live_query().all(Track).attr_eq('album',album1).make()\n check.equals(album1_tracks_query.current().length(),1)\n\n\n // make a track query for tracks on album2, verify 2 tracks\n let album2_tracks_query = create_live_query().all(Track).attr_eq('album',album2).make()\n check.equals(album2_tracks_query.current().length(),2)\n //check the titles\n check.equals(create_live_query().all(Track).attr_eq('title','title1').make().current().length(),1)\n check.equals(create_live_query().all(Track).attr_eq('title','title2').make().current().length(),1)\n //this one should fail\n check.equals(create_live_query().all(Track)\n .attr_eq('title','title4').make()\n .current().length(),0)\n\n //check if attr in array\n console.log(\"checking if title in [title1,title2]\")\n check.equals(create_live_query().all(Track)\n .attr_in_array('title',['title1','title2','title4']).make()\n .current().length(),2)\n\n //check if track in one of a set of albums\n check.equals(create_live_query().all(Track)\n .attr_in_array('album',[album1,album2]).make()\n .current().length(),3)\n\n // all tracks for all albums.\n let all_albums = create_live_query().all(Album).make()\n let all_album_tracks = create_live_query().all(Track)\n .attr_in_array('album',all_albums).make()\n check.equals(all_album_tracks.current().length(),3)\n\n // make a Selection which contains an array of Albums\n // let selected_albums = create_dummy(Selection, {albums:[album2, album3]})\n\n // make a query of albums in the selection\n // let selected_albums_query = create_live_query().all(Track)\n // .attr_in_array('album',selected_albums).make()\n // check.equals(selected_albums_query.current().length(),2)\n\n // make a query of tracks in albums in selection\n // let selected_tracks_query = create_live_query().all(Track)\n // .attr_eq('album',selected_albums_query).make()\n // check.equals(selected_tracks_query.current().length(),2)\n}", "async queryRecord(store, type, query) {\n let upstreamQuery = Ember.assign({}, query);\n upstreamQuery.page = { size: 1 };\n let response = await this._super(store, type, upstreamQuery);\n if (!response.data || !Array.isArray(response.data) || response.data.length < 1) {\n throw new DS.AdapterError([ { code: 404, title: 'Not Found', detail: 'branch-adapter queryRecord got less than one record back' } ]);\n }\n let returnValue = {\n data: response.data[0],\n };\n if (response.meta){\n returnValue.meta = response.meta;\n }\n return returnValue;\n }", "searchWithParams(query) {\n if (Object.keys(query).length) {\n this.set('isSearching', true);\n this.get('store').query('patient-search', query).then(results => {\n this.setProperties({\n results: results.filterBy('isActive'),\n isSearching: false\n });\n this.sendAction('didSearch');\n\n if (this.get('displayResults')) {\n this.set('showResults', true);\n this.set('showHints', false);\n }\n }).catch(error => {\n if (!this.get('isDestroyed')) {\n this.set('isSearching', false);\n this.sendAction('didSearch', error);\n }\n });\n }\n }", "async query(context, q) {\n return new Promise((resolve) => {\n axios({\n method: \"post\",\n url: `${process.env.VUE_APP_MAIN_URL}/${process.env.VUE_APP_GRAPHQL_URL}`,\n data: { query: `query { ${q} }` }\n }).then((res) => {\n resolve(res.data.data)\n }).catch((err) => {\n console.error(err.response)\n })\n })\n }", "function search()\n{\n //Show 10 hits\n return client.search({\n index: \"suv\",\n type: 'suv',\n body: {\n sort: [{ \"volume\": { \"order\": \"desc\" } }],\n size: 10,\n }\n });\n}", "_getQueryBy(callback) {\r\n var query = new Query(); // Create a new instance for nested scope.\r\n callback.call(query, query);\r\n query.sql = query.getSelectSQL();\r\n return query; // Generate SQL statement.\r\n }", "function testCreateQueryFromJsonCorrelation() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryCorrelation);\n var expectedOutput = \n 'Correlation between Unit Cost and Total for each Item';\n \n // Checking if generated output is same as expected output\n assertEquals(expectedOutput, generatedOutput, 'createQueryFromJsonCorrelation');\n}", "function stationsQuery (vm) {\n const searchText = vm.searchText.trim()\n const query = {\n enabled: true,\n organization_id: vm.state.organization._id,\n station_type: 'weather',\n slug: {$exists: 1},\n $limit: 200,\n $sort: {name: 1} // ASC\n }\n if (searchText.length > 0) {\n query.name = {\n $regex: searchText,\n $options: 'i'\n }\n }\n\n return query\n}", "findRoomby(query) {\n let res = this.db.get(tablename).filter(query).value();\n return res;\n }", "async queryContainer() {\n console.log(`Querying container:\\n${config.container.id}`)\n \n // query to return all children in a family\n // Including the partition key value of lastName in the WHERE filter results in a more efficient query\n const querySpec = {\n query: 'SELECT * FROM root r WHERE @Hours - r.Hours <=1',\n parameters: [\n {\n name: '@Hours',\n value: (new Date).getUTCHours()\n },\n {\n name: '@Minutes',\n value: (new Date).getUTCMinutes()\n }\n ]\n }\n \n const { resources: results } = await this.client\n .database(this.databaseId)\n .container(this.containerId)\n .items.query(querySpec)\n .fetchAll()\n return results;\n }", "function generateQuery (type) {\n const query = new rdf.Query()\n const rowVar = kb.variable(keyVariable.slice(1)) // don't pass '?'\n\n addSelectToQuery(query, type)\n addWhereToQuery(query, rowVar, type)\n addColumnsToQuery(query, rowVar, type)\n\n return query\n }", "function getQuery(queryFor, queryString){\n var query = '';\n if(queryFor == 'name'){\n query = 'SELECT * FROM battles WHERE name =\"' + queryString + '\"';\n }\n else if(queryFor == 'king'){\n query = 'SELECT * FROM battles WHERE attacker_king =\"' + queryString + '\"';\n }\n else if(queryFor == 'region'){\n query = 'SELECT * FROM battles WHERE region =\"' + queryString + '\"';\n }\n else if(queryFor == 'year'){\n query = 'SELECT * FROM battles WHERE year =\"' + queryString + '\"' ;\n }\n return query;\n}", "function loadQuery(action){\n\tif(globalInfoType == \"JSON\"){\n devicesArr = getDevicesNodeJSON();\n deviceArr = getDevicesNodeJSON();\n\t}\n\n\tvar query=\"\";\n\tvar arr=[];\n\tvar arr2=[];\n\tfor(var a=0; a<deviceArr.length; a++){\n\t\tif (deviceArr[a].DeviceName){\n\t\t\tarr.push(deviceArr[a].DeviceName);\n\t\t}else{\n\t\t\tarr.push(deviceArr[a].ObjectPath);\n\t\t}\n\t\tarr2.push(deviceArr[a].ModelType);\n\t}\n\tvar user=userInformation[0].userLevel;\n\tif(action == \"image\"){\n\t\tquery=\"deviceid=\"+arr+\"^\"+user+\"^\"+arr2;\n\t} else if(action == \"config\"){\n\t\tquery=\"deviceid=\"+arr+\"^\"+globalUserName+\"^\"+user+\"^\"+arr2;\n\t} else {\n\t\tquery=\"deviceid=\"+arr+\"^\"+arr2;\n\t}\n\treturn query;\n}", "async function test_14_in_params()\n{\n // TODO not expecting this to work yet.\n console.log(\"*** test_14_in_params ***\");\n // initialize a new database\n let [ db, retrieve_root ] = await TU.setup();\n\n // insert data\n const statements = [\n [ DT.addK, \"bob\", K.key(\":name\"), \"Bobethy\" ],\n [ DT.addK, \"bob\", K.key(\":likes\"), \"sandra\" ],\n [ DT.addK, \"sandra\", K.key(\":name\"), \"Sandithan\"]];\n\n db = await DB.commitTxn( db, statements );\n\n // query the data\n const q = Q.parseQuery(\n [Q.findK, \"?a\", \"?b\", \"?c\",\n Q.inK, \"$\", \"?b\", \"?c\",\n Q.whereK, \n [\"?a\", \"?b\", \"?c\"],\n ]\n );\n const r = await Q.runQuery( db, q, K.key( \":name\" ), \"Bobethy\" );\n\n console.log(\"r14\", r);\n assert(\n r.length === 1 && \n r[0][2] === \"Bobethy\", \n \"Query returned an unexpected value\");\n console.log(\"*** test_14_in_params PASSED ***\");\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set texture input/output size Dimensions are converted to integers
hasTextureSize(width, height) { return { output: [ width|0, height|0 ] }; }
[ "reallocate(newSize){\n const gl = this.gl;\n\n if(!!this.tex){\n gl.deleteTexture(this.tex);\n console.log(`Cleared previous texture for atlas (${this.maxSize})`);\n }\n\n this.maxSize = newSize || this.maxSize;\n \n this.tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, this.tex);\n \n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n let magFilter, minFilter;\n if(!!this.bilinearFiltering){\n magFilter = gl.LINEAR;\n minFilter = !!this.generateMipmaps ? gl.LINEAR_MIPMAP_NEAREST : gl.LINEAR;\n }else{\n magFilter = gl.NEAREST;\n minFilter = gl.NEAREST;\n }\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);\t\t\t\t\t\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); \n\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.maxSize, this.maxSize, 0, this.format, gl.UNSIGNED_BYTE, null);\n gl.bindTexture(gl.TEXTURE_2D, null); \n\n console.log(`Allocated texture atlas: ${this.maxSize}x${this.maxSize}`);\n }", "updateTexture() {\n let width = 1;\n let height = 1;\n let depth = 1;\n if(this.props.activations){\n this.activations = this.props.activations\n const [b, w, h, c] = this.props.activationShape;\n\n width = w;//sqrtW;\n height = h;//sqrtW;\n depth = c;\n } else{\n this.activations = this.defatultActivations;\n }\n\n //this.activationTexture = new RawTexture(this.activations, width, height,\n // Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n // Texture.BILINEAR_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n\n let sz;\n let sizeMatches = false;\n if(this.activationTexture) {\n sz = this.activationTexture.getSize();\n sizeMatches = (sz.width === width && sz.height === height\n && this.lastDepth === depth);\n }\n if(!this.activationTexture || !sizeMatches) {\n if(this.activationTexture){\n this.activationTexture.dispose();\n }\n this.activationTexture = new RawTexture3D(this.activations, width, height,\n depth, Engine.TEXTUREFORMAT_RED, this.scene, false, false,\n Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);\n } else {\n this.activationTexture.update(this.activations);\n }\n\n this.shaderMaterial.setTexture('textureSampler', this.activationTexture);\n this.lastDepth = depth;\n }", "setTextureUScale(u) {\n //TODO\n }", "function TextureOptimization(/**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */priority,/**\n * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n */maximumSize,/**\n * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */step){if(priority===void 0){priority=0;}if(maximumSize===void 0){maximumSize=1024;}if(step===void 0){step=0.5;}var _this=_super.call(this,priority)||this;_this.priority=priority;_this.maximumSize=maximumSize;_this.step=step;return _this;}", "static get VERTEX_FLOAT_SIZE() { return 3 + 3 + 2; }", "function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}", "setTextureVScale(v) {\n //TODO\n }", "function Image(user_texture_id, size, uv0 = ImVec2.ZERO, uv1 = ImVec2.UNIT, tint_col = ImVec4.WHITE, border_col = ImVec4.ZERO) {\r\n bind.Image(ImGuiContext.setTexture(user_texture_id), size, uv0, uv1, tint_col, border_col);\r\n }", "function Size(width,height){this.width=width;this.height=height;}", "resize( width, height )\r\n\t{\r\n\t\tif( width !== this._width || height !== this._height ) {\r\n\t\t\tthis._width = width;\r\n\t\t\tthis._height = height;\r\n\r\n\t\t\tthis._plasmaPixels = new Uint16Array( new ArrayBuffer( this._width * this._height * Uint16Array.BYTES_PER_ELEMENT ) );\r\n\r\n\t\t\tthis.generateNoiseImage();\r\n\t\t}\r\n\t}", "setSize(\n width, // The width of the game.\n height // The height of the game.\n ) {\n const { game } = this;\n if (width > 0) {\n game.width = width;\n }\n if (height > 0) {\n game.height = height;\n }\n }", "_gainFrameSize() {\n const image = this.texture.image;\n if (!image) return;\n if (image.width > 0 && image.height > 0) {\n this.loaded = true;\n this.frameAspect = image.width / image.height;\n this._updateAttributes();\n } else {\n image.addEventListener('load', () => {\n this.loaded = true;\n this.frameAspect = image.width / image.height;\n this._updateAttributes();\n });\n }\n }", "_setCreatureSize(data, actor, sceneId) {\n const sizes = {\n tiny: 0.5,\n sm: 0.8,\n med: 1,\n lg: 2,\n huge: 3,\n grg: 4,\n };\n const aSize = actor.data.data.traits.size;\n let tSize = sizes[aSize];\n\n // if size could not be found return\n if (tSize === undefined) return;\n\n const scene = game.scenes.get(sceneId);\n\n // If scene has feet/ft as unit, scale accordingly\n // 5 ft => normal size\n // 10 ft => double\n // etc.\n if (/(ft)|eet/.exec(scene.data.gridUnits) !== null)\n tSize *= 5 / scene.data.gridDistance;\n\n if (tSize < 1) {\n data.scale = tSize;\n data.width = data.height = 1;\n } else {\n const int = Math.floor(tSize);\n\n // Make sure to only have integers\n data.width = data.height = int;\n // And scale accordingly\n data.scale = tSize / int;\n // Set minimum scale 0.25\n data.scale = Math.max(data.scale, 0.25);\n }\n }", "map (tu, tv) {\n if (this.internalBuffer) { \n // using a % operator to cycle/repeat the texture if needed\n let u = Math.abs(((tu * this.width) % this.width)) >> 0;\n let v = Math.abs(((tv * this.height) % this.height)) >> 0;\n\n let pos = (u + v * this.width) * 4;\n\n let r = this.internalBuffer.data[pos];\n let g = this.internalBuffer.data[pos + 1];\n let b = this.internalBuffer.data[pos + 2];\n let a = this.internalBuffer.data[pos + 3];\n\n return new BABYLON.Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n }\n // Image is not loaded yet\n else {\n return new BABYLON.Color4(1, 1, 1, 1);\n }\n }", "function maxStageSize() {\n scene.setAttr('scaleX', 1);\n scene.setAttr('scaleY', 1);\n scene.setAttr('width', maxStageWidth);\n scene.setAttr('height', maxStageHeight);\n // document.getElementById(\"iframe\").style.transform = 1;\n // document.getElementById(\"iframe\").style.width = maxStageWidth;\n scene.draw();\n}", "function setSize(target, param){ \n\t\tvar opts = $.data(target, 'slider').options; \n\t\tvar slider = $.data(target, 'slider').slider; \n\t\t \n\t\tif (param){ \n\t\t\tif (param.width) opts.width = param.width; \n\t\t\tif (param.height) opts.height = param.height; \n\t\t} \n\t\tif (opts.mode == 'h'){ \n\t\t\tslider.css('height', ''); \n\t\t\tslider.children('div').css('height', ''); \n\t\t\tif (!isNaN(opts.width)){ \n\t\t\t\tslider.width(opts.width); \n\t\t\t} \n\t\t} else { \n\t\t\tslider.css('width', ''); \n\t\t\tslider.children('div').css('width', ''); \n\t\t\tif (!isNaN(opts.height)){ \n\t\t\t\tslider.height(opts.height); \n\t\t\t\tslider.find('div.slider-rule').height(opts.height); \n\t\t\t\tslider.find('div.slider-rulelabel').height(opts.height); \n\t\t\t\tslider.find('div.slider-inner')._outerHeight(opts.height); \n\t\t\t} \n\t\t} \n\t\tinitValue(target); \n\t}", "set requestedHeight(value) {}", "PushTextureID(texture_id) {\r\n this.native.PushTextureID(ImGuiContext.setTexture(texture_id));\r\n }", "render(program, renderParameters, textures){\n //renders the media source to the WebGL context using the pased program\n let overriddenElement;\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if (typeof this.mediaSourceListeners[i].render === 'function'){\n let result = this.mediaSourceListeners[i].render(this, renderParameters);\n if (result !== undefined) overriddenElement = result;\n }\n }\n\n this.gl.useProgram(program);\n let renderParametersKeys = Object.keys(renderParameters);\n let textureOffset = 1;\n for (let index in renderParametersKeys){\n let key = renderParametersKeys[index];\n let parameterLoctation = this.gl.getUniformLocation(program, key);\n if (parameterLoctation !== -1){\n if (typeof renderParameters[key] === \"number\"){\n this.gl.uniform1f(parameterLoctation, renderParameters[key]);\n }\n else if( Object.prototype.toString.call(renderParameters[key]) === '[object Array]'){\n let array = renderParameters[key];\n if(array.length === 1){\n this.gl.uniform1fv(parameterLoctation, array);\n } else if(array.length === 2){\n this.gl.uniform2fv(parameterLoctation, array);\n } else if(array.length === 3){\n this.gl.uniform3fv(parameterLoctation, array);\n } else if(array.length === 4){\n this.gl.uniform4fv(parameterLoctation, array);\n } else{\n console.debug(\"Shader parameter\", key, \"is too long and array:\", array);\n }\n }\n else{\n //Is a texture\n this.gl.activeTexture(this.gl.TEXTURE0 + textureOffset);\n this.gl.uniform1i(parameterLoctation, textureOffset);\n this.gl.bindTexture(this.gl.TEXTURE_2D, textures[textureOffset-1]);\n }\n }\n }\n \n this.gl.activeTexture(this.gl.TEXTURE0);\n let textureLocation = this.gl.getUniformLocation(program, \"u_image\");\n this.gl.uniform1i(textureLocation, 0);\n this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);\n if (overriddenElement !== undefined){\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, overriddenElement);\n } else {\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.element);\n }\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);\n }", "get tileSize() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function load font and write text on canvas
function loadFontAndWrite(font,text,x,y) { document.fonts.load(font).then(function () { ctx.font = font ctx.fillText(text, x, y) }); }
[ "function _loadFont(fontname){\n var canvas = document.createElement(\"canvas\");\n //Setting the height and width is not really required\n canvas.width = 16;\n canvas.height = 16;\n var ctx = canvas.getContext(\"2d\");\n\n //There is no need to attach the canvas anywhere,\n //calling fillText is enough to make the browser load the active font\n\n //If you have more than one custom font, you can just draw all of them here\n ctx.font = \"4px \"+fontname;\n ctx.fillText(\"text\", 0, 8);\n}", "setFont(font) {\n this.ctx.font = font;\n }", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "createText(){\n let text = Text.createText(this.activeColor);\n this.canvas.add(text);\n this.notifyCanvasChange(text.id, \"added\");\n }", "function drawText(txt,x,y,maxWidth,fontHeight,center) {\n if (center === undefined) {\n center = false;\n }\n\n // we need to scale the coordinate space in order to obtain the correct\n // max width and font height (i.e. sizes)\n var sx = canvas.width / 2;\n var sy = canvas.height / currentBlock.getHeight();\n\n if (center) {\n ctx.textAlign = \"center\";\n }\n else {\n ctx.textAlign = \"start\";\n }\n ctx.textBaseline = \"middle\"; // thank God for this\n\n // scale the context to undo the initial transformations; make sure\n // the scaling doesn't affect the specified text position\n ctx.save();\n ctx.scale(1/sx,1/sy);\n x *= sx; y *= sy;\n maxWidth *= sx; // this value converted to \"scaled pixels\"\n\n // the font is specified in pixels that are scaled; the transformations\n // take the font height from the calling context's coordinate space and\n // transforms it into units of \"scaled pixels\"\n var fontSz = fontHeight * sy;\n ctx.font = fontSz + \"px \" + DEFAULT_FONT;\n ctx.fillText(txt,x,y,maxWidth);\n\n ctx.restore();\n }", "function typeOnCanvas() {\n var memeText = $('#custom-text');\n gMeme.labels[0].txt = memeText.val();\n drawCanvas();\n}", "function Captcha() {\n for (var i = 0; i < 6; i++) {\n var a = alpha[Math.floor(Math.random() * alpha.length)];\n var b = alpha[Math.floor(Math.random() * alpha.length)];\n var c = alpha[Math.floor(Math.random() * alpha.length)];\n var d = alpha[Math.floor(Math.random() * alpha.length)];\n var e = alpha[Math.floor(Math.random() * alpha.length)];\n var f = alpha[Math.floor(Math.random() * alpha.length)];\n var g = alpha[Math.floor(Math.random() * alpha.length)];\n }\n captcha_text = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f + ' ' + g;\n\n document.fonts.load(font)\n .then(function() {\n tCtx.font = font;\n tCtx.canvas.width = tCtx.measureText(captcha_text).width;\n tCtx.canvas.height = 40;\n tCtx.font = font;\n tCtx.fillStyle = '#444';\n tCtx.fillText(captcha_text, 0, 20);\n\n var c = document.getElementById(\"textCanvas\");\n var ctx = c.getContext(\"2d\");\n // Draw lines\n for (var i = 0; i < 7; i++) {\n ctx.beginPath();\n ctx.moveTo(c.width * Math.random(), c.height * Math.random());\n ctx.lineTo(c.width * Math.random(), c.height * Math.random());\n ctx.strokeStyle = \"rgb(\" +\n Math.round(256 * Math.random()) + \",\" +\n Math.round(256 * Math.random()) + \",\" +\n Math.round(256 * Math.random()) + \")\";\n ctx.stroke();\n }\n\n imageElem.src = tCtx.canvas.toDataURL();\n });\n}", "function canvasPaint(topTextColor = 'white', bottomTextColor = 'red', transText = 0.5) {\n var elCanvas = document.getElementById('canvas');\n var ctx = canvas.getContext('2d');\n canvas.height = gCanvasHeight;\n canvas.width = gCanvasWidth;\n // ctx.fillStyle = '#0e70d1';\n var img = new Image();\n img.src = gMeme;\n img.onload = function () {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n // ctx.save();\n ctx.font = gTextFontSize + 'pt David';\n ctx.fillStyle = 'rgba(0,0,0,' + gTransText + ')';\n ctx.fillRect(0, 0, canvas.width, canvas.height / gTopTextHeight);\n ctx.fillRect(0, canvas.height - canvas.height / gBottomTextHeight, canvas.width, canvas.height / gBottomTextHeight);\n // ctx.save();\n ctx.fillStyle = topTextColor;\n ctx.fillText(gInputTopText.toUpperCase(), gTopTextAlign, gTextFontSize + 3);\n ctx.fillStyle = bottomTextColor;\n ctx.fillText(gInputBottomText.toUpperCase(), gBottomTextAlign, canvas.height - 5);\n ctx.font = '10pt Dvaid'\n ctx.fillStyle = '#fff';\n ctx.fillText(\"Noa's & Guy's MemeGenerator\", 10, 300);\n // ctx.restore();\n // ctx.fillStyle = '#fff';\n ctx.save();\n // return ctx\n };\n // var newImg=new Image();\n // newImg.id=\"meme\";\n // memeUrl = canvas.toDataURL();\n // document.getElementById('img_generated').appendChild(newImg);\n // console.log(ctx);\n // return res\n}", "function loadCCText(text) {\n\tclearCC();\n\t//console.log(\"Loading: \"+text);\n\t$('#'+shell.caption.textEl).append(text);\n\tif (CCIsDim) enableCC();\n}", "ctxDrawText (ctx, string, x, y, cssColor) {\n this.setIdentity(ctx)\n ctx.fillStyle = cssColor\n ctx.fillText(string, x, y)\n ctx.restore()\n }", "static addText (options) {\n const text = BABYLON.MeshBuilder.CreatePlane(options.name, { sideOrientation: BABYLON.Mesh.DOUBLESIDE, width: options.scaling.x, height: options.scaling.y }, options.scene)\n text.position = options.position || new BABYLON.Vector3(0,0,0)\n text.rotation = options.rotation || new BABYLON.Vector3(0,0,0)\n text.material = new BABYLON.PBRMaterial(options.materialName, options.scene)\n if (options.background === 'transparent') {\n text.material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND\n }\n text.material.metallic = 0\n text.material.roughness = 1\n\n const texture = new DrawText(this.scene, options.text, {\n color: options.color || '#000000',\n background: options.background,\n invertY: options.invertY || true,\n font: options.font || 0,\n rotation: options.rotationY || -Math.PI / 2,\n scaling: [options.scaling.x, options.scaling.y]\n }, options.donotwrap)\n text.material.albedoTexture = texture\n if (options.background === 'transparent') {\n text.material.opacityTexture = texture\n }\n \n return text\n }", "function styleText(text){ \n\t//console.log(\"style text called\");\n\ttext.style.fontFamily = getFont();\n\ttext.style.color = getColor(0); \n\ttext.style.backgroundColor = getColor(1);\n\tif (border) {\n\t\ttext.style.border = \"solid \"+ getBorder() + \"px\";\n\t\t//console.log(\"solid\"+ getBorder() + \"px\");\n\t\ttext.style.borderColor = getColor(2);\n\t};\n\ttext.style.fontSize = getSize() + \"px\"; \n}", "function drawText(line, col, text) {\r\n const length = text.length\r\n for (let i = 0; i < length && line < LINES; i++) {\r\n drawChar(line, col, text.charAt(i))\r\n if (++col >= COLUMNS) {\r\n col = 0\r\n line++\r\n }\r\n }\r\n}", "function initResourceText(stage, canvas){\n resourceText = new createjs.Text(\"Resources: 0\", \"20px Arial\", \"#00FFFF\");\n>>>>>>> 17dc8ba78ca466836f66aa20989aa32920076c56\n resourceText.x = 0;\n resourceText.y = canvas.height/12; //TODO more logically position Resources text\n resourceText.textBaseline = \"alphabet\"; //Not sure what this setting does\n stage.addChild(resourceText);\n return resourceText;\n<<<<<<< HEAD\n\n=======\n}", "text(...args) {\n let opts = args[args.length - 1];\n\n if (typeof opts !== 'object') {\n opts = {};\n }\n\n if (!opts.lineGap) {\n opts.lineGap = lineGap;\n }\n\n if (opts.font) {\n this.doc.font(opts.font);\n } else {\n this.doc.font(lightFont);\n }\n\n if (opts.color) {\n this.doc.fillColor(opts.color);\n } else {\n this.doc.fillColor('black');\n }\n\n if (opts.size) {\n this.doc.fontSize(opts.size);\n } else {\n this.doc.fontSize(10);\n }\n\n return this.doc.text(...args);\n }", "key(x, y, squareSize, font) {\n this.ctx.font = font;\n for (let i = 0; i < this.data.length; i++) {\n this.ctx.fillStyle = this.data[i].color;\n this.ctx.textBaseline = \"top\";\n this.ctx.textAlign = \"left\";\n this.ctx.fillRect(x, y + i * squareSize * 1.5, squareSize, squareSize);\n this.ctx.fillText(`${this.data[i].label}, ${this.data[i].unit}`, x + squareSize * 1.5, y + squareSize * i * 1.5);\n }\n }", "fillTexts(attrs, tarray, clip=null)\n {\n let ctx = this.canvasCtx;\n ctx.save();\n if(clip) this.doClip(ctx, clip);\n ctx.font = attrs[0];\n ctx.fillStyle = attrs[1];\n ctx.textBaseline = attrs[2];\n ctx.textAlign = attrs[3];\n for(let i=0;i<tarray.length;i++)\n {\n let t = tarray[i];\n ctx.fillText(t[0], t[1], t[2]);\n }\n ctx.restore();\n }", "function canvas_set_font(ctx, size, monospaced) {\n var s = window.getComputedStyle(onscreen_canvas);\n // First set something that we're certain will work. Constructing\n // the font string from the computed style is a bit fragile, so\n // this acts as a fallback.\n ctx.font = `${size}px ` + (monospaced ? \"monospace\" : \"sans-serif\");\n // In CSS Fonts Module Level 4, \"font-stretch\" gets serialised as\n // a percentage, which can't be used in\n // CanvasRenderingContext2d.font, so we omit it.\n ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +\n (monospaced ? \"monospace\" : s.fontFamily);\n}", "constructor(fontImg, fontInfo) {\n fontInfo = JSON.parse(fontInfo).font;\n\n function toInt(str) {\n return parseInt(str, 10);\n }\n\n this.lineHeight = toInt(fontInfo.common.lineHeight);\n this.baseline = toInt(fontInfo.common.base);\n\n // Create glyph map\n this.glyphs = {};\n for (var i=0; i<fontInfo.chars.count; ++i) {\n var cInfo = fontInfo.chars.char[i];\n var glyph = new Glyph(fontImg, cInfo.id, toInt(cInfo.x), toInt(cInfo.y), toInt(cInfo.width), toInt(cInfo.height), toInt(cInfo.xoffset), toInt(cInfo.yoffset), toInt(cInfo.xadvance));\n this.glyphs[glyph.charCode] = glyph;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This Creates a new Bar chart with the supplied data
function newBarChart(ctx,data){ var myChart = new Chart(ctx, { type: 'bar', data: { labels: (data["Label"]?data["Label"]:["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]), datasets: [{ label: (data["Title"]?data["Title"]:'# of Votes'), data: (data["Data"]?data["Data"]:[12, 19, 3, 5, 2, 3]), backgroundColor: 'rgba(92, 132, 255, 0.2)', borderColor: 'rgba(92,132,255,1)', borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); }
[ "function getBarDataset(label, data){\n return [{\n label: label,\n fillColor: \"rgba(151,187,205,0.2)\",\n strokeColor: \"rgba(151,187,205,1)\",\n highlightFill: \"rgba(151,187,205,0.1)\",\n highlightStroke: \"rgba(151,187,205,1)\",\n data: data\n }];\n}", "function drawBarChart(canvas, container, data) {\n let ctx = canvas[0].getContext(\"2d\"),\n chart = new Chart(ctx).Bar(data);\n chart.draw();\n return chart;\n}", "function drawBarChart(data, options, element) {\n\n}", "function createBarChart(_params, _parentEl) {\n // Organizing the input data\n var file = _params.dataPath,\n y_legend = _params.yAxisLabel,\n title = _params.title,\n type = _params.valueType,\n layerOfInterest = _params.layerName;\n\n // Inherit the width from the parent node.\n var width = d3.select(_parentEl).node().getBoundingClientRect().width,\n height = width * 0.3 ,\n margin = 0;\n // Setting up the svg element for the bar chart to be contained in\n var svg = d3.select(_parentEl)\n .append(\"svg\")\n .attr('height', height * 1.5)\n .attr('width', width - 15)\n .attr('preserveAspectRatio', 'xMinYMin meet')\n .attr(\n 'viewBox',\n '0 0 ' +\n (width + margin + margin) * 1.3 +\n ' ' +\n (height + margin + margin)\n );\n // Defining the container for the tooltip.\n var div = d3.select(_parentEl).append(\"div\")\n .attr(\"class\", \"tooltip\")\n .style(\"display\", \"none\");\n // Appending the title to svg.\n svg.append(\"text\")\n .attr(\"transform\", \"translate(\" + width * 0.1 + \",0)\")\n .attr(\"x\", width * 0.1)\n .attr(\"y\", width * 0.1)\n .attr(\"font-size\", \"24px\")\n .text(title)\n\n // Defining the the two axis\n var xScale = d3.scaleBand().range([0, width]).padding(0.4),\n yScale = d3.scaleLinear().range([height, 0]); //height\n\n // Defining the g to contain the actual graph\n var g = svg.append(\"g\")\n .classed('chart-body', true)\n .attr(\"transform\", \"translate(\" + margin + 70 + \",\" + margin + 80 + \")\");\n\n // Reading in the data\n d3.csv(file).then(function(data) {\n data.forEach(function(d) {\n d.value = +d.value;\n });\n\n // Placing the data on the axis\n xScale.domain(data.map(function(d) {\n return d.name;\n }));\n yScale.domain([0, d3.max(data, function(d) {\n return d.value;\n })]);\n\n // Setting the axis title and the tick-marks the x-axis.\n g.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(xScale))\n .append(\"text\")\n .attr(\"y\", height * 0.2)\n .attr(\"x\", width * 0.45)\n .attr(\"text-anchor\", \"end\")\n .attr(\"stroke\", \"black\")\n .text(\"Name\");\n\n // Setting the axis title and the tick-marks the y-axis.\n g.append(\"g\")\n .call(d3.axisLeft(yScale).tickFormat(function(d) {\n if (type == 'value') {\n return \"$\" + d;\n } else if (type == 'amount') {\n return d;\n }\n })\n .ticks(10))\n .append(\"text\")\n .attr(\"transform\", \"rotate(0)\")\n .attr(\"y\", 5)\n .attr(\"dy\", \"-2.1em\")\n .attr(\"text-anchor\", \"end\")\n .attr(\"stroke\", \"black\")\n .text(y_legend);\n\n // Appending the actual bars using rect elements\n g.selectAll(\".bar\")\n .data(data)\n .enter().append(\"rect\")\n .attr(\"class\", function(d){\n return 'bar '+d.code;\n })\n .attr(\"x\", function(d) {\n return xScale(d.name);\n })\n .attr(\"y\", function(d) {\n return yScale(d.value);\n })\n .attr(\"width\", xScale.bandwidth())\n .attr(\"height\", function(d) {\n return height - yScale(d.value);\n })\n .style('fill-opacity','0.7')\n // Enabling the interactivity when hovering\n .on('mouseenter', function(d) {\n\n d3.selectAll('.' + d.code)\n .classed('active', true)\n .style('fill-opacity','1');\n\n map.setFilter(layerOfInterest +'-highlighted', ['==', 'code', d.code]);\n })\n .on(\"mousemove\", function(d){\n div\n .text('Value: '+d.value)\n .style('display','block')\n .style('opacity','1')\n .style('font-weight','bold')\n .style(\"left\", (d3.mouse(this)[0]) + \"px\")\n .style(\"top\", (d3.mouse(this)[1]) + \"px\");\n })\n .on(\"mouseout\", function(d) {\n map.setFilter(layerOfInterest +'-highlighted', ['==', 'code', '']);\n\n d3.selectAll('.bar')\n .classed('active', false)\n .style('fill-opacity','0.7')\n\n div.style('opacity','0')\n });\n });\n}", "function createHorizontalBarchart(className,svgWidth,svgHeight,x,y,data,xTitle){\n //set width and height of bar chart\n let svg = d3.select(className)\n .attr(\"width\",svgWidth)\n .attr(\"height\",svgHeight)\n .attr(\"transform\",`translate(${x},${y})`);\n \n //Gaps between the barchart and svg\n let margin = { top: 0, right: 30, bottom:100, left: 100};\n \n //Calculate the real range for x and y scale\n let innerWidth = svgWidth - margin.left - margin.right;\n let innerHeight = svgHeight - margin.top - margin.bottom;\n \n //Round and the values\n let values = Array.from(data.values());\n let keys = Array.from(data.keys());\n \n //X scale of bar chart\n let xScale = d3.scaleLinear()\n .domain([0,d3.max(values)])\n .range([0,innerWidth]);\n \n //y scale of bar chart\n let yScale = d3.scaleBand()\n .domain(keys)\n .range([0,innerHeight])\n .padding(0.05);\n \n //Separate out the barchart\n let g = svg.append(\"g\")\n .attr(\"transform\",`translate(${margin.left},${margin.top})`);\n \n //Left axis with removed ticks\n g.append('g')\n .call(d3.axisLeft(yScale))\n .selectAll('.domain , .tick line')\n .remove();\n \n //this determine the value's format\n let valueType;\n if(d3.mean(values) < 1){\n valueType = \".0%\" \n }else {\n valueType = \".0f\";\n }\n \n g.append('g')\n .call(d3.axisLeft(yScale))\n .selectAll('.domain, .tick line')\n .remove();\n \n //Bottom axis\n let xAxis = g.append('g')\n .call(d3.axisBottom(xScale).tickFormat(d3.format(valueType)).tickSize(-innerHeight))\n .attr('transform',`translate(0,${innerHeight})`);\n \n xAxis.select(\".domain\")\n .remove();\n \n //add bars into the svg\n g.selectAll(\"rect\")\n .data(data)\n .enter()\n .append(\"rect\")\n .attr(\"y\", d => yScale(d[0]))\n .attr(\"height\", yScale.bandwidth())\n .transition()\n .duration(1000)\n .attr(\"width\",d => xScale(d[1]))\n \n \n //append the title\n svg.append(\"text\")\n .attr(\"transform\",`translate(${(margin.left+innerWidth)/2},${innerHeight + margin.bottom/2})`)\n .text(xTitle)\n .attr(\"fill\",\"#b3ecff\")\n .attr(\"font-size\",\"30px\");\n \n}", "function getBars(){\n for(var i = 0; i < dataset.length; i++){\n let height = getHeight(highNumberForYAxis, max, dataset[i]);\n let width = dataset.length > 2 ? (highNumberForXAxis - lowNumberForXAxis) / dataset.length - barPadding : 70;\n let x = (lowNumberForXAxis + barPadding) + rectangles.length * (highNumberForXAxis - lowNumberForXAxis - 5) / dataset.length;\n let y = highNumberForYAxis - height;\n rectangles.push(<Rect key={rectangles.length} x={x} y={y} width={width} height={height} fill={'rgb(23,153,173)'} />)\n }\n }", "function barChart(ndx) {\n var dim = ndx.dimension(dc.pluck('created'));\n var group = dim.group();\n \n dc.barChart(\"#bar-chart\")\n .width(350)\n .height(250)\n .margins({top: 30, right: 50, bottom: 45, left: 40})\n .dimension(dim)\n .group(group)\n .transitionDuration(1000)\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Customer created\")\n .yAxisLabel(\"# of customers\")\n .yAxis().ticks(10);\n}", "function createBarcharts(){\n\n // bar charts for age-group and birth cohort in county representation\n makeBarchart(d, featuresCB, \"#barchart1Position\",\"barchart1\",firstTimeData(d, selectedCategories), firstTimeData(d, selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2Position\",\"barchart2\",secondTimeData(d, selectedCategories), secondTimeData(d, selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in state representation\n makeBarchart(d, featuresCB, \"#barchart1BLPosition\",\"barchart1BL\",firstTimeDataBL(classes[1], selectedCategories), firstTimeDataBL(classes[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2BLPosition\",\"barchart2BL\",secondTimeDataBL(classes[1], selectedCategories), secondTimeDataBL(classes[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in kv representation\n makeBarchart(d, featuresCB, \"#barchart1KVPosition\",\"barchart1KV\",firstTimeDataKV(aships[1], selectedCategories), firstTimeDataKV(aships[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2KVPosition\",\"barchart2KV\",secondTimeDataKV(aships[1], selectedCategories), secondTimeDataKV(aships[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n\n\n // for the ranking of the top and worst 5 (=cutbarchart) counties when zoomed. If state has equal/less than 10 counties, all counties are shown\n if(lkData().length < 2*cutbarchart){\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",lkData(), numberLK(), \"lk\", rv, 3);\n d3.select(\"#barchart4\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n // 3 points shown in county ranking when zoomed\n else{\n d3.selectAll(\".circles\").remove();\n var worstLk = lkData().slice(cutbarchart,lkData().length);\n var topLk = lkData().slice(0,cutbarchart);\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",topLk, cutbarchart, \"lk\", rv, 3); // top 5 counties\n\n var svgCircles = d3.select(\"#circlesPosition\").append(\"g\")\n .attr(\"class\", \"circles\")\n .append(\"svg\")\n .attr(\"width\", 100)\n .attr(\"height\", 12)\n .attr(\"preserveAspectRatio\", \"xMidYMid meet\")\n .attr(\"viewBox\", \"0 0 \" + d3.select(\"#sidebarRight\").style(\"width\").split(\"px\")[0] + \" 12\")\n .append(\"g\")\n .attr(\"transform\", \"translate(0,0)\");\n\n var circles3 = [{\"cx\": 30, \"cy\":2 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":6 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":10 , \"r\": 1, \"color\": \"black\"}];\n\n var circles = svgCircles.selectAll(\"circle\")\n .data(circles3)\n .enter()\n .append(\"circle\");\n\n var circleAttributes = circles\n .attr(\"cx\", function (d) { return d.cx; })\n .attr(\"cy\", function (d) { return d.cy; })\n .attr(\"r\", function (d) { return d.r; })\n .style(\"fill\", function(d) { return d.color; });\n circleAttributes.attr(\"transform\",\"translate(0,0)\");\n\n makeBarchart(d, featuresCB, \"#barchart4Position\",\"barchart4\",worstLk, cutbarchart, \"lk\", rv, 3); // worst 5 counties\n }\n if(!zoomed){\n d3.select(\"#titel3\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n }", "function renderBarChart() {\n var i, j, p, a, x, y, w, h, len;\n\n if (opts.orient === \"horiz\") {\n rotate();\n }\n\n drawAxis();\n\n ctx.lineWidth = opts.stroke || 1;\n ctx.lineJoin = \"miter\";\n\n len = sets[0].length;\n\n // TODO fix right pad\n for (i = 0; i < sets.length; i++) {\n for (j = 0; j < len; j++) {\n p = 1;\n a = rotated ? height : width;\n w = ((a / len) / sets.length) - ((p / sets.length) * i) - 1;\n x = (p / 2) + getXForIndex(j, len + 1) + (w * i) + 1;\n y = getYForValue(sets[i][j]);\n h = y - getYForValue(0) || 1;\n\n if (isStacked()) {\n // TODO account for negative and positive values in same stack\n w = (a / len) - 2;\n x = getXForIndex(j, len + 1);\n y = getYForValue(sumY(sets.slice(0, i + 1), j));\n }\n\n drawRect(x, y, w, h, getColorForIndex(i));\n }\n }\n }", "function draw_g_bar(data) {\n\n let dates = [];\n let series_vivo = [];\n let series_muerto = [];\n let series_nose = [];\n let i = 0;\n while (i < data.length) {\n let j = i;\n dates.push(data[i]['fecha']); // add the new date\n while (j < data.length && data[i]['fecha'] === data[j]['fecha']) { // for all data on that date, append\n switch (data[j]['estado']) {\n case 'vivo':\n series_vivo.push(data[j]['n_avistamientos']);\n break;\n case 'muerto':\n series_muerto.push(data[j]['n_avistamientos']);\n break;\n case 'no sé':\n series_nose.push(data[j]['n_avistamientos']);\n break;\n }\n j++;\n }\n i = j;\n }\n\n\n let options = {\n chart: {\n height: 380,\n width: \"100%\",\n type: 'bar',\n animations: {\n initialAnimation: {\n enabled: false\n }\n }, plotOptions: {\n bar: {\n horizontal: false,\n dataLabels: {\n position: 'top',\n },\n }\n }, dataLabels: {\n enabled: true,\n offsetX: -6,\n style: {\n fontSize: '12px',\n colors: ['#fff']\n }\n }\n },\n stroke: {\n show: true,\n width: 1,\n colors: ['#fff']\n },\n tooltip: {\n shared: true,\n intersect: false\n },\n series: [{\n //data: [44, 55, 41, 64, 22, 43, 21],\n data: series_vivo,\n name: \"Vivo\"\n }, {\n // data: [53, 32, 33, 52, 13, 44, 32],\n data: series_muerto,\n name: \"Muerto\"\n }, {\n data: series_nose,\n name: \"No sé\"\n }],\n xaxis: {\n categories: dates,\n // categories: [2001, 2002, 2003, 2004, 2005, 2006, 2007],\n },\n };\n document.getElementById('grafico_barras_placeholder').innerText = \"\";\n let chart = new ApexCharts(document.getElementById('grafico_barras_placeholder'), options);\n\n chart.render();\n}", "function chart_chef(chef_data) {\n const labels = []\n const data_count = []\n for ( var i in chef_data ) {\n labels.push(chef_data[i]._id)\n data_count.push(chef_data[i].count)\n }\n const data = {\n labels: labels,\n datasets: [{\n label: 'Top 5 Chefs, by recipe count',\n data: data_count,\n backgroundColor: [\n 'rgba(255, 99, 132, 0.2)',\n 'rgba(255, 159, 64, 0.2)',\n 'rgba(255, 205, 86, 0.2)',\n 'rgba(75, 192, 192, 0.2)',\n 'rgba(54, 162, 235, 0.2)'\n ],\n borderColor: [\n 'rgb(255, 99, 132)',\n 'rgb(255, 159, 64)',\n 'rgb(255, 205, 86)',\n 'rgb(75, 192, 192)',\n 'rgb(54, 162, 235)'\n ],\n borderWidth: 1\n }]\n };\n\n const config = {\n type: 'bar',\n data,\n options: {\n scales: {\n y: {\n beginAtZero: true\n }\n }\n }\n };\n\n var myChart = new Chart(\n document.getElementById('chefChart'),\n config\n );\n}", "function add_bar_chart(props) {\n console.log(props);\n\n const data = [ {'origin': 'asian',\n 'percent': props.asian_percent},\n {'origin': 'black',\n 'percent': props.black_percent},\n {'origin': 'hispanic',\n 'percent': props.hispanic_percent},\n // {'origin': 'native american',\n // 'percent': props.native_percent},\n // {'origin': 'pacific islander',\n // 'percent': props.pacific_percent},\n {'origin': 'white',\n 'percent': props.white_percent},\n {'origin': 'other',\n 'percent': props.other_percent + props.native_percent + props.pacific_percent},\n ];\n\n // Remove previous svg element, if any\n d3.select(\".tooltip\")\n .selectAll(\"svg\")\n .remove();\n\n // Dimensions\n const m = {top: 10, right: 5, bottom: 5, left: 5},\n p = {top: 0, right: 15, bottom: 0, left: 33},\n width = 150 - m.left - m.right,\n height = 110 - m.top - m.bottom;\n\n // Initialize svg element\n const popup_svg = d3.select(\".tooltip\")\n .append(\"svg\")\n .attr(\"width\", width + m.left + m.right)\n .attr(\"height\", height + m.top + m.bottom)\n .append('g')\n .attr('transform', \"translate(\" + m.left + \",\" + m.top + \")\");\n\n\n // Scales\n const color = d3.scaleOrdinal([\"#98abc5\", \"#8a89a6\", \"#7b6888\", \"#6b486b\", \"#a05d56\", \"#d0743c\", \"#ff8c00\"]);\n \n const x = d3.scaleLinear()\n .rangeRound([0, width - p.left - p.right])\n .domain([0, 1]);\n\n const y = d3.scaleBand()\n .rangeRound([0, height])\n .paddingInner(0.2)\n .domain(data.map(d => d.origin));\n\n const yAxis = d3.axisLeft(y).tickSize(0);\n\n const format = d3.format(\".0%\");\n\n // y-Axis\n popup_svg.append(\"g\")\n .attr(\"class\", \"axis axis-y\")\n .call(yAxis)\n .attr('transform', \"translate(\" + p.left + \",0)\");\n\n // Bar + percent text group\n const bars = popup_svg.selectAll('g.bar')\n .data(data)\n .enter()\n .append('g')\n .attr('class', 'bar')\n .attr('transform', d => ('translate(' + p.left + ',' + y(d.origin) +')'));\n\n // Bars\n bars.append('rect')\n .attr('height', y.bandwidth())\n .attr('width', d => x(d.percent))\n .attr('fill', (d, i) => color(i))\n\n // Percent text\n bars.append('text')\n .attr('class', 'value')\n .attr('x', d => x(d.percent))\n .attr('y', d => (y.bandwidth() / 2))\n .attr('dx', 2)\n .attr('dy', '0.35em')\n .text(d => format(d.percent))\n \n }", "function createChart(quantity) {\n\treturn new Highcharts.Chart({\n\t\tchart : {\n\t\t\trenderTo : 'container',\n\t\t\tdefaultSeriesType : 'bar',\n\t\t\tevents : {\n\t\t\t\tload : updateChart(quantity)\n\t\t\t}\n\t\t},\n\t\tcredits : {\n\t\t\tenabled : true,\n\t\t\thref : \"http://nest.lbl.gov/products/spade/\",\n\t\t\ttext : 'Spade Data Management'\n\t\t},\n\t\ttitle : {\n\t\t\ttext : 'Total Counts for SPADE'\n\t\t},\n\t\tsubtitle : {\n\t\t\ttext : 'Loading ...'\n\t\t},\n\t\txAxis : {\n\t\t\ttitle : {\n\t\t\t\ttext : 'Activity',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tminWidth : '140px'\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tyAxis : [ {\n\t\t\ttitle : {\n\t\t\t\ttext : 'counts',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}],\n\t\tseries : [ {\n\t\t\tname : 'suspended'\n\t\t}, {\n\t\t\tname : 'pending'\n\t\t}, {\n\t\t\tname : 'executing'\n\t\t}, {\n\t\t\tname : 'total'\n\t\t} ]\n\t});\n}", "function drawSchool2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 28, 105],\n [\"MGHS\", 13, 84],\n [\"IHoMCS\", 10, 12],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n \"title\": \"Figure 8: Mode of Transportation to School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n\t\tcolors: ['#C52026','#ADADAD'],\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div9\"));\n chart.draw(data, options);\n }", "function barHelper(plot, xVal, yVal) {\n // Set attributes of the selected elements.\n plot.attr(\"class\", \"bar\").attr(\"x\", data => xVal(data.key))\n .attr(\"y\", data => yVal(data.value)).attr(\"width\", xVal.bandwidth())\n .attr(\"height\", data => height - margin - yVal(data.value))\n .attr('fill', data => colorScale(data.key));\n }", "function undergradEnrollChart() {\r\n\t\t\tvar undergradData = getEnrollmentCout(studentEnrollment);\r\n\t\t\tvar count = undergradData[1];\r\n\t\t\tvar year = undergradData[0];\r\n\r\n\t\t\tvar chartData = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Enrollment'],\r\n\t\t\t\t[year.year5, count.year5],\r\n\t\t\t\t[year.year4, count.year4],\r\n\t\t\t\t[year.year3, count.year3],\r\n\t\t\t\t[year.year2, count.year2],\r\n\t\t\t\t[year.year1, count.year1]\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' }\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('undergradEnrollChart'));\r\n\t\t\tchart.draw(chartData, google.charts.Bar.convertOptions(options));\r\n\t\t}", "function undergradAdultDataChart() {\r\n\t\t\tvar undergradData = getUndergradAdultData(galbyClassAndGen);\r\n\t\t\tvar maleUGData = undergradData[0];\r\n\t\t\tvar femaleUGData = undergradData[1];\r\n\r\n\t\t\tvar undergradAdultChart = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Male', 'Female', { role: 'annotation' }],\r\n\t\t\t\t['Freshman', maleUGData.freshman, femaleUGData.freshman, ''],\r\n\t\t\t\t['Sophomore', maleUGData.sophomore, femaleUGData.sophomore, ''],\r\n\t\t\t\t['Junior', maleUGData.junior, femaleUGData.junior, ''],\r\n\t\t\t\t['Senior', maleUGData.senior, femaleUGData.senior, '']\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' },\r\n\t\t\t\tisStacked: true\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('undergradAdultByClassificatioinGenderChart'));\r\n\t\t\tchart.draw(undergradAdultChart, google.charts.Bar.convertOptions(options));\r\n\t\t}", "function createStackedBarChart(jsonObj) {\r\n\r\n\t// create new svg\r\n\tvar svg = d3.select(\"svg\"),\r\n margin = {top: 20, right: 20, bottom: 30, left: 40},\r\n width = +svg.attr(\"width\") - margin.left - margin.right,\r\n height = +svg.attr(\"height\") - margin.top - margin.bottom,\r\n g = svg.append(\"g\").attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\r\n\tvar x = d3.scaleBand()\r\n\t .rangeRound([0, width])\r\n\t .padding(0.1)\r\n\t .align(0.1);\r\n\r\n\tvar y = d3.scaleLinear()\r\n \t.rangeRound([height, 0]);\r\n\r\n\tvar z = d3.scaleOrdinal()\r\n\t .range([\"#98abc5\", \"#8a89a6\"]);\r\n\r\n\tvar stack = d3.stack();\r\n\tvar data = jsonObj;\r\n\r\n\tz.domain(d3.keys(data[0]).filter(function(key) { return key !== \"jahr\"; }));\r\n\r\n\tdata.forEach(function(d) {\r\n\t var y0 = 0;\r\n\t d.jahre = z.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });\r\n\t d.total = d.jahre[d.jahre.length - 1].y1;\r\n \t});\r\n\r\n\tx.domain(data.map(function(d) { return d.jahr; }));\r\n\ty.domain([0, d3.max(data, function(d) { return d.total; })]);\r\n\r\n \tg.selectAll(\".serie\")\r\n \t.data(stack.keys([\"patienten_entlassen\", \"patienten_gestorben\"])(data))\r\n \t.enter().append(\"g\")\r\n \t.attr(\"class\", \"serie\")\r\n \t.attr(\"fill\", function(d) { return z(d.key); })\r\n \t.selectAll(\"rect\")\r\n\t .data(function(d) { return d; })\r\n\t .enter().append(\"rect\")\t \r\n\t .attr('jahr', function(d) {return d.data.jahr;}) \r\n\t .attr('data-togle', 'tooltip')\r\n\t .attr('data-placement', 'right')\r\n\t .attr('title', function(d) {\r\n\t \tvar patienten_gestorben = parseFloat(d.data.patienten_gestorben);\r\n\t \tvar patienten_entlassen = parseFloat(d.data.patienten_entlassen);\r\n\t \tvar gestorbenProzent = (patienten_gestorben / (patienten_gestorben + patienten_entlassen)) * 100; \r\n\t \tgestorbenProzent = gestorbenProzent.toFixed(4);\r\n\t \tgestorbenProzent = germanizeDecimal(gestorbenProzent);\r\n\t \tvar gestorben = humanizeNumber(patienten_gestorben);\r\n\t \tvar entlassen = humanizeNumber(patienten_entlassen);\r\n\t\t \tvar text = \"Entlassen: \" + entlassen + \"<br />Gestorben: \" + gestorben + \"<br />Gestorben %: \" + gestorbenProzent; \r\n\t \treturn text;\r\n\t \t})\r\n\t .attr(\"x\", function(d) { return x(d.data.jahr); })\r\n\t .attr(\"y\", function(d) { return y(d[1]); })\r\n\t .attr(\"height\", function(d) { return y(d[0]) - y(d[1]); })\r\n\t .attr(\"width\", x.bandwidth());\r\n\r\n\tg.append(\"g\")\r\n\t .attr(\"class\", \"axis axis--x\")\r\n\t .attr(\"transform\", \"translate(0,\" + height + \")\")\r\n\t .call(d3.axisBottom(x));\r\n\r\n\tg.append(\"g\")\r\n\t .attr(\"class\", \"axis axis--y\")\r\n\t .call(d3.axisLeft(y).ticks(10, \"s\"))\r\n\t .append(\"text\")\r\n\t .attr(\"x\", 2)\r\n\t .attr(\"y\", y(y.ticks(10).pop()))\r\n\t .attr(\"dy\", \"0.35em\")\r\n\t .attr(\"text-anchor\", \"start\")\r\n\t .attr(\"fill\", \"#000\")\r\n\t .text(\"Patienten\");\r\n\r\n\t/*\r\n \tvar legend = g.selectAll(\".legend\")\r\n \t.data(data.slice(2,4))\r\n \t.enter().append(\"g\")\r\n .attr(\"class\", \"legend\")\r\n .attr(\"transform\", function(d, i) { return \"translate(0,\" + i * 20 + \")\"; })\r\n .style(\"font\", \"10px sans-serif\");\r\n\r\n\tlegend.append(\"rect\")\r\n\t .attr(\"x\", width - 18)\r\n\t .attr(\"width\", 18)\r\n\t .attr(\"height\", 18)\r\n\t .attr(\"fill\", z);\r\n\r\n\tlegend.append(\"text\")\r\n\t .attr(\"x\", width - 24)\r\n\t .attr(\"y\", 9)\r\n\t .attr(\"dy\", \".35em\")\r\n\t .attr(\"text-anchor\", \"end\")\r\n\t .text(function(d) { return d; });\r\n\t*/\r\n\r\n}", "function barchart(selectedID){\n d3.json(\"data/samples.json\").then((data) => {\n var dropdownMenu = d3.select(\"#selDataset\");\n selectedID = dropdownMenu.node().value;\n var samples = data.samples;\n var selectID = samples.filter(person=>person.id==selectedID);\n var valuearray = selectID[0];\n var values = valuearray.sample_values.slice(0,10);\n var IDs = valuearray.otu_ids.map(otu => \"OTU \" + otu);\n var labels = valuearray.otu_labels.slice(0,10);\n // console.log(valuearray);\n\n // Create the trace for plotting\n var trace = {\n x : values,\n y : IDs,\n text : labels,\n type : 'bar',\n orientation : 'h'\n };\n\n // Define the plot layout\n var layout = {\n title: \"Top 10 OTU's for Selected Test Subject\",\n xaxis: { title: \"Sample Value\" },\n yaxis: { title: \"OTU ID\" }\n };\n\n // Define the data\n var plotdata = [trace]\n\n // Create plot using Plotly\n Plotly.newPlot('bar', plotdata, layout)\n\n})}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run a Haskell IO action synchronously, ignoring the result or any exception in the Haskell code a: the IO action cont: continue async if blocked returns: true if the action ran to completion, false otherwise throws: any uncaught Haskell or JS exception except WouldBlock
function h$runSync(a, cont) { var t = new h$Thread(); ; h$runSyncAction(t, a, cont); if(t.resultIsException) { if(t.result instanceof h$WouldBlock) { return false; } else { throw t.result; } } return t.status === (16); }
[ "function promiseWhile(condition, action) {\n\treturn new Promise((resolve, reject) => {\n\t\tvar loop = function() {\n\t\t\tif(!condition()) resolve();\t\n\t\t\telse Promise.resolve(action()).then(loop, reject);\n\t\t};\n\t\tprocess.nextTick(loop);\n\t});\t\n}", "async function cobaAsync(){\n try{\n const res=await coba();\n console.log(res);\n }catch(err){\n console.error(err);\n }\n}", "async function main() {\n // promise成功则运行否则不执行下一句语句\n await waitFor(p, 1000, canceler).catch(() => console.log(p))\n}", "async function __handleFlowExecuteActions (flow, recUser, message) {\n\n\t// Execute all the actions in the order they are specified, and stop here if one of the actions redirects us.\n\tconst actions = flow.definition.actions;\n\tconst continueWithFlow = await this.executeActions(`flow`, flow.uri, actions, recUser, message);\n\n\tif (!continueWithFlow) {\n\t\tthrow new Error(`STOP_SUCCESSFULLY_COMPLETED`);\n\t}\n\n}", "async function makeCoffee(){...}", "async function asyncFunc() {\n return 123;\n}", "async function invokeAction () {\n setState({ ...state, actionInvokeInProgress: true, actionResult: 'calling action ... ' })\n const actionName = state.actionSelected\n const headers = state.actionHeaders || {}\n const params = state.actionParams || {}\n const startTime = Date.now()\n // all headers to lowercase\n Object.keys(headers).forEach((h) => {\n const lowercase = h.toLowerCase()\n if (lowercase !== h) {\n headers[lowercase] = headers[h]\n headers[h] = undefined\n delete headers[h]\n }\n })\n // set the authorization header and org from the ims props object\n if (props.ims.token && !headers.authorization) {\n headers.authorization = `Bearer ${props.ims.token}`\n }\n if (props.ims.org && !headers['x-gw-ims-org-id']) {\n headers['x-gw-ims-org-id'] = props.ims.org\n }\n let formattedResult = \"\"\n try {\n // invoke backend action\n const actionResponse = await actionWebInvoke(actions[actionName], headers, params)\n formattedResult = `time: ${Date.now() - startTime} ms\\n` + JSON.stringify(actionResponse,0,2)\n // store the response\n setState({\n ...state,\n actionResponse,\n actionResult:formattedResult,\n actionResponseError: null,\n actionInvokeInProgress: false\n })\n console.log(`Response from ${actionName}:`, actionResponse)\n } catch (e) {\n // log and store any error message\n formattedResult = `time: ${Date.now() - startTime} ms\\n` + e.message\n console.error(e)\n setState({\n ...state,\n actionResponse: null,\n actionResult:formattedResult,\n actionResponseError: e.message,\n actionInvokeInProgress: false\n })\n }\n }", "async function watchContinue(ll){\n const continueAns = await prompt(continueQ);\n continueAns.continue === 'Yes' ? action(ll):null;\n}", "function OXN_ALift_Apply(async_f, xc, env, args) {\n this.xc = xc;\n this.xc.current = this;\n \n var pars = [bind(this.cont, this)];\n pars = pars.concat(args);\n this.abort_f = async_f.apply(env, pars);\n}", "function handeladblock(){\n console.log(\"blocking scripts\")\n chrome.storage.sync.get('mode', function({mode}){ \n chrome.storage.onChanged.addListener(function(changes,namespace){\n if(changes.mode == undefined)\n {return;}\n mode = changes.mode.newValue;\n });\n chrome.webRequest.onBeforeRequest.addListener(function(details){\n //sets up a listner that fires before request's \n if(checkIfScriptLocal(details.url) || mode !== 'block' ) // exits function if the request is local or if the addon is off\n {return;} \n if(!url.match(REGEXJSFILTER)) // if the url dosnt match the regex filter it cant match a url and comparing them would mean loss in efficancy\n {return;}\n var cancel = null;\n urllst.forEach(url => {// goes over the urls we have and compares them to the \n // current request if they are the same blocks the request\n if(details.url.includes(url))\n {\n console.log(details.url);\n cancel = {cancel: true}; \n }\n });\n if(cancel != null)\n {\n return cancel;\n }\n }, FILTER, OPT_EXREAINFOSPEC); \n });\n}", "function exodustimeout_sync(command) {\n\n logevent('exodustimeout_sync:geventhandler.done:' + geventhandler.done)\n\n //if another event handler is already running then defer execution for 100ms\n if (gblockevents) {\n window.setTimeout('exodustimeout_sync(\"' + command + '\")', 100)\n return\n }\n\n //the async function should run to completion\n // even if it pauses for multiple async operations on the way.\n //command MUST be prefixed with \"yield *\" and return a generator\n var generator = eval(command);\n exodusneweventhandler(generator, 'exodustimeout_sync() ' + command)//yielding code\n //not interested in result\n}", "_ensure_future() {\n let ptrobj = _getPtr(this);\n let resolveHandle;\n let rejectHandle;\n let promise = new Promise((resolve, reject) => {\n resolveHandle = resolve;\n rejectHandle = reject;\n });\n let resolve_handle_id = Module.hiwire.new_value(resolveHandle);\n let reject_handle_id = Module.hiwire.new_value(rejectHandle);\n let errcode;\n try {\n errcode = Module.__pyproxy_ensure_future(\n ptrobj,\n resolve_handle_id,\n reject_handle_id\n );\n } catch (e) {\n Module.fatal_error(e);\n } finally {\n Module.hiwire.decref(reject_handle_id);\n Module.hiwire.decref(resolve_handle_id);\n }\n if (errcode === -1) {\n Module._pythonexc2js();\n }\n return promise;\n }", "async function tryCrunch() {\n const msgs = new Set(buffer),\n api_ids = [...participants];\n\n buffer.clear();\n clearTimeout(timeout);\n timeout = undefined;\n\n participants.clear();\n\n if (SLOWMODE > 0) {\n logger.info(\"slowmode active, sleeping…\", { wait: SLOWMODE });\n await sleep(SLOWMODE * 1000);\n }\n\n try {\n await crunch(api_ids);\n } catch (err) {\n // log, move to failed queue, NACK\n logger.error(err);\n await Promise.map(msgs, async (m) => {\n await ch.sendToQueue(QUEUE + \"_failed\", m.content, {\n persistent: true,\n headers: m.properties.headers\n });\n await ch.nack(m, false, false);\n });\n return;\n }\n\n await Promise.map(msgs, async (m) => await ch.ack(m));\n // notify web\n await Promise.map(msgs, async (m) => {\n if (m.properties.headers.notify)\n await ch.publish(\"amq.topic\",\n m.properties.headers.notify,\n new Buffer(\"crunch_update\")\n );\n });\n }", "async runPyAsync(code, {\n returnResult = \"none\",\n printResult = false\n } = {\n returnResult: \"none\",\n printResult: false\n }) {\n const response = await this.postMessageAsync({\n type: \"runPythonAsync\",\n code,\n returnResult,\n printResult\n });\n if (response.error) {\n const err = postableErrorObjectToError(response.error);\n this.stderrCallback(err.message);\n throw err;\n }\n return response.value;\n }", "async function executeFlow (uri, recUser, message) {\n\n\t// Special errors will be thrown if we need to stop handling the prompt when we have finished successfully or failed.\n\ttry {\n\n\t\t// Skip if the bot has been disabled for this user.\n\t\tif (this.skipIfBotDisabled(`execute conversation flow`, recUser)) {\n\t\t\tthrow new Error(`STOP_NOT_COMPLETED`);\n\t\t}\n\n\t\tconst sharedLogger = this.__dep(`sharedLogger`);\n\t\tconst flow = this.__getFlow(uri);\n\n\t\tif (!flow) {\n\t\t\tthrow new Error(`There is no flow defined for the URI \"${uri}\".`);\n\t\t}\n\n\t\tsharedLogger.silly(`Executing conversation flow \"${flow.definition.uri}\"...`);\n\n\t\t// Handle the different parts of the flow.\n\t\tawait this.__handleFlowRedirectToNewFlow(flow, recUser, message);\n\t\tawait this.__handleFlowExecuteActions(flow, recUser, message);\n\t\tawait this.__handleFlowExecutePrompt(flow, recUser);\n\t\tawait this.__handleFlowUpdateConversationState(flow, recUser);\n\n\t}\n\tcatch (err) {\n\n\t\tswitch (err.message) {\n\t\t\tcase `STOP_SUCCESSFULLY_COMPLETED`: return true;\n\t\t\tcase `STOP_NOT_COMPLETED`: return false;\n\t\t\tdefault: throw err; // Throw all other errors further up the stack.\n\t\t}\n\n\t}\n\n\t// If we get here then the flow must have been completed successfully.\n\treturn true;\n\n}", "function awaitingCiteL34ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(){;}", "async function test() {\n const clamscan = await new NodeClam().init({\n debugMode: false,\n clamdscan: {\n bypassTest: true,\n host: 'localhost',\n port: 3310,\n socket: '/var/run/clamd.scan/clamd.sock',\n },\n });\n\n const passthrough = new PassThrough();\n const source = axios.get(testUrl);\n\n // Fetch fake Eicar virus file and pipe it through to our scan screeam\n source.pipe(passthrough);\n\n try {\n const { isInfected, viruses } = await clamscan.scanStream(passthrough);\n\n // If `isInfected` is TRUE, file is a virus!\n if (isInfected === true) {\n console.log(\n `You've downloaded a virus (${viruses.join(\n ''\n )})! Don't worry, it's only a test one and is not malicious...`\n );\n } else if (isInfected === null) {\n console.log(\"Something didn't work right...\");\n } else if (isInfected === false) {\n console.log(`The file (${testUrl}) you downloaded was just fine... Carry on...`);\n }\n process.exit(0);\n } catch (err) {\n console.error(err);\n process.exit(1);\n }\n}", "async function main() {\n let loop = true;\n try {\n await connect();\n while (loop) {\n await runInquirer();\n }\n } catch (error) {\n console.error(error);\n } finally {\n connection.end();\n }\n}", "function waitforgo() {\n $(\"#startingblock\").hide(\"slide\", { direction: \"left\" }, 250);\n setTimeout(() => {\n $(\"#mixplaycontrols\").show(\"slide\", { direction: \"right\" }, 250).show();\n }, 500);\n\n log(\"Waiting for you to login...\");\n $.ajax(\"https://mixer.com/api/v1/oauth/shortcode/check/\" + data.handle)\n .done((result, statusText, xhr) => {\n // console.log(xhr);\n switch (xhr.status) {\n case 204:\n setTimeout(waitforgo, 2000);\n break;\n case 200:\n // console.log(result.code);\n data.codetwo = result.code;\n finalstep();\n }\n })\n .fail((xhr, textStatus) => {\n switch (xhr.status) {\n case 403:\n // console.log(\"Why you say no?\");\n alert(\"You said no, now you have to reload.\");\n break;\n case 404:\n // console.log(\"You waited too long\");\n alert(\"You took too long, now you have to reload.\");\n break;\n }\n });\n}", "async function baz() {\n await new Promise((resolve, reject) => setTimeout(resolve, 1000));\n console.log(\"baz\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a page path, render the page
function render_response_page( res, path ){ var path_parts = path.split('/'); if( path_parts[0] == '' ){ path_parts.shift(); } if( path_parts.length && path_parts[ path_parts.length - 1 ] == '' ){ path_parts.pop(); } var page_spec = { path_parts : path_parts, actual_path : config.content, title : config.site_name, css : config.css, js : config.js, content : [], children : [] } assemble_page( res, page_spec ); }
[ "function route(){\n switch(req.url){\n case '/cats': page = 'cats'; break;\n case '/cars': page = 'cars'; break;\n case '/cars/new': page = 'new'; break;\n default: page = 'error';\n }\n fs.readFile(`views/${page}.html`, 'utf8', render);\n }", "function drawPage() {\n\t\n\tif ( !(ERROR_FOUND) ) {\n\t\t// first, draw a menu if there is one\n\t\tif ( CURRENT_PAGE.menu != null ) {\n\t\t \tdrawMenu();\n\t\t}\n\n\t\tdocument.getElementById(\"page_contents\").innerHTML = CURRENT_PAGE.html;\n\t}\n\n}", "function render (url) {\n $('.main-content .page').removeClass('visible');\n var section = url.split('/')[0],\n mapping = {\n '': function () {\n filters = {};\n checkboxes.prop('checked',false);\n renderProductsPage(products);\n },\n '#product': function () {\n var index = url.split('#product/')[1].trim();\n\n renderSingleProductPage(index, products);\n },\n '#filters': function () {\n try {\n filters = JSON.parse(url.split('#filters/')[1]);\n }\n catch (err) {\n window.location.hash = \"#\";\n return;\n }\n renderFilterResults(filters, products);\n }\n };\n if (mapping[section]) {\n mapping[section]();\n } else {\n renderError();\n }\n }", "function serveWicketPage(req, res) {\n time(\"serveWicketPage\");\n\n const pageWithPath = req.params[0];\n const queryVars = req.query;\n\n time(\"readWicketHtmlFile\");\n let html = readWicketHtmlFile(pageWithPath);\n timeEnd(\"readWicketHtmlFile\");\n\n const additionalHeadElements = [];\n\n if (!html) {\n res.status(404).send(\"Page not found.\");\n return;\n }\n\n time(\"expandPages\");\n html = expandPages(html, queryVars, additionalHeadElements);\n timeEnd(\"expandPages\");\n\n time(\"includePanels\");\n html = includePanels(html, queryVars);\n timeEnd(\"includePanels\");\n\n time(\"stripWicketTags\");\n html = stripWicketTags(html);\n timeEnd(\"stripWicketTags\");\n\n time(\"includeAdditionalHeadElements\");\n html = includeAdditionalHeadElements(html, additionalHeadElements);\n timeEnd(\"includeAdditionalHeadElements\");\n\n html = addLiveReload(html);\n\n res.set(\"Content-Type\", \"text/html; charset=utf-8\");\n res.send(html);\n timeEnd(\"serveWicketPage\");\n}", "function renderCustomPages(cb){\r\n var src = path.join(process.cwd(),'_bumblersrc/pages');\r\n fs.readdir(src,function(er,filenames){\r\n if (er){return cb(er);}\r\n async.eachOfLimit(filenames,ASYNC_LIMIT,(name,index,cb0)=>{\r\n fs.readFile(path.join(src,name),'utf8',(er,data)=>{\r\n if (er){return cb0(er);}\r\n var obj;\r\n var route;\r\n try{\r\n obj = JSON.parse(data);\r\n route = obj.route;\r\n if (!route){throw new Error('custom page must have a route')}\r\n }catch(e){\r\n return cb0(e);\r\n }\r\n var dest = path.join(process.cwd(),route+'.html');\r\n var locals = {\r\n page:{\r\n customPage:obj,\r\n isCustom:true,\r\n url:urlForHref(obj.route)\r\n }\r\n }\r\n var result = compiledFn(locals);\r\n fs.outputFile(dest,result,cb0);\r\n });\r\n },cb);\r\n })\r\n }", "render(viewPath, data = {}, scope = this.app) {\r\n if (!this.views.has(viewPath)) {\r\n throw new Error(`Not Found view ${viewPath}`);\r\n }\r\n\r\n let content = this.get(viewPath);\r\n \r\n // let start = performance.now();\r\n\r\n let compiler = new ViewCompiler(viewPath, content, data, scope);\r\n\r\n // let end = performance.now();\r\n\r\n // echo(viewPath + ' -> ' + (end - start));\r\n\r\n return compiler.html;\r\n }", "function renderPage(template, route, addRoute) {\n\tconst context = {};\n\n\tconst content = ReactDOMServer.renderToString(\n\t\t<Router location={ route } context={ context } basename={ BASE_URL }>\n\t\t\t<App />\n\t\t</Router>\n\t);\n\tconst helmet = Helmet.renderStatic();\n\n\tconst dom = new JSDOM(template);\n\n\tconst main = dom.window.document.querySelector(\"#app\");\n\tmain.innerHTML = content;\n\n\tconst extraHead = helmet.meta.toString() + helmet.title.toString();\n\tconst head = dom.window.document.querySelector(\"head\");\n\thead.insertAdjacentHTML(\"afterbegin\", extraHead);\n\n\tif (context.url != null) {\n\t\tconst redirect = dom.window.document.createElement(\"meta\");\n\t\tredirect.setAttribute(\"http-equiv\", \"refresh\");\n\t\tredirect.setAttribute(\"content\", `0; URL='${ context.url }'`);\n\n\t\thead.appendChild(redirect);\n\n\t\tconsole.log(\"...redirects to\", context.url);\n\t}\n\n\t// To add new pages, we can invoke `addRoute` with a site-relative\n\t// path.\n\t//\n\t// Here, we're just crawling the page for anything that looks like a\n\t// link.\n\tconst links = dom.window.document.querySelectorAll(\"a\");\n\tfor (const link of links) {\n\t\tlet url = link.href;\n\n\t\t// Rough pattern to ignore off-site links\n\t\tif (/^\\w+:\\/\\//.test(url)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (url.startsWith(BASE_URL)) {\n\t\t\turl = url.slice(BASE_URL.length);\n\t\t}\n\n\t\taddRoute(url);\n\t}\n\n\treturn dom.serialize();\n}", "function loadPageFromHistory() {\n\t\t//Load default page\n\t\trenderPage(getCurrentPageIdBasedOnHistory());\t\n\t}", "function loadPage (slug) {\n\tvar pagedata = fm(cat(PAGE_DIR+slug+'.md'));\n\treturn pagedata;\n}", "function createPage() {\n\t\t// check to see if the directory exists\n\t\tif (!fs.existsSync(OUTPUT_DIR)) {\n\t\t\t// if it does not, then make it\n\t\t\tfs.mkdirSync(OUTPUT_DIR);\n\t\t}\n\t\t// write the html file using the render(coworkers) data\n\t\tfs.writeFileSync(outputPath, render(coworkers), \"utf-8\");\n\t}", "navigate(page, pushState=true){\n\n if(pushState)window.history.pushState(\"\", \"\", page);\n\n\n\n let cardViewer = this.getCardViewer();\n if(cardViewer!=false && (page!=\"/search\" && page!=\"/\")){\n cardViewer.view(page);\n }else{\n $(\"#content\").fadeOut(500, () => {\n let pageView = this.getPageMaps()[page];\n\n //if there is no route avaible for current page, use the '*' route\n if(pageView==undefined) pageView = this.getPageMaps()[\"*\"];\n\n\n let pageTitle = pageView.getTitle();\n if(pageTitle!=false)document.title = pageTitle;\n\n //after page is done rendering, fade it in for style points\n let x = pageView.render().then(()=>{\n this.currentPage = pageView;\n $(\"#content\").fadeIn(500);\n });\n\n\n\n });\n }\n\n\n }", "function renderDocument(document, targetPath, level) {\n var outputDocument = deepcopy(document);\n\n //prepare relative url path\n outputDocument.relativeUrlPath = (new Array(level+1)).join('../');\n\n //prepare document menu\n var documentMenu = deepcopy(documentationMenu);\n markCurrentMenuItems(documentMenu, document.id);\n\n //render markdown\n var renderer = new marked.Renderer();\n renderer.image = function(href, title, text) {\n var externalUrlPattern = /^https?:\\/\\//i;\n if(!externalUrlPattern.test(href)) {\n href = outputDocument.relativeUrlPath + 'img/' + href;\n }\n title = title ? title : '';\n return '<img src=\"'+href+'\" title=\"'+title+'\" alt=\"'+text+'\">';\n };\n try {\n outputDocument.content = marked(document.content, {renderer: renderer});\n } catch(err) {\n log.error('Error occurred while rendering content of page \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n\n //render swig template\n var pageContent = '';\n try {\n pageContent = compiledPageTemplate({\n config: docConfig,\n menu: documentMenu,\n document: outputDocument\n });\n } catch(err) {\n log.error('Error occurred while rendering page template for file \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n\n //write into file\n try {\n fs.writeFileSync(targetPath, pageContent);\n } catch(err) {\n log.error('Error occurred while writing file \"%s\" (%s)', targetPath, err.message);\n process.exit(1);\n }\n}", "renderPage() {\n if (!this.props.client.accessToken) {\n return <div>Please wait....</div>;\n }\n if (this.state.page === \"user\") {\n return (\n <UserPage\n client={this.props.client}\n userId={this.state.viewingUserId}\n withReplies={this.state.withReplies}\n onPlay={this.onPlay.bind(this)}\n />\n );\n } else if (this.state.page === \"status\") {\n return (\n <StatusPage\n client={this.props.client}\n userId={this.state.viewingUserId}\n eventId={this.state.statusId}\n roomId={this.state.roomId}\n />\n );\n } else if (this.state.page === \"timeline\") {\n return <TimelinePage client={this.props.client} />;\n } else {\n return <div>Whoops, how did you get here?</div>;\n }\n }", "function fileRouter(parsedUrl, res) {\n\tvar code;\n\tvar page;\n\tvar filePath = './' + parsedUrl.pathname;\n\tif (fs.existsSync(filePath)) {\n\t\t// We found the page, read it and set the code\n\t\tcode = 200;\n\t\tpage = fs.readFileSync(filePath);\n\t}\n\telse {\n\t\t// We didn't find the requested page, so read the 404 page and set the code to 404\n\t\t// indicating that for the user\n\t\tcode = 404;\n\t\tpage = fs.readFileSync('./404.html');\n\t}\n\t// Setting content type & code appropriately and ending the request\n\tres.writeHead(code, {'content-type': mime.lookup(filePath) || 'text/html' });\n\tres.end(page);\n}", "function _page2_page() {\n}", "function addPage(page) {\r\n document.querySelector(\"#pages\").innerHTML += `\r\n <section id=\"${page.slug}\" class=\"page\">\r\n <header class=\"topbar\">\r\n <h2>${page.title.rendered}</h2>\r\n </header>\r\n ${page.content.rendered}\r\n </section>\r\n `;\r\n}", "render(opts) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (opts.publicPath && opts.documentFilePath && opts.url !== undefined) {\n const url = new URL(opts.url);\n // Remove leading forward slash.\n const pathname = url.pathname.substring(1);\n const pagePath = resolve(opts.publicPath, pathname, 'index.html');\n if (pagePath !== resolve(opts.documentFilePath)) {\n // View path doesn't match with prerender path.\n let pageExists = this.pageExists.get(pagePath);\n if (pageExists === undefined) {\n pageExists = yield exists(pagePath);\n this.pageExists.set(pagePath, pageExists);\n }\n if (pageExists) {\n // Serve pre-rendered page.\n return readFile(pagePath, 'utf-8');\n }\n }\n }\n // if opts.document dosen't exist then opts.documentFilePath must\n const extraProviders = [\n ...(opts.providers || []),\n ...(this.providers || []),\n ];\n let doc = opts.document;\n if (!doc && opts.documentFilePath) {\n doc = yield this.getDocument(opts.documentFilePath);\n }\n if (doc) {\n extraProviders.push({\n provide: INITIAL_CONFIG,\n useValue: {\n document: opts.inlineCriticalCss\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n ? doc.replace(/ media=\\\"print\\\" onload=\\\"this\\.media='all'\"><noscript><link .+?><\\/noscript>/g, '>')\n : doc,\n url: opts.url\n }\n });\n }\n const moduleOrFactory = this.moduleOrFactory || opts.bootstrap;\n const factory = yield this.getFactory(moduleOrFactory);\n const html = yield renderModuleFactory(factory, { extraProviders });\n if (!opts.inlineCriticalCss) {\n return html;\n }\n const { content, errors, warnings } = yield this.inlineCriticalCssProcessor.process(html, {\n outputPath: (_a = opts.publicPath) !== null && _a !== void 0 ? _a : (opts.documentFilePath ? dirname(opts.documentFilePath) : undefined),\n });\n // tslint:disable-next-line: no-console\n warnings.forEach(m => console.warn(m));\n // tslint:disable-next-line: no-console\n errors.forEach(m => console.error(m));\n return content;\n });\n }", "drawPage(page){\n\t\tthis.cleanOldPage();\n\t\tthis.activePage = page;\n\t\tthis.initAndDrawActivePage();\n\t}", "function renderNav() {\n var page = 'pages/menu';\n getPage(page, false, navContainer, false);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns an ObjectId embedded with a given datetime Accepts both Date object and string input
function objectIdWithTimestamp(timestamp) { // Convert string date to Date object (otherwise assume timestamp is a date) // if (typeof timestamp == "string") { // timestamp = new Date(timestamp); // } logger.log({ timestamp }); // Convert date object to hex seconds since Unix epoch var hexSeconds = Math.floor(timestamp / 1000).toString(16); logger.log({ hexSeconds }); // Create an ObjectId with that hex timestamp var constructedObjectId = mongoose.Types.ObjectId( hexSeconds + "0000000000000000" ); logger.log({ constructedObjectId }); return constructedObjectId; }
[ "function createDateTimeStringFromID(id) {\n date_ =\n id.substring(0, 4) + \"/\" + id.substring(4, 6) + \"/\" + id.substring(6, 8);\n time_ =\n id.substring(8, 10) +\n \":\" +\n id.substring(10, 12) +\n \":\" +\n id.substring(12, 14);\n console.log(\"date = \" + date_ + \", time =\" + time_);\n return date_ + \" at \" + time_;\n}", "function generateMongoObjectId() {\n var timestamp = (new Date().getTime() / 1000 | 0).toString(16);\n return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {\n return (Math.random() * 16 | 0).toString(16);\n }).toLowerCase();\n }", "function idAppointment2Day(id){\n let dateList = id.split(\"-\");\n return new Date(dateList[4], dateList[5]-1, dateList[6]);\n}", "function findSpecificDate(dateSpecific) {\n // Accept specific date and create a new object based on the date\n var d = new Date(dateSpecific);\n\n // get the date and assign to a variable d.\n d.setDate(d.getDate());\n \n // return the date in UNIX second\n return Math.floor( d / 1000); \n}", "function createObj(id, textValue, dateValue, timeValue) {\n let noteObjTemp = Object.create(noteObjTemplate);\n noteObjTemp.id = id;\n noteObjTemp.text = textValue;\n noteObjTemp.date = dateValue;\n noteObjTemp.time = timeValue;\n return noteObjTemp;\n }", "function findDate(id) {\n return db.one(`SELECT * from tours WHERE id=$1`, [id]);\n}", "createDateTime(date, time) {\n // set default values for any inputs that were not chosen\n if (!date) {\n date = moment();\n }\n if (!time) {\n time = moment();\n }\n\n return moment({\n y: date.year(),\n M: date.month(),\n d: date.date(),\n h: time.hour(),\n m: time.minute(),\n s: 0,\n ms: 0\n })\n }", "function fn_fromADO(o) {\r\n if (typeof o == 'date') {\r\n //Dates are stored in DB as UTC\r\n return Date.fromUTCString(o);\r\n }\r\n return o;\r\n }", "date(time){\n return moment(time);\n }", "function createPostID( time, title ){\n var trimmedTitle = title.substring(0, 15);\n var trimmedTime = time.substring(15,16) + time.substring(18,19);\n return trimmedTitle + trimmedTime;\n}", "async findAppointment(appointment,id) {\n return Appointment.findOne(appointment,{where:{id}});\n }", "function createDayEntry() {\n return connect().then(({ collection, client}) => {\n return new Promise((resolve, reject) => {\n let date = new Date();\n let datum = ('0' + date.getDate()).slice(-2) + '.' + ('0' + (date.getMonth() + 1)).slice(-2) + '.' + date.getFullYear();\n collection.findOne({\"dateWithoutTime\": datum}, async (err, res) => {\n if(err) {\n reject(err);\n } else if(res === null) {\n let day = new Day(date);\n await collection.insertOne(day, { safe: true }, (error, result) => {\n if(error) {\n reject(error);\n } else {\n resolve(result);\n }\n });\n } else {\n reject();\n }\n client.close();\n });\n });\n });\n}", "idOrCriteria(idOrCriteria) {\n if (typeof idOrCriteria === 'object') {\n return idOrCriteria;\n } else {\n return { _id: idOrCriteria };\n }\n }", "async findTrackingStreamByImeiAndDate(incomingImei, incomingTrackingDateTime) {\n let trackingStream = null;\n try {\n trackingStream = await tracking_stream_model_1.default.findOne({ where: { imei: incomingImei, trackingDateTime: incomingTrackingDateTime } });\n }\n catch (error) {\n console.error(error);\n }\n return trackingStream;\n }", "function checkIfValidMongoObjectID(str) {\n\t// regular expression to check if string is a valid MongoDB ObjectID\n\tconst regexExp = /^[0-9a-fA-F]{24}$/\n\n\treturn regexExp.test(str)\n}", "function to_db_time(time) {\n\n}", "function fetchMatchDate(matchObj)\n{\n const TIME_EPOCH = matchObj.start_time;\n var date = new Date(0);\n date.setUTCSeconds(TIME_EPOCH);\n return date;\n}", "function formatDateToDB(dateObject) {\r\n return format(dateObject, \"yyyy-MM-dd HH:mm:ss\");\r\n}", "function generateId(lat, lon) {\n\tlet date = new Date();\n\tlet res = +date;\n\tres += '_' + lat + '_' + lon;\n\treturn res;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw most vehicles reservations
function drawVehicleReservations() { var data = google.visualization.arrayToDataTable([ ['Ditet', 'Nr i Makinave', {role: 'style'}], ['E Hene', 1000, 'fill-color: #4285F4'], ['E Marte', 2000, 'fill-color: #DB4437'], ['E Merkure', 3000, 'fill-color: #F4B400'], ['E Enjte', 4000, 'fill-color: #1B9E77'], ['E Premte', 300, 'fill-color: #D95F02'], ['E Shtune', 1500, 'fill-color: #7570B3'], ['E Diele', 1500, 'fill-color: #DB4437'] ]); var options = { chart: { title: 'Car Reservations', subtitle: '2015' }, hAxis: { baselineColor: 'red' } }; var chart = new google.visualization.ColumnChart(document.getElementById('weekly-statistics')); chart.draw(data, options); }
[ "function drawVehicles() {\n for (i=0;i<vehicles.length;i++) {\n //Left side, right side+image width, top side, bottom side\n if (vehicles[i][0].pos[0] >= (window.innerWidth/2)-(10*tileSize)/2 && vehicles[i][0].pos[0] <= (window.innerWidth/2)+(10*tileSize)/2-vehicles[i][0].image.width*2 && vehicles[i][0].pos[1] >= (window.innerHeight/2)-(10*tileSize)/2 && vehicles[i][0].pos[1] <= (window.innerHeight/2)+(10*tileSize)/2) {\n vehicles[i][0].draw(vehicles[i][0].pos[0],vehicles[i][0].pos[1],vehicles[i][0].image.width*2,vehicles[i][0].image.height*2);\n } else {\n //If it's outside the grid space, remove it from the array\n vehicles.splice(i,1);\n }\n }\n //Create a car if this random number generator condition is true\n if (Math.random()*1 > 0.999) {\n createVehicle();\n }\n //The movement for the vehicles\n moveVehicles();\n}", "static async findBestCustomers() {\n\t\tconst results = await db.query(\n\t\t\t`\n\t\t\tSELECT c.id, first_name AS \"firstName\", last_name AS \"lastName\",phone,c.notes\n\t\t\tFROM customers c\n\t\t\tJOIN reservations ON c.id = reservations.customer_id\n\t\t\tGROUP BY c.id ORDER BY COUNT(customer_id) DESC LIMIT 10;\n\t\t\t`\n\t\t);\n\t\treturn results.rows.map((c) => new Customer(c));\n\t}", "function finalSlate(voteCount) {\n for(var office in voteCount) {//targets office position in voteCount variable\n var highestTally = 0;\n var studentName = \"\";\n var officePosition = voteCount[office];\n for(var officerName in officePosition) {\n var tally = officePosition[officerName];\n if (tally > highestTally) {\n highestTally = tally;\n studentName = officerName;\n }\n officers[office] = studentName;\n }\n }\n}", "function positionCapacity() {\r\n vertices.selectAll(\".capacity-text\")\r\n .attr(\"x\", function (n) {\r\n if (n.parity == 1)\r\n return -18;\r\n else\r\n return 18;\r\n });\r\n}", "renderGuests () {\n this.bus.seats.forEach(seat => {\n if (!seat.isFree) {\n this.renderGuest(seat)\n\n /**\n * seat numbers are indices for the guests array.\n * during the rendering process this method is\n * called multiple times, so we do not push guests\n */\n this.guests[seat.number] = seat.guest\n }\n })\n }", "function generateReservations(start=0, end=numRooms) {\n let reservationArray = [];\n let daysPerRoom = Math.floor(reservationDateRange * avgOccupancy);\n let startDate = new Date(moment());\n let endDate = new Date(moment().add(reservationDateRange,'days'));\n\n //handle situation where end passed ot file is greater than max number of rooms\n let boundedEnd = end;\n if(end > numRooms) {\n boundedEnd = numRooms;\n }\n\n //console.log(daysPerRoom);\n for(let i = start; i < boundedEnd; i++) {\n let remainingDays = daysPerRoom;\n let currentDate = startDate;\n\n while(remainingDays > 0) {\n let daysToSkip = Math.floor(randomNumber() * 3);\n let reservationLength = Math.floor(randomNumber() * maxReservationLength) + 1;\n remainingDays = remainingDays - reservationLength;\n\n currentDate = moment(currentDate).add(daysToSkip,'days');\n let reservationStartDate = currentDate;\n let reservationEndDate = moment(currentDate).add(reservationLength,'days');\n currentDate = reservationEndDate;\n //console.log(`Reservation from ${reservationStartDate} to ${reservationEndDate}`);\n let roomId = i;\n let userId = Math.floor(numUsers * randomNumber());\n let numAdults = Math.floor(randomNumber() * 2) + 1;\n let numChildren = Math.floor(randomNumber() * 3);\n let numInfants = Math.floor(randomNumber() * 2);\n\n reservationArray.push({\n \"roomId\": roomId,\n \"userId\": userId,\n \"startDate\": reservationStartDate.format(),\n \"endDate\": reservationEndDate.format(),\n \"numAdults\": numAdults,\n \"numChildren\": numChildren,\n \"numInfants\": numInfants\n });\n }\n }\n console.log(\"Reservation data generated with record count: \" + reservationArray.length);\n return reservationArray;\n}", "function drawRoad(counter){\n //set background\n background(50);\n //Space between lines\n let space = width / 4;\n //Gap between dashed lines\n let step = height / 10;\n //Line width\n let lineW = 10;\n //Road lines\n //Remove outline on shapes\n noStroke();\n //Dashed lines\n for (i = - 2; i < height; i++) {\n //Yellow lines\n fill(255,i * 25, 0);\n rect(space, step * i + counter, 10, 30);\n rect(space * 3, step * i + counter, 10, 30);\n }\n for(i = 0; i < maxH; i++){\n let val = map(i, 0, maxH, 0, 255);\n stroke(255, val, 0);\n line(0, i, lineW, i);\n \n line(space * 2 - lineW, i, space * 2 - lineW * 2, i);\n line(space * 2 + lineW, i, space * 2 + lineW * 2, i);\n line(maxW - lineW, i, maxW, i); \n }\n}", "function createVehicle() {\n var vehicleAssets = [\"tempCar\"];\n var randomAssetNo = Math.floor(Math.random()*vehicleAssets.length);\n var v = [new Sprite(\"/sprites/vehicles/\"+vehicleAssets[randomAssetNo]),\"right\"];\n v[0].pos[0]= (window.innerWidth/2)-(10*tileSize)/2+(0*tileSize);\n v[0].pos[1]= (window.innerHeight/2)-(10*tileSize)/2+(6*tileSize);\n vehicles[vehicles.length] = v;\n}", "function drawRooms() {\n for (let i = 0; i < numberOfFloors; i++) {\n line(0, (height * i) / numberOfFloors, width, (height * i) / numberOfFloors);\n }\n \n fill(0, 0, 0);\n line(width / 4, (height * 0) / numberOfFloors, width / 4, (height * 1) / numberOfFloors);\n line(width / 2, (height * 0) / numberOfFloors, width / 2, (height * 1) / numberOfFloors);\n line((width * 3) / 4, (height * 0) / numberOfFloors, (width * 3) / 4, (height * 1) / numberOfFloors);\n \n line(width / 4 - 20, (height * 1) / numberOfFloors, width / 4 - 20, (height * 2) / numberOfFloors);\n line(width / 2 - 30, (height * 1) / numberOfFloors, width / 2 - 30, (height * 2) / numberOfFloors);\n line((width * 3) / 4 + 50, (height * 1) / numberOfFloors, (width * 3) / 4 + 50, (height * 2) / numberOfFloors);\n \n line(width / 4, (height * 2) / numberOfFloors, width / 4, (height * 3) / numberOfFloors);\n line(width / 2, (height * 2) / numberOfFloors, width / 2, (height * 3) / numberOfFloors);\n line((width * 3) / 4, (height * 2) / numberOfFloors, (width * 3) / 4, (height * 3) / numberOfFloors);\n \n line(width / 4 - 30, (height * 3) / numberOfFloors, width / 4 - 30, (height * 4) / numberOfFloors);\n line(width / 2 + 50, (height * 3) / numberOfFloors, width / 2 + 50, (height * 4) / numberOfFloors);\n line((width * 3) / 4 + 20, (height * 3) / numberOfFloors, (width * 3) / 4 + 20, (height * 4) / numberOfFloors);\n \n line(width / 4 + 20, (height * 4) / numberOfFloors, width / 4 + 20, (height * 5) / numberOfFloors);\n line(width / 2, (height * 4) / numberOfFloors, width / 2, (height * 5) / numberOfFloors);\n line((width * 3) / 4 + 30, (height * 4) / numberOfFloors, (width * 3) / 4 + 30, (height * 5) / numberOfFloors);\n \n line(width / 4 - 30, (height * 5) / numberOfFloors, width / 4 - 30, (height * 6) / numberOfFloors);\n line(width / 2, (height * 5) / numberOfFloors, width / 2, (height * 6) / numberOfFloors);\n line((width * 3) / 4, (height * 5) / numberOfFloors, (width * 3) / 4, (height * 6) / numberOfFloors);\n \n line(width / 4, (height * 6) / numberOfFloors, width / 4, (height * 7) / numberOfFloors);\n line(width / 2, (height * 6) / numberOfFloors, width / 2, (height * 7) / numberOfFloors);\n line((width * 3) / 4, (height * 6) / numberOfFloors, (width * 3) / 4, (height * 7) / numberOfFloors);\n \n verticalCollisionLine1 = collideLineRect(width / 4, (height * 0) / numberOfFloors, width / 4, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine2 = collideLineRect(width / 2, (height * 0) / numberOfFloors, width / 2, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine3 = collideLineRect((width * 3) / 4, (height * 0) / numberOfFloors, (width * 3) / 4, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n\n verticalCollisionLine4 = collideLineRect(width / 4 - 20, (height * 1) / numberOfFloors, width / 4 - 20, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine5 = collideLineRect(width / 2 - 30, (height * 1) / numberOfFloors, width / 2 - 30, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine6 = collideLineRect((width * 3) / 4 + 50, (height * 1) / numberOfFloors, (width * 3) / 4 + 50, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine7 = collideLineRect(width / 4, (height * 2) / numberOfFloors, width / 4, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine8 = collideLineRect(width / 2, (height * 2) / numberOfFloors, width / 2, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine9 = collideLineRect((width * 3) / 4, (height * 2) / numberOfFloors, (width * 3) / 4, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine10 = collideLineRect(width / 4 - 30, (height * 3) / numberOfFloors, width / 4 - 30, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine11 = collideLineRect(width / 2 + 50, (height * 3) / numberOfFloors, width / 2 + 50, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine12 = collideLineRect((width * 3) / 4 + 20, (height * 3) / numberOfFloors, (width * 3) / 4 + 20, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine13 = collideLineRect(width / 4 + 20, (height * 4) / numberOfFloors, width / 4 + 20, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine14 = collideLineRect(width / 2, (height * 4) / numberOfFloors, width / 2, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine15 = collideLineRect((width * 3) / 4 + 30, (height * 4) / numberOfFloors, (width * 3) / 4 + 30, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine16 = collideLineRect(width / 4 - 30, (height * 5) / numberOfFloors, width / 4 - 30, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine17 = collideLineRect(width / 2, (height * 5) / numberOfFloors, width / 2, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine18 = collideLineRect((width * 3) / 4, (height * 5) / numberOfFloors, (width * 3) / 4, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine19 = collideLineRect(width / 4, (height * 6) / numberOfFloors, width / 4, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine20 = collideLineRect(width / 2, (height * 6) / numberOfFloors, width / 2, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine21 = collideLineRect((width * 3) / 4, (height * 6) / numberOfFloors, (width * 3) / 4, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width); \n \n horizontalCollisionLine0 = collideLineCircle(0, (height * 0) / numberOfFloors, width, (height * 0) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine1 = collideLineCircle(0, (height * 1) / numberOfFloors, width, (height * 1) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine2 = collideLineCircle(0, (height * 2) / numberOfFloors, width, (height * 2) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine3 = collideLineCircle(0, (height * 3) / numberOfFloors, width, (height * 3) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine4 = collideLineCircle(0, (height * 4) / numberOfFloors, width, (height * 4) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine5 = collideLineCircle(0, (height * 5) / numberOfFloors, width, (height * 5) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine6 = collideLineCircle(0, (height * 6) / numberOfFloors, width, (height * 6) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n \n \n \n collisionAssignment();\n}", "function drawVerticalDoors() {\n fill(360, 360, 360);\n door1 = new VerticalDoor(width / 4, 0);\n door2 = new VerticalDoor(width / 2, 0);\n door3 = new VerticalDoor((width * 3) / 4, 0);\n\n door4 = new VerticalDoor(width / 4 - 20, 1);\n door5 = new VerticalDoor(width / 2 - 30, 1);\n door6 = new VerticalDoor((width * 3) / 4 + 50, 1);\n\n door7 = new VerticalDoor(width / 4, 2);\n door8 = new VerticalDoor(width / 2, 2);\n door9 = new VerticalDoor((width * 3) / 4, 2);\n\n door10 = new VerticalDoor(width / 4 - 30, 3);\n door11 = new VerticalDoor(width / 2 + 50, 3);\n door12 = new VerticalDoor((width * 3) / 4 + 20, 3);\n\n door13 = new VerticalDoor(width / 4 + 20, 4);\n door14 = new VerticalDoor(width / 2, 4);\n door15 = new VerticalDoor((width * 3) / 4 + 30, 4);\n\n door16 = new VerticalDoor(width / 4 - 30, 5);\n door17 = new VerticalDoor(width / 2, 5);\n door18 = new VerticalDoor((width * 3) / 4, 5);\n\n door19 = new VerticalDoor(width / 4, 6);\n door20 = new VerticalDoor(width / 2, 6);\n door21 = new VerticalDoor((width * 3) / 4, 6);\n\n verticalDoorList.push(door1);\n verticalDoorList.push(door2);\n verticalDoorList.push(door3);\n verticalDoorList.push(door4);\n verticalDoorList.push(door5);\n verticalDoorList.push(door6);\n verticalDoorList.push(door7);\n verticalDoorList.push(door8);\n verticalDoorList.push(door9);\n verticalDoorList.push(door10);\n verticalDoorList.push(door11);\n verticalDoorList.push(door12);\n verticalDoorList.push(door13);\n verticalDoorList.push(door14);\n verticalDoorList.push(door15);\n verticalDoorList.push(door16);\n verticalDoorList.push(door17);\n verticalDoorList.push(door18);\n verticalDoorList.push(door19);\n verticalDoorList.push(door20);\n verticalDoorList.push(door21);\n}", "function makeReservation(rCell){\n \n rCell.setAttribute(\"class\", \"reserved-self\");\n rCell.onmousedown = mouseDownSelfReserved;\n rCell.onmouseover = mouseOverSelfReserved;\n if(rCell.hasToolTip){\n removeToolTip(rCell);\n rCell.hasToolTip = false;\n }\n \n var sCell = progressData[rCell.part].segments[rCell.segm];\n \n var jCell = reservationsJSONarr[rCell.part].segments[rCell.segm];\n var compCell = reservCompare[rCell.part].segments[rCell.segm];\n \n //set reservation data\n if(!jCell.isReserved){\n jCell.user = user;\n jCell.isReserved = true;\n if(!(rCell.part in updateData)){\n updateData[rCell.part] = { segments: {} };\n }\n updateData[rCell.part].segments[rCell.segm] = jCell;\n }else{ //better update data on screen\n\n getProgressData();\n }\n}", "function draw_seats() {\n var sections = window.project.settings.airplane;\n var xOff = Math.abs(delta);\n var height = 0;\n\n function addRowOfSeats(count, yOff, maxCount) {\n var seatIndex;\n var padding = Math.min(0, 0.5 * delta * (maxCount - count));\n\n yOff += padding;\n for (seatIndex = 0; seatIndex < count; seatIndex++) {\n seat_positions.push({'x': xOff, 'y': yOff});\n\n var circle = svgContainer.append('circle')\n .attr('cx', xOff)\n .attr('cy', yOff)\n .attr('r', 0.4 * Math.abs(delta))\n .classed('seat', true);\n yOff += delta;\n height = Math.min(yOff, height);\n }\n return yOff + padding;\n }\n\n sections.forEach(function (section) {\n var rowIndex, i, yOff;\n\n for (rowIndex = 0; rowIndex < section.rows; rowIndex++) {\n yOff = delta;\n for (i = 0; i < section.seats.length; i++) {\n yOff = addRowOfSeats(\n section.seats[i],\n yOff,\n max_seats[i]\n );\n\n if (i < section.seats.length - 1) {\n aisle_positions.push({'x': xOff, 'y': yOff});\n yOff += delta;\n }\n\n }\n xOff += Math.abs(delta);\n }\n });\n\n svgContainer.attr(\n 'viewBox',\n '0 ' + height + ' ' + xOff + ' ' + Math.abs(height)\n );\n }", "displayTopEightMatchedRespondents() {\n console.log(\"\\nTop 8 matches- by matching scores:\");\n console.log(\"===================================\\n\");\n\n for (let i = 0; i < 8; i++) {\n const curr = this.results[this.results.length - 1 - i];\n console.log(i);\n console.log(\n `Name: ${curr.name.slice(0, 1).toUpperCase()}${curr.name.slice(\n 1\n )}`\n );\n console.log(\n `Distance to closest available city: ${curr.closestAvailableCity.distance}km`\n );\n console.log(`Matching Score: ${curr.score}`);\n console.log(\"-------------------------------\");\n }\n }", "draw()\n {\n var canvas = document.getElementById(\"CANVAS\");\n var ctx = canvas.getContext(\"2d\");\n var cVehicles = this.getVehicleCount();\n\n ctx.save();\n ctx.scale(def.scale, def.scale);\n\n this._drawRoute(ctx);\n for (let iVehicle = 0; iVehicle < cVehicles; iVehicle ++)\n this._drawVehicle(ctx, route.getVehicle(iVehicle));\n\n ctx.restore();\n }", "function printTheBestResult(){\n\tvar edgesMap = new Object();\n\t$.map(edges, function(value, key){\n\t\tedgesMap[value.id] = value;\n\t});\n\t\n\tfor(var i in bestPath){\n\t\tvar key = bestPath[i]['id'];\n\t\tedgesMap[key]['color'] = '#006400';\n\t}\n\t\n\tedges = [];\n\tfor(var key in edgesMap){\n\t\tedges.push(edgesMap[key]);\n\t}\n\tplotGraph(nodes, edges, document.getElementById('mygraph'));\n}", "function countValley(road){\n \n let lowestPoint = 0;\n let naikTurun = 0;\n let mendaki = 0;\n\n for(let i = 0 ; i < road.length ; i++ ){\n\n\n if( road[i] == 'U'){\n naikTurun += 1\n }\n \n \n else if( road[i] == 'D'){\n \n naikTurun -= 1\n\n }\n\n\n \n \n if( naikTurun < lowestPoint ){\n lowestPoint = naikTurun\n mendaki = 0\n }\n else if(naikTurun == lowestPoint){\n mendaki += 1\n\n }\n\n\n\n}\n\nreturn mendaki\n\n}", "function calculateReservationCostAndUpdateDOM(adventure, persons) {\n // TODO: MODULE_RESERVATIONS\n // 1. Calculate the cost based on number of persons and update the reservation-cost field\n let costPerHead = adventure.costPerHead;\n let totalReservationCost = costPerHead*persons;\n document.getElementById('reservation-cost').innerHTML = totalReservationCost;\n}", "function draw_travels() {\n removeLines();\n for (var i = 0, len = data.length; i < len; i++) {\n drawLine(data[i])\n }\n}", "function mostFavorableGrid(){\r\n var bestGrid = 0;\r\n var index = 0;\r\n for(var i = 0; i < fitness.length; i++){\r\n if(fitness[i] > bestGrid){\r\n bestGrid = fitness[i];\r\n index = i;\r\n }\r\n }\r\n //console.log(\"Most favorable grid is grid:\" + index);\r\n\tdocument.getElementById(\"favGrid\").innerHTML = \"Grid #\" + index;\r\n return index;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
receive payment from customer, recipient can be unikey or merchant if it is unikey, can just complete payment and update channel if it is merchant, will require to look up channel of merchant, and create condtional payment from UniKey to merchant
async receive_conditional_payment(who, recipient, signed_state) { this.log(`Receive Conditional Payment from ${who.address} to ${recipient}`) return new Promise(async ( resolve, reject) => { let channelID = signed_state.channelID try { assert(this.channels[channelID]) } catch (e) { reject('channel not exist') } if (signed_state.verify_signature(who.address)) { this.log("Signature OK") if (recipient == this.owner.address) { // just pay to unikey? this.log(`Owner address matches recipient address. Verifying preimage hash.`) // owner must know the preimage... // skipped for the demo let preimage = this.preimage let preimage_hash = signed_state.payment.preimage_hash if (utils.web3.utils.sha3(preimage) == preimage_hash) { // verify the hash this.log(`Preimage Hash OK. Publish Secret to Sender`) this.publish_preimage(who, preimage, channelID ) resolve({ cmd: 'revealed', channelID: channelID, preimage: preimage }) } else { this.log(`Error: Preimage Hash not matched.`) reject('hash not match') } } else { this.log(`Create Link payment from ${who.address} to ${recipient}`) // create condtional payment let other_channelID = this.search_channelID(recipient) assert(other_channelID >= 0) let payment = signed_state.payment assert(other_channelID) // not on dictionary? // need to depoist, and let's deposit 10 time of amount let owner_deposit = await this.channels[other_channelID].get_deposit(this.owner) let owner_credit = await this.channels[other_channelID].get_credit(this.owner) let owner_balance = BigNumber(owner_deposit).plus(owner_credit) if (BigNumber(owner_balance).isLessThan(BigNumber(payment.amount))) { await this.deposit(this.owner, payment.amount * 2, other_channelID) } let s = await this.channels[other_channelID].conditional_payment_with_preimage_hash(this.owner, recipient, payment.amount, payment.preimage_hash) this.channelStates[other_channelID] = s.to_unsigned() // // now need to make payment resolve( {cmd: 'open', signed_state: s.serialize()}) } } else { this.log(`Signature not matches with ${who.address}`) reject('signature not matches') } }) }
[ "function executePayment(clientId,secret,price,paymentId,payerId,callback){\n request.post(PAYPAL_URI + '/v1/payments/payment/' + paymentId + '/execute',\n {\n auth:\n {\n user: clientId,\n pass: secret\n },\n body:\n {\n payer_id: payerId,\n transactions: [\n {\n amount:\n {\n total:price,\n currency: 'GBP'\n }\n }]\n },\n json: true\n },\n function(err,response){\n if(err){\n callback(err);\n }\n else if(response.body.id){\n callback(false,response);\n }\n else{\n callback(\"VALIDATION_ERROR\");\n }\n });\n}", "function processPayment(amount, { number, expMonth, expYear, cvc }, callback){\n\n // Configure the request details\n const options = {\n protocol: \"https:\",\n hostname: \"api.stripe.com\",\n method: \"POST\",\n auth: `${config.stripe.secretKey}:`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" }\n };\n\n // Configure the token request payload\n const tokenStringPayload = querystring.stringify({\n 'card[number]': number,\n 'card[exp_month]': expMonth,\n 'card[exp_year]': expYear,\n 'card[cvc]': cvc,\n });\n\n options.path = \"/v1/tokens\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(tokenStringPayload);\n\n // Instantiate the token request\n const tokenReq = https.request(options, function(res){\n\n // Grab status from response\n const tokenResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(tokenResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const tokenId = parseJsonToObject(chunk).id;\n\n // Configure the token request payload\n const chargeStringPayload = querystring.stringify({\n amount,\n currency: 'eur',\n // Extract token id from token response\n source: tokenId,\n });\n\n options.path = \"/v1/charges\";\n options.headers[\"Content-Length\"] = Buffer.byteLength(chargeStringPayload);\n\n // Create charge using order information using stripe service\n const chargeReq = https.request(options, function(res){\n\n // Grab status from response\n const chargeResStatus = res.statusCode\n\n // Callback successfully if the request went through\n if(successStatus(chargeResStatus)){\n\n // Parse and read response\n res.setEncoding('utf8');\n res.on('data', chunk => {\n // Parse string response\n const chargeStatus = parseJsonToObject(chunk).status;\n\n // Callback successfully if charge succeeded\n if(chargeStatus === 'succeeded'){\n callback(false);\n } else {\n callback(`Failed to charge payment successfully. Charge status returned was ${chargeStatus}`);\n };\n });\n\n } else {\n callback(`Failed charge request. Status code returned was ${chargeResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n chargeReq.on(\"error\", e => callback(e));\n\n // Add the payload\n chargeReq.write(chargeStringPayload);\n\n // End the request\n chargeReq.end();\n });\n\n } else {\n callback(`Failed token request. Status code returned was ${tokenResStatus}`);\n };\n });\n\n // Bind to the error event so it doesn't get thrown\n tokenReq.on(\"error\", e => callback(e));\n\n // Add the payload\n tokenReq.write(tokenStringPayload);\n\n // End the request\n tokenReq.end();\n}", "function receive_payment_ack(payment_ack) {\n\n var purchase_amount = payment_ack.amount_purchased;\n var payment_amount = payment_ack.amount_spent;\n\n console.log(\"Sanity check: purchase_amount = \" + purchase_amount);\n console.log(\"payment_amount = \" + payment_amount);\n console.log(\"price_per_second = \" + price_per_second);\n\n console.log(\"Increasing time purchased by \" + purchase_amount);\n time_purchased = parseInt(time_purchased);\n time_purchased += purchase_amount;\n total_paid += payment_amount;\n\n var date = new Date();\n var now = date.getTime()/1000.0;\n last_payment_update_time = now;\n payment_update_timer = setInterval(update_payment, 100);\n\n received_ack = true;\n update_display();\n set_ui_state(UI_STATES.CONNECTED);\n}", "function buy() { // eslint-disable-line no-unused-vars\n document.getElementById('msg').innerHTML = '';\n\n if (!window.PaymentRequest) {\n print('Web payments are not supported in this browser');\n return;\n }\n\n let details = {\n total: {label: 'Total', amount: {currency: 'USD', value: '0.50'}},\n };\n\n let networks = ['visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb',\n 'unionpay', 'mir'];\n let payment = new PaymentRequest( // eslint-disable-line no-undef\n [\n {\n supportedMethods: ['https://android.com/pay'],\n data: {\n merchantName: 'Web Payments Demo',\n allowedCardNetworks: ['AMEX', 'MASTERCARD', 'VISA', 'DISCOVER'],\n merchantId: '00184145120947117657',\n paymentMethodTokenizationParameters: {\n tokenizationType: 'GATEWAY_TOKEN',\n parameters: {\n 'gateway': 'stripe',\n 'stripe:publishableKey': 'pk_live_lNk21zqKM2BENZENh3rzCUgo',\n 'stripe:version': '2016-07-06',\n },\n },\n },\n },\n {\n supportedMethods: networks,\n },\n {\n supportedMethods: ['basic-card'],\n data: {\n supportedNetworks: networks,\n supportedTypes: ['debit', 'credit', 'prepaid'],\n },\n },\n \n ],\n details,\n {\n requestShipping: true,\n requestPayerName: true,\n requestPayerPhone: true,\n requestPayerEmail: true,\n shippingType: 'shipping',\n });\n\n payment.addEventListener('shippingaddresschange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n fetch('/ship', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: addressToJsonString(payment.shippingAddress),\n })\n .then(function(options) {\n if (options.ok) {\n return options.json();\n }\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n })\n .then(function(optionsJson) {\n if (optionsJson.status === 'success') {\n canShip(details, optionsJson.shippingOptions, resolve);\n } else {\n cannotShip('Unable to calculate shipping options.', details,\n resolve);\n }\n })\n .catch(function(error) {\n cannotShip('Unable to calculate shipping options. ' + error, details,\n resolve);\n });\n }));\n });\n\n payment.addEventListener('shippingoptionchange', function(evt) {\n evt.updateWith(new Promise(function(resolve) {\n for (let i in details.shippingOptions) {\n if ({}.hasOwnProperty.call(details.shippingOptions, i)) {\n details.shippingOptions[i].selected =\n (details.shippingOptions[i].id === payment.shippingOption);\n }\n }\n\n canShip(details, details.shippingOptions, resolve);\n }));\n });\n\n let paymentTimeout = window.setTimeout(function() {\n window.clearTimeout(paymentTimeout);\n payment.abort().then(function() {\n print('Payment timed out after 20 minutes.');\n }).catch(function() {\n print('Unable to abort, because the user is currently in the process ' +\n 'of paying.');\n });\n }, 20 * 60 * 1000); /* 20 minutes */\n\n payment.show()\n .then(function(instrument) {\n window.clearTimeout(paymentTimeout);\n\n if (instrument.methodName !== 'https://android.com/pay') {\n simulateCreditCardProcessing(instrument);\n return;\n }\n\n let instrumentObject = instrumentToDictionary(instrument);\n instrumentObject.total = details.total;\n let instrumentString = JSON.stringify(instrumentObject, undefined, 2);\n fetch('/buy', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: instrumentString,\n })\n .then(function(buyResult) {\n if (buyResult.ok) {\n return buyResult.json();\n }\n complete(instrument, 'fail', 'Error sending instrument to server.');\n }).then(function(buyResultJson) {\n print(instrumentString);\n complete(instrument, buyResultJson.status, buyResultJson.message);\n });\n })\n .catch(function(error) {\n print('Could not charge user. ' + error);\n });\n}", "function sendReadReceipt(recipientId,senderId){console.log(\"Sending a read receipt to mark message as seen\");var messageData={recipient:{id:recipientId},sender_action:\"mark_seen\"};return callSendAPI(messageData,senderId);}", "function expressCheckout(sender, productId) {\n\n apiClient.buyProduct(sender, productId)\n .then(function (response) {\n sessionStore.userData.get(sender).cart = response.id;\n\n apiClient.preCheckout(sender)\n .then(function (response) {\n let jsonResponse = JSON.parse(response);\n\n //Get default address\n let addresses = jsonResponse.shippingAddresses;\n for (let i = 0; i < addresses.length; i++) {\n if (addresses[i].selectedAsDefault)\n sessionStore.userData.get(sender).address = addresses[i].addressId;\n }\n\n //Get default card\n let cards = jsonResponse.cards;\n for (let i = 0; i < cards.length; i++) {\n if (cards[i].selectedAsDefault)\n sessionStore.userData.get(sender).card = cards[i].cardId;\n }\n\n //Do expresscheckout\n let cartId = sessionStore.userData.get(sender).cart;\n let cardId = sessionStore.userData.get(sender).card;\n let addressId = sessionStore.userData.get(sender).address;\n\n apiClient.expressCheckout(sender, cartId, cardId, addressId)\n .then(function (response) {\n console.log(response);\n sendMessage(sender, Templates.buildReceipt(sender, response));\n })\n .catch(errorCallback);\n })\n .catch(errorCallback);\n })\n .catch(errorCallback);\n}", "function Process() {\n var results = {};\n var arr = request.httpParameters.keySet().toArray();\n arr.filter(function (el) {\n results[el] = request.httpParameters.get(el).toLocaleString();\n return false;\n })\n\n var verificationObj = {\n ref: results.REF,\n returnmac: results.RETURNMAC,\n eci: results.ECI,\n amount: results.AMOUNT,\n currencycode: results.CURRENCYCODE,\n authorizationcode: results.AUTHORISATIONCODE,\n avsresult: results.AVSRESULT,\n cvsresult: results.CVVRESULT,\n fraudresult: results.FRAUDRESULT,\n externalreference: results.FRAUDRESULT,\n hostedCheckoutId: results.hostedCheckoutId\n\n }\n\n var order = session.getPrivacy().pendingOrder;\n var orderNo = session.getPrivacy().pendingOrderNo;\n var returnmac = session.getPrivacy().payment3DSCode;\n\n var cancelOrder = true;\n\n if (verificationObj.returnmac == returnmac) {\n var result = null;\n if(verificationObj.hostedCheckoutId != null){\n result = IngenicoPayments.getHostedPaymentStatus(verificationObj.hostedCheckoutId, true);\n }else if(verificationObj.ref){\n result = IngenicoPayments.getPaymentStatus(verificationObj.ref);\n }else{\n Logger.error(\"Missing verification reference - Params: \" + JSON.stringify(results) + \" VerificationObj: \" + JSON.stringify(verificationObj))\n }\n\n if(!result || result.error){\n Logger.warn(\"Error getting payment status: \" + JSON.stringify(result));\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation', \"error=400\") }).render(\"checkout/3DSredirect\");\n return;\n }\n\n if(result.createdPaymentOutput){\n if(\"tokens\" in result.createdPaymentOutput && result.createdPaymentOutput && result.createdPaymentOutput.payment && result.createdPaymentOutput.payment.paymentOutput && result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput){\n IngenicoOrderHelper.processHostedTokens(order.getCustomer(), result.createdPaymentOutput.tokens, result.createdPaymentOutput.payment.paymentOutput.cardPaymentMethodSpecificOutput)\n }\n result = result.createdPaymentOutput.payment;\n }\n \n var updatedOrderOK = UpdateOrder.updateOrderFromCallback(orderNo, result);\n\n if (result && result.status) {\n switch (result.status) {\n case ReturnStatus.REDIRECTED:\n case ReturnStatus.CAPTURE_REQUESTED:\n case ReturnStatus.PENDING_CAPTURE:\n case ReturnStatus.PENDING_PAYMENT:\n case ReturnStatus.AUTHORIZATION_REQUESTED: \n case ReturnStatus.PAID:\n case ReturnStatus.CAPTURED:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.PENDING_FRAUD_APPROVAL:\n case ReturnStatus.PENDING_APPROVAL:\n cancelOrder = false;\n app.getView({ redirect: URLUtils.url('COVerification-Confirmation') }).render(\"checkout/3DSredirect\");\n return;\n case ReturnStatus.REJECTED:\n case ReturnStatus.REVERSED:\n case ReturnStatus.REJECTED_CAPTURE:\n case ReturnStatus.CANCELLED:\n case ReturnStatus.CHARGEBACKED: // Should never get this status back during checkout process.\n app.getView({ redirect: URLUtils.url('COVerification-COSummary') }).render(\"checkout/3DSredirect\");\n return; \n default:\n break;\n } \n }\n }\n}", "function paymentFromComponent(req, res, next) {\n const reqDataObj = JSON.parse(req.form.data);\n if (reqDataObj.cancelTransaction) {\n return handleCancellation(res, next, reqDataObj);\n }\n const currentBasket = BasketMgr.getCurrentBasket();\n let paymentInstrument;\n Transaction.wrap(() => {\n collections.forEach(currentBasket.getPaymentInstruments(), (item) => {\n currentBasket.removePaymentInstrument(item);\n });\n\n paymentInstrument = currentBasket.createPaymentInstrument(\n constants.METHOD_ADYEN_COMPONENT,\n currentBasket.totalGrossPrice,\n );\n const { paymentProcessor } = PaymentMgr.getPaymentMethod(\n paymentInstrument.paymentMethod,\n );\n paymentInstrument.paymentTransaction.paymentProcessor = paymentProcessor;\n paymentInstrument.custom.adyenPaymentData = req.form.data;\n\n if (reqDataObj.partialPaymentsOrder) {\n paymentInstrument.custom.adyenPartialPaymentsOrder =\n session.privacy.partialPaymentData;\n }\n paymentInstrument.custom.adyenPaymentMethod =\n AdyenHelper.getAdyenComponentType(req.form.paymentMethod);\n paymentInstrument.custom[\n `${constants.OMS_NAMESPACE}__Adyen_Payment_Method`\n ] = AdyenHelper.getAdyenComponentType(req.form.paymentMethod);\n paymentInstrument.custom.Adyen_Payment_Method_Variant =\n req.form.paymentMethod.toLowerCase();\n paymentInstrument.custom[\n `${constants.OMS_NAMESPACE}__Adyen_Payment_Method_Variant`\n ] = req.form.paymentMethod.toLowerCase();\n });\n\n handleExpressPayment(reqDataObj, currentBasket);\n\n let order;\n // Check if gift card was used\n if (currentBasket.custom?.adyenGiftCards) {\n const giftCardsOrderNo = currentBasket.custom.adyenGiftCardsOrderNo;\n order = OrderMgr.createOrder(currentBasket, giftCardsOrderNo);\n handleGiftCardPayment(currentBasket, order);\n } else {\n order = COHelpers.createOrder(currentBasket);\n }\n session.privacy.orderNo = order.orderNo;\n\n let result;\n Transaction.wrap(() => {\n result = adyenCheckout.createPaymentRequest({\n Order: order,\n PaymentInstrument: paymentInstrument,\n });\n });\n\n currentBasket.custom.amazonExpressShopperDetails = null;\n currentBasket.custom.adyenGiftCardsOrderNo = null;\n\n if (result.resultCode === constants.RESULTCODES.REFUSED) {\n handleRefusedResultCode(result, reqDataObj, order);\n }\n\n if (AdyenHelper.isApplePay(reqDataObj.paymentMethod?.type)) {\n result.isApplePay = true;\n }\n\n result.orderNo = order.orderNo;\n result.orderToken = order.orderToken;\n res.json(result);\n return next();\n}", "function SingleUseAuthCapture(card, order) {\n var dfd = $q.defer();\n var token = OrderCloud.Auth.ReadToken();\n var cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": order.ID,\n \"transactionType\": \"authOnlyTransaction\",\n \"amount\": order.Total,\n \"cardDetails\": {\n \"paymentID\": null,\n \"creditCardID\": null,\n \"cardType\": card.CardType,\n \"cardNumber\": card.CardNumber,\n \"expirationDate\": card.ExpMonth + card.ExpYear,\n \"cardCode\": card.CVV\n }\n };\n //authorize payment\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(response){\n if(response.messages && response.messages.resultCode && response.messages.resultCode == 'Error') {\n toastr.info('Sorry, something went wrong. Please try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n } else {\n cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": order.ID,\n \"transactionType\": \"priorAuthCaptureTransaction\",\n \"amount\": order.Total,\n \"cardDetails\": {\n \"paymentID\": response.PaymentID,\n \"creditCardID\": null,\n \"cardType\": null,\n \"cardNumber\": null,\n \"expirationDate\": null,\n \"cardCode\": null\n }\n };\n //capture payment\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(){\n if(response.messages && response.messages.resultCode && response.messages.resultCode == 'Error') {\n toastr.info('Sorry, something went wrong. Please try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n }\n dfd.resolve();\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again')\n dfd.resolve();\n });\n }\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again')\n });\n return dfd.promise;\n }", "async sellCar(ctx, carCRN, dealerCRN, adhaarNumber) {\n //Verify if this funtion is called by Dealer\n let verifyDealer = await ctx.clientIdentity.getMSPID();\n //calling the function carDeatils to retrieve the car details\n let carObject = this.carDetails(ctx, carCRN);\n //Verify if the function is called by Dealer and and also if he is the owner of the car\n if (verifyDealer === \"dealerMSP\" && dealerCRN === carObject.owner) {\n if (carObject !== undefined) {\n carObject.status = \"SOLD\";\n carObject.owner = adhaarNumber;\n //creating the composite key\n const carKey = ctx.stub.createCompositekey(\n \"org.cartracking-network.carnet.car\",\n [carCRN]\n );\n //converting the json object to buffer and saving it in blockchain\n let databuffer = Buffer.from(JSON.stringify(carObject));\n await ctx.stub.putState(carKey, carObject);\n }\n }\n }", "function submitPaymentJSON() {\n var order = Order.get(request.httpParameterMap.order_id.stringValue);\n if (!order.object || request.httpParameterMap.order_token.stringValue !== order.getOrderToken()) {\n app.getView().render('checkout/components/faults');\n return;\n }\n session.forms.billing.paymentMethods.clearFormElement();\n var requestObject = JSON.parse(request.httpParameterMap.requestBodyAsString);\n var form = session.forms.billing.paymentMethods;\n for (var requestObjectItem in requestObject) {\n var asyncPaymentMethodResponse = requestObject[requestObjectItem];\n var terms = requestObjectItem.split('_');\n if (terms[0] === 'creditCard') {\n var value = terms[1] === 'month' || terms[1] === 'year' ? Number(asyncPaymentMethodResponse) : asyncPaymentMethodResponse;\n form.creditCard[terms[1]].setValue(value);\n } else if (terms[0] === 'selectedPaymentMethodID') {\n form.selectedPaymentMethodID.setValue(asyncPaymentMethodResponse);\n }\n }\n if (app.getController('COBilling').HandlePaymentSelection('cart').error || handlePayments().error) {\n app.getView().render('checkout/components/faults');\n return;\n }\n app.getView().render('checkout/components/payment_methods_success');\n}", "function requesDonate(to, amount, ssid) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tvar url = 'http://webgold' + nconf.get('server:workdomain') + \"/api/webgold/donate?amount=\" + amount + \"&to=\" + to + \"&sid=\" + ssid;\n\t\t\tconsole.log(url);\n\t\t\trequest.get(url)\n\t\t\t\t.\n\t\t\tend((err, res) => {\n\t\t\t\tif (err) {\n\t\t\t\t\t//console.log(err);\n\t\t\t\t\t//console.log(res.body);\n\t\t\t\t\tif (res.body) {\n\t\t\t\t\t\tif (res.body.error) {\n\t\t\t\t\t\t\treturn reject(res.body.error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn reject(err);\n\t\t\t\t}\n\t\t\t\tresolve(res.body);\n\t\t\t});\n\t\t});\n\n\t}", "function paymentFactory() {\n\tvar payment = {\n\t\tcNumber: \"\",\n\t\tcType: \"\",\n\t\tCName: \"\",\n\t\tcExp: \"\",\n\t\tcCvv: \"\"\n\t}\n\treturn payment;\n}", "function handle_cm_get_payment_card(req, startTime, apiName, fromSubmittPay) {\n this.req = req;\n this.startTime = startTime;\n this.apiName = apiName;\n this.fromSubmittPay = fromSubmittPay;\n}", "charge(payee, amt){\n if (this.balance()< amt){\n return;\n// This is overdraft protection. It basically says that if the charge issued\n// to the account is greater than the account balance then do not allow the \n// charge to process. \n }\n let charge = new Transaction (-amt, payee)\n// charge is using the same structure of deposit however its taking on the negative\n// of the amount value and a payee.\n\n this.transactions.push(charge)\n// In the same manner as the deposit. We are taking in the charge method, and pushing\n// our inputs to the end of the transactions array\n}", "function postDPMrelay(req, res) {\n var data = req.body;\n\n data.x_MD5_Hash_Validated = validateGatewayMD5(data);\n data.formData_Validated = (data.order_id === hashFormData(data));\n\n if (!data.x_MD5_Hash_Validated || !data.formData_Validated) return res.status(403).end();\n\n // merge and save - returns order object with merged payment data - ignore save errors\n dpm.savePaymentData(data, function(saveErr, order) {\n\n // process - returns thank-you url - adds additional data to order\n dpm.processOrder(order, function(processErr, url) {\n\n // merge and save again - returns yet another object with merged data - ignore save errors\n dpm.savePaymentData(order, function(saveErr, savedOrder) {\n\n if (processErr) return res.status(500).send(processErr);\n url = url || defaultThankYouUrl(savedOrder);\n\n // redirect\n var resp = '<html><head>' +\n '<script type=\"text/javascript\" charset=\"utf-8\">window.location=\"' + url + '\";</script>' +\n '<noscript><meta http-equiv=\"refresh\" content=\"0;url=' + url + '\"></noscript>' +\n '</head><body>Please go to <a href=\"' + url + '\">' + url + '</a></body></html>';\n\n res.send(resp);\n\n });\n });\n });\n }", "goToReceipt(receipt) {\n const {user, goToReceipt} = this.props;\n const userRole = user.get('role');\n goToReceipt(receipt.get('_id'), userRole);\n }", "function payment() {\n // оплатить можно только с непустым заказом\n if (order.length){\n unpayed = false;\n var btn = document.querySelector('.make-order');\n btn.disabled = true;\n btn.innerHTML = 'заказ оплачен';\n }\n }", "BurnFrom(_from, _amount){\n\n Utils.contract.burnFrom(_from, _amount).send({\n shouldPollResponse: true,\n callValue: 0\n }).then(res => Swal({\n title:'Burn Successful',\n type: 'success'\n })).catch(err => Swal({\n title:'Burn Failed',\n type: 'error'\n\n }));\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
translateCtrl Controller for translate
function translateCtrl($translate, $scope) { $scope.changeLanguage = function(langKey) { $translate.use(langKey); $scope.language = langKey; }; }
[ "translate(text, target, callback){\n\t\t\t\t// Assume that our default language on every JS or HTML template is en_US\n\t\t\t\ttranslates('en_US', target, text, callback);\n\t\t\t}", "function translate(key) {\n var lang = getLang(),\n text = translations[key];\n\n if (typeof text === 'undefined') {\n if (SC_DEV) { console.log('Unable to get translation for text code: \"'+ key + '\" and language: \"' + lang + '\".'); }\n return '-';\n }\n\n return text;\n }", "function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n}", "function googleTranslateElementInit(){\n new google.translate.TranslateElement({pageLanguage:'en'},'google_translate_element');\n}", "function gTranslate(x,y,z) {\r\n modelViewMatrix = mult(modelViewMatrix,translate([x,y,z])) ;\r\n}", "constructor(translation) {\n this.translated = false;\n this.replacements = [];\n this.translation = translation;\n }", "function loadTranslations(translations) {\n // Ensure the translate function exists\n if (!$localize.translate) {\n $localize.translate = translate;\n }\n if (!$localize.TRANSLATIONS) {\n $localize.TRANSLATIONS = {};\n }\n Object.keys(translations).forEach(key => {\n $localize.TRANSLATIONS[key] = parseTranslation(translations[key]);\n });\n}", "function confirmTranslation() {\n\n $log.debug(\"Confirming translation\");\n\n // Force a save.\n $scope.values.saved = \"\";\n onChange($scope.item.format, \"confirmTranslation\");\n\n // Locally change the from_default to indicate that we no longer should show the warning etc.\n // The server should have received the update already, so in a refresh from_default will\n // also be set to false.\n $scope.item.from_default = false;\n }", "function controlerTitre() {\n return Ctrl.controler(titre);\n}", "function addTranslation(item){\n if (item.hasOwnProperty(\"label\")){\n if (typeof languages[\"es\"][item.label.key] === 'undefined'){\n languages[\"es\"][item.label.key]=\"\";\n }\n if (typeof languages[\"en\"][item.label.key] === 'undefined'){\n languages[\"en\"][item.label.key]=\"\";\n }\n languages[\"es\"][item.label.key] = item.label.es;\n languages[\"en\"][item.label.key] = item.label.en;\n }\n}", "static translate(_matrix, _xTranslation, _yTranslation, _zTranslation) {\n return Mat4.multiply(_matrix, this.translation(_xTranslation, _yTranslation, _zTranslation));\n }", "function clearTranslations() {\n $localize.TRANSLATIONS = {};\n}", "function countryCodeController($rootScope, $scope, ngTableParams, $filter, ngTableEventsChannel, $sce, countryCodeApi) {\n\n\t\tvar self = this;\n\t\t/**\n\t\t * Messages\n\t\t */\n\t\tself.COUNTRY_CODE_DELETE_MESSAGE_HEADER = 'Delete Country Code';\n\t\tself.COUNTRY_CODE_LIMIT_DELETE_CONFIRM_MESSAGE_STRING = 'Deleting Country Codes is limited to 15 records at a time.';\n\t\tself.COUNTRY_CODE_DELETE_CONFIRM_MESSAGE_STRING = 'Are you sure you want to delete the selected Country Code?';\n\t\tself.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING = 'There are no changes on this page to be saved. Please make any changes to update.';\n\t\tself.UNSAVED_DATA_CONFIRM_MESSAGE_STRING = 'Unsaved data will be lost. Do you want to save the changes before continuing?';\n\t\t/**\n\t\t * Error Message\n\t\t * @type {string}\n\t\t */\n\t\tself.UNKNOWN_ERROR = 'An unknown error occurred.';\n\t\tself.COUNTRY_ABBR_MANDATORY_FIELD_ERROR = 'Country Abbr. is a mandatory field.';\n\t\tself.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR = 'Country Abbr. must be 2 characters.';\n\t\tself.COUNTRY_MANDATORY_FIELD_ERROR = 'Country is a mandatory field.';\n\t\tself.ISO_ALPHA_MANDATORY_FIELD_ERROR = 'ISO Alpha (A3) is a mandatory field.';\n\t\tself.ISO_ALPHA_MUST_BE_3_CHARS_ERROR = 'ISO Alpha (A3) must be 3 characters.';\n\t\tself.NUMBERIC_N3_MANDATORY_FIELD_ERROR = 'Numeric (N3) Code is a mandatory field.';\n\t\tself.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR = 'Numeric (N3) Code value must be greater than 0 and less than or equal to 999.';\n\t\t/**\n\t\t * Start position of page that want to show on country code table\n\t\t *\n\t\t * @type {number}\n\t\t */\n\t\tself.PAGE = 1;\n\t\t/**\n\t\t * The number of records to show on the country code table.\n\t\t *\n\t\t * @type {number}\n\t\t */\n\t\tself.PAGE_SIZE = 20;\n\t\t/**\n\t\t * Add action code.\n\t\t * @type {string}\n\t\t */\n\t\tself.ADD_ACTION = 'ADD';\n\t\t/**\n\t\t * Edit action code.\n\t\t * @type {string}\n\t\t */\n\t\tself.EDIT_ACTION = 'EDIT';\n\t\t/**\n\t\t * Holds the total of rows to show scroll on add/edit\n\t\t * @type {number}\n\t\t */\n\t\tself.TOTAL_ROWS_TO_SHOW_SCROLL = 15;\n\t\t/**\n\t\t * Validattion country code key.\n\t\t * @type {string}\n\t\t */\n\t\tself.VALIDATE_COUNTRY_CODE = 'validateCountryCode';\n\t\t/**\n\t\t * Return tab key.\n\t\t * @type {string}\n\t\t */\n\t\tself.RETURN_TAB = 'returnTab';\n\t\t/**\n\t\t * Empty model.\n\t\t * @type {{countryAbbreviation: string, countryName: string, countIsoA3Cod: string, countIsoN3Cd: string, countryId: number}}\n\t\t */\n\t\tself.EMPTY_MODEL = {\n\t\t\tcountryAbbreviation: '',\n\t\t\tcountryName: '',\n\t\t\tcountIsoA3Cod: '',\n\t\t\tcountIsoN3Cd: '',\n\t\t\tcountryId: 0\n\t\t};\n\t\tself.isReturnToTab = false;\n\t\t/**\n\t\t * Holds the list of country codes.\n\t\t *\n\t\t * @type {Array} the list of country codes.\n\t\t */\n\t\tself.countryCodes = [];\n\t\t/**\n\t\t * Selected edit country code.\n\t\t * @type {null}\n\t\t */\n\t\tself.selectedCountryCode = null;\n\t\t/**\n\t\t * Selected edited row index.\n\t\t * @type {null}\n\t\t */\n\t\tself.selectedRowIndex = -1;\n\t\t/**\n\t\t * Validation model.\n\t\t */\n\t\tself.validationModel = angular.copy(self.EMPTY_MODEL);\n\t\t/**\n\t\t * Initialize the controller.\n\t\t */\n\t\tself.init = function () {\n\t\t\tself.loadCountryCodes();\n\t\t\tif($rootScope.isEditedOnPreviousTab){\n\t\t\t\tself.error = $rootScope.error;\n\t\t\t\tself.success = $rootScope.success;\n\t\t\t}\n\t\t\t$rootScope.isEditedOnPreviousTab = false;\n\t\t}\n\t\t/**\n\t\t * Initial the table to show list of country codes.\n\t\t */\n\t\tself.loadCountryCodes = function () {\n\t\t\tself.isWaitingForResponse = true;\n\t\t\tcountryCodeApi.getCountryCodes(function (response) {\n\t\t\t\tself.isWaitingForResponse = false;\n\t\t\t\tself.setCountryCodes(response);\n\t\t\t}, function (error) {\n\t\t\t\tself.fetchError(error);\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t * Initial country codes table.\n\t\t */\n\t\tself.initCountryCodesTable = function () {\n\t\t\t$scope.filter = {\n\t\t\t\tcountryAbbreviation: undefined,\n\t\t\t\tdisplayNameOnGrid: undefined,\n\t\t\t\tdisplayCountIsoOnGrid: undefined\n\t\t\t};\n\t\t\t$scope.tableParams = new ngTableParams({\n\t\t\t\tpage: self.PAGE, /* show first page */\n\t\t\t\tcount: self.PAGE_SIZE, /* count per page */\n\t\t\t\tfilter: $scope.filter\n\t\t\t}, {\n\t\t\t\tcounts: [],\n\t\t\t\tdebugMode: false,\n\t\t\t\tdata: self.countryCodes\n\t\t\t});\n\t\t\t/* Handles paging*/\n\t\t\tself.selectedTableEvents = [];\n\t\t\tvar logPagesChangedEvent = _.partial(function (list, name) {\n\t\t\t\tif (self.selectedCountryCode !== null) {\n\t\t\t\t\tif (self.selectedCountryCode.countryAbbreviation === undefined) {\n\t\t\t\t\t\tself.selectedCountryCode.countryAbbreviation = self.validationModel.countryAbbreviation;\n\t\t\t\t\t}\n\t\t\t\t\tif (self.selectedCountryCode.countryName === undefined) {\n\t\t\t\t\t\tself.selectedCountryCode.countryName = self.validationModel.countryName;\n\t\t\t\t\t}\n\t\t\t\t\tif (self.selectedCountryCode.countIsoA3Cod === undefined) {\n\t\t\t\t\t\tself.selectedCountryCode.countIsoA3Cod = self.validationModel.countIsoA3Cod;\n\t\t\t\t\t}\n\t\t\t\t\tif (self.selectedCountryCode.countIsoN3Cd === undefined) {\n\t\t\t\t\t\tself.selectedCountryCode.countIsoN3Cd = self.validationModel.countIsoN3Cd;\n\t\t\t\t\t}\n\t\t\t\t\tif (self.selectedCountryCode.countryId === undefined) {\n\t\t\t\t\t\tself.selectedCountryCode.countryId = self.validationModel.countryId;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, self.selectedTableEvents, \"pagesChanged\");\n\t\t\tngTableEventsChannel.onPagesChanged(logPagesChangedEvent, $scope.tableParams);\n\t\t}\n\t\t/**\n\t\t * Initial country code table for add edit mode.\n\t\t */\n\t\tself.initCountryCodesTableForAddMode = function(){\n\t\t\t$scope.tableParamsForAddEditMode = new ngTableParams({\n\t\t\t\tpage: self.PAGE, /* show first page */\n\t\t\t\tcount: 100000000, /* count per page */\n\t\t\t}, {\n\t\t\t\tcounts: [],\n\t\t\t\tdebugMode: false,\n\t\t\t\tdata: self.countryCodesHandle\n\t\t\t});\n\t\t}\n\t\t/**\n\t\t * Add new countryCode handle when add new button click.\n\t\t */\n\t\tself.addNewCountryCode = function () {\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t\tself.errorPopup = '';\n\t\t\t$('#addEditContainer').attr('style', '');\n\t\t\tself.resetValidation();\n\t\t\tself.countryCodesHandle = [];\n\t\t\tvar countryCode = angular.copy(self.EMPTY_MODEL);\n\t\t\tself.countryCodesHandle.push(countryCode);\n\t\t\tself.countryCodesHandleOrig = angular.copy(self.countryCodesHandle);\n\t\t\tself.titleModel = self.ADD_NEW_TITLE_HEADER;\n\t\t\tself.action = self.ADD_ACTION;\n\t\t\tself.initCountryCodesTableForAddMode();\n\t\t\t$('#countryCodeModal').modal({backdrop: 'static', keyboard: true});\n\t\t};\n\t\t/**\n\t\t * Reset validation.\n\t\t */\n\t\tself.resetValidation = function(){\n\t\t\t$scope.addEditForm.$setPristine();\n\t\t\t$scope.addEditForm.$setUntouched();\n\t\t\t$scope.addEditForm.$rollbackViewValue();\n\t\t};\n\t\t/**\n\t\t * Resets tooltip on add/edit form.\n\t\t */\n\t\tself.resetTooltips = function(){\n\t\t\tfor (var i = 0; i < self.countryCodesHandle.length; i++) {\n\t\t\t\t$('#countryAbbreviation'+i).attr('title', \"\");\n\t\t\t\t$('#countryName'+i).attr('title', \"\");\n\t\t\t\t$('#countIsoA3Cod'+i).attr('title', \"\");\n\t\t\t\t$('#countIsoN3Cd'+i).attr('title', \"\");\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Add one more country Code row.\n\t\t */\n\t\tself.addMoreRowCountryCode = function () {\n\t\t\tif(self.validateCountryCodeBeforeInsert()) {\n\t\t\t\tvar countryCode = angular.copy(self.EMPTY_MODEL);\n\t\t\t\tself.countryCodesHandle.push(countryCode);\n\t\t\t\tself.initCountryCodesTableForAddMode();\n\t\t\t\tself.showScrollViewOnAddCountryCodeForm();\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Add scroll to add form when the total of rows are greater than 15 rows.\n\t\t */\n\t\tself.showScrollViewOnAddCountryCodeForm = function(){\n\t\t\tif(self.countryCodesHandle.length > self.TOTAL_ROWS_TO_SHOW_SCROLL){\n\t\t\t\t$('#addEditContainer').attr('style', 'overflow-y: auto;height:500px');\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tvar element = document.getElementById('addEditContainer');\n\t\t\t\t\telement.scrollTop = element.scrollHeight - element.clientHeight;\n\t\t\t\t},200);\n\t\t\t}else{\n\t\t\t\t$('#addEditContainer').attr('style', '');\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Edit Country Code handle. This method is called when click on edit button.\n\t\t */\n\t\tself.editCountryCode = function (countryCode) {\n\t\t\tif (self.selectedRowIndex === -1) {\n\t\t\t\tself.action = self.EDIT_ACTION;\n\t\t\t\tself.error = '';\n\t\t\t\tself.success = '';\n\t\t\t\tcountryCode.isEditing = true;\n\t\t\t\tself.validationModel = angular.copy(countryCode);\n\t\t\t\tself.selectedCountryCode = countryCode;\n\t\t\t\tself.selectedRowIndex = self.getRowIndex();\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Return edited row index.\n\t\t *\n\t\t * @returns {number}\n\t\t */\n\t\tself.getRowIndex = function () {\n\t\t\tif (self.selectedCountryCode == null) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (self.selectedCountryCode.countryId == 0) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfor (var i = 0; i < self.countryCodes.length; i++) {\n\t\t\t\tif (self.countryCodes[i].countryId === self.selectedCountryCode.countryId) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Sets Country Codes into table modal.\n\t\t */\n\t\tself.setCountryCodes = function (countryCodes) {\n\t\t\tself.countryCodes = countryCodes;\n\t\t\tself.countryCodesOrig = angular.copy(self.countryCodes);\n\t\t\tself.initCountryCodesTable();\n\t\t};\n\t\t/**\n\t\t * Checks the countryCode is changed or not.\n\t\t *\n\t\t * @param countryCode the country code.\n\t\t * @param origData the list of original countries\n\t\t * @returns {boolean}\n\t\t */\n\t\tself.isCountryCodeChanged = function (countryCode, origData) {\n\t\t\tvar isChanged = false;\n\t\t\tvar countryCodeTemp = angular.copy(countryCode);\n\t\t\tdelete countryCodeTemp['isEditing'];\n\t\t\tif (countryCodeTemp.countryAbbreviation == null) {\n\t\t\t\tcountryCodeTemp.countryAbbreviation = '';\n\t\t\t}\n\t\t\tif (countryCodeTemp.countryName == null) {\n\t\t\t\tcountryCodeTemp.countryName = '';\n\t\t\t}\n\t\t\tif (countryCodeTemp.countIsoA3Cod == null) {\n\t\t\t\tcountryCodeTemp.countIsoA3Cod = '';\n\t\t\t}\n\t\t\tif (countryCodeTemp.countIsoN3Cd == null) {\n\t\t\t\tcountryCodeTemp.countIsoN3Cd = '';\n\t\t\t}\n\t\t\tfor (var i = 0; i < origData.length; i++) {\n\t\t\t\tif (origData[i].countryId == countryCodeTemp.countryId) {\n\t\t\t\t\tif (JSON.stringify(origData[i]) !== JSON.stringify(countryCodeTemp)) {\n\t\t\t\t\t\tisChanged = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn isChanged;\n\t\t};\n\t\t/**\n\t\t * Validate and call the api to update the list of Country Codes. Call to back end to insert to database.\n\t\t */\n\t\tself.updateCountryCode = function () {\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t\tif (self.selectedRowIndex > -1) {\n\t\t\t\t// editing mode.\n\t\t\t\tif (self.isCountryCodeChanged(self.selectedCountryCode, self.countryCodesOrig)) {\n\t\t\t\t\tif (self.validateCountryCodeBeforeUpdate()) {\n\t\t\t\t\t\tself.isWaitingForResponse = true;\n\t\t\t\t\t\tcountryCodeApi.updateCountryCodes([self.selectedCountryCode],\n\t\t\t\t\t\t\tfunction (results) {\n\t\t\t\t\t\t\t\tself.resetSelectedCountryCode();\n\t\t\t\t\t\t\t\tself.isWaitingForResponse = false;\n\t\t\t\t\t\t\t\tself.checkAllFlag = false;\n\t\t\t\t\t\t\t\tself.setCountryCodes(results.data);\n\t\t\t\t\t\t\t\tself.success = results.message;\n\t\t\t\t\t\t\t\tif(self.isReturnToTab){\n\t\t\t\t\t\t\t\t\t$rootScope.success = self.success;\n\t\t\t\t\t\t\t\t\t$rootScope.isEditedOnPreviousTab = true;\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tself.returnToTab();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tfunction (error) {\n\t\t\t\t\t\t\t\tself.fetchError(error);\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} else {\n\t\t\t\t\tself.error = self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tself.error = self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING;\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Check all field is valid before add new or update Country Code.\n\t\t * @returns {boolean}\n\t\t */\n\t\tself.validateCountryCodeBeforeUpdate = function () {\n\t\t\tvar errorMessages = [];\n\t\t\tvar message = '';\n\t\t\tif (self.validationModel.countryAbbreviation == null || self.validationModel.countryAbbreviation == undefined ||\n\t\t\t\tself.validationModel.countryAbbreviation.trim().length == 0) {\n\t\t\t\tmessage = '<li>' + self.COUNTRY_ABBR_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\terrorMessages.push(message);\n\t\t\t\tself.showErrorOnTextBox('countryAbbreviation', self.COUNTRY_ABBR_MANDATORY_FIELD_ERROR);\n\t\t\t} else {\n\t\t\t\tif (self.validationModel.countryAbbreviation.trim().length == 1) {\n\t\t\t\t\tmessage = '<li>' + self.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR + '</li>';\n\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\tself.showErrorOnTextBox('countryAbbreviation', self.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (self.validationModel.countryName == null || self.validationModel.countryName == undefined ||\n\t\t\t\tself.validationModel.countryName.trim().length == 0) {\n\t\t\t\tmessage = '<li>' + self.COUNTRY_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\terrorMessages.push(message);\n\t\t\t\tself.showErrorOnTextBox('countryName', self.COUNTRY_MANDATORY_FIELD_ERROR);\n\t\t\t}\n\t\t\tif (self.validationModel.countIsoA3Cod == null || self.validationModel.countIsoA3Cod == undefined ||\n\t\t\t\tself.validationModel.countIsoA3Cod.trim().length == 0) {\n\t\t\t\tmessage = '<li>' + self.ISO_ALPHA_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\terrorMessages.push(message);\n\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod', self.ISO_ALPHA_MANDATORY_FIELD_ERROR);\n\t\t\t} else {\n\t\t\t\tif (self.validationModel.countIsoA3Cod.trim().length < 3) {\n\t\t\t\t\tmessage = '<li>' + self.ISO_ALPHA_MUST_BE_3_CHARS_ERROR + '</li>';\n\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod', self.ISO_ALPHA_MUST_BE_3_CHARS_ERROR);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (self.validationModel.countIsoN3Cd == null || self.validationModel.countIsoN3Cd == undefined ||\n\t\t\t\tself.validationModel.countIsoN3Cd.length == 0) {\n\t\t\t\tmessage = '<li>' + self.NUMBERIC_N3_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\terrorMessages.push(message);\n\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd', self.NUMBERIC_N3_MANDATORY_FIELD_ERROR);\n\t\t\t} else {\n\t\t\t\tif (parseInt(self.validationModel.countIsoN3Cd) <= 0) {\n\t\t\t\t\tmessage = '<li>' + self.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR + '</li>';\n\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd',\n\t\t\t\t\t\tself.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (errorMessages.length > 0) {\n\t\t\t\tvar errorMessagesAsString = 'Country Code:';\n\t\t\t\tangular.forEach(errorMessages, function (errorMessage) {\n\t\t\t\t\terrorMessagesAsString += errorMessage;\n\t\t\t\t});\n\t\t\t\tself.error = $sce.trustAsHtml('<ul style=\"text-align: left;\">' + errorMessagesAsString + '</ul>')\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn errorMessages;\n\t\t}\n\t\t/**\n\t\t * Delete countryCodes handle when click on delete button.\n\t\t */\n\t\tself.deleteCountryCode = function (item) {\n\t\t\tself.selectedDeletedCountryCode = item;\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t\tself.confirmHeaderTitle = self.COUNTRY_CODE_DELETE_MESSAGE_HEADER;\n\t\t\tself.messageConfirm = self.COUNTRY_CODE_DELETE_CONFIRM_MESSAGE_STRING;\n\t\t\tself.labelClose = 'No';\n\t\t\tself.allowDeleteCountryCode = true;\n\t\t\t$('#confirmModal').modal({backdrop: 'static', keyboard: true});\n\t\t};\n\t\t/**\n\t\t * Do delete Country Code, call to back end to delete.\n\t\t */\n\t\tself.doDeleteCountryCode = function () {\n\t\t\t$('#confirmModal').modal('hide');\n\t\t\tif (self.selectedDeletedCountryCode.countryId === 0) {\n\t\t\t\tself.setCountryCodes(self.countryCodes.slice(1, self.countryCodes.length));\n\t\t\t\tself.resetSelectedCountryCode();\n\t\t\t} else {\n\t\t\t\tself.isWaitingForResponse = true;\n\t\t\t\tcountryCodeApi.deleteCountryCodes(\n\t\t\t\t\t[self.selectedDeletedCountryCode],\n\t\t\t\t\tfunction (results) {\n\t\t\t\t\t\tself.resetSelectedCountryCode();\n\t\t\t\t\t\tself.isWaitingForResponse = false;\n\t\t\t\t\t\tself.checkAllFlag = false;\n\t\t\t\t\t\tself.setCountryCodes(results.data);\n\t\t\t\t\t\tself.success = results.message;\n\t\t\t\t\t},\n\t\t\t\t\tfunction (error) {\n\t\t\t\t\t\tself.fetchError(error);\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Callback for when the backend returns an error.\n\t\t *\n\t\t * @param error The error from the back end.\n\t\t */\n\t\tself.fetchError = function (error) {\n\t\t\tself.isWaitingForResponse = false;\n\t\t\tself.success = null;\n\t\t\tself.error = self.getErrorMessage(error);\n\t\t\tself.isWaitingForResponse = false;\n\t\t\tif(self.isReturnToTab){\n\t\t\t\t$rootScope.error = self.error;\n\t\t\t\t$rootScope.isEditedOnPreviousTab = true;\n\t\t\t};\n\t\t\tself.isReturnToTab = false;\n\t\t};\n\t\t/**\n\t\t * Returns error message.\n\t\t *\n\t\t * @param error\n\t\t * @returns {string}\n\t\t */\n\t\tself.getErrorMessage = function (error) {\n\t\t\tif (error && error.data) {\n\t\t\t\tif (error.data.message) {\n\t\t\t\t\treturn error.data.message;\n\t\t\t\t} else {\n\t\t\t\t\treturn error.data.error;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn self.UNKNOWN_ERROR;\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Clear filter.\n\t\t */\n\t\tself.clearFilter = function () {\n\t\t\t$scope.filter.countryAbbreviation = undefined;\n\t\t\t$scope.filter.displayNameOnGrid = undefined;\n\t\t\t$scope.filter.displayCountIsoOnGrid = undefined;\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t};\n\t\t/**\n\t\t * This method is used to close the add popup or show confirm data changes, if there are the data changes.\n\t\t */\n\t\tself.closeAddNewPopup = function(){\n\t\t\tif(self.isDataChangedForPopup() === true){\n\t\t\t\tself.isConfirmSaveCountryCode = true;\n\t\t\t\tself.allowDeleteCountryCode = false;\n\t\t\t\tself.allowCloseButton = false;\n\t\t\t\t// show popup\n\t\t\t\tself.confirmHeaderTitle='Confirmation';\n\t\t\t\tself.error = '';\n\t\t\t\tself.success = '';\n\t\t\t\tself.errorPopup = '';\n\t\t\t\tself.messageConfirm = self.UNSAVED_DATA_CONFIRM_MESSAGE_STRING;\n\t\t\t\tself.labelClose = 'No';\n\t\t\t\t$('#confirmModal').modal({backdrop: 'static', keyboard: true});\n\t\t\t\t$('.modal-backdrop').attr('style',' z-index: 100000; ');\n\t\t\t}else{\n\t\t\t\t$('#countryCodeModal').modal('hide');\n\t\t\t\tself.isConfirmSaveCountryCode = false;\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Check change data in add new pop up.\n\t\t *\n\t\t * @returns {boolean}\n\t\t */\n\t\tself.isDataChangedForPopup = function () {\n\t\t\tvar isChanged = false;\n\t\t\tvar index = 0;\n\t\t\tangular.forEach(self.countryCodesHandle, function (countryCode) {\n\t\t\t\tif(!isChanged){\n\t\t\t\t\tself.synchronizeCountryModelWithInputText(countryCode, index);\n\t\t\t\t\tif(self.isCountryCodeChanged(countryCode, self.countryCodesHandleOrig)){\n\t\t\t\t\t\tisChanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t});\n\t\t\treturn isChanged;\n\t\t};\n\t\t/**\n\t\t * Reset data orig for pop up handle add new, edit.\n\t\t */\n\t\tself.resetDataOrig = function () {\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t\tif (self.selectedCountryCode != null && self.selectedCountryCode.countryId == 0) {\n\t\t\t\tself.countryCodes = angular.copy(self.countryCodesOrig);\n\t\t\t\tself.setCountryCodes(self.countryCodes);\n\t\t\t} else {\n\t\t\t\tself.countryCodes[self.selectedRowIndex] = angular.copy(self.countryCodesOrig[self.selectedRowIndex]);\n\t\t\t\t$scope.tableParams.reload();\n\t\t\t}\n\t\t\tself.resetSelectedCountryCode();\n\t\t};\n\t\t/**\n\t\t * Reset data orig for pop up handle add new, edit.\n\t\t */\n\t\tself.resetDataOrigForPopUp = function () {\n\t\t\tself.error = '';\n\t\t\tself.success = '';\n\t\t\tself.errorPopup = '';\n\t\t\tself.countryCodesHandle = angular.copy(self.countryCodesHandleOrig);\n\t\t\tself.initCountryCodesTableForAddEditMode();\n\t\t\tself.resetValidation();\n\t\t\tself.resetTooltips();\n\t\t};\n\t\t/**\n\t\t * Reset the status add or edit country code.\n\t\t */\n\t\tself.resetSelectedCountryCode = function () {\n\t\t\tself.selectedRowIndex = -1;\n\t\t\tself.selectedCountryCode = null;\n\t\t\tself.action = '';\n\t\t};\n\t\t/**\n\t\t * Validate and call api to save new data. Call to back end to insert to database.\n\t\t */\n\t\tself.saveNewData = function () {\n\t\t\tif (self.validateCountryCodeBeforeInsert()) {\n\t\t\t\t$('#countryCodeModal').modal('hide');\n\t\t\t\tself.isWaitingForResponse = true;\n\t\t\t\tcountryCodeApi.addNewCountryCodes(\n\t\t\t\t\tself.countryCodesHandle,\n\t\t\t\t\tfunction (results) {\n\t\t\t\t\t\tself.resetSelectedCountryCode();\n\t\t\t\t\t\tself.isWaitingForResponse = false;\n\t\t\t\t\t\tself.checkAllFlag = false;\n\t\t\t\t\t\tself.setCountryCodes(results.data);\n\t\t\t\t\t\tself.success = results.message;\n\t\t\t\t\t},\n\t\t\t\t\tfunction (error) {\n\t\t\t\t\t\tself.fetchError(error);\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * This method is used to save the data changes when user click on\n\t\t * Yes button of confirm popup for data changes.\n\t\t */\n\t\tself.saveDataChanged = function () {\n\t\t\tif(self.action == self.EDIT_ACTION) {\n\t\t\t\t// Edit\n\t\t\t\tif (self.validateCountryCodeBeforeUpdate()) {\n\t\t\t\t\tself.updateCountryCode();\n\t\t\t\t} else {\n\t\t\t\t\tself.isReturnToTab = false;\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t// Add new\n\t\t\t\tself.saveNewData();\n\t\t\t}\n\t\t\t$('.modal-backdrop').attr('style','');\n\t\t\tself.isConfirmSaveCountryCode = false;\n\t\t\t$('#confirmModal').modal('hide');\n\t\t};\n\t\t/**\n\t\t * This method is used to hide add/edit popup and confirm popup when user click on\n\t\t */\n\t\tself.noSaveDataChanged = function () {\n\t\t\tif(self.action == self.EDIT_ACTION) {\n\t\t\t\tif (self.isReturnToTab) {\n\t\t\t\t\t$('#confirmModal').on('hidden.bs.modal', function () {\n\t\t\t\t\t\tself.returnToTab();\n\t\t\t\t\t\t$scope.$apply();\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tself.countryCodes[self.selectedRowIndex] = angular.copy(self.countryCodesOrig[self.selectedRowIndex]);\n\t\t\t\t\t$scope.tableParams.reload();\n\t\t\t\t\tself.resetSelectedCountryCode();\n\t\t\t\t}\n\t\t\t}\n\t\t\tself.isConfirmSaveCountryCode = false;\n\t\t\t$('.modal-backdrop').attr('style','');\n\t\t\t$(\"#confirmModal\").modal('hide');\n\t\t\t$('#countryCodeModal').modal('hide');\n\t\t};\n\t\t/**\n\t\t * Hides save confirm dialog.\n\t\t */\n\t\tself.cancelConfirmDialog = function () {\n\t\t\t$('.modal-backdrop').attr('style','');\n\t\t\tself.isReturnToTab = false;\n\t\t\t$('#confirmModal').modal('hide');\n\t\t\tself.isConfirmSaveCountryCode = false;\n\t\t};\n\t\t/**\n\t\t * Show red border on input text.\n\t\t *\n\t\t * @param id if of input text.\n\t\t */\n\t\tself.showErrorOnTextBox = function (id, message) {\n\t\t\tif ($('#' + id).length > 0) {\n\t\t\t\t$('#' + id).addClass('ng-invalid ng-touched');\n\t\t\t\t$('#' + id).attr('title', message);\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * This method is used to synchronize country model with add/edit form\n\t\t * when user enter the data on input text is invalid.\n\t\t * @param country\n\t\t */\n\t\tself.synchronizeCountryModelWithInputText = function(country, index){\n\t\t\tvar inputTextId = index.toString();\n\t\t\tvar countryAbbreviationInputValue = $('#countryAbbreviation'+inputTextId).val();\n\t\t\tif(countryAbbreviationInputValue != null){\n\t\t\t\tcountry.countryAbbreviation = countryAbbreviationInputValue.trim();\n\t\t\t}\n\t\t\tvar countryNameInputValue = $('#countryName'+inputTextId).val();\n\t\t\tif(countryNameInputValue != null){\n\t\t\t\tcountry.countryName = countryNameInputValue.trim();\n\t\t\t}\n\t\t\tvar countIsoA3CodInputValue = $('#countIsoA3Cod'+inputTextId).val();\n\t\t\tif(countIsoA3CodInputValue != null){\n\t\t\t\tcountry.countIsoA3Cod = countIsoA3CodInputValue.trim();\n\t\t\t}\n\t\t\tvar countIsoN3CdInputValue = $('#countIsoN3Cd'+inputTextId).val();\n\t\t\tif(countIsoN3CdInputValue != null){\n\t\t\t\tif(countIsoN3CdInputValue.length>0){\n\t\t\t\t\tcountry.countIsoN3Cd = parseInt(countIsoN3CdInputValue);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Returns the display status for unedit button.\n\t\t *\n\t\t * @param country the selected country code.\n\t\t * @returns {boolean} true the unedit button will be showed.\n\t\t */\n\t\tself.isShowingUneditButton = function (country) {\n\t\t\tif (country.countryId == 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn country.isEditing;\n\t\t};\n\t\t/**\n\t\t * This method is used to return to the selected tab.\n\t\t */\n\t\tself.returnToTab = function () {\n\t\t\tif (self.isReturnToTab) {\n\t\t\t\t$rootScope.$broadcast(self.RETURN_TAB);\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Clear message listener.\n\t\t */\n\t\t$scope.$on(self.VALIDATE_COUNTRY_CODE, function () {\n\t\t\tif (self.selectedCountryCode != null && self.isCountryCodeChanged(self.selectedCountryCode, self.countryCodesOrig)) {\n\t\t\t\tself.isReturnToTab = true;\n\t\t\t\tself.isConfirmSaveCountryCode = true;\n\t\t\t\tself.allowDeleteCountryCode = false;\n\t\t\t\tself.allowCloseButton = false;\n\t\t\t\t// show popup\n\t\t\t\tself.confirmHeaderTitle = 'Confirmation';\n\t\t\t\tself.error = '';\n\t\t\t\tself.success = '';\n\t\t\t\tself.messageConfirm = self.UNSAVED_DATA_CONFIRM_MESSAGE_STRING;\n\t\t\t\tself.labelClose = 'No';\n\t\t\t\t$('#confirmModal').modal({backdrop: 'static', keyboard: true});\n\t\t\t} else {\n\t\t\t\t$rootScope.$broadcast(self.RETURN_TAB);\n\t\t\t}\n\t\t});\n\t\t/**\n\t\t * This method is used to check invalid the data on textbox when paging.\n\t\t *\n\t\t * @param fieldName\n\t\t */\n\t\tself.onChanged = function (fieldName) {\n\t\t\tvar value = null;\n\t\t\tif (fieldName === 'countryAbbreviation') {\n\t\t\t\tvalue = $('#countryAbbreviation').val();\n\t\t\t\tif (value == null || value == undefined ||\n\t\t\t\t\tvalue.trim().length == 0) {\n\t\t\t\t\tself.showErrorOnTextBox('countryAbbreviation', self.COUNTRY_ABBR_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif (value.trim().length == 1) {\n\t\t\t\t\t\tself.showErrorOnTextBox('countryAbbreviation', self.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (fieldName === 'countryName') {\n\t\t\t\tvalue = $('#countryName').val();\n\t\t\t\tif (value == null || value == undefined ||\n\t\t\t\t\tvalue.trim().length == 0) {\n\t\t\t\t\tself.showErrorOnTextBox('countryName', self.COUNTRY_MANDATORY_FIELD_ERROR);\n\t\t\t\t}\n\t\t\t} else if (fieldName === 'countIsoA3Cod') {\n\t\t\t\tvalue = $('#countIsoA3Cod').val();\n\t\t\t\tif (value == null || value == undefined ||\n\t\t\t\t\tvalue.trim().length == 0) {\n\t\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod', self.ISO_ALPHA_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif (value.trim().length < 3) {\n\t\t\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod', self.ISO_ALPHA_MUST_BE_3_CHARS_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (fieldName === 'countIsoN3Cd') {\n\t\t\t\tvalue = $('#countIsoN3Cd').val();\n\t\t\t\tif (value == null || value == undefined ||\n\t\t\t\t\tvalue.length == 0) {\n\t\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd', self.NUMBERIC_N3_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif (parseInt(value) <= 0) {\n\t\t\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd',\n\t\t\t\t\t\t\tself.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Check all field is valid before add new.\n\t\t * @returns {boolean}\n\t\t */\n\t\tself.validateCountryCodeBeforeInsert = function () {\n\t\t\tvar errorMessages = [];\n\t\t\tvar message = '';\n\t\t\tvar countryCode = null;\n\t\t\tfor (var i = 0; i < self.countryCodesHandle.length; i++) {\n\t\t\t\tcountryCode = self.countryCodesHandle[i];\n\t\t\t\tif ($('#countryAbbreviation' + i.toString()).val() == null ||\n\t\t\t\t\t$('#countryAbbreviation' + i.toString()).val().trim().length == 0) {\n\t\t\t\t\tmessage = '<li>' + self.COUNTRY_ABBR_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t}\n\t\t\t\t\tself.showErrorOnTextBox('countryAbbreviation' + i.toString(), self.COUNTRY_ABBR_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif ($('#countryAbbreviation' + i.toString()).val().trim().length == 1) {\n\t\t\t\t\t\tmessage = '<li>' + self.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR + '</li>';\n\t\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.showErrorOnTextBox('countryAbbreviation' + i.toString(), self.COUNTRY_ABBR_MUST_BE_2_CHARS_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($('#countryName' + i.toString()).val() == null ||\n\t\t\t\t\t$('#countryName' + i.toString()).val().trim().length == 0) {\n\t\t\t\t\tmessage = '<li>' + self.COUNTRY_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t}\n\t\t\t\t\tself.showErrorOnTextBox('countryName' + i.toString(), self.COUNTRY_MANDATORY_FIELD_ERROR);\n\t\t\t\t}\n\t\t\t\tif ($('#countIsoA3Cod' + i.toString()).val() == null ||\n\t\t\t\t\t$('#countIsoA3Cod' + i.toString()).val().trim().length == 0) {\n\t\t\t\t\tmessage = '<li>' + self.ISO_ALPHA_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t}\n\t\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod' + i.toString(), self.ISO_ALPHA_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif ($('#countIsoA3Cod' + i.toString()).val().trim().length < 3) {\n\t\t\t\t\t\tmessage = '<li>' + self.ISO_ALPHA_MUST_BE_3_CHARS_ERROR + '</li>';\n\t\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.showErrorOnTextBox('countIsoA3Cod' + i.toString(), self.ISO_ALPHA_MUST_BE_3_CHARS_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($('#countIsoN3Cd' + i.toString()).val() == null ||\n\t\t\t\t\t$('#countIsoN3Cd' + i.toString()).val().length == 0) {\n\t\t\t\t\tmessage = '<li>' + self.NUMBERIC_N3_MANDATORY_FIELD_ERROR + '</li>';\n\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t}\n\t\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd' + i.toString(), self.NUMBERIC_N3_MANDATORY_FIELD_ERROR);\n\t\t\t\t} else {\n\t\t\t\t\tif (parseInt($('#countIsoN3Cd' + i.toString()).val()) <= 0) {\n\t\t\t\t\t\tmessage = '<li>' + self.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR + '</li>';\n\t\t\t\t\t\tif (errorMessages.indexOf(message) == -1) {\n\t\t\t\t\t\t\terrorMessages.push(message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.showErrorOnTextBox('countIsoN3Cd' + i.toString(),\n\t\t\t\t\t\t\tself.NUMBERIC_N3_MUST_BE_GREATER_THAN_0_AND_LESS_THAN_100_ERROR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (errorMessages.length > 0) {\n\t\t\t\tvar errorMessagesAsString = 'Country Code:';\n\t\t\t\tangular.forEach(errorMessages, function (errorMessage) {\n\t\t\t\t\terrorMessagesAsString += errorMessage;\n\t\t\t\t});\n\t\t\t\tself.errorPopup = errorMessagesAsString;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\t/**\n\t\t * Returns the disabled status of button by country code id.\n\t\t *\n\t\t * @param id the country code id.\n\t\t * @returns {boolean} the disable status.\n\t\t */\n\t\tself.isDisabledButton = function (id) {\n\t\t\tif (self.selectedRowIndex == -1 || self.selectedCountryCode.countryId == id) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\t/**\n\t\t * Returns the style for icon button.\n\t\t *\n\t\t * @param id the id of country code.\n\t\t * @returns {*} the style.\n\t\t */\n\t\tself.getDisabledButtonStyle = function (id) {\n\t\t\tif (self.isDisabledButton(id)) {\n\t\t\t\treturn 'opacity: 0.5;'\n\t\t\t}\n\n\t\t\treturn 'opacity: 1.0;';\n\t\t}\n\t}", "function translation() {\n return gulp\n .src(theme.php.src)\n .pipe(wpPot({\n domain: 'wpg_theme',\n package: 'Powiat Bartoszycki',\n bugReport: 'http:/powiatbartoszyce.pl'\n }))\n .pipe(gulp.dest(theme.lang.dist + 'powiat-bartoszycki.pot'))\n}", "function getTranslatedUrl(text){\n return serverUrl + \"?\" + \"text=\" + text; \n\n}", "function menutoshowlang(){\n}", "constructor() { \n \n LocalizationRead.initialize(this);\n }", "async function getTranslatedString(string, targetLang){\n AWS.config.region = \"us-east-1\";\n var ep = new AWS.Endpoint(\"https://translate.us-east-1.amazonaws.com\");\n AWS.config.credentials = new AWS.Credentials(\"AKIAJQLVBELRL5AAMZOA\", \"Kl0ArGHFySw+iBEdGXZDrTch2V5VAaDbSs+EKKEZ\");\n var translate = new AWS.Translate();\n translate.endpoint = ep;\n var params = {\n Text: string,\n SourceLanguageCode: \"en\",\n TargetLanguageCode: targetLang\n };\n var promise = new Promise((resolve, reject)=>{\n translate.translateText(params, (err, data)=>{\n if (err) return reject(err);\n else {\n return resolve(data);\n }\n });\n });\n var result = await promise;\n return result.TranslatedText;\n}", "function bindLabels(data) {\n $scope.langproLables = data.labels;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new RigidBody using the given body type. Defaults to Box2D.BodyType.DYNAMIC.
function RigidBody(bodyType) { if (typeof bodyType === "undefined") { bodyType = 2 /* Dynamic */; } _super.call(this, "RigidBody"); /** * The type of body (Dynamic, Static, or Kinematic) associated with this Collider. * Defaults to Dynamic. * The types are defined in Box2D.BodyType. */ this.bodyType = 2 /* Dynamic */; this.bodyType = bodyType; }
[ "function addBody(){\n\tvar s = time();\n\tvar is_space = false;\n\twhile(!is_space && time()-s<1000){\n\t\tvar x = rand(0, win_w);\n\t\tvar y = rand(0, win_h);\n\t\tvar m = rand(7,30);\n\t\tvar r = m;\n\t\tvar is_space = true;\n\t\tfor(var i = 0, l = bodies.length; i < l && is_space; i++){\n\t\t\tvar b = bodies[i];\n\t\t\tvar d = point_dist(x,y,b.x,b.y);\n\t\t\tif(d <= r + b.r) is_space = false;\n\t\t}\n\t}\n\tif(is_space) bodies.push(new OrbitalBody(m,r,x,y));\n}", "function setupPhysics(world){\n var fixDef = new b2FixtureDef;\n fixDef.density = DENSITY;\n fixDef.friction = this.isGround ? GROUND_FRICTION : FRICTION;\n fixDef.restitution = RESTITUTION;\n\n var bodyDef = new b2BodyDef;\n bodyDef.type = b2Body.b2_staticBody;\n \n // positions the center of the object (not upper left!)\n bodyDef.position.x = this.x;\n bodyDef.position.y = this.y;\n\n fixDef.shape = new b2PolygonShape;\n \n // half width, half height.\n fixDef.shape.SetAsBox(this.width / 2, this.height / 2);\n fixDef.userData = this;\n\n this.body = world.CreateBody(bodyDef)\n this.fix = this.body.CreateFixture(fixDef);\n }", "function Boundary(x_,y_, w_, h_) {\n // But we also have to make a body for box2d to know about it\n // Body b;\n\n this.x = x_;\n this.y = y_;\n this.w = w_;\n this.h = h_;\n\n var fd = new box2d.b2FixtureDef();\n fd.density = 1.0;\n fd.friction = 0.5;\n fd.restitution = 0.2;\n\n var bd = new box2d.b2BodyDef();\n\n bd.type = box2d.b2BodyType.b2_staticBody;\n bd.position = scaleToWorld(this.x, this.y);\n fd.shape = new box2d.b2PolygonShape();\n fd.shape.SetAsBox(this.w/(scaleFactor*2), this.h/(scaleFactor*2));\n this.body = world.CreateBody(bd).CreateFixture(fd);\n\n // Draw the boundary, if it were at an angle we'd have to do something fancier\n this.display = function() {\n fill(127);\n stroke(200);\n rectMode(CENTER);\n rect(this.x,this.y,this.w,this.h);\n };\n}", "static _create2DShape (typeofShape, width, depth, height, scene) {\n switch (typeofShape) {\n case 0:\n var faceUV = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV[4] = new BABYLON.Vector4(0, 0, 1, 1)\n faceUV[5] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options = {\n width: width,\n height: height,\n depth: depth,\n faceUV: faceUV\n }\n\n return BABYLON.MeshBuilder.CreateBox('pin', options, scene)\n case 1:\n var faceUV2 = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV2[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV2[0] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options2 = {\n diameterTop: width,\n diameterBottom: depth,\n height: height,\n tessellation: 32,\n faceUV: faceUV2\n }\n\n return BABYLON.MeshBuilder.CreateCylinder('pin', options2, scene)\n }\n }", "function PhysicsJoint(/**\n * The type of the physics joint\n */type,/**\n * The data for the physics joint\n */jointData){this.type=type;this.jointData=jointData;jointData.nativeParams=jointData.nativeParams||{};}", "function updatePhysicsBodies() {\n // three.js model positions updates using cannon-es simulation\n // sphereMesh.position.copy(sphereBody.position)\n // sphereMesh.quaternion.copy(sphereBody.quaternion)\n\n shipModel.position.copy(shipBody.position);\n shipModel.quaternion.copy(shipBody.quaternion);\n playerCustom.position.copy(shipBody.position);\n playerCustom.quaternion.copy(shipBody.quaternion);\n playerBox\n .copy(playerCustom.geometry.boundingBox)\n .applyMatrix4(playerCustom.matrixWorld);\n}", "function b2FrictionJoint(def)\r\n{\r\n\tthis.parent.call(this, def);\r\n\r\n\tthis.m_localAnchorA = def.localAnchorA.Clone();\r\n\tthis.m_localAnchorB = def.localAnchorB.Clone();\r\n\r\n\tthis.m_linearImpulse = new b2Vec2();\r\n\tthis.m_angularImpulse = 0.0;\r\n\r\n\tthis.m_maxForce = def.maxForce;\r\n\tthis.m_maxTorque = def.maxTorque;\r\n\r\n\t// Solver temp\r\n\tthis.m_indexA = 0;\r\n\tthis.m_indexB = 0;\r\n\tthis.m_rA = new b2Vec2();\r\n\tthis.m_rB = new b2Vec2();\r\n\tthis.m_localCenterA = new b2Vec2();\r\n\tthis.m_localCenterB = new b2Vec2();\r\n\tthis.m_invMassA = 0;\r\n\tthis.m_invMassB = 0;\r\n\tthis.m_invIA = 0;\r\n\tthis.m_invIB = 0;\r\n\tthis.m_linearMass = new b2Mat22();\r\n\tthis.m_angularMass = 0;\r\n}", "createTetronimo(position, type) {\n\t\tif (type === TETRONIMO_TYPES.RANDOM) {\n\t\t\ttype = this._randomType();\n\t\t}\n\n\t\tconst origin = new Block(position);\n\t\tconst blocks = this._createOtherBlocksAround(position, type);\n\t\tblocks.push(origin);\n\n\t\treturn new Tetronimo({ origin: origin, blocks: blocks, type: type });\n\t}", "function Box2dModelNode(nodeType, view) {\n\tthis.view = view;\n\tthis.type = nodeType;\n\tthis.prevWorkNodeIds = [];\n\t\n\t/////\n\t////\tTHESE NEED TO BE PLACED IN box2dModelEvents as well;\n\n\tthis.customEventTypes = ['make-model', 'delete-model', 'make-beaker', 'delete-beaker', 'make-scale', 'delete-scale', 'make-beaker', 'delete-beaker', 'add-to-beaker', 'add-to-scale', 'add-to-balance', 'remove-from-beaker', 'remove-from-scale', 'remove-from-balance', 'test-in-beaker', 'test-on-scale', 'test-on-balance','gave-feedback'];\t\n}", "function Model (name, price, sizeCategory) {\n this.name = name;\n this.price = price;\n this.sizeCategory = sizeCategory;\n \n this.head = new BodyPart();\n this.torso = new BodyPart();\n this.leftArm = new BodyPart();\n this.rightArm = new BodyPart();\n this.leftLeg = new LeftLeg();\n this.rightLeg = new RightLeg();\n}", "function p2RaceCar(collision_id,clientID, world, position, angle, width, height, mass) {\n // Create a dynamic body for the chassis\n let chassisBody = new p2.Body({\n mass: mass,\n position: position,\n id: clientID\n });\n let boxShape = new p2.Box({\n width: width,\n height: height,\n collisionGroup: Math.pow(2, collision_id),\n collisionMask: -1\n });\n chassisBody.addShape(boxShape);\n chassisBody.angle = angle;\n world.addBody(chassisBody);\n\n // Create the vehicle\n let vehicle = new p2.TopDownVehicle(chassisBody);\n\n // Add one front wheel and one back wheel\n let frontWheel = vehicle.addWheel({\n localPosition: [0, 0.5] // front\n });\n frontWheel.setSideFriction(4);\n\n // Back wheel\n let backWheel = vehicle.addWheel({\n localPosition: [0, -0.5] // back\n });\n backWheel.setSideFriction(4.5); // Less side friction on back wheel makes it easier to drift\n\n backWheel.engineForce = 0;\n frontWheel.steerValue = 0;\n\n vehicle.addToWorld(world);\n return [vehicle, frontWheel, backWheel];\n}", "function b2RopeJointDef()\n{\n\tthis.parent.call(this);\n\n\tthis.type = b2Joint.e_ropeJoint;\n\tthis.localAnchorA = new b2Vec2(-1.0, 0.0);\n\tthis.localAnchorB = new b2Vec2(1.0, 0.0);\n\tthis.maxLength = 0.0;\n\n\tObject.seal(this);\n}", "function applybox(context, phys, platformLevel, platformRadius)\n{\n\tvar objectradius = 135*0.4;\n\tvar restitution = 0.8;\n\t\n\t// bounce on platform\n\tonPlatform = (Math.pow(phys.x - phys.x0, 2) < platformRadius*platformRadius) && (phys.y <= platformLevel+50) ;\n\t\n\tif (phys.y>platformLevel && onPlatform)\n\t\tphys.vy = phys.v0;\n\t\n\t// bounce on all borders of the canvas\n\tif (phys.x < objectradius && phys.vx < 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\n\tif (phys.x > context.canvas.width - objectradius && phys.vx > 0)\n\t{\n\t\tphys.vx = -phys.vx * restitution;\n\t\tphys.vy = phys.vy * restitution;\n\t}\n\t\t\n\tif (phys.y > context.canvas.height - objectradius && phys.vy > 0)\n\t{\n\t\tphys.vx = phys.vx * restitution;\n\t\tphys.vy = -phys.vy * restitution;\n\t}\n\t\n\t// if falling off the platform, add rotation\n\tvar v = Math.sqrt(phys.vx*phys.vx + phys.vy*phys.vy);\n\tvar vr = v/500;\n\tif (!onPlatform)\n\t{\n\t\tif (phys.x > phys.x0)\n\t\t\tphys.vr = vr;\n\t\telse\n\t\t\tphys.vr = -vr;\n\t}\n\t\n\treturn onPlatform;\n}", "constructor(x, y, s, options = {}) {\n this.s = s;\n // Polygon with random radius\n this.body = Bodies.polygon(x, y, s, random(8, 14), options);\n // Add shape to body\n World.add(engine.world, this.body);\n }", "constructor() { \n \n Body18.initialize(this);\n }", "function spawnBox(rate){\r\n\tif(difficulty%rate == 0){\r\n\t\tvar box = new Box(Math.floor(Math.random() * 1060) + 1030);\r\n\t\tBoxes.push(box);\r\n\t}\r\n}", "function FixedUpdate(){\n\tvar v = rb.velocity;\n\t// We use sqrMagnitude instead of magnitude for performance reasons.\n\tvar vSqr = v.sqrMagnitude;\n\t\n\t//Initializing new velocity values if the speed limit changes.\n\tInitialize(dragStartVelocity, dragMaxVelocity, maxVelocity, maxDrag);\n\t\n\tif(vSqr > sqrDragStartVelocity){\n\t\tif(sqrDragVelocityRange == 0)\n\t\t\tsqrDragVelocityRange = 1;\n\t\trigidbody.drag = Mathf.Lerp(originalDrag, maxDrag, Mathf.Clamp01((vSqr - sqrDragStartVelocity)/sqrDragVelocityRange));\n\n\t\t// Clamp the velocity, if necessary\n\t\tif(vSqr > sqrMaxVelocity){\n\t\t\t// Vector3.normalized returns this vector with a magnitude\n\t\t\t// of 1. This ensures that we're not messing with the\n\t\t\t// direction of the vector, only its magnitude.\n\t\t\trb.velocity = v.normalized * maxVelocity;\n\t\t}\n\t} else {\n\t\trb.drag = originalDrag;\n\t}\n}", "function Shape(_type) {\n var type = _type;\n this.getType = function(){\n return type;\n }\n}", "function runtimeByType(type) {\n if (type === 'vertx') {\n return getGeneratorModule('rest-vertx');\n } else {\n throw `Unsupported runtime type: ${type}`;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts categories into a sorted array for each place it has the values: [categoryNid, category item count, category item ids as an array]
function sortCategories(cats){ var ar = [], ret = {}; $.each(cats, function(idx, d){ ar.push([idx, d.length, d]); }); ar = ar.sort(function(a,b) { return b[1] - a[1]; }); return ar; }
[ "function fillCatPositionsArray() {\n\tcatPositions = new Array()\n\tvar idx = 0;\n\t$('#categories').find('li').each(function() {\n\t\tcatPositions[idx++] = getCategoryId($(this).attr('id'));\n\t});\n}", "function sortGroceries() {\n let categories = Array.from(new Set(groceryList.map((grocery) => grocery.category))).sort();\n let tempgroceryList = [];\n categories.forEach((category) => {\n let currentCategoryItems = groceryList.filter((grocery) => grocery.category == category);\n currentCategoryItems = currentCategoryItems.sort((a, b) => (a.qty > b.qty) ? 1 : ((b.qty > a.qty) ? -1 : 0));\n currentCategoryItems.forEach((item) => {\n tempgroceryList.push(item)\n })\n })\n groceryList = tempgroceryList;\n}", "function countTopCategories() {\n var data = library.categories;\n model.data.top_categories =\n data\n .map(function (x, i) {\n return { id: i, data: x };\n })\n .sort(function (a, b) {\n return b.data.books.length - a.data.books.length;\n })\n .map(function (x) {\n return {\n id: x.id,\n Name: x.data.Name,\n Title: x.data.Title,\n booksCount: x.data.books.length\n }\n });\n }", "function getAssignedCategoriesForAccordionMenu(cat){\r\n var assignedCategoriesPOPStageArray = null; // this stores array of the specialized assigned Categories for speicalized users to be work on in case of ParallelizedOPStage\r\n var assignedCategoryList = new Array(); // this stores the array/list of assigned categories medical hierachy list only for filtered accordion menu only\r\n\r\n if(assignedCategoriesForParallelizedOPStage != null)\r\n assignedCategoriesPOPStageArray = assignedCategoriesForParallelizedOPStage.split(',');\r\n\r\n var count = -1;\r\n if(assignedCategoriesPOPStageArray != null){\r\n // it will check from total categories\r\n for( k = 0; k < cat.length; k++) {\r\n // then will check and populate for primary assigned categories\r\n for( j = 0; j < assignedCategoriesPOPStageArray.length; j++) {\r\n if(cat[k].name == assignedCategoriesPOPStageArray[j].trim() && cat[k].level == 1) {\r\n count++;\r\n assignedCategoryList[count] = cat[k];\r\n break;\r\n }\r\n }\r\n // then will check and populate the assigend subcategories\r\n for(var l = 0; l < assignedCategoryList.length; l++) {\r\n if(cat[k].parentid == assignedCategoryList[l].id) {\r\n count++;\r\n assignedCategoryList[count] = cat[k];\r\n break;\r\n }\r\n }\r\n }\r\n return assignedCategoryList; \r\n }\r\n}", "function getCategories(cv){\n\t'use strict';\n\tvar arr = [];\n\tfor(var i=0; i<cv.category.length; i++){\n\t\tarr.push(cv.category[i].title);\n\t}\n\treturn arr;\n}", "function getCategoryList(category) {\n var catList = [];\n self.features.forEach(function(feat, index, array) {\n if (! mrlUtil.arrayContains(catList, feat.category)) {\n catList.push(feat.category);\n }\n });\n return catList;\n }", "function getListOfContentsOfAllcategories(categories) {\r\n $scope.dlListOfContentsOfAllcategories = [];\r\n var sortField = 'VisitCount';\r\n var sortDirAsc = false;\r\n\r\n if (categories instanceof Array) {\r\n categories.filter(function(category) {\r\n var dlCategoryContent = {};\r\n dlCategoryContent.isLoading = true;\r\n dlCategoryContent = angular.extend(Utils.getListConfigOf('pubContent'), dlCategoryContent);\r\n $scope.dlListOfContentsOfAllcategories.push(dlCategoryContent);\r\n\r\n pubcontentService.getContentsByCategoryName(category.name, sortField, sortDirAsc, dlCategoryContent.pagingPageSize).then(function(response) {\r\n if (response && response.data) {\r\n var contents = new EntityMapper(Content).toEntities(response.data.Contents);\r\n var category = new Category(response.data.Category);\r\n var totalCount = response.data.TotalCount;\r\n\r\n dlCategoryContent.items = contents;\r\n dlCategoryContent.headerTitle = category && category.title || '';\r\n dlCategoryContent.headerRightLabel = totalCount + '+ articles';\r\n dlCategoryContent.pagingTotalItems = totalCount;\r\n dlCategoryContent.footerLinkUrl = [dlCategoryContent.footerLinkUrl, category && category.name].join('/');\r\n dlCategoryContent.tags = pubcontentService.getUniqueTagsOfContents(contents);\r\n } else {\r\n resetContentList(dlCategoryContent);\r\n }\r\n dlCategoryContent.isLoading = false;\r\n }, function() {\r\n resetContentList(dlCategoryContent);\r\n });\r\n });\r\n }\r\n\r\n function resetContentList(dlCategoryContent) {\r\n dlCategoryContent.items = new EntityMapper(Content).toEntities([]);\r\n dlCategoryContent.headerRightLabel = '0 articles';\r\n dlCategoryContent.pagingTotalItems = 0;\r\n dlCategoryContent.tags = [];\r\n dlCategoryContent.isLoading = false;\r\n }\r\n }", "function createCountList(totalItems) {\n var order = [];\n if ((totalItems % 3) == 2) {\n for (var x = 0; x < Math.floor(totalItems / 3); x++) {\n order.push(3);\n }\n order.push(2);\n } else if ((totalItems % 3) == 1) {\n for (var x = 0; x < Math.floor(totalItems / 3); x++) {\n order.push(3);\n }\n order[order.length - 1] = 2;\n order.push(2);\n } else if ((totalItems % 3) == 0) {\n for (var x = 0; x < Math.floor(totalItems / 3); x++) {\n order.push(3);\n }\n }\n\n return order;\n}", "function sortClumps (clumped) {\n var bigArray = [];\n\n while (clumped.length > 0) {\n var biggest = 0;\n var bigIndex = 0;\n for (var i = 0; i < clumped.length; i++) {\n if (clumped[i][0][0].getTime() > biggest) {\n biggest = clumped[i][0][0].getTime();\n bigIndex = i;\n };\n };\n bigArray.unshift(clumped[bigIndex]);\n clumped.splice(bigIndex, 1);\n };\n return bigArray;\n}", "function orderResults(ids, items) {\n\tconst indexed = _.indexBy(items, '_id');\n\treturn ids.map(function(id) { return indexed[id]; });\n}", "getSortedTags() {\n return this.data.map(series => series.tags)\n .reduce((a, b) => a.concat(b))\n .filter((el, i, a) => i === a.indexOf(el))\n .sort();\n }", "_initCategoryIdxMap () {\n let param = this.parameter\n if (!param.categoryEncoding) return\n \n // categorical parameter with integer encoding\n // Note: The palette order is equal to the categories array order.\n let max = -Infinity\n let min = Infinity\n let categories = param.observedProperty.categories\n let encoding = param.categoryEncoding\n for (let category of categories) {\n if (encoding.has(category.id)) {\n for (let val of encoding.get(category.id)) {\n max = Math.max(max, val)\n min = Math.min(min, val)\n }\n }\n }\n let valIdxMap\n if (categories.length < 256) {\n if (max > 10000 || min < 0) {\n // TODO implement fallback to Map implementation\n throw new Error('category values too high (>10000) or low (<0)')\n }\n valIdxMap = new Uint8Array(max+1)\n for (let i=0; i <= max; i++) {\n // the above length < 256 check ensures that no palette index is ever 255\n valIdxMap[i] = 255\n }\n \n for (let idx=0; idx < categories.length; idx++) {\n let category = categories[idx]\n if (encoding.has(category.id)) {\n for (let val of param.categoryEncoding.get(category.id)) {\n valIdxMap[val] = idx\n }\n }\n }\n } else {\n throw new Error('Too many categories: ' + categories.length)\n }\n this._categoryIdxMap = valIdxMap\n }", "function getAppearedLabels(){\n\tvar arr = [] \n\tfor (var i = 0; i<labels.length; i++) {\n\t\tarr.push(labels[i].name.label);\n\t}\n\tvar appearedLabelsUnsort = arr.filter( onlyUnique );\n\t// manually add \"treeSphere\" and \"treeCube\" as their names are saved as \"vegetation\"\n\tappearedLabelsUnsort.push('treeSphere');\n\tappearedLabelsUnsort.push('treeCube');\n\n\tappearedLabels = [];\n\tfor (var label in category) {\n\t\tif (appearedLabelsUnsort.indexOf(label)>-1){\n\t\t\tappearedLabels.push(label);\n\t\t}\n\t}\n}", "function makeCVNArray() {\n for (var i = 0; i < itemArray.length; i++) {\n clickedArray.push(itemArray[i].clicked);\n viewedArray.push(itemArray[i].viewed);\n nameArray.push(itemArray[i].title);\n }\n }", "function getUniqueCategories(deals) {\n const set = new Set();\n for (const deal of deals) {\n for (const category of deal.categories || []) {\n set.add(category.toLowerCase());\n }\n }\n const uniqueCategories = [...set.values()];\n uniqueCategories.sort((a, b) => a.localeCompare(b));\n return uniqueCategories;\n}", "function createFrequencyData(data, dimension) {\n var result = [];\n data.reduce(function (res, value) {\n if (!res[value[dimension]]) {\n res[value[dimension]] = {\n Id: value[dimension],\n count: 0,\n entireData: value,\n };\n result.push(res[value[dimension]]);\n }\n res[value[dimension]].count += 1;\n return res;\n }, {});\n return result.sort((data1, data2) => {\n return parseInt(data1.Id) - parseInt(data2.Id);\n });\n}", "function sortChocolateBasedOnCount(chocolates) {\n var chocolatesCount = {};\n var sortArray = [];\n\n // Count chocolates and store count with color name in object chocolatesCount\n for (i = 0; i < chocolates.length; i++) {\n if (chocolatesCount[chocolates[i]] == undefined) {\n chocolatesCount[chocolates[i]] = 1;\n } else {\n chocolatesCount[chocolates[i]]++;\n }\n }\n\n // Sort chocolateCount Object with its count and color\n sortArray = Object.entries(chocolatesCount).sort().sort((a, b) => b[1] - a[1]);\n\n // empty array\n chocolates.length = 0;\n\n // store colors with N times(count of color) in chocolates array from sortArray\n for (i = 0; i < sortArray.length; i++) {\n for (j = 0; j < sortArray[i][1]; j++) {\n chocolates.push(sortArray[i][0]);\n }\n }\n\n return chocolates;\n}", "getReflectionCategories(reflections) {\n const categories = new Map();\n for (const child of reflections) {\n const childCategories = this.getCategories(child);\n if (childCategories.size === 0) {\n childCategories.add(CategoryPlugin_1.defaultCategory);\n }\n for (const childCat of childCategories) {\n const category = categories.get(childCat);\n if (category) {\n category.children.push(child);\n }\n else {\n const cat = new models_2.ReflectionCategory(childCat);\n cat.children.push(child);\n categories.set(childCat, cat);\n }\n }\n }\n for (const cat of categories.values()) {\n this.sortFunction(cat.children);\n }\n return Array.from(categories.values());\n }", "function getMatchingCategories(categoryId, categories){\n console.log(matchingCategories);\n angular.forEach(categories, function(category) {\n if(category.parentCategory === categoryId)\n {\n this.push(category);\n if(category.parentCategory != 0) {\n getMatchingCategories(category.categoryId, categories);\n }\n }\n }, matchingCategories);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Slider filter Filters element in slider and reinits swiper slider after
function initSliderFilter(swiper) { var btns = jQuery('.slider-filter'), container = jQuery('.slider-filter-container'); var ww = jQuery(window).width(), wh = jQuery(window).height(); if (btns.length) { btns.on('click', 'a.cat, span.cat, span.img', function() { var el = jQuery(this), filter = el.data('filter'), limit = el.data('limit'); container.find('.filter-item').show(); el.parent().parent().find('.cat-active').removeClass('cat-active') el.parent().parent().find('.cat-li-active').removeClass('cat-li-active') el.addClass('cat-active'); el.parent().addClass('cat-li-active'); if (filter !== '') { container.find('.filter-item').hide(); container.find('.filter-item.filter-type-' + filter + '').fadeIn(900); } if (swiper !== 0) { swiper.slideTo(0, 0); swiper.update(); } return false; }); // First Init, Activating first tab var firstBtn = btns.find('.cat:first') firstBtn.addClass('cat-active'); firstBtn.parent().addClass('cat-li-active'); container.find('.filter-item').hide(); container.find('.filter-item.filter-type-' + firstBtn.data('filter') + '').show(); } }
[ "function handleFilter () {\n $('.js-checked-filter').on('change', function (){\n let usrInput;\n if( $(this).is(':checked') ) usrInput = 'noCheckedItems';\n else {usrInput = 'noFilter';}\n\n setFilter(usrInput);\n renderShoppingList();\n });\n}", "function cs_page_composer_filterable(id) {\n\n var $container = jQuery(\"#page_element_container\" + id),\n elclass = \"cs-filter-item\";\n $container.find('.element-item').addClass(\"cs-filter-item\");\n jQuery(document).on('click', '#filters' + id + ' li', function (event) {\n var $selector = jQuery(this).attr('data-filter'),\n $elem = $container.find(\".\" + $selector + \"\");\n jQuery(\"#filters\" + id + \" li\").removeClass(\"active\");\n jQuery(this).addClass(\"active\");\n $container.find('.element-item').removeClass(elclass);\n if ($selector == \"all\") {\n $container.find('.element-item').addClass(elclass);\n } else {\n jQuery($elem).addClass(elclass);\n }\n event.preventDefault();\n });\n // Search By input\n jQuery(\"#quicksearch\" + id).keyup(function () {\n var _val = jQuery(this).val(),\n $this = jQuery(this);\n $container.find('.element-item').addClass(\"cs-filter-item\");\n jQuery(\"#filters\" + id + \" li\").removeClass(\"active\");\n var filter = jQuery(this).val(),\n count = 0;\n jQuery(\"#page_element_container\" + id + \" .element-item span\").each(function () {\n if (jQuery(this).text().search(new RegExp(filter, \"i\")) < 0) {\n jQuery(this).parents(\".element-item\").removeClass(elclass);\n } else {\n jQuery(this).parents(\".element-item\").addClass(elclass);\n count++;\n }\n });\n })\n}", "function setupFilters() {\n // Finds all filter items in both sidebar and nav.\n const $filters = $('[data-role=\"filter\"]');\n\n $filters.click((event) => {\n const $target = $(event.currentTarget);\n\n // Make this filter the only active filter.\n const wasActive = $target.hasClass('active');\n $filters.removeClass('active');\n $target.toggleClass('active', !wasActive);\n\n // Set up filter function.\n let filterFn;\n if (wasActive) {\n filterFn = () => true;\n } else if ($target.attr('data-filter') === 'category') {\n const category = $target.attr('data-category');\n filterFn = ($deal) =>\n $deal.find(`.categories [data-category=\"${category}\"]`).length;\n } else {\n filterFn = ($deal) => $deal.hasClass('featured');\n }\n\n // Apply filter.\n $('[data-role=\"deal\"]')\n .each((_, elem) => {\n const $deal = $(elem);\n $deal.css('display', filterFn($deal) ? '' : 'none');\n });\n });\n}", "function resetFilters(){\n \n console.log(\"resetFilters()\");\n d3.selectAll(\".mainFilterCheckbox\").property('checked', false);\n \n resetZoom();\n \n updateVis();\n }", "function resetSlider() {\n currentSlideIndex = 0\n }", "function filterChange() {\n Data.Svg.Node.style.filter = getFiltersCss(\n Data.Controls.Brightness.value,\n Data.Controls.Contrast.value,\n Data.Controls.Hue.value,\n Data.Controls.Saturation.value);\n}", "function initializeFilterComp() {\n subViews.filtersComp = new Filters($outlet.find(SEL_FILTERS).first());\n\n DataCache().get(URL_FILTERS).then(function(data) {\n subViews.filtersComp.setState(data);\n });\n }", "function resetFilters() {\n Filters.distance = 10;\n Filters.minPrice = 0.0;\n Filters.maxPrice = 100.0;\n Filters.itemQuality = 0;\n Filters.gender = 'all';\n Filters.type = 'all';\n Filters.size = 'all';\n Filters.color = 'all';\n Filters.freeOnly = false;\n}", "function onFilterChange () {\n self.prodSelected = false;\n if (self.filterVal === \"All\") {\n self.filteredProducts = [];\n self.filteredProducts = self.products;\n } else if (self.filterVal === \"Less Than $500\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price < 500) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"From $500 to $1000\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 500 && self.products[i].price < 1000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"From $1000 to $2000\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 1000 && self.products[i].price < 2000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n } else if (self.filterVal === \"$2000 or more\") {\n self.filteredProducts = [];\n for (let i = 0; i < self.products.length; i++) {\n if (self.products[i].price >= 2000) {\n self.filteredProducts.push(self.products[i]);\n }\n }\n }\n }", "function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }", "function updateFilter() {\n docBtn.enabled = filterBox.selectedIndex > 0;\n setErrorMessage(null);\n for (let i = 0; i < filterControls.length; ++i) {\n try {\n let name = filterControls[i].getClientProperty('pName');\n let array = filterControls[i].getClientProperty('pArray');\n let value = filterControls[i].text;\n if (value == '') value = array[1];\n let code = 'curFilter.' + name + ' = ' + array[0] + value + array[2] + ';';\n eval(code);\n } catch (ex) {\n setErrorMessage(ex);\n }\n }\n}", "function setupSearchFilter() {\n // an internal function that will add/remove a hidden element called \"addl_query\" to the\n // participant search form. The element will contain filtering information that will be used by\n // lunr in the participant search to filter out the found results based on the additional filter\n // items.\n function updateSearchFormFields(ev) {\n let searchForm = document.getElementById(\"participant_search_form\");\n let form = ev.target.closest(\"[data-js-search-filter]\");\n let checked = [...form.querySelectorAll(\":checked\")];\n let queries = {};\n for (let i = 0; i < checked.length; i++) {\n if (!queries[checked[i].name]) {\n queries[checked[i].name] = [];\n }\n queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`);\n }\n newQueries = Object.values(queries).map((q) => q.join(\" \"));\n searchForm\n .querySelectorAll(\"input[type='hidden']\")\n .forEach((e) => e.remove());\n for (let i = 0; i < newQueries.length; i++) {\n let input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"hidden\");\n input.setAttribute(\"name\", \"addl_query\");\n input.setAttribute(\"value\", newQueries[i]);\n searchForm.append(input);\n }\n searchForm.querySelector(\"[type='submit']\").click();\n }\n\n // when the search filter items are changed, update the search fields\n on(\"change\", \"[data-js-search-filter]\", updateSearchFormFields);\n\n // when the search filter items are reset, update the search fields once the call stack clears (\n // setTimeout with timeout of 0)\n on(\"reset\", \"[data-js-search-filter]\", function (ev) {\n setTimeout(function () {\n updateSearchFormFields(ev);\n }, 0);\n });\n}", "function pin_filters () {\n if(Math.floor($(document).scrollTop()) >= fundamental_vars.searchPos && $.getSizeClassification('large_up')){\n $('.domain-results-searchbar').css({'position': 'fixed','top': 0,'width': '100%','z-index': '100'}).addClass('fixed-top');\n if($.getSizeClassification('xlarge')) {\n if (($('.singleResult').length < 1 || (Math.floor($(document).scrollTop()) >= $('.domain-results').position().top)) && $(window).height() > 900 && $('.domain-results-searchbar').hasClass('fixed-top')) {\n $('.filtering').addClass('fixed-filters').css({'width': $('.domains-more-results .small-12').width() + 'px'});\n } else {\n $('.filtering').removeClass('fixed-filters');\n }\n }\n }else{\n $('.domain-results-searchbar').css({'position': '','top': 0,'width': '','z-index': ''}).removeClass('fixed-top');\n $('.filtering').removeClass('fixed-filters');\n setTimeout(function(){\n },1);\n }\n}", "function installSlider(){\n\t\t $(\"#slider\").rangeSlider({\n\t\t \tbounds:{\n\t\t \t\tmin: 1995,\n\t\t \t\tmax: 2014\n\t\t \t\t},\n\t\t \tdefaultValues:{\n\t\t \t\tmin: 1995,\n\t\t \t\tmax: 2014\n\t\t \t\t},\n\t\t \tstep: 1,\t \n\t\t\t\tscales : [\n\t\t\t\t\t// primary scale\n\t\t\t\t\t{\n\t\t\t\t\t\tfirst : function(val) {\n\t\t\t\t\t\t\treturn val;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnext : function(val) {\n\t\t\t\t\t\t\treturn val + 3;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstop : function(val) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlabel : function(val) {\n\t\t\t\t\t\t\treturn val;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tformat : function(tickContainer, tickStart, tickEnd) {\n\t\t\t\t\t\t\ttickContainer.addClass(\"myCustomClass\");\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t// secondary scale\n\t\t\t\t\t{\n\t\t\t\t\t\tfirst: function(val){ return val; },\n\t\t\t\t\t\tnext: function(val){\n\t\t\t\t\t\tif (val % 3 === 2){\n\t\t\t\t\t\treturn val + 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn val + 1;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstop: function(val){ return false; },\n\t\t\t\t\t\tlabel: function(){ return \"\"; }\n\t\t\t\t\t }\n\t\t\t\t ]\n\t\t\t\t});\n\t\t \n\t\t var initialSliderBounds = $(\"#slider\").rangeSlider(\"bounds\");\n\t\t dateFilterChanged(initialSliderBounds.min, initialSliderBounds.max);\n\t\t \n\t\t $(\"#slider\").bind(\"valuesChanged\", function(e, data){\n\t\t \t dateFilterChanged(data.values.min, data.values.max);\n\t\t });\n\t}", "function setFilter (input) {\n STORE.filter = input;\n}", "function datagrid_prep_filters(){\n $('.datagrid .filters tr').each(function(){\n var jq_tr = $(this);\n // Added _filter to address CSS collision with Bootstrap\n // Ref: https://github.com/level12/webgrid/issues/28\n var filter_key = jq_tr.attr('class').replace(new RegExp('_filter$'),'');\n if( filter_key != 'add-filter') {\n var op_select = jq_tr.find('.operator select');\n if( op_select.val() != '' ) {\n // filter should be active, so activate it\n datagrid_activate_filter(filter_key);\n } else {\n // the filter is not active, hide the row\n jq_tr.hide();\n }\n datagrid_toggle_filter_inputs(jq_tr);\n }\n });\n}", "function ensureFilteredComponent() {\n if (FilteredComponent === undefined) {\n FilteredComponent = Object(__WEBPACK_IMPORTED_MODULE_7__wordpress_hooks__[\"c\" /* applyFilters */])(hookName, OriginalComponent);\n }\n }", "onBetFiltersChange(filter) {\n\t\tthis.setState({searchToken: ''});\n\t\tmodel.filter = filter;\n\t}", "function updateListSensors() {\n\n // clean DOM\n var $mylistSensors = $(\"#list-captors\").empty();\n\n // if no filters are checked\n if( filters.length == 0 ){\n $.each( listSensors ,function(i) {\n\n // add sensor to DOM\n $mylistSensors.append(\n '<div class=\"draggableSensor\" id=\"' + listSensors[i].name + '\" style=\"cursor: -webkit-grab; cursor:-moz-grab;\">'\n + '<img class=\"sensorIcon\" src=\"/assets/images/sensorIcons/' + listSensors[i].kind + '.png\">'\n + listSensors[i].displayName\n + '</img> </div>'\n );\n\n });\n\n // if filters are checked\n }else{\n $.each( listSensors , function(i) {\n\n // if sensor category is in filters array\n if ( $.inArray(listSensors[i].category,filters) !== -1 ) {\n\n // add sensor to DOM\n $mylistSensors.append(\n '<div class=\"draggableSensor\" id=\"' + listSensors[i].name + '\" style=\"cursor: -webkit-grab; cursor:-moz-grab;\">'\n + '<img class=\"sensorIcon\" src=\"/assets/images/sensorIcons/' + listSensors[i].kind + '.png\">'\n + listSensors[i].displayName\n + '</img> </div>'\n );\n\n }\n });\n }\n\n // add sensors draggable\n $(\".draggableSensor\").draggable({\n helper: function (event) {\n return $(\"<div style='cursor:-webkit-grabbing; cursor:-moz-grabbing;' id='\" + event.currentTarget.id + \"'>\" + event.currentTarget.innerHTML + \"</div>\");\n },\n revert: \"invalid\",\n cursorAt: { bottom: 10, left: 60 }\n });\n\n // filter by value in the search input\n $( '#search' ).keyup();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close the comments section
function closeComments(){ document.getElementById('commentsOverlay').style.display = 'none'; }
[ "function closeCreateCommentMenu(){\n var createCommentMenu = document.getElementById( 'create-comment-body' );\n createCommentMenu.classList.add( 'closed' );\n clearInputs( \"comment\" );\n}", "closeFile() {\n\t\tthis.code.closeEditor(this.path);\n\t}", "close() {\n this.nodes.wrapper.classList.remove(BlockSettings.CSS.wrapperOpened);\n\n /** Clear settings */\n this.nodes.toolSettings.innerHTML = '';\n this.nodes.defaultSettings.innerHTML = '';\n\n /** Tell to subscribers that block settings is closed */\n this.Editor.Events.emit(this.events.closed);\n }", "static RemoveExceedComment()\r\n {\r\n const Max = Settings.MaxDisplayComment;\r\n if( Max > 0 )\r\n {\r\n while( $('#CommentArea #Body .Row').length > Max )\r\n {\r\n $('#ViewCommentArea #Body .Row:first-child').remove(); \r\n }\r\n }\r\n }", "close() {\n if(this.added) {\n this.added = false;\n this.getJQueryObject().remove();\n\n // Remove entry from global entries variable\n entries = _.omit(entries, this.id);\n\n GUI.onEntriesChange();\n GUI.updateWindowHeight();\n }\n }", "close() {\n return spPost(WebPartDefinition(this, \"CloseWebPart\"));\n }", "function collapseComments() {\n $('.commentarea .comment .child').hide();\n $('.tagline').append('<span class=\"expand-children\">[+]</span>');\n $('.tagline .expand-children')\n .css('cursor', 'pointer')\n .click(function() {\n toggleExpandButton(this);\n $(this).closest('.comment').find('.child').toggle();\n });\n loadImage();\n\n /**\n * Toggle expand button from + to -.\n *\n * @param {Element} el\n */\n\n function toggleExpandButton(el) {\n if (~$(el).text().indexOf('+'))\n $(el).text('[-]');\n else\n $(el).text('[+]');\n }\n}", "close() {\n\n // Pop the activity from the stack\n utils.popStackActivity();\n\n // Hide the disclaimer\n this.disclaimer.scrollTop(0).hide();\n\n // Hide the screen\n this.screen.scrollTop(0).hide();\n\n // Reset the fields\n $(\"#field--register-email\").val(\"\");\n $(\"#field--register-password\").val(\"\");\n $(\"#field--register-confirm-password\").val(\"\");\n\n // Reset the selectors\n utils.resetSelector(\"register-age\");\n utils.resetSelector(\"register-gender\");\n utils.resetSelector(\"register-occupation\");\n\n // Set the flag to false\n this._isDisclaimerOpen = false;\n\n }", "_cancelComment() {\n this._comment = '';\n this._displayFormActions = false;\n }", "function CloseArticleInfoWindow ()\n {\n CloseWindow ( wInfo );\n }", "function closeEditingWindow() {\n document.getElementById(\"fileEditing\").style.display = \"none\";\n document.getElementById(\"pageTitle\").childNodes[1].textContent = \"Files\";\n document.getElementById(\"fileBrowser\").style.display = \"block\";\n\n console.log(\"HUB: Closing editing tool\");\n}", "function handleWidgetClose(){\n confirmIfDirty(function(){\n if(WidgetBuilderApp.isValidationError)\n {\n WidgetBuilderApp.dirtyController.setDirty(true,\"Widget\",WidgetBuilderApp.saveOnDirty);\n return;\n }\n $(\".perc-widget-editing-container\").hide();\n $(\"#perc-widget-menu-buttons\").hide();\n $(\"#perc-widget-def-tabs\").tabs({disabled: [0,1,2, 3]});\n });\n }", "close()\r\n {\r\n var fs = require('fs');\r\n fs.appendFileSync(this.filePath, '</body>');\r\n fs.appendFileSync(this.filePath, '</html>');\r\n }", "endGroup() {\n this.macros.endGroup();\n }", "function bypassCommentBlock(){\n\tisCommenting=true; // set flag true if leave pg was a commenting action\n}", "function commentEdit(id) {\n var comment = jQuery('#comment-' + id);\n var content = comment.find('.comment-text');\n\n comment.find('.comment-edit').hide();\n\n var form = jQuery(template('template-comment-edit', {\n id: id,\n content: content.text()\n }))\n .find('.comment-edit-abort')\n .click(function(e) {\n e.preventDefault();\n comment.find('.comment-edit').show();\n jQuery(this).parents('form').replaceWith(content);\n })\n .end();\n\n content.replaceWith(form);\n}", "function removecommentsubtree( pid ) {\n\tvar myctrclass = \".descendent-of-\" + pid;\n\n\t$( myctrclass ).each( function () { removecommentsubtree( $(this).attr( \"id\" ) ); } )\n\t\t.remove();\n}", "close() {\n\t\tif( $('#gantt_container').css('bottom') != '-450px'){\n\t\t\t$('#not_gantt_container').addClass('full_height').removeClass('partial_height');\n\t\t\t$('#gantt_container').animate({bottom:'-450px'}, \"slow\", function() {\n\t\t\t\t$( '#gantt_button_text' ).addClass('rotate_0').removeClass('rotate_180');\n G.ganttManager.open = false;\n\t\t\t});\n\t\t\t$('#gantt_button').animate({bottom:'0px'}, \"slow\");\n\t\t}\n\t}", "function closeDepartment() {\n\tconsole.log(chalk.underline.red(\"\\nClose Department function under development\\n\"));\n\toverview();\n}", "function closeDoc() {\n for (let i = 0; i < appData.documents.length; i++) {\n if (appData.documents[i].id === appData.active) {\n appData.documents.splice(i, 1);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines a double value for the similarity of two pokemon based on aggregate shades. Should always be called after prepping the raw pokemon data.
function comparePokemon(p1, p2) { /*console.log(pokeData[p1]); console.log(p2); p1 = pokeData[p1].colors; p2 = pokeData[p2].colors;*/ //get the total pixels in the pokemon so we can work with percentages var p1Total = 0.0; var p2Total = 0.0; for (var i = 0; i < p1.length; i++) { p1Total += p1[i].count; } for (var i = 0; i < p2.length; i++) { p2Total += p2[i].count; } var result = 0.0; for (var i = 0; i < p1.length; i++) { for (var j = 0; j < p2.length; j++) { //result += getShades(p1[i].color, p2[j].color); //Average between the percentage make-ups of the two matching shades result += Math.sqrt(getShades(p1[i].color, p2[j].color)) * (((p1[i].count * 1.0) / p1Total + (p2[j].count * 1.0) / p2Total) / 2.0); } } return result; }
[ "wholePaintingCompare(data){\n let dataColorValues = dataParser(data);\n let matchPercent = 0;\n let matchTotals = 0;\n for (var i = 0; i < dataColorValues.length; i++) {\n let compareValue = this.singleColorCompare(dataColorValues[i].hex);\n if (compareValue != 0) {\n matchTotals++;\n }\n if (compareValue < dataColorValues[i].percent) {\n matchPercent += compareValue;\n } else {\n matchPercent += dataColorValues[i].percent\n }\n }\n return {\"percent\": matchPercent, \"total\": matchTotals};\n }", "function calculateSimilarityScore(dict1, dict2) {\n // Calculate vector norms\n var ss1 = 0.0;\n for (var i in dict1) {\n ss1 += dict1[i] * dict1[i];\n }\n ss1 = Math.sqrt(ss1);\n var ss2 = 0.0;\n for (var i in dict2) {\n ss2 += dict2[i] * dict2[i];\n }\n ss2 = Math.sqrt(ss2);\n // calculate dot product\n var dp = 0.0;\n for (var i in dict1) {\n if (i in dict2) {\n dp += (dict1[i] / ss1) * (dict2[i] / ss2);\n }\n }\n return 100 - Math.acos(dp) * 100 / Math.PI;\n}", "function triplespergame (player) {\n\treturn player.triples / player.games;\n}", "function scoresSpecial(a, b) {\n let c = findSpecial(a);\n let d = findSpecial(b);\n let e = a[c];\n let f = b[d];\n if (a[c] === undefined) e = 0 ;\n if (b[d] === undefined) f = 0 ;\n return e + f;\n}", "function compute_value () {\n var that = this;\n var flat_values = _.pluck(this.cards,'_value');\n var occurences = {};\n var new_cards = null;\n var hand_occurence_pattern = null;\n\n // Is flush\n var first_card_color = this.cards[0]._color;\n var is_flush = _.all(this.cards, function(card) { return first_card_color === card._color; });\n\n // Is a straight\n var top_value = this.cards[0]._value + 1;\n var is_straight = _.reduce(this.cards, function(ok, card){\n ok = ok && (1 === (top_value - card._value));\n top_value = card._value;\n return ok;\n }, true);\n\n if(is_flush || is_straight) {\n this._compareValues = flat_values;\n if(is_flush && is_straight) {\n this._handNature = hand_types.straightflush;\n }\n else if(is_flush) {\n this._handNature = hand_types.flush; \n }\n else {\n this._handNature = hand_types.straight;\n }\n }\n else {\n // Counting occurences of each value\n _.each(this.cards, function(card) {\n var value = card._value;\n //occurences[value] = occurences[value] ? 1 : occurences[value] + 1;\n if(_.has(occurences,value)) {\n ++(occurences[value].count);\n }\n else {\n occurences[value] = {val:value, count:1};\n }\n });\n\n // Get rid of the keys and sorts\n occurences = _.values(occurences);\n occurences.sort(function(elem1,elem2){ \n var on_count = -_ucengine_.compareInt(elem1.count, elem2.count);\n return (0 === on_count) ? -_ucengine_.compareInt(elem1.val, elem2.val) : on_count;\n });\n\n this._compareValues = _.pluck(occurences,'val');\n\n hand_occurence_pattern = _.pluck(occurences,'count');\n if(_.isEqual([4,1], hand_occurence_pattern)) {\n this._handNature = hand_types.square;\n }\n else if(_.isEqual([3,2], hand_occurence_pattern)) {\n this._handNature = hand_types.full;\n }\n else if(_.isEqual([3,1,1], hand_occurence_pattern)) {\n this._handNature = hand_types.trips;\n }\n else if(_.isEqual([2,2,1], hand_occurence_pattern)) {\n this._handNature = hand_types.twopairs;\n }\n else if(_.isEqual([2,1,1,1], hand_occurence_pattern)) {\n this._handNature = hand_types.pair;\n }\n else {\n this._handNature = hand_types.highcard;\n }\n\n // Re-sorting the cards\n if(hand_types.highcard != this._handNature) {\n new_cards = [];\n _.each(that._compareValues, function(value_to_top){\n _.each(that.cards, function(card){\n if(value_to_top === card._value) {\n new_cards.push(card);\n }\n });\n });\n\n this.cards = new_cards;\n }\n }\n\n // For any hand\n this._compareValues.unshift(this._handNature.value);\n }", "function calcHdcpDiff(gross, crsHcp, par) {\r\n\r\n//========================================================================================================\r\n\r\n var whichNine = 0,\r\n i = 0,\r\n j = 0,\r\n maxScore = 0,\r\n scores = {\r\n grossScore: [],\r\n adjGrossScore: []\r\n };\r\n\r\n scores.grossScore = gross;\r\n\r\n for (i = 18; i < 21; i += 1) {\r\n scores.grossScore[i] = 0;\r\n scores.adjGrossScore[i] = 0;\r\n }\r\n\r\n\r\n//========================================================================================================\r\n// Calculate hole max based on cours handicap. Low hcp max will be calculated by hole based on par.\r\n//========================================================================================================\r\n if (crsHcp >= 40) {\r\n maxScore = 10;\r\n } else if (crsHcp >= 30) {\r\n maxScore = 9;\r\n } else if (crsHcp >= 20) {\r\n maxScore = 8;\r\n } else if (crsHcp >= 10) {\r\n maxScore = 7;\r\n }\r\n\r\n\r\n//========================================================================================================\r\n// Calculate values for Front Nine, then for Back Nine.\r\n//========================================================================================================\r\n\r\n for (whichNine = 0; whichNine < 2; whichNine += 1) { /* process each nine in a separate pass */\r\n j = whichNine * 9;\r\n\r\n//========================================================================================================\r\n// Calculate adjusted scores for each hole on the current \"Nine\".\r\n//========================================================================================================\r\n\r\n for (i = 0; i < 9; i += 1) {\r\n if (crsHcp < 10) {\r\n maxScore = par[i] + 2; /* calculate low handicap max score */\r\n }\r\n scores.adjGrossScore[i + j] = Math.min(scores.grossScore[i + j], maxScore);\r\n\r\n//========================================================================================================\r\n// Calculate total gross and adj gross scores for current \"Nine\" [18]/[19] and overall round [20].\r\n//========================================================================================================\r\n\r\n scores.grossScore[18 + whichNine] += scores.grossScore[i + j];\r\n scores.adjGrossScore[18 + whichNine] += scores.adjGrossScore[i + j];\r\n scores.grossScore[20] += scores.grossScore[i + j];\r\n scores.adjGrossScore[20] += scores.adjGrossScore[i + j];\r\n }\r\n }\r\n\r\n return (scores);\r\n }", "function heuristicAverage(a, b)\n{ return (lineDistance(a, b) + TaxicabDistance(a, b))/ 2; }", "hueuristic() {\n // This hueristic is simply the distance to the goal\n return Math.sqrt(Math.pow(this.x - goal.x, 2) + Math.pow(this.y - goal.y, 2));\n }", "function analyze() {\n var highest = 0,\n lowest = 1000000000,\n averageQA = 0,\n averageAuton = 0,\n averageFouls = 0,\n totalNulls = 0,\n averagePlayoff = 0,\n totalPlayoffs = 0;\n\n for (var matchNum = 0; matchNum < matches.length; matchNum++) {\n\n var currentMatch = matches[matchNum];\n var currentMatchAlliances = currentMatch.alliances;\n var alliance = \"\";\n\n if (currentMatchAlliances.red.teams.indexOf(teamNumber) >= 0) {\n alliance = \"red\";\n } else {\n alliance = \"blue\";\n }\n\n if (currentMatchAlliances[alliance].score >= 0) {\n if (currentMatchAlliances[alliance].score > highest) {\n highest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatchAlliances[alliance].score < lowest) {\n lowest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatch.comp_level === 'qm') {\n averageQA += currentMatchAlliances[alliance].score;\n } else {\n averagePlayoff += currentMatchAlliances[alliance].score;\n totalPlayoffs++;\n }\n\n averageAuton += matches[matchNum].score_breakdown[alliance].atuo;\n\n averageFouls += matches[matchNum].score_breakdown[alliance].foul;\n\n } else {\n totalNulls++;\n }\n }\n\n if (totalPlayoffs !== 0) {\n averagePlayoff /= totalPlayoffs;\n }\n\n averageQA /= matches.length - totalNulls - totalPlayoffs;\n averageFouls /= matches.length - totalNulls;\n averageAuton /= matches.length - totalNulls;\n\n console.log('Analytics');\n console.log('Team Name: ' + teamName);\n console.log(\"Highest Number of points: \" + highest);\n console.log(\"Lowest Number of points: \" + lowest);\n console.log(\"Average QA: \" + averageQA);\n console.log(\"Average Playoff Points (If Applicable): \" + averagePlayoff);\n console.log(\"Average Auton points: \" + averageAuton);\n console.log(\"Average Foul points: \" + averageFouls);\n}", "function calcSimilarity(node1, node2) {\r\n\t\t\t\tvar calcedSimilarty = 0, weight = 0;\r\n\t\t\t\tfor (var calcF in calcFunctions)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar cf = calcFunctions[calcF];\r\n\t\t\t\t\tif (cf.weight > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcalcedSimilarty += cf.func(node1,node2);\r\n\t\t\t\t\t\tweight += cf.weight;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn calcedSimilarty/weight;\r\n\t\t\t}", "function calculateHousingServicesScore(housingServiceData, serviceField, serviceKeys){\n //Reset municipalColourKey for plotting\n for (var municipality in tempMunicContainer) {\n tempMunicContainer[municipality] = [0,0];\n }// for\n //Perform aggregation of various Household services\n for (var i = 0; i < housingServiceData.length; i++) {\n if (tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]] != undefined) {\n // Determine if given key matches service field\n if (serviceKeys.indexOf(housingServiceData[i][serviceField]) > -1) {\n tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]][0] = tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]][0] + housingServiceData[i]['Amount'];\n tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]][1] = tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]][1] + housingServiceData[i]['Amount'];\n } else {\n tempMunicContainer[keyToMunicipality[housingServiceData[i]['MunicipalityKey']]][1] += housingServiceData[i]['Amount'];\n }// else\n }// if tempMunicContainer != undefined\n }// for housingServiceData\n //Average all values\n for (municipality in municipalColourKey){\n municipalColourKey[municipality] = tempMunicContainer[municipality][0]/tempMunicContainer[municipality][1];\n if (municipalColourKey[municipality] == NaN) {\n municipalColourKey[municipality] = 0;\n }// if == NaN\n }//for municipality\n}// housingServiceData", "function calculateColorRarity(colonyData) {\n // pick the \"rarest\" 3 colors among these colonies\n // TODO: make this calculation use all colonies in the last X days\n // Use an object as a map to count how many times each color name appears.\n // Then transfer the counts to an array which we sort.\n // The least common colors will be at the top.\n var numberOfRarestColors = 3;\n\n // get the number of colonies\n var countAllColonies = colonyData.length;\n var stats = Visualizations.findOne({'id': 'stats'});\n if (stats && stats.coloniesCount) countAllColonies += stats.coloniesCount;\n\n // retrieve counts for colors of previous colonies and add colonyData\n var colorNamesMap = Visualizations.findOne({'id': 'colorCounts'}) || {};\n colonyData.forEach(function(colony, index) {\n if (colorNamesMap[colony.ColorName] === undefined)\n colorNamesMap[colony.ColorName] = 1;\n else\n colorNamesMap[colony.ColorName]++;\n });\n\n // Calculate the fraction of all colonies which are each color.\n // This includes the current colonyData, so each should have a defined count.\n colonyData.forEach(function(colony) {\n var count = colorNamesMap[colony.ColorName];\n colony.NumberOfColoniesThisColor = count;\n colony.Rarity = count / countAllColonies;\n });\n\n // sort ascending by count\n colonyData.sort(function(a, b) {\n return a.Rarity - b.Rarity;\n });\n\n // walk through the sorted colonies, and save the indices of max 3 unique colors\n var rareColorIndices = [];\n var numberToChoose = Math.min(colonyData.length, numberOfRarestColors);\n for (var i = 0; rareColorIndices.length < numberToChoose; i++) {\n // have we picked this color already?\n var seenColor = false;\n rareColorIndices.forEach(function(j) {\n if (colonyData[j].ColorName == colonyData[i].ColorName) seenColor = true;\n });\n if (seenColor == false) rareColorIndices.push(i);\n }\n\n // set the rarest 3 indices as an array in the db; also set the total number of colonies\n var set = {$set: {rareColorIndices:rareColorIndices, coloniesCountAtThisTime:countAllColonies}};\n WorkstationSessions.update(workstationSession, set);\n}", "function test_numeric_attribute(){\r\n\t\r\n\tconsole.log(\"test_numeric_attribute....\")\r\n\t\t\r\n\tvar myMap = new Map();\r\n\tmyMap.set(\"Numeric\", new Numeric(20.0, 0.0));\r\n\r\n\t//initialize\r\n\tvar numericSimilarityDistance = new SimilarityDistanceClass(myMap);\r\n\r\n\tvar data = [ {\"Numeric\": 5},\r\n\t\t\t\t {\"Numeric\": 2},\r\n\t\t\t\t {\"Numeric\": 5},\r\n\t\t\t\t {\"Numeric\": 8},\r\n\t\t\t\t {\"Numeric\": 9},\r\n\t\t\t\t {\"Numeric\": 20},\r\n\t\t\t\t {\"Numeric\": -1}\r\n\t\t\t\t ];\r\n\t\r\n\tvar similarity_0_1 = numericSimilarityDistance.compute(data[0], data[1]);\r\n\tvar similarity_0_2 = numericSimilarityDistance.compute(data[0], data[2]);\r\n\tvar similarity_0_3 = numericSimilarityDistance.compute(data[0], data[3]);\r\n\tvar similarity_0_4 = numericSimilarityDistance.compute(data[0], data[4]);\r\n\tvar similarity_0_5 = numericSimilarityDistance.compute(data[0], data[5]);\r\n\tvar similarity_0_6 = numericSimilarityDistance.compute(data[0], data[6]); //with missing value\r\n\tvar similarity_6_0 = numericSimilarityDistance.compute(data[6], data[0]); //with missing value\r\n\tvar similarity_6_6 = numericSimilarityDistance.compute(data[6], data[6]); //with missing value\r\n\t\r\n\r\n\t//check that 5 is identical to 5\r\n\tassert(similarity_0_2 == 1.0);\r\n\t\r\n\t//check that 2 is same similar to 5 with 8\r\n\tassert(similarity_0_1 == similarity_0_3);\r\n\t\r\n\t//check that 2 is more similar to 5 than 9\r\n\tassert(similarity_0_1 > similarity_0_4);\r\n\r\n\t//check that 9 is more similar to 5 than 20\r\n\tassert(similarity_0_4 > similarity_0_5);\r\n\t\r\n\t\r\n\t//two missing values are identical\r\n\tassert(similarity_6_6 == 1.0);\r\n\t\r\n\t//distance with missing value is symmetric\r\n\tassert(similarity_0_6 == similarity_6_0);\r\n\t\r\n\t//check that 2 is more similar than missing value\r\n\tassert(similarity_0_1 > similarity_0_6);\r\n\t\r\n\t//check that 9 is more similar than missing value\r\n\tassert(similarity_0_4 > similarity_0_6);\r\n\t\r\n\t//check that missing value is more similar than 20\r\n\tassert(similarity_0_6 > similarity_0_5);\r\n\t\r\n\tconsole.log(\"PASS\")\r\n}", "function test_mixed_attributes(){\r\n\t\r\n\tconsole.log(\"test_mixed_attributes....\")\r\n\r\n\tvar myMap = new Map();\r\n\tmyMap.set(\"Nominal\", new Nominal([\"0\",\"1\",\"2\", \"3\", \"4\"]));\r\n\tmyMap.set(\"Ordinal\", new Ordinal([\"0\",\"1\",\"2\",\"3\",\"4\"], 4, 0));\r\n\tmyMap.set(\"Numeric\", new Numeric(20.0, 0.0));\r\n\r\n\t//initialize\r\n\tvar similarityDist = new SimilarityDistanceClass(myMap);\r\n\r\n\tvar data = [ {\"Nominal\": \"1\", \"Ordinal\": \"1\", \"Numeric\": 5},\r\n\t\t\t\t {\"Nominal\": \"0\", \"Ordinal\": \"0\", \"Numeric\": 2},\r\n\t\t\t\t {\"Nominal\": \"1\", \"Ordinal\": \"1\", \"Numeric\": 5},\r\n\t\t\t\t {\"Nominal\": \"2\", \"Ordinal\": \"2\", \"Numeric\": 8},\r\n\t\t\t\t {\"Nominal\": \"3\", \"Ordinal\": \"3\", \"Numeric\": 9},\r\n\t\t\t\t {\"Nominal\": \"4\", \"Ordinal\": \"4\", \"Numeric\": 20}\r\n\t\t\t\t ];\r\n\t\r\n\tvar similarity_0_1 = similarityDist.compute(data[0], data[1]);\r\n\tvar similarity_0_2 = similarityDist.compute(data[0], data[2]);\r\n\tvar similarity_0_3 = similarityDist.compute(data[0], data[3]);\r\n\tvar similarity_0_4 = similarityDist.compute(data[0], data[4]);\r\n\tvar similarity_0_5 = similarityDist.compute(data[0], data[5]);\r\n\r\n\t//check that the first element is identical to second\r\n\tassert(similarity_0_2 == 1.0);\r\n\t\r\n\t//check that the first element and third one have the same similarity distance\r\n\tassert(similarity_0_1 == similarity_0_3);\r\n\t\r\n\t//check that the first element is more similar than the fourth one\r\n\tassert(similarity_0_1 > similarity_0_4);\r\n\r\n\t//check that the fourth element is more similar than the fifth\r\n\tassert(similarity_0_4 > similarity_0_5);\r\n\t\r\n\tconsole.log(\"PASS\")\r\n}", "get railScore() {\n var comfort = this.normalizedUserComfort;\n var efficiency = this.normalizedEfficiency;\n return weightedAverage2(comfort, efficiency, COMFORT_IMPORTANCE);\n }", "function calculate(Gold) {\n console.log(smallinMedium + \" \" + mediuminLarge);\n console.log(Gold);\n smallGold = Gold || {};\n smallGoldMath = Math.floor(smallGold / smallinMedium);\n smallGold %= smallinMedium;\n mediumGold = smallGoldMath;\n mediumGoldMath = Math.floor(mediumGold / mediuminLarge);\n mediumGold %= mediuminLarge;\n largeGold = mediumGoldMath;\n return smallGold\n return mediumGold\n return largeGold\n}", "static Distance(value1, value2) {\n return Math.sqrt(Vector3.DistanceSquared(value1, value2));\n }", "function getDamage(poke1, poke2){\n\tvar max = -1;\n\tfor(var i = 0; i < poke2.types.length; i++){\n\t\tvar time = 1;\n\t\tfor(var j = 0; j < poke1.dtables.length; j++){\t\t\n\t\t\tif (poke1.dtables[j].noDamage.indexOf(poke2.types[i]) != -1){\n\t\t\t\ttime *= 0;\n\t\t\t}\n\t\t\telse if (poke1.dtables[j].halfDamage.indexOf(poke2.types[i]) != -1){\n\t\t\t\ttime *= 0.5;\n\t\t\t}\n\t\t\telse if (poke1.dtables[j].doubleDamage.indexOf(poke2.types[i]) != -1){\n\t\t\t\ttime *= 2;\n\t\t\t}\n\t\t}\n\t\tif(time > max){\n\t\t\tmax = time;\n\t\t}\n\t}\n\treturn max;\n\n}", "static DistanceSquared(value1, value2) {\n const x = value1.x - value2.x;\n const y = value1.y - value2.y;\n return x * x + y * y;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sparkline generator with xscale information
function sparkline_xscale(type,selector,formater) { var sparkline = $(selector); var data = JSON.parse(sparkline.html()); var xscale = data.reduce(function(x,y,i){ var item = {}; item[i] = formater(y[0]); return $.extend(x,item) },{}); var values = data.map(function(x){return x[1]}); sparkline.sparkline(values, { type: 'line', width: '100%', height: '38px', lineColor: '#1a0dab', spotColor: '#FFFFFF', minSpotColor: '#DA4336', maxSpotColor: '#10a461', highlightSpotColor: '#1a0dab', tooltipFormat: '<span style="color: {{color}}">&#9679;</span> {{prefix}}{{x:label}} : {{y}}{{suffix}}</span>', tooltipValueLookups: { label: $.range_map(xscale) } }); }
[ "function sparkline_charts() {\r\n\t\t\t$('.sparklines').sparkline('html');\r\n\t\t}", "function initSparkline(el, values, opts) {\r\n el.sparkline(values, $.extend(sparkOpts, el.data()));\r\n }", "function _drawSequenceScale(paper, x, l, w, c, scaleColors)\n{\n var sequenceScaleY = c + 20;\n var i = 0; // loop variable\n\n paper.path(\"M\" + x + \" \" + (sequenceScaleY + 6) +\n \"L\" + x + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(l, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(l, w, l)) + \" \" + (sequenceScaleY + 6))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n\n // sequence scale minor ticks\n for (i = 50; i < l; i += 100) {\n paper.path(\"M\" + (x + scaleHoriz(i, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(i, w, l)) + \" \" + (sequenceScaleY + 2))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n }\n\n // sequence scale major ticks\n for (i = 0; i < l; i += 100) {\n paper.path(\"M\" + (x + scaleHoriz(i, w, l)) + \" \" + sequenceScaleY +\n \"L\" + (x + scaleHoriz(i, w, l)) + \" \" + (sequenceScaleY + 4))\n .attr({\"stroke\": scaleColors[0], \"stroke-width\": 1});\n }\n\n // sequence scale labels\n for (i = 0; i < l; i += 100) {\n if ((l < 1000) || ((i % 500) == 0)) {\n if (scaleHoriz(l - i, w, l) > 30) {\n paper.text(x + scaleHoriz(i, w, l), sequenceScaleY + 16, i)\n .attr({\"text-anchor\": \"middle\", \"fill\": scaleColors[1], \"font-size\": \"11px\", \"font-family\": \"sans-serif\"});\n }\n }\n }\n\n paper.text(x + scaleHoriz(l, w, l), sequenceScaleY + 16, l + \" aa\")\n .attr({\"text-anchor\": \"middle\", \"fill\": scaleColors[1], \"font-size\": \"11px\", \"font-family\": \"sans-serif\"});\n\n}", "static mxScale(it,s) { \r\n\t\tvar res = new mx4(); \t\t\r\n\t\tfor (var i=0; i<16; ++i) { res.M[i] = it.M[i] *s; }\r\n\t\treturn res; \r\n\t}", "xValues() {\n return this.data()\n .map(d => this.x()(d))\n .map(d => this.scaleX().transform(d));\n }", "function sparklineChartCtrl() {\n\n /**\n * Inline chart\n */\n var inlineData = [34, 43, 43, 35, 44, 32, 44, 52, 25];\n var inlineOptions = {\n type: 'line',\n lineColor: '#f04544',\n fillColor: '#e35b5a'\n };\n\n /**\n * Bar chart\n */\n var barSmallData = [5, 6, 7, 2, 0, -4, -2, 4];\n var barSmallOptions = {\n type: 'bar',\n barColor: '#e35b5a',\n negBarColor: '#c6c6c6'\n };\n\n /**\n * Pie chart\n */\n var smallPieData = [1, 1, 2];\n var smallPieOptions = {\n type: 'pie',\n sliceColors: ['#e35b5a', '#b3b3b3', '#e4f0fb']\n };\n\n /**\n * Long line chart\n */\n var longLineData = [34, 43, 43, 35, 44, 32, 15, 22, 46, 33, 86, 54, 73, 53, 12, 53, 23, 65, 23, 63, 53, 42, 34, 56, 76, 15, 54, 23, 44];\n var longLineOptions = {\n type: 'line',\n lineColor: '#e35b5a',\n fillColor: '#ffffff'\n };\n\n /**\n * Tristate chart\n */\n var tristateData = [1, 1, 0, 1, -1, -1, 1, -1, 0, 0, 1, 1];\n var tristateOptions = {\n type: 'tristate',\n posBarColor: '#e35b5a',\n negBarColor: '#bfbfbf'\n };\n\n /**\n * Discrate chart\n */\n var discreteData = [4, 6, 7, 7, 4, 3, 2, 1, 4, 4, 5, 6, 3, 4, 5, 8, 7, 6, 9, 3, 2, 4, 1, 5, 6, 4, 3, 7, ];\n var discreteOptions = {\n type: 'discrete',\n lineColor: '#e35b5a'\n };\n\n /**\n * Pie chart\n */\n var pieCustomData = [52, 12, 44];\n var pieCustomOptions = {\n type: 'pie',\n height: '150px',\n sliceColors: ['#e35b5a', '#b3b3b3', '#e4f0fb']\n };\n\n /**\n * Bar chart\n */\n var barCustomData = [5, 6, 7, 2, 0, 4, 2, 4, 5, 7, 2, 4, 12, 14, 4, 2, 14, 12, 7];\n var barCustomOptions = {\n type: 'bar',\n barWidth: 8,\n height: '150px',\n barColor: '#e35b5a',\n negBarColor: '#c6c6c6'\n };\n\n /**\n * Line chart\n */\n var lineCustomData = [34, 43, 43, 35, 44, 32, 15, 22, 46, 33, 86, 54, 73, 53, 12, 53, 23, 65, 23, 63, 53, 42, 34, 56, 76, 15, 54, 23, 44];\n var lineCustomOptions = {\n type: 'line',\n lineWidth: 1,\n height: '150px',\n lineColor: '#e35b5a',\n fillColor: '#ffffff'\n };\n\n\n /**\n * Definition of variables\n * Flot chart\n */\n this.inlineData = inlineData;\n this.inlineOptions = inlineOptions;\n this.barSmallData = barSmallData;\n this.barSmallOptions = barSmallOptions;\n this.pieSmallData = smallPieData;\n this.pieSmallOptions = smallPieOptions;\n this.discreteData = discreteData;\n this.discreteOptions = discreteOptions;\n this.longLineData = longLineData;\n this.longLineOptions = longLineOptions;\n this.tristateData = tristateData;\n this.tristateOptions = tristateOptions;\n this.pieCustomData = pieCustomData;\n this.pieCustomOptions = pieCustomOptions;\n this.barCustomData = barCustomData;\n this.barCustomOptions = barCustomOptions;\n this.lineCustomData = lineCustomData;\n this.lineCustomOptions = lineCustomOptions;\n}", "function create_scales(){\n //Initializes the axis domains for the big chart\n x.domain(d3.extent(data.map(function(d){return new Date(d.TIMESTAMP)})));\n y.domain(d3.extent(data.map(function(d){return +d[areaYparameter]})));\n //Initializes the axis domains for the small chart\n x2.domain(x.domain());\n y2.domain(y.domain());\n }", "function calculateXScaleAndValuesShown() {\n var zoomPointDistanceFromGraphLeftEdge = zoomX - leftMargin;\n var leftPortion = zoomPointDistanceFromGraphLeftEdge / graphWidth;\n var rightPortion = 1 - leftPortion;\n \n var measurementIndex = convertXToMeasurementIndex(zoomX);\n var nrOfMeasurementsToInclude = Math.round(signal.getMeasurements().length / zoomLevel);\n var leftIndex, rightIndex;\n var lastIndex = signal.getMeasurements().length - 1;\n var nrOfMeasurementsOnTheLeft = Math.round(leftPortion * nrOfMeasurementsToInclude);\n var nrOfMeasurementsOnTheRight = Math.round(rightPortion * nrOfMeasurementsToInclude);\n\n \n if (measurementIndex - nrOfMeasurementsOnTheLeft < 0) {\n leftIndex = 0;\n rightIndex = nrOfMeasurementsToInclude - 1;\n } else if (measurementIndex + nrOfMeasurementsOnTheRight > lastIndex) { \n rightIndex = lastIndex;\n leftIndex = lastIndex - (nrOfMeasurementsToInclude - 1);\n } else {\n leftIndex = measurementIndex - nrOfMeasurementsOnTheLeft;\n rightIndex = measurementIndex + nrOfMeasurementsOnTheRight;\n }\n \n xLeftMost = {measurementIndex: leftIndex, value: signal.getMeasurements()[leftIndex].time};\n xRightMost = {measurementIndex: rightIndex, value: signal.getMeasurements()[rightIndex].time};\n xScale = graphWidth / (xRightMost.value - xLeftMost.value);\n xTranslation = -xScale * xLeftMost.value + leftMargin;\n }", "static xAxis() { return newVec(1.0,0.0,0.0); }", "function createScreePlot(information, defaultXValue) { \r\n console.log(information);\r\n data = information[\"graph\"];\r\n \r\n // remove existing elements\r\n $(\"#graphRender\").empty();\r\n\r\n // set the dimensions and margins of the graph\r\n var margin = {top: 20, right: 20, bottom: 30, left: 40},\r\n width = 900 - margin.left - margin.right,\r\n height = 700 - margin.top - margin.bottom;\r\n\r\n // set the ranges\r\n var x = d3.scaleBand()\r\n .range([0, width])\r\n .padding(0.1);\r\n var y = d3.scaleLinear()\r\n .range([height, 0]).nice();\r\n\r\n // var x = d3.scale.ordinal().rangeBands([0, width], .09); // <-- to change the width of the columns, change the .09 at the end to whatever\r\n // var y = d3.scale.linear().range([height, 0]);\r\n\r\n // set the ranges\r\n // var x = d3.scaleTime().range([0, width]);\r\n // var y = d3.scaleLinear().range([height, 0]);\r\n\r\n var valueline = d3.line()\r\n .x(function(d) { return x(d.principalComponent); })\r\n .y(function(d) { return y(d.cumulativeSum); });\r\n\r\n var valuelineX75 = d3.line()\r\n .x(function(d) { return (defaultXValue); })\r\n .y(function(d) { return y(d.x75); });\r\n\r\n var valuelineY75 = d3.line()\r\n .x(function(d) { return (d.y75); })\r\n .y(function(d) { return y(75); });\r\n \r\n // append the svg object to the body of the page\r\n // append a 'group' element to 'svg'\r\n // moves the 'group' element to the top left margin\r\n var svg = d3.select(\"#graphRender\").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\r\n // Scale the range of the data in the domains\r\n x.domain(data.map(function(d) { return d.principalComponent; }));\r\n y.domain([0, d3.max(data, function(d) { return d.cumulativeSum; })]);\r\n\r\n // // Scale the range of the data\r\n // x.domain(d3.extent(data, function(d) { return d.principalComponent; }));\r\n // y.domain([0, d3.max(data, function(d) { return d.eigenValuePercentage; })]);\r\n\r\n // append the rectangles for the bar chart\r\n svg.selectAll(\".bar\")\r\n .data(data)\r\n .enter().append(\"rect\")\r\n .attr(\"class\", \"bar\")\r\n .attr(\"x\", function(d) { return x(d.principalComponent); })\r\n .attr(\"width\", x.bandwidth())\r\n .attr(\"y\", function(d) { return y(d.eigenValuePercentage); })\r\n .attr(\"height\", function(d) { return height - y(d.eigenValuePercentage); });\r\n\r\n // Add the valueline path.\r\n svg.append(\"path\")\r\n .data([data])\r\n .attr(\"class\", \"line\")\r\n .attr(\"d\", valueline);\r\n\r\n // Add the valuelineX75 path.\r\n svg.append(\"path\")\r\n .data([data])\r\n .attr(\"class\", \"line redLine\")\r\n .attr(\"stroke\", \"red\")\r\n .attr(\"d\", valuelineX75);\r\n\r\n // Add the valuelineY75 path.\r\n svg.append(\"path\")\r\n .data([data])\r\n .attr(\"stroke\", \"red\")\r\n .attr(\"class\", \"line redLine\")\r\n .attr(\"d\", valuelineY75);\r\n\r\n // add the x Axis\r\n svg.append(\"g\")\r\n .attr(\"transform\", \"translate(0,\" + height + \")\")\r\n .call(d3.axisBottom(x));\r\n\r\n // text label for the x axis\r\n svg.append(\"text\") \r\n .attr(\"transform\",\r\n \"translate(\" + (width/2) + \" ,\" + \r\n (height + margin.top + 10) + \")\")\r\n .style(\"text-anchor\", \"middle\")\r\n .text(\"Principal Component\")\r\n .attr(\"font-family\", \"sans-serif\")\r\n .attr(\"font-size\", \"90%\"); \r\n\r\n // add the y Axis\r\n svg.append(\"g\")\r\n .call(d3.axisLeft(y)\r\n .tickValues(d3.range(0, 110, 10)));\r\n\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))\r\n .attr(\"x\",0 - (height / 2))\r\n .attr(\"dy\", \"1em\")\r\n .style(\"text-anchor\", \"middle\")\r\n .text(\"Explained Varience\")\r\n .attr(\"font-family\", \"sans-serif\")\r\n .attr(\"font-size\", \"90%\"); \r\n \r\n // Add Legend\r\n var legend = [{\"color\" : \"#69b3a2\", \"label\" : \"Eigen Value Percentage\"}, {\"color\" : \"steelblue\", \"label\" : \"Cumulative Sum\"}, {\"color\" : \"#b7d8d6\", \"label\" : \"Possible Threshold 75% of data varience\"}];\r\n\r\n var margin = 10;\r\n\r\n svg.selectAll(\"g.legend\").data(legend).enter().append(\"g\")\r\n .attr(\"class\", \"legend\").attr(\"transform\", function(d,i) {\r\n return \"translate(\" + margin + \",\" + (margin + i*20) + \")\";\r\n }).each(function(d, i) {\r\n d3.select(this).append(\"rect\").attr(\"width\", 30).attr(\"height\", 15)\r\n .attr(\"fill\", d.color);\r\n d3.select(this).append(\"text\").attr(\"text-anchor\", \"start\")\r\n .attr(\"x\", 30+10).attr(\"y\", 15/2).attr(\"dy\", \"0.35em\")\r\n .text(d.label);\r\n });\r\n}", "function SVGStackedRowChart() {\n}", "function hLine(i){\n var x1 = scaleUp(0);\n var x2 = scaleUp(boardSize - 1);\n var y = scaleUp(i); \n drawLine(x1, x2, y, y);\n //alert(\"i:\" + i+ \" x1:\"+x1+ \" x2:\"+x2+\" y1:\"+y+ \" y2:\"+y);\n }", "static scale(v) {\r\n\t\tres = identity(); \t\tres.M[0] = v.x; \r\n\t\tres.M[5] = v.y; \t\tres.M[10] = v.z; \r\n\t\treturn res; \r\n\t}", "function scatterPlotMatrix(a, dataType){\n // if(activeSvg ==1){\n // //checks if there is already a graph, and removes it\n // d3.select(\"svg\").remove();\n // }\n // activeSvg = 1;\n\n var tempA = JSON.parse(a);\n\n //get the data and put it into the right format\n var data;\n var tempData = new Array([]);\n var temp1 = [];\n var temp2 =[];\n var temp3 = [];\n\n if(dataType==\"rand\"){\n data = tempA.rand3LoadData;\n attributeNames = tempA.rand3AttrNames;\n bigData = tempA.bigRand3Array;\n } else if(dataType==\"strat\"){\n data = tempA.strat3LoadData;\n attributeNames = tempA.strat3AttrNames;\n bigData = tempA.bigStrat3Array;\n } else{\n data = tempA.org3LoadData;\n attributeNames = tempA.org3AttrNames;\n bigData = tempA.bigOrg3Array;\n }\n for(var i=0;i<data.length;i++){\n var superTempArray = [];\n for(var j=0;j<3;j++){\n superTempArray[j] = data[i][j];\n //tempData[i][j] = data[i][j];\n }\n tempData[i]= superTempArray;\n }\n for (var i=0; i<data.length;i++){\n //in order to get a column of features\n temp1[i] = tempData[i][0]\n temp2[i]= tempData[i][1]\n temp3[i] = tempData[i][2]\n }\n\n //standart parameters\n n = 3;\n var size = 230,\n padding = 60;\n\n var padDiv2 = padding/2;\n var sizeMinPadDiv2 = size - (padding/2);\n var sizeTnPlusPad = (size*n)+padding;\n\n //scales\n var yScale = d3.scaleLinear()\n .range([sizeMinPadDiv2, padDiv2]);\n\n var xScale = d3.scaleLinear()\n .range([padDiv2, sizeMinPadDiv2]);\n\n var yAxis = d3.axisLeft()\n .ticks(6)\n .tickFormat(d3.format(\"d\"))\n .scale(yScale)\n .tickSize(-size*n)\n ;\n var xAxis = d3.axisBottom()\n .ticks(6)\n .tickFormat(d3.format(\"d\"))\n .scale(xScale)\n .tickSize(size*n)\n ;\n\n \n var colors = [\"FA8D62\",\"#7D26CD\",\"#42C0FB\", \"E6D72A\"];\n var ftrNames = Object.keys(attributeNames);\n // console.log(\"ftr Names \" + ftrNames)\n var ftrs = [temp1, temp2,temp3]\n\n\n //gives domain for each attribute\n var domainByFtr ={};\n ftrNames.forEach(function(ftr) {\n var tempHere = d3.values(tempData[ftr])\n domainByFtr[ftr] = d3.extent(tempHere);\n })\n ;\n\n //create instance of svg\n var svg = d3.select(\"#scatterPlotMatrix\").append(\"svg\")\n .attr(\"x\", 70)\n .attr(\"height\", sizeTnPlusPad)\n .attr(\"width\", sizeTnPlusPad)\n .attr('id', 'svg')\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + padding + \",\" + padDiv2+ \")\")\n ;\n\n //create instance of x axis\n svg.selectAll(\".x.axis\")\n .data(ftrNames)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", function(d,i){return \"translate(\" + ((-1-d+n)*size) + \",0)\";})\n .each(function(d,i) { \n xScale\n .domain(domainByFtr[d]); \n d3.select(this)\n .call(xAxis); \n });\n\n //labels the x axis by attribute names\n for(var i=0; i<3; i++){\n var xAxisLabel = svg.append(\"text\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"font-family\", \"Courier\")\n .style(\"font-size\", \"20px\")\n .attr(\"transform\", \"translate(\" + ((size/2)+(size*i)) +\",\"+ (0) + \")\" )\n .text(attributeNames[2-i]);\n }\n\n //creates an instance of the y axis\n svg.selectAll(\".y.axis\")\n .data(ftrNames)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"y axis\")\n .attr(\"transform\", function(d,i) { return \"translate(0,\" + (i * size) + \")\"; })\n .each(function(d,i) { \n yScale\n .domain(domainByFtr[d]); \n d3.select(this)\n .call(yAxis)\n });\n \n //labels the y axis\n for(var i=0; i<3; i++){\n var yAxisLabel = svg.append(\"text\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"font-family\", \"Courier\")\n .style(\"font-size\", \"20px\")\n .attr(\"transform\", \"translate(\" + (-padding/2) +\",\"+ ((size/2)+(size*i)) + \")rotate(-90)\" )\n .text(attributeNames[i]);\n }\n\n //brings object to front\n d3.selection.prototype.move2Front = function() {\n return this.each(function(){\n this.parentNode.appendChild(this);\n });\n };\n var tempCross = cross(ftrs, ftrs);\n //create an instance of a cell\n var cell = svg.selectAll(\".cell\")\n .data(tempCross)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"cell\")\n .attr(\"transform\", function(d) { return \"translate(\" + (n - d.i - 1) * size + \",\" + d.j * size + \")\"; })\n .each(plot)\n ;\n\n //in order to plot each cell and data associated with cell\n function plot(p){\n var cell = d3.select(this);\n\n //sets the x and y domain of each corresponding cell\n xScale.domain([d3.min(p.x),d3.max(p.x)]);\n yScale.domain([d3.min(p.y),d3.max(p.y)]);\n\n //creates the instance of the cell\n cell.append(\"rect\")\n .attr(\"class\", \"frame\")\n .attr(\"y\", padDiv2)\n .attr(\"x\", padDiv2)\n .attr(\"height\", size - padding)\n .attr(\"width\", size - padding)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"black\");\n\n //just so that I go through the appropriate amount of data points\n var arrayForIndex = new Array(data.length)\n\n cell.selectAll(\"circle\")\n .data(arrayForIndex)\n .enter()\n .append(\"circle\")\n .attr(\"cx\", function(d,i) { \n return xScale(p.x[i]); })\n .attr(\"cy\", function(d,i) { \n return yScale(p.y[i]); \n })\n .attr(\"r\", 3)\n .style(\"fill\",function(d,i){\n if(data[i][3]!=2){\n d3.select(this).move2Front();\n }\n return colors[data[i][3]]})\n .on(\"mouseover\", function(d,i){\n d3.select(this).style(\"fill\", \"red\");\n })\n .on(\"mouseout\", function(d,i){\n d3.select(this).style(\"fill\", colors[data[i][3]]);\n });\n }\n //for title\n document.getElementById(\"t1\").style.color = \"#4682b4\";\n document.getElementById(\"t1\").style.textDecoration = \"underline\";\n if(dataType==\"org\"){\n document.getElementById(\"t1\").value = \"Scatter Plot Matrix\";\n } else if(dataType==\"rand\"){\n document.getElementById(\"t1\").value = \"Random Data Scatter Plot Matrix\";\n } else if (dataType==\"strat\"){\n document.getElementById(\"t1\").value = \"Stratified Data Scatter Plot Matrix\";\n }\n document.getElementById(\"topnav\").style.width =\"1350px\";\n document.getElementById(\"topnav\").style.transform = \"translate(\" + (-10) + \"px,\" + (-8) + \"px)\";\n document.getElementById(\"topnav\").style.height =\"41px\";\n // document.getElementById(\"topnav\").style.transform = \"translate(\" + (-10) + \"px,\" + (-428) + \"px)\";\n\n document.getElementById(\"scatterPlotMatrix\").style.transform = \"translate(\" + (-100) + \"px,\" + (-130) + \"px)\";\n document.getElementById(\"t1\").style.transform =\"translate(\" + (0) + \"px,\" + (-110) + \"px)\";\n}", "function createXAxis() {\n $(element + \" .xAxis\").css({\n \"grid-area\": \"3/3/4/4\",\n display: \"grid\",\n \"grid-template-columns\": \"repeat(\" + lenData + \",1fr)\",\n \"grid-template-rows\": \"1fr\",\n \"grid-column-gap\": defaultOptions.barSpacing,\n \"padding-left\": \"10px\",\n \"padding-right\": \"10px\",\n });\n\n $(element + \" .xAxis\").append(function () {\n let result = \"\";\n for (let i = 0; i < lenData; i++) {\n result += `<div class=\"xAxisLabel-${i}\">${defaultOptions.xAxisLabels[i]}</div>`;\n }\n\n return result;\n });\n\n //css for xAxis label divs\n for (let i = 0; i < lenData; i++) {\n let xAxisLabel = element + \" .xAxisLabel-\" + i;\n\n $(xAxisLabel).css({\n display: \"flex\",\n \"align-items\": \"center\",\n \"justify-content\": \"center\",\n \"font-family\": defaultOptions.xAxisLabelFont,\n \"font-size\": defaultOptions.xAxisLabelFontSize,\n });\n }\n }", "function scaleMatrix(sx,sy,sz) { // identidade\n return [\n [sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]\n ]; //retorna matriz 4x4\n}", "function GeneratePoints() {\n // Generate and push points to points[] for rose\n // Your code goes here:\n var x, y;\n var point1 = 0.15;\n var j = 3;\n var start = vec2(0,0)\n\n points.push(start)\n\n for (let i = 0; i<RosePoints; i++) {\n x = point1*Math.cos(j*i*Math.PI/180)*Math.cos(i*Math.PI/180)\n y = point1*Math.cos(j*i*Math.PI/180)*Math.sin(i*Math.PI/180)\n let rose = scale(0.7,vec2(x,y))\n points.push(rose)\n }\n \n // Generate and push 1500 points to points[] for spiral\n\n var point2 = 0.04;\n\n for (let i=0; i<SpiralPoints; i++) {\n x = point2*i*Math.cos(i*Math.PI/180)\n y = point2*i*Math.sin(i*Math.PI/180)\n let spiral = scale(0.015,vec2(x,y))\n points.push(spiral)\n }\n\n}", "function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}", "function drawLinePrice() {\n\t\t\tlet svgHeight = 500;\n\n\t\t\tvar margin = {top: 10, right: 20, bottom: 50, left: 60}\n\t\t\t , width = svgWidth - margin.left - margin.right // Use the window's width \n\t\t\t , height = svgHeight - margin.top - margin.bottom;\n\n\t\t\tlet svg = d3.select(\"svg#line-price\")\n\t\t\t\t\t\t\t.attr(\"width\", svgWidth)\n\t\t\t\t\t\t\t.attr(\"height\", svgHeight)\n\t\t\t\t\t\t\t.attr(\"viewBox\", \"0 0 \" + svgWidth + \" \" + svgHeight);\n\n\t\t\tvar g = svg.append(\"g\")\n\t\t\t\t\t.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\t\t\tlet values = [];\n\n\t\t\tfor (let i = 2015; i < 2021; i++) {\n\t\t\t\tvalues.push({\n\t\t\t\t\tdate: i,\n\t\t\t\t\tvalue: price[i]\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet xScale = d3.scaleBand().range([0, width]);\n\n\t\t\txScale.domain(values.map(function(d) {\n\t\t\t\treturn d[\"date\"];\n\t\t\t}));\n\n\t\t\tlet yScale = d3.scaleLinear().range([height, 0]);\n\n\t\t\tyScale.domain([d3.min(values, function(d) { return d.value; }), d3.max(values, function(d) { return d.value; })]);\n\n\t\t\tvar line = d3.line()\n\t\t\t\t.x(function(d) { return xScale(d.date); }) // set the x values for the line generator\n\t\t\t\t.y(function(d) { return yScale(d.value); }) // set the y values for the line generator\n\n\t\t\tlet xAxis = g.append(\"g\")\n\t\t\t\t.attr(\"transform\", \"translate(0,\" + height + \")\")\n\t\t\t\t.call(d3.axisBottom(xScale))\n\t\t\t\t.attr(\"class\", \"x-axis\")\n\t\t\t\t.append(\"text\")\n\t\t\t\t.attr(\"class\", \"label\")\n\t\t\t\t.attr(\"y\", 40)\n\t\t\t\t.attr(\"x\", width)\n\t\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t\t.text(\"Year\");\n\n\t\t\tlet yAxis = g.append(\"g\")\n\t\t\t\t.call(d3.axisLeft(yScale).tickFormat(function(d){\n\t\t\t\t\tif (d >= 1000000) {\n\t\t\t\t\t\treturn d / 1000000 + \"M\";\n\t\t\t\t\t} else if (d >= 1000) {\n\t\t\t\t\t\treturn d / 1000 + \"K\";\n\t\t\t\t\t} else if (d < 1000) {\n\t\t\t\t\t\treturn d;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.ticks(10))\n\t\t\t\t.attr(\"class\", \"y-axis\")\n\t\t\t\t.append(\"text\")\n\t\t\t\t.attr(\"transform\", \"rotate(-90)\")\n\t\t\t\t.attr(\"y\", -50)\n\t\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t\t.attr(\"class\", \"label\")\n\t\t\t\t.text(\"Average Home Price\");\n\n\t\t\tg.append(\"path\")\n\t\t\t\t.datum(values) // 10. Binds data to the line \n\t\t\t\t.attr(\"class\", \"line\") // Assign a class for styling \n\t\t\t\t.attr('fill', 'none')\n\t\t\t\t.attr('stroke', colorMain)\n\t\t\t\t.attr('stroke-width', 1.5)\n\t\t\t\t.attr('d', line);\n\n\t\t\td3.select(\"div.line-price\").style(\"display\", \"none\");\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if this video has an equal video in a Videos array
in(videos) { if(Array.isArray(videos)) { for(let video of videos) { if(this.equals(video)) { return true; } } } return false; }
[ "equals(video) {\n if(video && video instanceof Video && video.id === this.id) {\n return true;\n }\n return false;\n }", "function checkDupeVideo(videoId)\n {\n for (var i = 0; i < videoList.length; i++)\n {\n if (videoId == videoList[i].id)\n {\n sendServerMsgUser(\"Video is already on playlist\");\n return true;\n }\n }\n return false;\n }", "function compareArrays() {\n\n for (var i = 0; i < game.player.length; i++) {\n if (game.player[i] !== game.turns[i]) {\n var result = false;\n } else if (game.player[i] === game.turns[i]) {\n result = true;\n }\n }\n return result;\n }", "function channelHasVideo(videoTitle, channel) {\n let found = false;\n channel.videos.forEach((vid) => {\n if (vid.title.toLowerCase() === videoTitle.toLowerCase()) found = true;\n });\n return found;\n\n // Alternative Solution:\n // return channel.videos.some(\n // (video) => video.title.toLowerCase() === videoTitle.toLowerCase()\n // );\n}", "function allVideoIdsReady() {\n if (!useVideoJs()) {\n return (nrOfPlayersReady == videoIds.length); // TODO\n } else {\n for (var i = 0; i < videoIds.length; ++i) {\n if (!videoIdsReady[videoIds[i]]) {\n return false;\n }\n }\n return true;\n }\n }", "function checkIfNewVideoEvent(videoEvent) {\n if (videoEvent.timestamp !== _mostRecentVideoEventTime) {\n return true;\n } else {\n return false;\n }\n}", "function checkWatchedVideos(title_content, image_url, video_url) {\n recently_watched_videos = JSON.parse(localStorage.getItem('watchedVideosArray'));\n\n if (recently_watched_videos.length == 0) {\n // ADD FIRST VIDEO TO JSON\n pushVideosToWatchedList(title_content, image_url, video_url);\n } else {\n // ADD MORE VIDEO TO JSON\n var isExistInWatched = false;\n var watchedVideoIndex = 0;\n $.each(recently_watched_videos, function(ind, obj_val) {\n watchedVideoIndex = ind + 1;\n if (obj_val.title === title_content && obj_val.image === image_url && obj_val.video === video_url) {\n isExistInWatched = true;\n console.log(\"Index number = \" + ind);\n recently_watched_videos.splice(ind, 1);\n }\n if (recently_watched_videos.length === watchedVideoIndex) {\n pushVideosToWatchedList(title_content, image_url, video_url);\n }\n });\n }\n}", "function gotSomethingDifferent(){\n if (prevDetections.length != detections.length){\n return true;\n }\n var prev = getCountedObjects(prevDetections);\n var curr = getCountedObjects(detections);\n for (var k in curr){\n if (curr[k] !== prev[k]){\n return true;\n }\n }\n for (var k in prev){\n if (prev[k] !== curr[k]){\n return true;\n }\n }\n return false;\n}", "function findMovie(movie) {\n for (var i = 0; i < movieQueue.length; i++) {\n if (movieQueue[i] === movie) {\n return true;\n }\n }\n return false;\n}", "isVideoTrack() {\n return this.getType() === MediaType.VIDEO;\n }", "function allVideoIdsInitialized() {\n if (!useVideoJs()) {\n return (nrOfPlayersReady == videoIds.length);\n } else {\n for (var i = 0; i < videoIds.length; ++i) {\n if (!videoIdsInit[videoIds[i]]) {\n return false;\n }\n }\n return true;\n }\n }", "hasIdenticalEndPoints(tileArr1,tileArr2){\n return (tileArr1.filter(endPoint=>{\n return tileArr2.indexOf(endPoint)!=-1;\n }).length>0);\n }", "function arrayOfObjectsEquals(a, b) {\n\n if (a === null || b === null) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n\n a.sort();\n b.sort();\n\n\n for (var i = 0; i < a.length; ++i) {\n if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) {\n return false;\n }\n }\n\n return true;\n}", "function isEqual(){\n let equality = true\n if (!Object.keys(prevOpts).length){\n equality = false\n } else {\n for (let pkey in prevOpts){\n // console.log(`pkey is ${pkey}`)\n if (pkey in opts){\n if (!isArrEqual(prevOpts[pkey], opts[pkey])){\n equality = false\n break\n }\n } else {\n equality = false\n break\n }\n }\n }\n\n if (equality){ loopCount += 1 }\n // console.log(prevOpts)\n // console.log(opts)\n // console.log(loop)\n // console.log(equality)\n return equality\n}", "function movieExistsById(movieList, id){\r\n\r\n for(let i = 0; i < movieList.length; i++){\r\n if (movieList[i].id === id) {\r\n return true\r\n }\r\n }\r\n\r\n return false\r\n}", "isSynced(syncVideoTime){\n this.log(\"isSynced: this.video.currentTime \"+ this.video.currentTime);\n this.log('isSynced: videoTime ' + syncVideoTime);\n return Math.abs(this.getTimeDiff(syncVideoTime)) <= this.syncWindowMS / 1000;\n }", "function checkColl(x, y, array){\n\t\t\tfor(var i = 0; i < array.length; i++){\n\t\t\t\tif(array[i].x == x && array[i].y == y){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}", "equals(matrix) {\n //check if same size\n if (this.height() === matrix.height() && this.width() === matrix.width()) {\n //check each element\n let flag = true;\n for (let i = 0; i < this.height(); i++)\n for (let j = 0; j < this.height(); j++) {\n if (this.get(i, j) !== matrix.get(i, j)) {\n flag = false;\n break;\n }\n }\n return flag;\n }\n return false;\n }", "equals(grid) {\n if (this.height !== grid.height) { return false; }\n if (this.width !== grid.width) { return false; }\n\n let ans = true;\n for (let r = 0; r < this.height; r++) {\n for (let c = 0; c < this.width; c++) {\n if (this.get(r,c) !== grid.get(r,c)) { ans = false; }\n }\n }\n return ans;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is for Group Name text box validation text box accept alphanumeric,space and period first char should not be special char and numeric single space or single period accepted between two word not end with special character
function groupNameValidation(e) { var ret var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode; if (document.getElementById('groupId').value.length == 0) { ret = ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys .indexOf(e.keyCode) != -1 && e.charCode != e.keyCode)); } else if ((preLocVal == 32 || preLocVal == 46) && (keyCode == 32 || keyCode == 46)) { ret = false; } else { ret = ((keyCode == 32) || (keyCode == 46) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (keyCode >= 48 && keyCode <= 57)|| (specialKeys .indexOf(e.keyCode) != -1 && e.charCode != e.keyCode)); preLocVal = keyCode } document.getElementById("error1").style.display = ret ? "none" : "inline"; return ret; }
[ "function groupNameValid(name) {\n return (typeof name === \"string\" && name.length <= 50 && name.length > 2)\n}", "function ValidNameField(sender) {\n var id = $(sender).attr('id');\n var nameField = $('#' + id).val();\n var regexpp = /^[a-zA-Z][a-zA-ZéüöóêåÁÅÉá .´'`-]*$/\n var Exp = /^[0-9]+$/;\n\n if (nameField.length > 0) {\n if (nameField.trim() == '')\n return false\n else {\n if (Exp.test(nameField.trim()))\n return false\n else\n return regexpp.test(nameField)\n }\n } else\n return true;\n}", "function nameValidate(name) {\r\n var nameValue = document.getElementById('contact-name').value;\r\n var nameRegex = /^[a-zA-Z \\-\\']+(?:\\s[a-zA-Z]+)*$/.test(nameValue);\r\n var inputErr = document.getElementsByTagName('input')[1];\r\n\r\n if (nameValue == null || nameValue == \"\") {\r\n document.getElementById('name-err').innerHTML = \"This field is required.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (!nameRegex) {\r\n document.getElementById('name-err').innerHTML = \"Alphabet characters only.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (nameRegex) {\r\n var inputValid = document.getElementsByTagName('input')[1];\r\n inputValid.setAttribute('class', 'input-valid');\r\n document.getElementById('name-err').style.display = 'none';\r\n return true;\r\n }\r\n }", "function validateName()\n{\n\t//variable name is set by element id contactName from the form\n\tvar name = document.getElementById(\"contactName\").value; \n\t\n\t//validation for name\n\tif(name.length == 0)\n\t{\n\t\tproducePrompt(\"Name is Required\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!name.match(/^[A-Za-z]*\\s{1}[A-Za-z]*$/))\n\t{\n\t\tproducePrompt(\"First and Last name Please\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Welcome \" + name, \"namePrompt\", \"green\"); \n\t\treturn true; \n\t\n}", "function isValidGroupName(name) {\n\treturn isValidUsername(name);\n}", "function isNameOK(field) {\r\n\t\r\n\tvar name = field.value.trim();\r\n\tconsole.log(name); // TEST CODE\r\n\t\r\n\tif (emptyString(name)) {\r\n\t\talert('Le nom du groupe doit être renseigné.');\r\n\t\treturn false;\r\n\t}\r\n\telse if (fiftyChar(name)) {\r\n\t\talert('Le nom du groupe ne peut pas dépasser cinquante caractères.');\r\n\t\treturn false;\r\n\t}\r\n\telse {\r\n\t\treturn true;\r\n\t}\r\n}", "function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}", "function uomShortNameValidation(e) {\n\tvar ret\n\tvar keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;\n\tif (document.getElementById('uomShortNameText').value.length == 0) {\n\t\tret = ((keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t} else if ((test == 32) && (keyCode == 32 )) {\n\t\tret = false;\n\t} else {\n\t\tret = ((keyCode == 32)\n\t\t\t\t|| (keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t\ttest = keyCode\n\n\t}\n\tdocument.getElementById(\"error1\").style.display = ret ? \"none\" : \"inline\";\n\treturn ret;\n}", "function usernameValidation(str) {\n const regex = /[^A-Za-z0-9\\_]/;\n return (\n str.length >= 4 &&\n str.length <= 25 &&\n str[0].match(/[A-z]/) &&\n !regex.test(str) &&\n str[str.length - 1] !== \"_\"\n );\n}", "function validateStringWithSpacesInput(value){\n\t\n\tvar stringWithSpaceRegExp = /(^[\\w-,\\(\\)]+)((\\s+)(\\w-,\\(\\)))*$/;\n\t//alert(stringWithSpaceRegExp);\n\t\n\tif(stringWithSpaceRegExp.test(value)==true){\n\t\t//alert(\"2\");\n\t\treturn true;\n\t}else{\n\t\t//alert(\"3\");\n\t\treturn false;\n\t}\n}", "function checkverifychar(formname,fieldname,message)\n{\n\tvar e=eval(\"document.\" + formname + \".\" + fieldname);\n\t//var alphaExp = new RegExp(\"[a-zA-Z\"+allowchar+\"]\", \"g\");\n\tvar validRegExp = /^[a-zA-Z]+$/\n\t//var alphaExp = new RegExp(\"[a-zA-Z]\", \"g\");\n\tvar isValid = validRegExp.test(e.value);\n\tif(!isValid)\n\t{\n\t\talert(message);\n\t\te.focus();\n\t\treturn false;\n\t}\n\treturn true;\n}", "function validatefullname(Fullname) {\n var pattern = /^[a-zA-Z\\s]+$/;\n return $.trim(Fullname).match(pattern) ? true : false;\n}", "function validName(input) {\n return input.length > 0\n }", "function validatePartNo(aField)\n{\n var lstrValue = aField.value;\n var lchrTemp;\n\n re = new RegExp(\"-\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n\n/* for(i=0;i<lstrValue.length;i++) {\n\n lchrTemp = lstrValue.charAt(i);\n if (!( (lchrTemp >= 'A' && lchrTemp <= 'Z')\n || (lchrTemp >= 'a' && lchrTemp <= 'z')\n || (lchrTemp >= '0' && lchrTemp <= '9'))) {\n return false;\n }\n }*/\n\n return true;\n}", "function check_gardening_botanical_name() \n\t\t{ \n\t\t\tvar boname_length = $(\"#update_gardening_botanical_name\").val().length;\n\n\t\t\tif(boname_length == \"\" || boname_length == null)\n\t\t\t\t{\n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Please fill in data into the field\"); \n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t\t}\n\t\t\t\n\t\t\telse if(boname_length <2 || boname_length > 20) {\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Should be between 2-20 characters\");\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t}\n\t\t\t\n\t\t\telse \n\t\t\t{\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").hide();\n\t\t\t}\n\t\t}", "function validateUserFullName(){\n\n\tif (usersReg_Form.usersFullName.value === \"\" || usersReg_Form.usersFullName.value === null ) {\n\n usersReg_Form.usersFullName.style.borderColor = 'red';\n nameErrorReg.innerHTML = 'Enter your name';\n\n\t}else if (usersReg_Form.usersFullName.value !== \"\" && usersReg_Form.usersFullName.value !== null && usersReg_Form.usersFullName.value.length <= 4) {\n\n usersReg_Form.usersFullName.style.borderColor = 'red';\n nameErrorReg.innerHTML = 'Name must be more than 4 letters';\n\n\t}else{\n \n nameErrorReg.innerHTML = '';\n usersReg_Form.usersFullName.style.borderColor = 'green';\n \n\t}\n\n}", "function validateUpdateOwnerName(firstname,e) {\n if (!isValidName(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει τουλάχιστον δύο χαρακτήρες)');\n e.preventDefault();\n } else if (!isOnlyLetters(firstname)) {\n $(\".nameOwnerUpdateErr\").text(' (Το όνομα πρέπει να περιέχει μόνο γράμματα)');\n e.preventDefault();\n } else {\n $(\".nameOwnerUpdateErr\").text(\"\");\n }\n } //end function ", "function validarCaracteres(input,output){ \n var alphaExp = /^[0-9a-zA-Z\\s]+$/;\n //NO cumple longitud minima \n if(input.val().length == 0){\n output.text(\" * Campo Requerido\");// mensaje de error\n output.css(\"visibility\", \"visible\"); \n return false; \n } \n //SI longitud pero caracteres diferentes de A-z \n else if(!input.val().match(alphaExp)){\n output.text(\" * No se permiten caracteres diferentes de [a-zA-Z]\");// mensaje de error\n output.css(\"visibility\", \"visible\");\n return false; \n } \n // SI longitud, SI caracteres A-z hace oculto el tag que muestra el mensaje\n else{ \n output.css(\"visibility\", \"hidden\");\n return true; \n } \n }", "function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_SysName,\"+LANG_LOCALE['12134'];\n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n \n if (alphaNumericValueCheck (\"tf1_SysName\", '-', '') == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, \"'\\\" \", NOT_SUPPORTED) == false) \n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hide or show mail attachment link
function showAttLink(view, show) { if (view) { if (show) { view.$el.find('.links.shareAttachments').show(); } else { view.$el.find('.links.shareAttachments').hide(); } } }
[ "function stopAttLink() {\n require(['io.ox/core/extPatterns/links'], function (links) {\n new links.Action('io.ox/mail/compose/attachment/shareAttachmentsEnable', {\n id: 'stop',\n index: 1,\n requires: function (e) {\n try {\n if (e.baton.view.model.get('encrypt')) { // Do not offer shareAttachments if encrypted\n console.log('stopping');\n e.stopPropagation();\n return false;\n }\n } catch (f) {\n console.log(f);\n }\n return false;\n }\n });\n });\n }", "function checkAttLink(model, view) {\n if (model.get('share_attachments')) {\n if (model.get('share_attachments').enable) {\n if (model.get('encrypt')) {\n showAttLink(view, false);\n }\n }\n }\n }", "function attachmentCallBack( filename, mimeType, attachment ) {\n\t\t\t\t\tvar ifrm = $('#message-iframe-'+ message.id)[0].contentWindow.document;\n\t\t\t\t\tvar link = getAttachmentBody( attachment, filename, mimeType );\n\t\t\t\t\t$( link ).insertAfter( $( ifrm.body ) );\n\t\t\t\t}", "function emailFunction() {\n var x = document.getElementById(\"contactMe\");\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n } else {\n x.style.display = \"none\";\n }\n }", "function checkAttLinkChange(model) {\n if (model.get('share_attachments')) {\n if (model.get('share_attachments').enable) {\n require(['io.ox/core/tk/dialogs', 'settings!io.ox/mail'], function (dialogs, mail) {\n var dialog = new dialogs.CreateDialog({ width: 450, height: 300, center: true, enter: 'ok' });\n dialog.header($('<h4>').text(gt('Not Supported')));\n var text = $('<p>').text(gt('%s is not supported with secured email and will be disabled.', mail.get('compose/shareAttachments/name')));\n dialog.getBody().append(text);\n dialog\n .addPrimaryButton('ok', gt('OK'), 'ok')\n .show();\n });\n }\n }\n }", "function disableEditLink() {\n if ( mw.config.get('wgNamespaceNumber') !== 110 && mw.config.get('wgNamespaceNumber') % 2 !== 1 ) { return; }\n var skin = mw.config.get('skin');\n if ( ( skin !== 'oasis' && skin !== 'monaco' && skin !== 'monobook' ) || // might be unnecessary, other skins haven't been checked\n $.inArray( 'sysop', mw.config.get('wgUserGroups') ) > -1 || // disable completely for admins\n typeof enableOldForumEdit !== 'undefined' ||\n !$('#archived-edit-link')[0] ) { return; }\n\n var editLink = ( skin === 'oasis' || skin === 'monaco' ) ? $('#ca-edit') : $('#ca-edit a');\n if ( !editLink[0] ) { return; }\n\n editLink.html('Archived').removeAttr('href').removeAttr('title').css({'color':'gray','cursor':'auto'});\n\n $('span.editsection-upper').remove();\n\n}", "function showSendMail(selected) {\n\tif (selected.indexOf(\"YES\") > -1) {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = false;\n\t} else {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = true;\n\t}\n}", "function clickReportBrokenLink (obj,form_name) {\n\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'inline');\n\tvar email = document.getElementById('id_e-mail').value;\n\tvar note = document.getElementById('id_client_note').value;\n\tset_element_display_by_id_safe('report_error1', 'none');\n\tset_element_display_by_id_safe('report_error2', 'none');\n\tvar report_div = document.getElementById('ReportWindow');\n\t\n\tif ( email ) {\n\t\tvar filter = /^\\s*([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+\\s*$/;\n\t\tif (!filter.test(email)) {\n\t\t\tset_element_display_by_id_safe('report_error1', 'inline');\n\t\t\tset_element_display_by_id_safe('error_div', 'inline');\n\t\t\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'none');\n\t\t\treturn;\n\t\t}\n\t}\n\telse {\n\t\tif ( note ) {\n\t\t\tset_element_display_by_id_safe('report_error2', 'inline');\n\t\t\tset_element_display_by_id_safe('error_div', 'inline');\n\t\t\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'none');\n\t\t\treturn;\n\t\t}\n\t}\n\tcloseReportWindow ();\n\tsendEmailToLibrary(obj, form_name);\n\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'none');\n\tset_element_display_by_id_safe(form_name + '-reportlink', 'none');\n\tset_element_display_by_id_safe(form_name + '-reportlink-thankyou', 'inline');\n}", "hideAndroidDownload() {\n this.addFilter('android_download', entry => {\n if (entry.filesystem && entry.filesystem.name === 'android_files' &&\n entry.fullPath === '/Download') {\n return false;\n }\n return true;\n });\n }", "function isAttachment(session) { \n var msg = session.message.text;\n if ((session.message.attachments && session.message.attachments.length > 0) || msg.includes(\"http\")) {\n //call custom vision\n customVision.retreiveMessage(session);\n\n return true;\n }\n else {\n return false;\n }\n }", "function show_hide_link(elt_id, link_elt_id, hide_label, show_by_default) {\n $(document).ready(function() {\n var to_toggle = $('#' + elt_id);\n var link_elt = $('#' + link_elt_id);\n var show_label = link_elt.html();\n if (show_by_default) {\n\tlink_elt.html(hide_label);\n\tto_toggle.show();\n }\n else {\n\tlink_elt.html(show_label);\n\tto_toggle.hide();\n }\n link_elt.click (function() {\n\t if (link_elt.html() == hide_label) {\n\t link_elt.html(show_label);\n\t }\n\t else {\n\t link_elt.html(hide_label);\n\t }\n\t to_toggle.toggle();\n\t return false;\n\t});\n });\n}", "function getAttachmentId(link){\n \n var replacedStr = link.replace(\"https://drive.google.com/open?id=\",\"\");\n return replacedStr;\n}", "function showembed(){\n document.getElementById('hideembed').style.visibility=\"hidden\";\n document.getElementById('hideembed').style.display=\"none\";\n document.getElementById('showembed').style.display=\"block\";\n document.getElementById('showembed').style.visibility=\"visible\";\n document.getElementById('embed').innerHTML=\"<a style=\\\"cursor:pointer;\\\" onClick=\\\"hideembed()\\\"><img src=\\\"addons/mw_eclipse/skin/images/icons/icon_share.png\\\" align=\\\"absmiddle\\\" />&nbsp;Share / Embed<\\/a>\";\n\n}", "function hideFilterLinkIcon() {\n\tvar element = document.querySelector(\"#filter-link\");\n\tif (element) {\n\t\telement.style.display = \"none\";\n\t}\n\t// also deactivate the filter in the toolbar\n\tdetachGlobalFilter();\n}", "function eca_email_link_to_contact_form_lightbox() {\n\tvar $lightbox = jQuery('#eca-cf7-author-email');\n\tif ( $lightbox.length < 1 ) return;\n\n\tvar $form = $lightbox.find('form.wpcf7-form');\n\tif ( $form.length < 1 ) return;\n\n\tvar $input = jQuery( '<input>', { type: 'hidden', name: 'eca-author-id' } );\n\t$form.append( $input );\n\n\tvar $author_name = $lightbox.find('.eca-cf7-author-name');\n\n\t// When clicking on a link, fill the author id and show the lightbox\n\tjQuery('body').on('click', '.eca-email-cf7', function(e) {\n\t\tvar author_id = jQuery(this).attr('data-author');\n\t\tif ( author_id < 1 ) return;\n\n\t\tvar full_name = jQuery(this).attr('data-name');\n\n\t\t$input.val( author_id );\n\t\t$author_name.text( full_name );\n\n\t\t$lightbox.css('display', 'block' );\n\n\t\treturn false;\n\t});\n\n\t// Allow closing the lightbox\n\tvar close_lightbox = function(force_reset) {\n\t\tif ( typeof force_reset == \"undefined\" || force_reset !== true ) {\n\t\t\tvar is_form_filled = false;\n\n\t\t\tjQuery(\":text, :file, :checkbox, select, textarea\").each(function() {\n\t\t\t\tif ( jQuery(this).is(':visible') === false ) return; // Ignore hidden fields, those can be filled\n\n\t\t\t\tif ( jQuery(this).val() != \"\" ) {\n\t\t\t\t\tis_form_filled = true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif ( is_form_filled ) {\n\t\t\t\tif ( !confirm('You are about to close the contact form. You will lose your changes.' + \"\\n\\n\" + 'Close anyway?') ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t$lightbox.css('display', 'none');\n\t\t$form.resetForm();\n\t};\n\n\t// Close lightbox via underlay\n\t$lightbox.children('.eca-lightbox-underlay').on('click', function(e) {\n\t\tif ( jQuery(e.target).is('.eca-lightbox-underlay') ) {\n\t\t\tclose_lightbox();\n\t\t\treturn false;\n\t\t}\n\t});\n\n\t// Close lightbox using the X button\n\t$lightbox.on( 'click', 'a.eca-lightbox-close', function(e) {\n\t\tclose_lightbox();\n\t\treturn false;\n\t});\n}", "function setAttachButtonHandler() {\n const attachmentButton = document.getElementById('attachmentButton');\n const attachmentInput = document.getElementById('attachmentInput');\n const attachmentSaveA = document.getElementById('attachmentSaveA');\n const deleteImg = document.getElementById('deleteImg');\n deleteImg.addEventListener('click', function() {\n\tattachmentSaveA.href = '';\n\tattachmentSaveA.download = '';\n\tattachmentInput.value = attachmentInput.files = null;\n\tattachmentSaveA.style.display = 'none';\n\tcommon.replaceElemClassFromTo('attachmentInput', 'visibleIB', 'hidden', true);\n\tcommon.replaceElemClassFromTo('attachmentButton', 'hidden', 'visibleIB', false);\n\tdeleteImg.style.display = 'none';\n\tif (msgTextArea.value == '')\n\t document.getElementById('msgFeeArea').value = 'Fee: 0 Wei';\n });\n attachmentButton.addEventListener('click', function() {\n\tattachmentInput.value = attachmentInput.files = null;\n\tcommon.replaceElemClassFromTo('attachmentButton', 'visibleIB', 'hidden', true);\n\tcommon.replaceElemClassFromTo('attachmentInput', 'hidden', 'visibleIB', false);\n });\n attachmentInput.addEventListener('change', function() {\n\tconsole.log('attachmentInput: got change event');\n\tif (attachmentInput.files && attachmentInput.files[0]) {\n\t console.log('attachmentInput: got ' + attachmentInput.files[0].name);\n\t const reader = new FileReader();\n\t reader.onload = (e) => {\n\t\t//eg. e.target.result = data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAACx1BMV...\n\t\tconsole.log('attachmentInput: e.target.result = ' + e.target.result);\n\t\t//\n\t\tattachmentSaveA.href = e.target.result;\n\t\tattachmentSaveA.download = attachmentInput.files[0].name;\n\t\tconst attachmentSaveSpan = document.getElementById('attachmentSaveSpan');\n\t\tattachmentSaveSpan.textContent = attachmentInput.files[0].name;\n\t\tattachmentSaveA.style.display = 'inline-block';\n\t\tdeleteImg.style.display = 'inline-block';\n\t\tcommon.replaceElemClassFromTo('attachmentInput', 'visibleIB', 'hidden', true);\n\t\t//message has content...\n\t\tdocument.getElementById('msgFeeArea').value = 'Fee: ' + ether.convertWeiBNToComfort(common.numberToBN(mtDisplay.composeFee));\n\t };\n\t reader.readAsDataURL(attachmentInput.files[0]);\n } else {\n\t attachmentSaveA.href = null;\n\t}\n });\n}", "function showInsertLinkDialog(list) {\n var itemList = [];\n tinymce.each(list, function(item) {\n itemList.push({ text: item.attachment, value: item.attachment });\n });\n \n function onSubmit() {\n var filename = this.find('#insert').value();\n var inst = top.tinymce.activeEditor;\n var url = foswiki.getPreference(\"PUBURL\") + \"/\"\n + foswiki.getPreference(\"WEB\") + \"/\"\n + foswiki.getPreference(\"TOPIC\");\n url += '/' + filename;\n var tmp = filename.lastIndexOf(\".\");\n if (tmp >= 0)\n tmp = filename.substring(tmp + 1, filename.length).toLowerCase();\n \n var html;\n if (tmp == \"jpg\" || tmp == \"gif\" || tmp == \"jpeg\" ||\n tmp == \"png\" || tmp == \"bmp\") {\n html = \"<img src='\" + url + \"' alt='\" + filename + \"'>\";\n } else {\n html = \"<a href='\" + url + \"'>\" + filename + \"</a>\";\n }\n inst.execCommand('mceInsertContent', false, html);\n }\n \n tinymce.activeEditor.windowManager.open(\n \t {\n\t\ttitle: 'Insert link to attachment',\n onSubmit: onSubmit,\n\t\tbodyType: 'form',\n\t\tbody: [\n {\n\t\t\tlabel: 'Insert link',\n\t\t\tname: 'insert',\n\t\t\ttype: 'listbox',\n values: itemList\n\t\t },\n ]\n\t });\n }", "function hide_download_icons_android(){\r\n if(IsAndroid() === true){\r\n CSSLoad(\"style_hide_download_section.css?v0221\");\r\n CSSLoad(\"style_hide_window_control_section.css?v023\");\r\n\r\n //and hide buttons on mobile devices PDF and XLS save documents\r\n element_id_hide(\"btn_export_pdf_profile\");\r\n element_id_hide(\"btn_export_xls\");\r\n element_id_hide(\"btn_tbl_pdf\");\r\n element_id_hide(\"btn_export_pdf_pp\");\r\n }\r\n}", "function hideEmail(email) {\n var result = \"\";\n var etindex;\n for (i = 0; i < email.length; i++) {\n if (i < 3) {\n result += email[i];\n }\n } result += \"...\"\n for (j = 0; j < email.length; j++) {\n if (email[j] == \"@\") {\n etindex = j;\n }\n }\n for (k = etindex; k < email.length; k++) {\n result += email[k];\n } return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over all the directives for a node and returns index of a directive for a given type.
function getIdxOfMatchingDirective(node, type) { var defs = node.view[TVIEW].directives; var flags = node.tNode.flags; var count = flags & 4095 /* DirectiveCountMask */; var start = flags >> 14 /* DirectiveStartingIndexShift */; var end = start + count; for (var i = start; i < end; i++) { var def = defs[i]; if (def.type === type && def.diPublic) { return i; } } return null; }
[ "function _nodeIndex(node) {\n\t\t// \n\t\tif (!node.parentNode) return 0;\n\t\t// \n\t\tvar nodes = node.parentNode.childNodes,\n\t\t\tindex = 0;\n\t\t// \n\t\twhile (node != nodes[index]) ++index;\n\t\t// \n\t\treturn index;\n\t}", "function findStyleAttributeIndex(attributeType, styleArray) {\n return styleArray.findIndex(s => s.attribute == attributeType);\n}", "getIndex(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.idx : null;\n }", "function getElIndex(nList, el){\n\n var index = 0\n\n for(element of nList){\n\n if(element == el){\n return index\n }\n index++\n }\n\n}", "function indexInParent(node) {\n var children = node.parentNode.childNodes;\n var num = 0;\n for (var i=0; i<children.length; i++) {\n\tif (children[i]==node) return num;\n\tif (children[i].nodeType==1) num++;\n }\n return -1;\n}", "function tcbProcessDirective(el, dir, unclaimed, tcb, scope) {\n var id = scope.getDirectiveId(el, dir);\n if (id !== null) {\n // This directive has been processed before. No need to run through it again.\n return id;\n }\n id = scope.allocateDirectiveId(el, dir);\n var bindings = tcbGetInputBindingExpressions(el, dir, tcb, scope);\n // Call the type constructor of the directive to infer a type, and assign the directive instance.\n scope.addStatement(tsCreateVariable(id, tcbCallTypeCtor(el, dir, tcb, scope, bindings)));\n tcbProcessBindings(id, bindings, unclaimed, tcb, scope);\n return id;\n }", "visitIndextype(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitIndextype_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "_getColumnIndex(subCtrlName) {\n\t\tfor (let i = 0; i < this.props.control.subControls.length; i++) {\n\t\t\tif (this.props.control.subControls[i].name === subCtrlName) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "getColumnIndex(): number {\n const { row, cell } = this;\n const cells = row.nodes;\n\n return cells.findIndex(x => x === cell);\n }", "function parseIdx(p, n){ // PathPoints, number for index\n var len = p.length;\n if( p.parent.closed ){\n return n >= 0 ? n % len : len - Math.abs(n % len);\n } else {\n return (n < 0 || n > len - 1) ? -1 : n;\n }\n }", "function getArrayId(node) \r\n{\r\n\tfor (i=0; i<TreeNodes.length; i++) \r\n\t{\r\n\t\tvar nodeValues = TreeNodes[i].split(\"|\");\r\n\t\tif (nodeValues[0]==node) return i;\r\n\t}\r\n}", "function getItemIndex(item) {\n return item.parent()\n .find(opts['ui-model-items'])\n .index(item);\n }", "visitOid_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "get index_attrs(){\n\t\treturn [...module.iter(this)] }", "visitTable_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "inCache(addr) {\n console.assert(0 <= addr.idx && addr.idx < this.setNum, \"Illegal index: \" + addr.idx);\n\n var entries = this.sets[addr.idx];\n for(var i = 0; i < entries.length; i++) {\n if(addr.tag == entries[i].tag && entries[i].valid) {\n return i;\n }\n }\n\n return null;\n }", "function getVariableTypeFromDirectiveContext(value, query, templateElement) {\n for (const { directive } of templateElement.directives) {\n const context = query.getTemplateContext(directive.type.reference);\n if (context) {\n const member = context.get(value);\n if (member && member.type) {\n return member.type;\n }\n }\n }\n return query.getBuiltinType(symbols_1.BuiltinType.Any);\n}", "visitIndex_expr(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getToggledIndex() {\n var i = 0;\n for (var obj of children) {\n if (typeof obj.isToggled != \"undefined\" && obj.isToggled())\n return i;\n i += 1;\n }\n return -1;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a hex string converts it to a big int in the valid private key range
function hex2bigIntKey(s){ return bigInt2bigIntKey(hex2bigInt(removeWhiteSpace(s))); }
[ "function hex2bigInt(s){ return new BigInteger(removeWhiteSpace(s), 16); }", "function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }", "function bigInt2bigIntKey(i){ return i.mod(getSECCurveByName(\"secp256k1\").getN()); }", "function bigInt2ECKey(i){ return new Bitcoin.ECKey(bigInt2bigIntKey(i)); }", "function getdec(hexencoded) {\n\tif (hexencoded.length == 3) {\n\t\tif (hexencoded.charAt(0) == \"%\") {\n\t\t\tif (hexchars.indexOf(hexencoded.charAt(1)) != -1 && hexchars.indexOf(hexencoded.charAt(2)) != -1) {\n\t\t\t\treturn parseInt(hexencoded.substr(1, 2), 16);\n\t\t\t}\n\t\t}\n\t}\n\treturn 256;\n}", "function siiB(e) {\r\n\treturn Math.round(parseInt(e)).toString(36);\r\n}", "function pubKeyHash2bitAdd(k){\r\n var b = new Bitcoin.Address(hex2bytes(k));\r\n return b.toString();\r\n}", "static bytes22(v) { return b(v, 22); }", "function sha256bigint(m,l)\n{\n\tlet a = bigint2bytes(m,l);\n\tlet hash = sha256.sha256(a);\n\treturn array2bigint(new Uint8Array(hash));\n}", "function generateDecimalFromHex (hiByte, LoByte) {\n var strCompleteHex = '' + hiByte + LoByte;\n var sum = -8192;\n var hex = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'};\n\n for (var positionIndex = 3; positionIndex >= 0; positionIndex--) {\n var baseTen = hex[strCompleteHex[positionIndex]];\n // console.log(baseTen);\n var ExponentIndex = 3 - positionIndex;\n // console.log(baseTen * Math.pow(16, ExponentIndex));\n sum += baseTen * Math.pow(16, ExponentIndex);\n }\n return sum;\n}", "function array2bigint(bytes)\n{\n\tlet hex;\n\n\tif (typeof(bytes) == \"string\")\n\t{\n\t\thex = bytes\n\t\t.split('')\n\t\t.map( c => ('00' + c.charCodeAt(0).toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\tif (typeof(bytes) == \"object\")\n\t{\n\t\thex = Array.from(bytes)\n\t\t.map( c => ('00' + c.toString(16)).slice(-2) )\n\t\t.join('');\n\t} else\n\t{\n\t\tconsole.log('ERROR', bytes);\n\t}\n\n\tif (hex.length == 0)\n\t{\n\t\tconsole.log(\"ERROR: empty hex string?\", typeof(bytes), bytes);\n\t\thex = \"00\";\n\t}\n\n\tlet bi = BigInt(\"0x\" + hex);\n\t//console.log(bytes, bi);\n\treturn bi;\n}", "function bigInt2hex(i){ return i.toString(16); }", "function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256ripe160(hex2bytes(k))); }", "function hexToInt(str, def)\n {\n if (typeof str === 'number')\n { return str; }\n\n const result = parseInt(str.replace('#', '0x'));\n\n if (isNaN(result)) return def;\n\n return result;\n }", "function ipV6ToBigInteger(ipv6) {\n const address = new Address6(ipv6);\n\n return address.bigInteger();\n}", "function scanDigits( str, p, ret ) {\n var ch, val = 0;\n for (var p2=p; (ch = str.charCodeAt(p2)) >= 0x30 && ch <= 0x39; p2++) {\n val = val * 10 + ch - 0x30;\n }\n ret.end = p2;\n ret.val = val;\n}", "function bufferToBigInt(buf) {\n return BigInt('0x' + bufferToHex(buf))\n}", "function generateChecksum(str) {\n\tvar buff = new buffer.Buffer(str);\n\n\tvar num = 0;\n\n\tfor(var i = 0; i < buff.length; i++) {\n\t\tnum += buff.readUInt8(i);\n\n\t\t// Handle overflow\n\t\tnum = num % 4294967296;\n\t}\n\t\n\treturn (num * 157 + num) % 4294967296;\n}", "function hash52 (str) {\n var prime = fnv_constants[52].prime,\n hash = fnv_constants[52].offset,\n mask = fnv_constants[52].mask;\n\n for (var i = 0; i < str.length; i++) {\n hash ^= Math.pow(str.charCodeAt(i), 2);\n hash *= prime;\n }\n\n return new FnvHash(bn(hash).and(mask), 52);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }