query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Tells the server to delete the task.
function deleteTask(task) { const params = new URLSearchParams(); params.append('id', task.id); fetch('/delete-task', {method: 'POST', body: params}); }
[ "function deleteTask(task) {\r\n const params = new URLSearchParams();\r\n params.append('id', task.id);\r\n fetch('/delete-task', {method: 'POST', body: params});\r\n}", "delete(task) {\n this.$http.delete('/api/teams/' + this.currentTeam.id + '/tasks/' + task.id);\n\n this.removeTaskFromData(task.id);\n }", "function deleteTask(task) {\n const params = new URLSearchParams();\n params.append('id', task.id);\n fetch('/delete-rec', {method: 'POST', body: params});\n}", "function deleteTask(e){\n const taskID = document.getElementById('id').value;\n http\n .delete(`http://localhost:3000/Tasks/${taskID}`)\n .then(task=>{\n //clearing field\n ui.clearFiled();\n //showing message\n ui.showAlertMessage('Task deleted','alert alert-warning');\n //getting task\n getTasks();\n })\n}", "function deleteTask() {\n if (confirm(\"Are you sure you want to delete task(s)?\")) {\n $.post(\"deleteTask.php\", null, function () {\n deleteMessageResponse();\n refreshTask(\"showTaskCompleted\");\n });\n } else {\n refreshTask(\"showTaskCompleted\");\n }\n }", "delete() {\n\t\tthis.room.getTasks().del(this);\n\t}", "handleDelete(task) {\n this.props.actions.deleteTask(task);\n }", "function deleteTask(id){\n console.log(deleteTask);\n\n $.ajax({\n type: 'DELETE',\n url: '/tasks/' + id,\n success: function(response){\n console.log('delete successful!');\n getTasks();\n },\n error: function(){\n console.log('could not delete');\n }\n\n });\n }", "function handleDeleteTaskClicked() {\n var taskId = getElementTaskId(this);\n sendTaskDeletion(taskId);\n}", "function deleteEventTask(id) {\n\tinteraction.deleteEventTask(id);\n}", "deleteTask(task_id) {\n return fetch(`${config.API_ENDPOINT}/tasks/${task_id}`, {\n method: 'DELETE',\n headers: {\n 'content-type': 'application/json',\n 'authorization': `Bearer ${TokenService.getAuthToken()}`\n }\n });\n }", "deleteTask(id){\n\n // If input\n if(id){\n Tasks.remove(id);\n return true;\n\n } else {\n // Bad request\n throw new Meteor.Error(400, 'No id provided');\n }\n\n }", "function deleteTask(request, response){\n // const id = request.params.id;\n const {id} = request.params;\n const SQL = 'DELETE FROM todos WHERE id=$1';\n client.query(SQL, [id])\n .then(() => {\n response.redirect('/tasks');\n });\n}", "_deleteTaskById(id) {\n var task = this._getDataById(id);\n task.deleted = true;\n this._renderItems();\n }", "deleteTask(taskId, callback) {\n\n var result, response;\n\n this.db.deleteItem({ TableName: this.tableName, Key: { taskId: taskId } }, function (err, data) {\n if (err) {\n callback(err, null);\n } else {\n response = {\n statusCode: 200,\n body: JSON.stringify({\n message: \"task \" + taskId + \" has been deleted.\"\n }),\n };\n callback(null, response);\n }\n });\n }", "function deleteTask() {\n const taskElement = this.parentNode;\n taskElement.remove();\n taskCount--;\n displayCount(taskCount);\n }", "function deleteTask(id) {\n setCreate(false)\n \n api.delete(`/${id}`)\n }", "function deleteFromFluence(task) {\n const query = `DELETE FROM ${todoTable} WHERE task = '${task}'`;\n session.request(query).result().then((res) => {\n console.log(\"task deleted: \" + res.asString());\n })\n }", "delete(taskInstanceID) {\n\n console.log(\"Removing TaskInstanceID\", taskInstanceID, \" From Email Notification List...\");\n\n EmailNotification.destroy({\n where: {\n TaskInstanceID: taskInstanceID\n }\n }).catch(function(err) {\n console.log(err);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Have the function flip(input) take the input parameter, comprised of As and Zs being passed and return the string with each character flipped. For example: if the input string is "AAZZA" then your program should return the string "ZZAAZ".
flip(input){ // get letters from A to Z and swap letter values // using regex with global parameter // let swapChr = input.replace(/A/g, "_").replace(/Z/g, "A").replace(/_/g, "Z"); // output results return swapChr; }
[ "flip(input) {\n //Split string into array of letters\n //Iterate through letters\n //if letter is \"A\" then update letter to \"Z\"\n //else letter update letter to \"A\"\n //join letters \n //return output with flipped input \n\n let letters = input.split(\"\");\n for (let i = 0; i < letters.length; i++) {\n if (letters[i] === \"A\") letters[i] = \"Z\";\n else letters[i] = \"A\";\n }\n\n return letters.join(\"\");\n }", "flip(input){\n // set empty variable \n let string = '';\n\n // split eatch letter, iterate through each letter. If the letter is A\n // change to Z and add it to the string array, if Z, change to A.\n // condition ? exprIfTrue : exprIfFalse\n\n input.split('').forEach(letter => {\n string += letter === 'A' ? 'Z' : 'A';\n });\n console.log(string);\n // return populated string with reverse output\n return string;\n }", "flip(input){\n // set empty variable \n let string = '';\n\n // split eatch letter, iterate through each letter. If the letter is A\n // change to Z and add it to the string array, if Z, change to A.\n // condition ? exprIfTrue : exprIfFalse\n\n input.split('').forEach(letter => {\n string += letter === 'A' ? 'Z' : 'A';\n });\n console.log(string);\n // return populated string with reverse output\n return string;\n }", "function flipPairs(input){\n\t// Create Output String\n\tvar output = \"\";\n\t// Iterate through the string every 2nd character\n\tfor(var i = 0; i < input.length; i += 2){\n\t\t// Iterate through the string backwards, starting at 0. (2 - 1) is to convert to the index\n\t\tfor(var j = 2 - 1; j >= 0; j--){\n\t\t\t// Assign the first character + the second character to the output\n\t\t\toutput += input[i+j]\n\t\t}\n\t}\n\t// Return Output\n\treturn output;\n}", "function flipPairs( str ) {\n \n let flippedStr = \"\";\n for( let i = 0; i < str.length; i+=2 ) {\n flippedStr += charFlipper( str.charAt(i), str.charAt(i + 1) );\n }\n return flippedStr;\n}", "function stringFlip(s){\n var result = \"\";\n for (var i = 0; i < s.length; i++){\n result += s[s.length - 1 - i]\n }\n return result;\n}", "function flipEveryNChars(input, num){\n //Create Array to store 5 characters\n var flippedString = '';\n //Populate the Array with 5 characters\n //Flip the Array\n //Combine all arrays together into one string\n for(var i = 0; i < input.length; i += num){\n var charArray = [];\n charArray.push(input[i]);\n charArray.push(input[i + 1]);\n charArray.push(input[i + 2]);\n charArray.push(input[i + 3]);\n charArray.push(input[i + 4]);\n flippedString += charArray.reverse().join('');\n }\n return flippedString;\n}", "function reverse(input) {\n\n\n}", "function flipPairs(string) {\n let flippedStr = '';\n for(let i = 0; i < string.length; i += 2) {\n if(i === string.length - 1) {\n flippedStr += string[i];\n } else {\n flippedStr += string[i+1];\n flippedStr += string[i];\n }\n }\n return flippedStr;\n}", "function flipOver(str) {\r\n let strReversed = '';\r\n for (let i = str.length - 1; i >= 0; i--) {\r\n strReversed += str[i];\r\n }\r\n return strReversed;\r\n}", "function reverseChars(str) {\n var flipStr = '';\n \n for (var i = str.length - 1; i >= 0 ; i--) {\n flipStr += str.charAt(i).toLowerCase();\n }\n return flipStr;\n}", "function flipFlipGuy(flippedChars, i) {\n var flippedGuy = '/( . 0 .\\\\)'\n , flippedGuyArr\n ;\n\n flippedGuyArr = flippedGuy.split('');\n flippedGuyArr.forEach(function (c) {\n flippedChars.push(c);\n });\n return i - 7;\n }", "function flip(input){\n\t\tinput = input.reverse();\n\t\t\n\t\t// Flip any options back into the right order\n\t\tfor(let i = 0, l = input.length; i < l; ++i){\n\t\t\tconst arg = input[i];\n\t\t\tconst opt = shortNames[arg] || longNames[arg];\n\t\t\t\n\t\t\tif(opt){\n\t\t\t\tconst from = Math.max(0, i - opt.arity);\n\t\t\t\tconst to = i + 1;\n\t\t\t\tconst extract = input.slice(from, to).reverse();\n\t\t\t\tinput.splice(from, extract.length, ...extract);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn input;\n\t}", "function flipEveryNChars(input, n){\n \n arr = input.split('');\n final = [];\n for (var i=0; i<arr.length-4; i=i+5){\n arr1 = arr.slice(i,n+i);\n arr1.reverse();\n final = final.concat(arr1);\n }\n \n final = final.concat(arr.slice(i,arr.length)); //concat the remainder as-is\n final = final.join('');\n \n return final;\n}", "function flipWord(word) {\r\nvar len = word.length;\r\nvar len1 = parseInt(len/2);\r\nvar len2 = len-len1;\r\n\r\nvar tmp=\"\";\r\nfor(var i=0; i<=len; i++) {\r\n tmp+=word.charAt(len-i);\r\n}\r\n\r\nword=tmp.substr(len1,len)+tmp.substr(0,len1);\r\nreturn word;\r\n}", "function reversal(input) {\n\tvar string = input;\n\tvar toArray = string.toUpperCase().split(\"\");\n\tvar reverse = toArray.reverse(\"\").join(\"\");\n\twrite.innerHTML += \"Your reversed string is: \" + reverse + \"<br>\";\n}", "function flipEveryNChars (str, n) {\n var reversedStr = '';\n for(var x = 0; x < str.length; x+=n) {\n var nthLetter = str.substr(x, n);\n reversedStr += nthLetter.split('').reverse().join('');\n console.log(reversedStr);\n }\n return reversedStr;\n\n}", "function reverse(string) {}", "function flipPairs(str) {\n let workingCopy = str;\n let stringWithPairsReversed = '';\n // turn string into array\n let workingCopyArr = [...str];\n if (workingCopyArr.length % 2 === 1) {\n workingCopyArr.push(' ');\n }\n // loop\n do {\n let pair = workingCopyArr[1] + workingCopyArr[0];\n stringWithPairsReversed += pair;\n workingCopyArr.shift();\n workingCopyArr.shift();\n } while (workingCopyArr.length > 0);\n return stringWithPairsReversed;\n // read first two characters from array then remove from the array\n\n // flip the two characters' order and construct a new \"pair\"\n // insert the new pair into a new string\n // return the completed new string\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates table of images based on chosen manuscripts
function generateTable(sizeChoice, imageChoice){ //pulls selected manuscripts and creates array chosenManuscripts var chosenManuscripts = getChosenValuesFromList("manuscripts"); //pulls letters and creates array chosenLetters var chosenLetters = getChosenValuesFromList("letters"); var chosenWidth=getImagePixelSize(sizeChoice); //create the table with manuscrips, letters, and images document.getElementById('letterTable').innerHTML = ' '; chosenManuscripts.splice(0, 0, ""); //formatting var body = document.getElementById('letterTable'); var tableDiv = document.createElement('div'); tableDiv.style.width = "100%"; tableDiv.style.height = "100%"; tableDiv.style.overflow = "scroll"; var tbl = document.createElement('table'); tbl.style.border = "1px solid black"; var tableHead = document.createElement('thead'); var tableBody = document.createElement('tbody'); for(var k = 0; k < chosenManuscripts.length; k++) { var th = document.createElement("th"); th.style.border = "1px solid black"; var title = chosenManuscripts[k] + " "; var name = title.slice(0, title.indexOf(":")); var pageurl = getexamplePage(name); var date = title.slice(title.indexOf(":")+2); //regex that searches for first number var search = name.search(/\d/); var shelfmark = name.substring(search); var manuscript = name.substring(0,search); // bold date unbold name var tableDate = document.createTextNode(date); var spanTableDate = document.createElement('span'); spanTableDate.style.fontWeight = "bold"; spanTableDate.appendChild(tableDate); var tablemanu = document.createTextNode(manuscript); var tableshelf = document.createTextNode(shelfmark); var spanInfo = document.createElement('div'); spanInfo.style.fontWeight = "normal"; if (pageurl!=null){ var link = document.createElement('a'); link.appendChild(tablemanu); link.href = pageurl; link.target = "_blank"; spanInfo.appendChild(link); } else{ spanInfo.appendChild(tablemanu); } // spanInfo.appendChild(document.createElement('br')); spanInfo.appendChild(tableshelf); // margin and even width of column //spanInfo.style.width = "119px"; spanInfo.style.width = (chosenWidth-1)+"px"; th.appendChild(spanInfo); //th.appendChild(document.createElement('br')); //th.appendChild(document.createTextNode(shelfmark)); th.appendChild(document.createElement('br')); th.appendChild(spanTableDate); th.style.textAlign = "center"; //tbl.appendChild(th); tableHead.appendChild(th); } //tableHead.style.background = "#B8C1C8"; tableHead.style.background = "#F5DEB3"; tableHead.style.zIndex="2"; tableHead.style.display="block"; tbl.appendChild(tableHead); for(var i = 0; i < chosenLetters.length; i++) { //var tr = tbl.insertRow(); var tr = tableBody.insertRow(); //letter names var td2 = tr.insertCell(); td2.style.border = "1px solid black"; td2.appendChild(document.createTextNode(chosenLetters[i])); //td2.style.width= "120px"; //td2.style.height= "100px"; td2.style.width=chosenWidth+"px"; td2.style.height= chosenWidth+"px"; td2.style.textAlign = "center"; tr.appendChild(td2); for(var j = 0; j < chosenManuscripts.length; j++){ if(j != 0) { var str = chosenManuscripts[j]; var res = str.split(":"); //creates fileName to pull image var imageSrc = "images/" + imageChoice + "/" + chosenLetters[i] + "_" + res[0] + ".png"; var td = tr.insertCell(); var img = document.createElement("img"); td.style.position = "relative"; img.setAttribute("alt", chosenLetters[i]); //set up for alternative img.setAttribute("class", res[0]); img.onload = function() { var letterName = this.getAttribute("alt"); var sizeChoice = getImageSize(); var width =getImagePixelSize(sizeChoice,letterName); //this.width = width; // img has same size //this.width = '80'; //this.height='80'; this.width = (width-40); this.height=(width-40); }; img.onerror = function() { this.onerror = null; this.src = "images/noImage.png"; // handle different forms of letters var letterName = this.getAttribute("alt"); var imgClass = this.getAttribute("class"); // check the url with page number var pageext = getPage(imgClass); var nopage = 1<2; for(i=0;i<pageext.length;i++){ var pageSrc="images/" + "binaryrep" + "/" + letterName + "_" + pageext[i]; if(imageExists(pageSrc)){ this.src=pageSrc; nopage=1>2; break; } } if(nopage){ if(letterName in twoAlt){ var altSrc = "images/" + "binaryrep" + "/" + twoAlt[letterName] + "_" + imgClass + ".png"; if(imageExists(altSrc)){ this.src="images/hasAlt.png"; } else{ this.src = "images/noImage.png"; } } else if (letterName in thrAlt){ var altSrc1 = "images/" + "binaryrep" + "/" + thrAlt[letterName][0] + "_" + imgClass + ".png"; var altSrc2 = "images/" + "binaryrep" + "/" + thrAlt[letterName][1] + "_" + imgClass + ".png"; if(imageExists(altSrc1)||imageExists(altSrc2)){ this.src="images/hasAlt.png"; } else{ this.src = "images/noImage.png"; } } else{ this.src = "images/noImage.png"; } } }; img.onmousedown = function() { var obj = this; var letterName = this.getAttribute("alt"); var sizeChoice = getImageSize(); //width = getImageScaledSize(letterName, sizeChoice); obj.style.top = (-(chosenWidth-40)/4)+"px"; obj.style.left = (-(chosenWidth-40)/4)+"px"; obj.style.position = "absolute"; obj.style.width = (2*(chosenWidth-40))+"px"; //2*width; obj.style.height = (2*(chosenWidth-40))+"px"; //alert(obj.style.height); obj.style.zIndex = 10; obj.style.border = "5px silver outset"; // make sure be above other img obj.parentNode.style.zIndex = 10; }; img.onmouseup = function() { var obj = this; var letterName = this.getAttribute("alt"); var sizeChoice = getImageSize(); //width = getImageScaledSize(letterName, sizeChoice); //obj.style.width = width+"px"; //width/2; //obj.style.width = "80px"; //obj.style.height = "80px"; var wid=getImagePixelSize(sizeChoice,letterName); obj.style.width = (wid-40)+"px"; obj.style.height = (wid-40)+"px"; obj.style.zIndex = 1; obj.parentNode.style.zIndex = 1; obj.style.position = "static"; obj.style.border = "0px"; }; img.setAttribute('src', imageSrc); //img.style.width= "1"; td.appendChild(img); td.style.border = "1px solid black"; td.style.textAlign = "center"; // fixed head (img does not cover head) td.style.zIndex="1"; td.style.width= (chosenWidth)+"px"; } } //tableBody.appendChild(tr); } // fixed head and inner scroll tableBody.style.display="block"; tableBody.style.overflow="auto"; tableBody.style.height ="500px"; //alert(tableBody.style.overflow); tbl.appendChild(tableBody); tableDiv.appendChild(tbl); body.appendChild(tableDiv); }
[ "function generateTable(sizeChoice, imageChoice){\n\n //change triangle\n var string = window.location.href + \"images/closedTriangle.png\";\n document.getElementById('img2').innerHTML = ' <img src=\"'+string+'\" width = 15px>';\n secondTriangle = \"closed\";\n\n //pulls selected manuscripts and creates array chosenManuscripts\n var chosenManuscripts = getChosenValuesFromList(\"manuscripts\");\n\n //pulls letters and creates array chosenLetters\n var chosenLetters = getChosenValuesFromList(\"letters\");\n\n\n if(chosenLetters.length > 0 && chosenManuscripts.length > 0) {\n\n //create the table with manuscrips, letters, and images\n document.getElementById('letterTable').innerHTML = ' ';\n chosenManuscripts.splice(0, 0, \"\"); //formatting\n var body = document.getElementById('letterTable');\n var tableDiv = document.createElement('div');\n tableDiv.style.width = \"100%\";\n tableDiv.style.height = \"100%\";\n tableDiv.style.overflow = \"scroll\";\n var tbl = document.createElement('table');\n tbl.style.backgroundColor = \"#f0eff0\";\n tbl.style.border = \"1px solid black\";\n\n for(var k = 0; k < chosenManuscripts.length; k++) {\n var th = document.createElement(\"th\");\n th.style.border = \"1px solid black\";\n var title = chosenManuscripts[k] + \" \";\n var name = title.slice(0, title.indexOf(\":\"));\n var date = title.slice(title.indexOf(\":\")+2);\n\n //regex that searches for first number\n var search = name.search(/\\d/);\n var shelfmark = name.substring(search);\n var manuscript = name.substring(0,search);\n\n th.appendChild(document.createTextNode(manuscript));\n th.appendChild(document.createElement('br'));\n// th.appendChild(document.createElement('br'));\n\n th.appendChild(document.createTextNode(shelfmark));\n th.appendChild(document.createElement('br'));\n// th.appendChild(document.createElement('br'));\n\n th.appendChild(document.createTextNode(date));\n\n th.style.textAlign = \"center\";\n tbl.appendChild(th);\n }\n\n for(var i = 0; i < chosenLetters.length; i++) {\n var tr = tbl.insertRow();\n //letter names\n var td2 = tr.insertCell();\n td2.style.border = \"1px solid black\";\n td2.appendChild(document.createTextNode(chosenLetters[i]));\n tr.appendChild(td2);\n\n\n for(var j = 0; j < chosenManuscripts.length; j++){\n if(j != 0) {\n var str = chosenManuscripts[j];\n var formatted = str.replace(/ /g, \"_\");\n var res = formatted.split(\":\");\n\n //creates fileName to pull image\n var imageFileName = \"images/\" + imageChoice + \"/\" + chosenLetters[i] + \"_\" + res[0] + \".png\";\n var imageSrc = imageFileName.toLowerCase();\n\n var td = tr.insertCell();\n\n var img = document.createElement(\"img\");\n\n img.setAttribute(\"alt\", chosenLetters[i]);\n\n img.onmouseover = function() {\n var obj = this;\n console.log(obj);\n width = obj.naturalWidth;\n obj.style.top = \"0px\";\n obj.style.left = \"0px\";\n obj.style.position = \"absolute\";\n obj.style.width = (2*width)+\"px\"; //2*width;\n obj.style.zIndex = 1;\n obj.style.border = \"5px silver outset\";\n };\n\n img.onload = function() {\n //could reverse engineer this from filename\n //store letter name in alt field to access here\n\n var width = this.clientWidth;\n //set height to x, multiply by scaleFactor\n var scaleFactor = 2;\n\n if(sizeChoice==\"small\") {\n this.width = 25*scaleFactor;\n }\n else if (sizeChoice ==\"medium\") {\n this.width = 40*scaleFactor;\n }\n else {\n this.width = 50*scaleFactor;\n }\n };\n\n img.setAttribute('src', imageSrc);\n\n img.onerror = function() {\n this.onerror = null;\n this.src = \"images/noImage.png\";\n };\n\n\n td.appendChild(img);\n td.style.border = \"1px solid black\";\n td.style.textAlign = \"center\";\n }\n }\n }\n\n tableDiv.appendChild(tbl);\n body.appendChild(tableDiv);\n // body.appendChild(tbl);\n }\n else {\n document.getElementById('letterTable').innerHTML = '<h4> Error: Incorrect selection </h4> ';\n }\n}", "function fillEachTable(numTable)\n{\n\n var baseFileName;\n var size;\n var angle;\n var fileNumber;\n var i;\n \n if (numTable == 0)\n {\n usedList = [];\n table1Equal = getRandom(9) + 1;\n table2Equal = getRandom(9) + 1;\n baseNameRepeated = String(getRandom(image_quatity)).padStart(2, '0');\n usedList[usedList.length] = baseNameRepeated;\n }\n\n for (i = 1; i < 10; i++) {\n \n while(usedList.length < image_quatity && !(numTable == 0 && i == table1Equal) && !(numTable == 1 && i == table2Equal))\n {\n baseFileName = String(getRandom(image_quatity)).padStart(2, '0');\n if (!usedList.includes(baseFileName))\n {\n usedList[usedList.length] = baseFileName;\n break;\n }\n \n }\n size = getRandomSize();\n angle = getRandomAngle();\n if( (numTable == 0 && i == table1Equal) || (numTable == 1 && i == table2Equal) )\n {\n document.getElementById(\"img\"+(i+(numTable*9))).src = \"./images/\" + baseNameRepeated + \".png\";\n }\n else\n {\n document.getElementById(\"img\"+(i+(numTable*9))).src = \"./images/\" + baseFileName + \".png\";\n }\n\n document.getElementById(\"img\"+(i+(numTable*9))).height = size;\n document.getElementById(\"img\"+(i+(numTable*9))).width = size;\n document.getElementById(\"img\"+(i+(numTable*9))).style.transform = \"rotate(\"+ angle + \"deg)\";\n }\n\n}", "function setup() {\n\n //count the columns\n //print(table.getRowCount() + ' total rows in table');\n //print(table.getColumnCount() + ' total columns in table');\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount()-1; c++) {\n //print(table.getString(r, c));\n words_raw[wordscount] = table.getString(r, c);\n wordscount++;\n }\n\n //console.log(words_raw); // prints the whole file contents\n var words = words_raw;\n\n for(var i = 0;i < words.length/8;i++){\n //var words = lines[i].split(',');\n //console.log(words[i]);\n\n var Left_id = words[0+i*8];\n var Left_Arrangement = words[1+i*8];\n var Left_Percentage = words[2+i*8];\n var Left_Size = words[3+i*8];\n var Right_id = words[4+i*8];\n var Right_Arrangement = words[5+i*8];\n var Right_Percentage = words[6+i*8];\n var Right_Size = words[7+i*8];\n\n var left = Left_id + \"_\" + Left_Arrangement + \"_\" + Left_Percentage + \"_\" + Left_Size;\n var right = Right_id + \"_\" + Right_Arrangement + \"_\" + Right_Percentage + \"_\" + Right_Size;\n\n var l = new Image();\n l.src = \"./svgs/\" + left + \".svg\";;\n var r = new Image();\n r.src = \"./svgs/\" + right + \".svg\";\n\n l_images.push(l);\n r_images.push(r);\n\n l_images.push(r);\n r_images.push(l);\n //console.log();\n }\n\n // shuffle the array to show comparisons in different order each time\n //shuffle(l_images,r_images);\n shuffleLeft(l_images);\n shuffleRight(r_images);\n //shuffled_l_images = shuffled_imgs[0];\n //shuffled_r_images = shuffled_imgs[1];\n // console.log(\"l_images len :\" + l_images.length);\n // console.log(\"shuffled left :\" + shuffled_l_images);\n // console.log(\"shuffled left :\" + shuffled_r_images);\n //console.log(shuffled_l_images);\n}", "function fill_image_table(type, action){\n\t\tvar image_table = document.createElement(\"table\");//Table\n\t\timage_table.id = \"image_table\";\n\t\timage_table.width = \"100%\";\n\t\timage_table.classList.add(\"image_table\");\n\t\t\n\t\tvar sortable = [];//Sort data\n\t\tfor(var i in IPython.notebook.metadata[\"image.base64\"]){\n\t\t\tsortable.push(i);\n\t\t}\n\t\tsortable.sort(function (a, b){\n\t\t\treturn a.toLowerCase().localeCompare(b.toLowerCase());\n\t\t});\n\t\tfor(var x in sortable){\n\t\t\tvar i = sortable[x];//Table row\n\t\t\tconsole.log(i);\n\t\t\tvar tr = document.createElement(\"tr\");\n\t\t\t\tvar td_text = document.createElement(\"td\");//Cell with image name\n\t\t\t\ttd_text.appendChild(document.createTextNode(i));\n\t\t\t\t\n\t\t\t\tvar td_image = document.createElement(\"td\");//Cell with small version of the image\n\t\t\t\ttd_image.style.width = \"100px\";\n\t\t\t\ttd_image.style.height = \"79px\";\n\t\t\t\ttd_image.style.overflow = \"auto\";\n\t\t\t\ttd_image.setAttribute(\"data-src\", i);\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tvar image = document.createElement(\"img\");\n\t\t\t\t\timage.setAttribute(\"src\", IPython.notebook.metadata[\"image.base64\"][this.getAttribute(\"data-src\")]);\n\t\t\t\t\timage.setAttribute(\"alt\", this.getAttribute(\"data-src\"));\n\t\t\t\t\timage.style[\"max-width\"] = \"90px\";\n\t\t\t\t\timage.style[\"max-height\"] = \"75px\";\n\t\t\t\t\tthis.innerHTML = \"\";\n\t\t\t\t\tthis.appendChild(image);\n\t\t\t\t\tthis.onclick = null;\n\t\t\t\t}.bind(td_image), 2);\n\t\t\t\ttd_image.innerHTML = \"Image\";\n\t\t\t\t\n\t\t\t\tvar td_base64_value = document.createElement(\"td\");//Cell with base64 value\n\t\t\t\ttd_base64_value.style.width = \"100px\";\n\t\t\t\ttd_base64_value.style.height = \"79px\";\n\t\t\t\ttd_base64_value.setAttribute(\"data-src\", i);\n\t\t\t\ttd_base64_value.onclick = function(){\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\tvar p_base64 = document.createElement(\"p\");\n\t\t\t\t\t\tp_base64.style.width = \"90px\";\n\t\t\t\t\t\tp_base64.style.height = \"70px\";\n\t\t\t\t\t\tp_base64.style[\"word-break\"] = \"break-all\";\n\t\t\t\t\t\tp_base64.style[\"overflow\"] = \"auto\";\n\t\t\t\t\t\tp_base64.innerHTML = IPython.notebook.metadata[\"image.base64\"][this.getAttribute(\"data-src\")];\n\t\t\t\t\t\tthis.innerHTML = \"\";\n\t\t\t\t\t\tthis.appendChild(p_base64);\n\t\t\t\t\t\tthis.onclick = null;\n\t\t\t\t\t}.bind(this), 2);\n\t\t\t\t}\n\t\t\t\ttd_base64_value.innerHTML = \"Click to show base64\";\n\t\t\t\t\n\t\t\t\tvar td_buttons = document.createElement(\"td\");//Cell for buttons\n\t\t\t\t\tvar button_delete = document.createElement(\"button\");//Button for delete\n\t\t\t\t\tbutton_delete.onclick = delete_image.bind(button_delete, i, this);\n\t\t\t\t\t\tvar icon_delete = document.createElement(\"i\");\n\t\t\t\t\t\ticon_delete.classList.add(\"fa\");\n\t\t\t\t\t\ticon_delete.classList.add(\"fa-trash\");\n\t\t\t\t\tbutton_delete.appendChild(icon_delete);\n\t\t\t\t\t\n\t\t\t\t\tvar button_add_image = document.createElement(\"button\");//Button for adding image cell to document\n\t\t\t\t\tbutton_add_image.onclick = add_image_cell.bind(this, i);\n\t\t\t\t\t\tvar icon_plus = document.createElement(\"i\");\n\t\t\t\t\t\ticon_plus.classList.add(\"fa\");\n\t\t\t\t\t\ticon_plus.classList.add(\"fa-plus\");\n\t\t\t\t\tbutton_add_image.appendChild(icon_plus);\n\t\t\t\t\t\n\t\t\t\t\tvar button_add_image_invisible = document.createElement(\"button\");\n\t\t\t\t\tbutton_add_image_invisible.onclick = add_image_cell_invisible.bind(this, i);\n\t\t\t\t\t\tvar icon_plus_invisible = document.createElement(\"i\");\n\t\t\t\t\t\ticon_plus_invisible.classList.add(\"fa\");\n\t\t\t\t\t\ticon_plus_invisible.classList.add(\"fa-plus\");\n\t\t\t\t\t\ticon_plus_invisible.style.opacity = \"0.5\";\n\t\t\t\t\tbutton_add_image_invisible.appendChild(icon_plus_invisible);\n\t\t\t\ttd_buttons.appendChild(button_delete);\n\t\t\t\ttd_buttons.appendChild(button_add_image);\n\t\t\t\t//td_buttons.appendChild(button_add_image_invisible);\n\t\t\ttr.appendChild(td_text);\n\t\t\ttr.appendChild(td_image);\n\t\t\ttr.appendChild(td_base64_value);\n\t\t\ttr.appendChild(td_buttons);\n\t\t\t\n\t\t\timage_table.appendChild(tr);\n\t\t}\n\t\t$(this).find(\"#image_table\").replaceWith(image_table);//Replaces the table\n\t}", "function imGenerator (userInput){\n\tconsole.log(\"start\");\n\t\n\t\n\t// uncomment to get html content\n\t//var textField = document.getElementById(e);\n\t//var userInput = textField.value;\n\tvar jimps = [];\n\n\t// all chars and their image path\n\tvar charToPath = {\n\t\t'א' : \"../Images/alef/alef_\",\n\t\t'ב' : \"../Images/bet/bet_\",\n\t\t'ג' : \"../Images/gimel/gimel_\",\n\t\t'ד' : \"../Images/dalet/dalet_\",\n\t\t'ה' : \"../Images/hey/hey_\",\n\t\t'ו' : \"../Images/vav/vav_\",\n\t\t'ז' : \"../Images/zain/zain_\",\n\t\t'ח' : \"../Images/het/het_\",\n\t\t'ט' : \"../Images/tet/tet_\",\n\t\t'י' : \"../Images/yud/yud_\",\n\t\t'כ' : \"../Images/chaf/chaf_\",\n\t\t'ך' : \"../Images/chaf_sofit/chaf_sofit_\",\n\t\t'ל' : \"../Images/lamed/lamed_\",\n\t\t'מ' : \"../Images/mem/mem_\",\n\t\t'ם' : \"../Images/mem_sofit/mem_sofit_\",\n\t\t'נ' : \"../Images/nun/nun_\",\n\t\t'ן' : \"../Images/nun_sofit/nun_sofit_00000\",\n\t\t'ס' : \"../Images/samech/samech_\",\n\t\t'ע' : \"../Images/ayin/ayin_\",\n\t\t'פ' : \"../Images/pei/pei_\",\n\t\t'צ' : \"../Images/tsadik/tsadik_\",\n\t\t'ץ' : \"../Images/tsadik_sofit/tsadik_sofit_\",\n\t\t'ק' : \"../Images/kof/kof_\",\n\t\t'ר' : \"../Images/resh/resh_\",\n\t\t'ש' : \"../Images/shin/shin_\",\n\t\t'ת' : \"../Images/taf/taf_\",\n\t\t'space' : \"../Images/space/space.png\",\n\t};\n\n\n\t// letters size\n\tconst srcImWidth = 275;\n\tconst srcImHeight = 275; // delete this one if symetric\n\n\t// Background size\n\tconst bgWidth = 1920;\n\n\t//imPath contains the full path to be added\n\t// just an example, need to parse the string \n\t// into a relevant map\n\t// background in index 0, all images will be on top of it\n\tvar allImages = [\"../Images/floor_bg.png\"];\n\tvar lineStart = bgWidth - srcImWidth;\n\n\tvar currX = lineStart;\n\tvar currY = 0;\n\tvar imSrc = '';\n\n\t// this need to be similar to the number\n\t// of letters fit inside textArea in html\n\tvar lettersInLine = Math.floor(bgWidth/srcImWidth);\n\tconsole.log(\"lettersInLine = \" , lettersInLine);\t\t\n\n\tvar currWord = [];\t\t// used to collect a complete word and calculate its position\n\tvar currWordLen = 0;\n\n\t// for loop to initilize allImages variable\n\t// looking for \\n \\0 or ' ' to make a word\n\t// calculate the \n\tfor (var i = 0; i < userInput.length ; i++){\n\t\t//console.log(\"enter for..\");\n\t\t//console.log(\"currX: \", currX, \", currY: \", currY, \", src: \", srcPaths[i]);\n\n\t\t// cases for \\n \\0 and ' '\n\t\t// this will be expanded\n\t\t\n\t\t//example for path: \"Images/g-letter.jpg\"\n\t\t\n\n\t\t// in this case currWord contain a complete\n\t\t// word and needed to insert to allImages\n\t\tif (userInput.charAt(i) === '\\n' || userInput.charAt(i) === ' ' || userInput.charAt(i) === '\\0'){\n\t\t\t\n\t\t\t// check if the word fits to the current row\n\t\t\tif (bgWidth - currWordLen >= 0){\n\t\t\t\tif(userInput.charAt(i) === ' '){\n\t\t\t\t\timSrc = charToPath['space'];\n\t\t\t\t\tallImages.push(setLetterInfo(imSrc, currX, currY));\n\t\t\t\t\tcurrX = currX - srcImWidth;\n\t\t\t\t\tcurrWordLen = 0;\n\t\t\t\t\tif (currX < 0){\n\t\t\t\t\t\tcurrX = lineStart;\n\t\t\t\t\t\tcurrY = currY + srcImHeight;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tallImages = pushWord(allImages, currWord);\n\t\t\t}\n\t\t\t\t\n\t\t\t// need to break this scenario to \\n, \\0 and space\n\t\t\t// maybe adding functionality to rescale images??\t\n\t\t\telse{\n\t\t\t\t// TODO: deal with long words, throw error etc..\n\t\t\t\tif (currWordLen > lettersInLine){\n\t\t\t\t\tconsole.log(\"word too long!!\");\n\t\t\t\t}\n\t\t\t\t// word fits to new line\n\t\t\t\telse{\n\t\t\t\t\t// enter key case\n\t\t\t\t\tif (userInput.charAt(i) === '\\n'){\n\t\t\t\t\t\t//console.log(\"Enter_key found\")\n\t\t\t\t\t\tallImages = fillLine(allImages, charToPath[' '] , currX, currY); // TODO: implement\n\t\t\t\t\t\tcurrX = lineStart;\n\t\t\t\t\t\tcurrY = currY + srcImHeight;\n\t\t\t\t\t}\n\t\t\t\t\t// space key entered\n\t\t\t\t\telse if(userInput.charAt(i) === ' '){\n\t\t\t\t\t\timSrc = charToPath['space'];\n\t\t\t\t\t\tallImages.push(setLetterInfo(imSrc, currX, currY));\n\t\t\t\t\t\tcurrX = currX - srcImWidth;\n\t\t\t\t\t\tif (currX < 0){\n\t\t\t\t\t\t\tcurrX = lineStart;\n\t\t\t\t\t\t\tcurrY = currY + srcImHeight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// end of userInput\n\t\t\t\t\telse if(userInput.charAt(i) === '\\0'){\n\t\t\t\t\t\tallImages = pushWord(allImages, currWord);\n\t\t\t\t\t\tcurrWord = [];\n\t\t\t\t\t\tcurrWordLen = 0;\n\t\t\t\t\t\t// TODO: finish\n\t\t\t\t\t}\n\t\t\t\t}//End of word fits\n\t\t\t}\n\t\t} //End if complete word\n\n\t\t// build a word\n\t\telse{\n\t\t\t// checking for valid word length\n\t\t\tif(currWordLen < lettersInLine){\n\t\n\t\t\t\timSrc = charToPath[userInput.charAt(i)]; // takes the character path\n\t\t\t\timSrc = imSrc + '000.png';\n\t\t\t\tcurrWord.push({src: imSrc, x: currX, y: currY});\n\t\n\t\t\t\tcurrWordLen++;\n\t\t\t\tcurrX = currX - srcImWidth;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(\"Trying to insert too long word!\");\n\t\t\t}\n\t\t} // end of word build\n\t} // end of for loop\n\tconsole.log(allImages);\n\t\n\tallImages = pushWord(allImages, currWord); // push the last word\n\n\t// read the background\n\tjimps.push(jimp.read(allImages[0]));\n\t// jimp read the images to promises\n\n\tfor (var i = 1; i < allImages.length; i++){\n\t\tjimps.push(jimp.read(allImages[i].src));\n\t}\n\n\n\tPromise.all(jimps).then(function(data){\n\t\treturn Promise.all(jimps);\n\t}).then(function(data){ //top left cords is 0,0\n\t\tfor(var i = 1; i < allImages.length; i++){\n\t\t\tdata[0].composite(data[i], allImages[i].x , allImages[i].y);\t\n\t\t}\n\t\t\n\n\t\tdata[0].write('../final-images/test.png', function(){\n\t\t\tconsole.log(\"wrote the image\");\n\t\t});\n\t});\n\n/*\n\tvar canvas = document.getElementById('out-im'),\n\tcontext = canvas.getContext('2d');\n\twindow.addEventListener('DOMContentLoaded', initImageLoader);\n*/\n}", "function createSmileysTable(tableNum, areaId)\r\n{\r\n\tvar SMILEY_COUNT = 21;\r\n\tvar currentSmiley = (SMILEY_COUNT * tableNum);\r\n\r\n\t// Converts numbers in hexadecimal string\r\n\tfunction base10ToBase16 ()\r\n\t{\r\n\t\t// Here is the conversion\r\n\t\tvar str = (++currentSmiley).toString(16);\r\n\t\tstr = str.toUpperCase();\r\n\t\tif (currentSmiley < 16) str = '0' + str;\r\n\t\treturn str;\r\n\t}\r\n\r\n\tvar tr = document.createElement('tr');\r\n\t\tfor (var i=0; i < SMILEY_COUNT; i++)\r\n\t\t{ \r\n\t\t\tvar td = document.createElement('td');\r\n\t\t\tvar a = document.createElement('a');\r\n\t\t\ta.href = 'javascript:add2tag(' + \"'\" + getSmiley((SMILEY_COUNT*tableNum)+i) + \"'\" + ', \"'+ areaId +'\",\"0\")';\r\n\t\t\ta.areaId = areaId.substr(\"area\".length, areaId.length);\r\n\r\n\t\t\tvar image = document.createElement('img');\r\n\t\t\timage.src = 'http://www.kramages.org/s/' + base10ToBase16() +'.gif'\r\n\t\t\ta.appendChild(image);\r\n\t\t\ttd.appendChild(a);\r\n\t\t\ttr.appendChild(td);\r\n\t\t}\r\n\treturn tr;\r\n}", "function repopulateImages() {\r\n const dateNow = Date.now();\r\n var CCTVNo, NN;\r\n for ( var index = 0; index < camDef.length; index++ ) {\r\n [ , , CCTVNo ] = camDef[ index ];\r\n tester[ index ].src = `${HeadCCTV}${CCTVNo}${TailCCTV}${dateNow}`;\r\n }\r\n }", "function fillTable(game){\n var template=[];\n for(var i=1;i<=4;i++){\n for(var j=1;j<=4;j++){\n template.push(\"<img id='fila-\"+i+\" col-\"+j+\"'src='../img/\"+game+\"/fila-\"+i+\"-col-\"+j+\".jpg'>\");\n }\n }\n // console.log(\"ordenado\",template);\n disorderPuzzle(template);\n}", "function generateImages()\n{\n createArray(); // Calling array that puts images into the array\n \n document.getElementById('picturePlace').innerHTML = \"<table>\"; //Starting the table\n \n for(var j = 1; j <= 3; j++) //Row Loop\n {\n document.getElementById(\"picturePlace\").innerHTML += \"<tr>\"; //Creates a row on each loop\n \n for(var i = 1; i <= 4; i++) //Column loop\n {\n var randomNum = Math.floor(Math.random() * (11 - 0 + 1)) + 0; // Random number from 0-11\n\n if(!inArray(randomNum)) //Check to see if we've used this number before\n {\n arrayCheck[arrayCheck.length] = randomNum; //Since we haven't, we put it in the array\n \n var jString = new String(j); //String of the j value\n var iString = new String(i); //String of the i value\n var imageID = new String(\"Row\" + jString + \"Col\" + iString); //String that will become the image HTML ID\n \n var imgString = new String(\"<img src='\"+imgAry[randomNum]+\"' id='\"+imageID+\"'>\"); //String that will be used to create the html\n \n //The HTML created will look like: <td><img src='xy.jpg' id='RowxColy'></td>\n document.getElementById(\"picturePlace\").innerHTML += \"<td>\"+imgString+\"</td>\"; //Creating the column HTML \n }\n else i= i-1; //If the number IS in the array, we just minus one and retry\n }\n document.getElementById(\"picturePlace\").innerHTML += \"</tr><br>\"; //Ending Row\n }\n document.getElementById(\"picturePlace\").innerHTML += \"</table>\"; //Ending Table\n \n}//End of Generate Images", "function createPNGFiles(data){\n for(i = 0; i < data.length ; i++){\n var name = data[i].name;\n var description = data[i].description;\n updateText(name, description);\n var docName = name.replace(/\\s/g,'');\n exportPNG(docName);\n }\n // close the photoshop file without saving it to leave the template as it was\n app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n // quit the photoshop application - comment out if you don't want PS to quit\n executeAction(app.charIDToTypeID('quit'), undefined, DialogModes.NO);\n}", "function generateImagesMainPage() {\n\t\tfor (i = 0; i < totalNumberOfItems; i++) {\n\t\t\tvar insertPlace = $(\".flowersandleaves\"); //all over the page\n\t\t\tvar insertedDiv = $(\"<div> </div>\");\n\t\t\tvar insertElement = $(\"<img> </img>\");\n\t\t\tinsertedDiv.append(insertElement);\n\t\t\tinsertedDiv.addClass(\"randomElement\");\n\t\t\tinsertPlace.append(insertedDiv);\n\t\t\tvar x = ramdomNumberWhat();\n\t\t\tvar randomAngle = Math.floor((Math.random() * 45) - 65);\n\t\t\tvar randomAngleSmall = Math.floor((Math.random() * 45) - 25);\n\t\t\t//top image left and right \n\t\t\tif (x === 0) {\n\t\t\t\tinsertedDiv.css(\"top\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.css(\"left\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.addClass(\"mediumItems\");\n\t\t\t\tinsertedDiv.addClass(\"farLeft\");\n\t\t\t\tinsertElement.attr(\"src\", theItems[x]);\n\n\n\n\t\t\t} else {\n\t\t\t\tinsertedDiv.css(\"top\", bottomBottom() + \"%\");\n\t\t\t\tinsertedDiv.css(\"left\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.addClass(\"bottomItems\");\n\t\t\t\tinsertElement.attr(\"src\", theItems[x]);\n\t\t\t\tinsertElement.css({\n\t\t\t\t\t'-webkit-transform': 'rotate(' + randomAngle + 'deg)',\n\t\t\t\t\t'-moz-transform': 'rotate(' + randomAngle + 'deg)'\n\t\t\t\t});\n\t\t\t}\n\n\n\t\t}\n\t}", "function buildTable(start, end, gen)\n{\n\t//initialize first row of table\n\tvar out = \"<table style='width:100%', font-family:.pokemonfont3>\";\n\tout += \"<tr>\"\n\t\t+ \"<td>SPRITE</td>\"\n\t\t+ \"<td>ID</td>\"\n\t\t+ \"<td>NAME</td>\"\n\t\t+ \"<td>DESC</td>\"\n\t\t+ \"<td>HEIGHT</td>\"\n\t\t+ \"<td>WEIGHT</td>\"\n\t\t+ \"<td>BMI</td>\"\n\t\t+ \"<td>STATUS</td>\"\n\t\t+ \"</tr>\";\n\t\t\n\t//iterate over a range of pokedex entries\n\tfor(var i = start; i <= end; ++i)\n\t{\n\t\tvar dexJSON = getEntry(i);\n\t\tvar height = dexJSON.height / 10;\n\t\tvar weight = dexJSON.weight / 10;\n\t\t\n\t\tout += \"<tr>\"\n\t\t\t+ \"<td width='150'><img src='\" + getImage(dexJSON) + \"'></td>\"\n\t\t\t+ \"<td>\" + dexJSON.national_id + \"</td>\"\n\t\t\t+ \"<td width='100'>\" + dexJSON.name + \"</td>\"\n\t\t\t+ \"<td width='250'>\" + getDesc(dexJSON, gen) + \"</td>\"\n\t\t\t+ \"<td>\" + height + \" m</td>\"\n\t\t\t+ \"<td>\" + weight + \" kg</td>\"\n\t\t\t+ \"<td>\" + calcBMI(height,weight) + \"</td>\"\n\t\t\t+ \"<td>\" + interpretBMI(calcBMI(height,weight)) + \"</td>\"\n\t\t\t+ \"</tr>\";\n\t}\n\t\n\tout += \"</table>\";\n\tdocument.getElementById(\"id01\").innerHTML += out\n}", "function generateImages() {\n for (i = 0; i < images.length; i++) {\n var imageCrystal = $(\"<img>\");\n imageCrystal.addClass(\"image-crystal\");\n imageCrystal.attr(\"id\", \"crystal\");\n $(\"#images\").append(imageCrystal);\n imageCrystal.attr(\"src\", images[i]);\n imageCrystal.attr(\"data-crystalvalue\", RandNumber[i]);\n }\n }", "createXMLIExampledatabaseLS() {\n\t\tthis.zscoreNormalization();\n\t\tfor (let i = 0; i < this.allpictures.stuff.length; i++) {\n\t\t\tfor (let j = 0; j < this.allpictures.stuff.length; j++) {\n\t\t\t\tlet distancia = this.calcManhattanDist(this.allpictures.stuff[i], this.allpictures.stuff[j]);\n\t\t\t\tthis.allpictures.stuff[i].manhattanDist.push(distancia);\n\t\t\t}\n\t\t}\n\t\tlet imagens = this.allpictures.stuff.slice();\n\t\tfor (let i = 0; i < this.allpictures.stuff.length; i++) {\n\t\t\tlet xmlRowString = '<images>';\n\t\t\tthis.sortbyManhattanDist(i, imagens);\n\t\t\tfor (let x = 0; x < this.numshownpic; x++) {\n\t\t\t\txmlRowString += '<image class=\"Manhattan\"><path>' + imagens[x].impath + '</path></image>';\n\t\t\t}\n\t\t\txmlRowString += '</images>';\n\t\t\tthis.LS_db.saveLS_XML(this.allpictures.stuff[i].impath, xmlRowString);\n\t\t}\n\t}", "function getgPunctuationImage(number) {\n let source;\n switch (number) {\n case \"0\":\n source = '<img src=\"assets/images/card_Ampresand.jpg\">';\n break;\n case \"1\":\n source = '<img src=\"assets/images/card_Apostrope.jpg\">';\n break;\n case \"2\":\n source = '<img src=\"assets/images/card_At.jpg\">';\n break;\n case \"3\":\n source = '<img src=\"assets/images/card_Colon.jpg\">';\n break;\n case \"4\":\n source = '<img src=\"assets/images/card_Comma.jpg\">';\n break;\n case \"5\":\n source = '<img src=\"assets/images/card_Dollar.jpg\">';\n break;\n case \"6\":\n source = '<img src=\"assets/images/card_Equals.jpg\">';\n break;\n case \"7\":\n source = '<img src=\"assets/images/card_Exclamation.jpg\">';\n break;\n case \"8\":\n source = '<img src=\"assets/images/card_Hyphen.jpg\">';\n break;\n case \"9\":\n source = '<img src=\"assets/images/card_ParanthesisClose.jpg\">';\n break;\n case \"10\":\n source = '<img src=\"assets/images/card_ParanthesisOpen.jpg\">';\n break;\n case \"11\":\n source = '<img src=\"assets/images/card_Period.jpg\">';\n break;\n case \"12\":\n source = '<img src=\"assets/images/card_Plus.jpg\">';\n break;\n case \"13\":\n source = '<img src=\"assets/images/card_Question.jpg\">';\n break;\n case \"14\":\n source = '<img src=\"assets/images/card_Quotation.jpg\">';\n break;\n case \"15\":\n source = '<img src=\"assets/images/card_Slash.jpg\">';\n break;\n case \"16\":\n source = '<img src=\"assets/images/card_Underscore.jpg\">';\n break;\n default:\n source = '<img src=\"assets/images/card_back.jpg\">';\n }\n return source;\n}", "function processImageFileAsHtml (res, imgfpath, imgwsfpath, imgtitle, imgurl, imglfn, outputdesign, labeltype, uselang) {\n // Arrays of objects for output of the PMD in different sections of the HTML output\n // for the 'perstandard' design\n let iimOutObjarr = [];\n let xmpOutObjarr = [];\n let exifOutObjarr = [];\n // for the 'pertopics' design\n let gimgcontOutObjarr = [];\n let personOutObjarr = [];\n let locationOutObjarr = [];\n let othingsOutObjarr = [];\n let rightsOutObjarr = [];\n let licOutObjarr = [];\n let adminOutObjarr = [];\n let imgregOutObjarr = [];\n let anyOutObjStdarr = [];\n let anyOutObjarrTopic = [];\n let noneOutObjarrStd = [];\n let noneOutObjarrTopic = [];\n // for special feature designs\n let isearch1SpecOutObjarr = []; // for the design of image search metadata\n let noneOutObjarrSpec = [];\n // for other purposes\n let schemaorgObjarr = []; // container of schema.org metadata (property name/value pair objects)\n\n let labelId = -1;\n if (labeltype === undefined){\n labelId = 1;\n }\n else {\n switch (labeltype.toLowerCase()) {\n case 'et':\n labelId = 0;\n break;\n case 'ipmd':\n labelId = 1;\n break;\n case 'std':\n labelId = 2;\n break;\n }\n }\n if (ep.isOpen) {\n ep.close().then(() => {\n console.log('Start action: close exiftool');\n }).catch(err => {\n tools1.write2Log('ERROR @default closing of exiftool: ' + err);\n });\n }\n\n // An ExifTool process is started to retrieve the metadata\n ep.open().then((pid) => {\n console.log('Started exiftool process %s', pid);\n return ep.readMetadata(imgfpath, ['j', 'G1', 'struct' ]).then((pmdresult) => {\n // metadata has been retrieved and are processed as pmdresult object\n console.log ('Image tested by ExifTool: ' + imgfpath);\n\n // each property must be displayed in one of the output objects\n // these target... objects are set by the PMD Investigation Guide\n let targetObjStd = null; // values will be set later\n let targetObjTopics = null; // values will be set later\n // ... for special output designs:\n let targetObjSpecIsearch1 = null; // values will be set later\n\n\n let topPmdPropNames = Object.getOwnPropertyNames(pmdresult.data[0]);\n\n // iterate across all top level property names found in the pmd result\n for (let tPPNidx = 0; tPPNidx < topPmdPropNames.length; tPPNidx++){\n let topPmdPropName = topPmdPropNames[tPPNidx];\n let topPmdPropName4ref = topPmdPropName.replace(\":\",\"_\");\n if (!(refTopPropNamesWPf.includes(topPmdPropName4ref))){ // topPmdPropName not in reference list\n continue;\n }\n // topPmdPropName found in reference list\n\n let topProp = pmdresult.data[0][topPmdPropName];\n let propType = undefined;\n\n let usedPropLabelCode = pmdinvguide.data.topwithprefix[topPmdPropName4ref].label;\n if (uselang !== 'en') {\n if (pmdinvguide.data.topwithprefix[topPmdPropName4ref].labellocal) {\n if (pmdinvguide.data.topwithprefix[topPmdPropName4ref].labellocal[uselang]) {\n usedPropLabelCode = pmdinvguide.data.topwithprefix[topPmdPropName4ref].labellocal[uselang];\n }\n }\n }\n let propLabel = tools1.getLabelPart(topPmdPropName + \"|\" + usedPropLabelCode, labelId);\n let propSortorder = pmdinvguide.data.topwithprefix[topPmdPropName4ref].sortorder;\n let propOutputAll = pmdinvguide.data.topwithprefix[topPmdPropName4ref].output;\n let propValue = undefined; // value will be set in different ways (further down)\n // retrieve where this top level property and all its sub-properties should be\n // displayed in the output of this system and set the target... variables\n let outputList = propOutputAll.split(','); // array of all 'output' terms\n // iterate array and set where a property should be displayed\n for (let io = 0; io < outputList.length; io++){\n targetObjSpecIsearch1 = noneOutObjarrSpec;\n switch(outputList[io]){\n case 'iim':\n targetObjStd = iimOutObjarr;\n break;\n case 'xmp':\n targetObjStd = xmpOutObjarr;\n break;\n case 'exif':\n targetObjStd = exifOutObjarr;\n break;\n case 'gimgcont':\n targetObjTopics = gimgcontOutObjarr;\n break;\n case 'person':\n targetObjTopics = personOutObjarr;\n break;\n case 'location':\n targetObjTopics = locationOutObjarr;\n break;\n case 'othings':\n targetObjTopics = othingsOutObjarr;\n break;\n case 'rights':\n targetObjTopics = rightsOutObjarr;\n break;\n case 'licensing':\n targetObjTopics = licOutObjarr;\n break;\n case 'admin':\n targetObjTopics = adminOutObjarr;\n break;\n case 'imgreg':\n targetObjTopics = imgregOutObjarr;\n break;\n case 'any':\n targetObjTopics = anyOutObjStdarr;\n targetObjStd = anyOutObjarrTopic;\n break;\n case 'isearch1':\n targetObjSpecIsearch1 = isearch1SpecOutObjarr;\n break;\n default :\n targetObjStd = noneOutObjarrStd;\n targetObjTopics = noneOutObjarrTopic;\n targetObjSpecIsearch1 = noneOutObjarrSpec;\n break;\n }\n }\n let topPropSpecidx = \"\";\n if (pmdinvguide.data.topwithprefix[topPmdPropName4ref].specidx){\n topPropSpecidx = pmdinvguide.data.topwithprefix[topPmdPropName4ref].specidx;\n }\n\n let topPropIsArray = Array.isArray(topProp);\n if (topPropIsArray){ // the values of the topProp are in an array\n if (topProp.length > 0){\n if (typeof topProp[0] === 'object' ){ // array items are objects\n propType = structptype;\n propValue = getPropValueData(topProp, labelId, schemaorgObjarr)[pvdValue]; // investigate the value object of the topProp\n }\n else { // array items are a string, make a single one out of them\n let pvalueConcat = \"\";\n // iterate items of the array\n for (let arrIdx = 0; arrIdx < topProp.length; arrIdx++) {\n pvalueConcat += '[' + (arrIdx + 1).toString() + '] ' + topProp[arrIdx] + \" \";\n }\n propType = plainptype;\n propValue = pvalueConcat;\n }\n\n }\n }\n else { // topProp has a single value, not an array of values\n\n if (typeof topProp === 'object' ){ // the value is an object\n propType = structptype;\n propValue = getPropValueData(topProp, labelId, schemaorgObjarr)[pvdValue]; // investigate the value object of the topProp\n }\n else { // the value is a string\n propType = plainptype;\n propValue = topProp;\n }\n }\n\n addPropObject(targetObjStd, propType, propLabel, propSortorder, topPropSpecidx, propValue);\n addPropObject(targetObjTopics, propType, propLabel, propSortorder, topPropSpecidx, propValue);\n addPropObject(targetObjSpecIsearch1, propType, propLabel, propSortorder, topPropSpecidx, propValue);\n\n if (pmdinvguide.data.topwithprefix[topPmdPropName4ref].schemaorgpropname){\n addSchemaorgProp(schemaorgObjarr, pmdinvguide.data.topwithprefix[topPmdPropName4ref].schemaorgpropname, propValue);\n }\n\n } // eo: iterate across all top level property names found in the pmd result\n\n // sort all output objects of the top level properties\n iimOutObjarr.sort(compareByPropname);\n xmpOutObjarr.sort(compareByPropname);\n exifOutObjarr.sort(compareByPropname);\n anyOutObjStdarr.sort(compareBySortorder);\n gimgcontOutObjarr.sort(compareBySortorder);\n personOutObjarr.sort(compareBySortorder);\n locationOutObjarr.sort(compareBySortorder);\n othingsOutObjarr.sort(compareBySortorder);\n rightsOutObjarr.sort(compareBySortorder);\n licOutObjarr.sort(compareBySortorder);\n adminOutObjarr.sort(compareBySortorder);\n anyOutObjarrTopic.sort(compareBySortorder);\n isearch1SpecOutObjarr.sort(compareBySortorder);\n\n let techMd = tools1.getTechMd(pmdresult.data[0]);\n\n switch(outputdesign) {\n case designStds:\n res.render('pmdresult_stds', { imageTitle: imgtitle, imgurl, imgwsfpath, imglfn, labeltype, techMd, iimOutObj: iimOutObjarr, xmpOutObj: xmpOutObjarr, exifOutObj: exifOutObjarr, anyOutObjStd: anyOutObjStdarr });\n break;\n case designTopics:\n res.render('pmdresult_topics', { imageTitle: imgtitle, imgurl, imgwsfpath, imglfn, labeltype, techMd, gimgcontOutObj: gimgcontOutObjarr, personOutObj: personOutObjarr, locationOutObj: locationOutObjarr, othingsOutObj: othingsOutObjarr, rightsOutObj: rightsOutObjarr, licOutObj: licOutObjarr, adminOutObj: adminOutObjarr, imgregOutObj: imgregOutObjarr, anyOutObjTopic: anyOutObjarrTopic });\n break;\n case designIsearch1:\n let codeStr = transfromSchemaorgObj2Code1(schemaorgObjarr, imgurl);\n res.render('pmdresult_isearch1', {imageTitle: imgtitle, imgurl, imgwsfpath, imglfn, labeltype, techMd, isearch1OutObj: isearch1SpecOutObjarr, schemaorgCode: codeStr});\n break;\n case designCompStds:\n break;\n default:\n break;\n }\n console.log('Next: HTML is rendered');\n });\n // repeat as many times as required\n }).then(() => {\n return ep.close().then(() => {\n console.log('Closed exiftool');\n });\n }).catch( err => {\n tools1.write2Log('ERROR @retrieving PMD by exiftool: ' + err);\n });\n}", "function writePictures(imageArray) {\n\t\t\n\t\t//console.log(\"imageArray: \" imageArray);\n\t\tvar rows;\n\t\trows = Math.ceil(imageArray.length / 5);\n\t\tconsole.log(\"Rows: \" + rows);\n\t\tconsole.log(\"iMax: \" + iMax);\n\t\tfor (var i = 0; i < iMax; i++) {\n\t\t\tconsole.log(\"i : \" + i);\n\t\t\tif (i % 5 == 0) {\n\t\t\t\tpictureShow += \"<tr>\"\n\t\t\t}\n\t\t\tpictureShow += \"<td>\" + \"<a href=\"+imageArray[i][2]+\">\" + \"<img src=\" + imageArray[i][1] + \">\" + \"</a>\" + \"</td>\";\n\t\t\tif (i % 5 == 4) {\n\t\t\t\tpictureShow += \"</tr>\"\n\t\t\t}\n\t\t}\n\t\tif ((i - 1) % 5 != 4) {\n\t\t\tpictureShow += \"</tr>\"\n\t\t}\n\t\tconsole.log(pictureShow);\n\t\t$(\".picture-table\").html(pictureShow);\n\n\t}", "function generatePresentations() {\n const base_dir = './images/'\n presentations = []\n for (fn of audioLibrary.getFilenames()) {\n base_fn = base_dir + fn\n images = []\n toContinue = true\n for (number = 0; toContinue && number < 3; number++) {\n complete_path_to_file = `${base_fn}${number}.jpg`\n // Synchronous method\n try {\n // TODO this enxt part doesn't allow for a dynamic image extension\n if (fs.existsSync(complete_path_to_file)) {\n //file exists\n images.push(fn + number + '.jpg')\n } else {\n toContinue = false\n }\n } catch (err) {\n console.error(err)\n }\n }\n presentations.push(images)\n }\n return presentations\n }", "function generarHmtlImagenes(cantidadFila, lista){\n\n\tvar html=\"\"\n\n\tfor(var i=1; i<lista.length; i++)\n\t{\n\n\n\t\t if((i)%cantidadFila==1)\n {\n \thtml+=\" <tr> \";\n }\n\n\t\thtml+=\" <th> \"\n +\" <div class=\\\"elemento_menu1 imagen_fondo\\\" \" \n +\" style=\\\"background-image: url(img_ext/\"+lista[i]+\"); \\\" \"\n +\" data-elemento=\\\"<div data-tipo='tipo1' \"\n\n +\" \t\t\t\t class='imagen_fondo' \" \n +\"\t\t\t\t data-imagen='img_ext/\"+lista[i]+\"' \"\n +\" style='background:url(img_ext/\"+lista[i]+\"); background-size: 100%; height:100px ; width:100px' ></div>\\\"> \"\n +\" </div> \" \n +\" </th> \";\n\n\n if((i)%cantidadFila==0)\n {\n \thtml+=\" </tr> \";\n }\n\n\n\t}\n\n\n\treturn html;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parentDims: This is an xstream operator that will take a stream of elements, and return a stream of [offsetWidth, offsetHeight] parent resizes.
function parentDims(element$) { const resizes$ = xs.merge(xs.of(undefined), fromEvent(window, 'resize')); return xs.combine(element$, resizes$) .filter(([el]) => el && el.parentNode) .map(([el]) => [el.parentNode.offsetWidth, el.parentNode.offsetHeight]) .compose(dropRepeats(([a, b], [c, d]) => a === c && b === d)); }
[ "parentSize() {\n if (!this.parent) {\n console.warn('HView#parentSize; no parent!');\n return [0, 0];\n }\n if (this.parent.elemId === 0) {\n return ELEM.windowSize();\n }\n else {\n return ELEM.getSize(this.parent.elemId);\n }\n }", "function calcParentSizes(elements) {\n _.map(elements, function (e) {\n e.lastParentSize = e.parentSize;\n var sizedParent = findSizedParent(e.element);\n e.parentSize = sizedParent && sizedParent.width();\n });\n }", "function getElementDimensions(){\n\n\t\t\tvar dimensions = wrapper.getBoundingClientRect();\n\t\t\tvar parentdimensions = parentEl.getBoundingClientRect();\n\n\t\t\twindowwidth = Math.ceil( dimensions.width );\n\t\t\twindowheight = Math.ceil( dimensions.height );\n\t\t\tparentwidth = Math.floor( parentdimensions.width );\n\t\t\tparentheight = Math.floor( parentdimensions.height );\n\n\t\t}", "function set_sizes() {\n\n // get the width from the viewports parent\n var w = viewport.parentNode.clientWidth,\n unit = \"px\";\n\n if (parseInt(w) == 0) {\n w = parseInt(viewport.parentNode.style.width);\n }\n\n \n // the viewport get the width\n viewport.style.width = w+unit;\n \n // set a width that's big enough for the children inside\n el.style.width = (el.children.length * w) + unit;\n \n // set a width on all the children\n for (var i = 0, els = el.children, len = els.length; i < len; i++) {\n els[i].style.width = w+unit;\n }\n\n }", "function parent_div_size_pos(params) {\n\n // get outer_margins\n if ( params.viz.expand == false ){\n var outer_margins = params.viz.outer_margins;\n } else {\n var outer_margins = params.viz.outer_margins_expand;\n }\n\n if (params.viz.resize) {\n\n // get the size of the window\n var screen_width = window.innerWidth;\n var screen_height = window.innerHeight;\n\n // define width and height of clustergram container\n var cont_dim = {};\n cont_dim.width = screen_width - outer_margins.left - outer_margins.right;\n cont_dim.height = screen_height - outer_margins.top - outer_margins.bottom;\n\n // size the svg container div - svg_div\n d3.select('#' + params.viz.svg_div_id)\n .style('margin-left', outer_margins.left + 'px')\n .style('margin-top', outer_margins.top + 'px')\n .style('width', cont_dim.width + 'px')\n .style('height', cont_dim.height + 'px');\n\n } else {\n\n // size the svg container div - svg_div\n d3.select('#' + params.viz.svg_div_id)\n .style('margin-left', outer_margins.left + 'px')\n .style('margin-top', outer_margins.top + 'px');\n }\n }", "function rootDims(el, w, h){\n $(el).css(\"width\", (w + \"px\"));\n $(el).css(\"height\", (h + \"px\"));\n\n $('#chart').css(\"width\", (w + \"px\"));\n $('#chart').css(\"height\", (h + \"px\"));\n\nreturn;\n}", "function onPymParentResize(width) {}", "updateInnerWidthDependingOnChilds(){}", "function calculateDims(){\n\n\t\t\t\t\t// set the logical canvas dims\n\t\t\t\t\tcanvasHeight = (parentWidth / displayWidth) * displayHeight;\n\t\t\t\t\tcanvasWidth = parentWidth;\n\n\t\t\t\t\t// shrink image if necessary to show entire height\n\t\t\t\t\tif(canvasHeight > parentHeight){\n\t\t\t\t\t\tcanvasWidth *= parentHeight / canvasHeight;\n\t\t\t\t\t\tcanvasHeight = parentHeight;\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tcanvasLeft = (parentWidth - canvasWidth) / 2;\n\t\t\t\t\tcanvasTop = (parentHeight - canvasHeight) / 2;\t\t\t\t\t\n\n\t\t\t\t\tcanvas.width = displayWidth;\n\t\t\t\t\tcanvas.height = displayHeight;\n\t\t\t\t\tcanvas.style.width = canvasWidth + 'px';\n\t\t\t\t\tcanvas.style.height = canvasHeight + 'px';\n\n\t\t\t\t\tif(canvasLeft !== 0 || canvasTop !== 0){\n\t\t\t\t\t\tTweenMax.set(canvas, { x: canvasLeft, y: canvasTop });\n\t\t\t\t\t}\n\t\t\t\t}", "function setParentWrapperWidth(){\n slides.forEach(slide => slide.style.width = slidersParentContainer.clientWidth+'px');\n //slidersWrapper.style.width = (slides.length - 1 * slides[0].clientWidth)+'px';\n }", "function GetParentWindowWidth()\r\n{\r\n if(IsIE6())\r\n {\r\n return parent.document.documentElement.offsetWidth;\r\n }\r\n else if(IsIE7OrLater())\r\n {\r\n return parent.document.documentElement.offsetWidth;\r\n }\r\n else if(IsFireFox())\r\n {\r\n\r\n return parent.document.documentElement.clientWidth;\r\n }\r\n else if(IsWindowSafari())\r\n {\r\n return parent.self.innerWidth;\r\n }\r\n else if(IsMacSafari())\r\n {\r\n return parent.self.innerWidth;\r\n }\r\n else // for all other brosers\r\n {\r\n return parent.document.documentElement.offsetWidth;\r\n }\r\n}", "get xMax() {return this.parentWidth - this.width;}", "function getOuterSizes(element){var window=element.ownerDocument.defaultView;var styles=window.getComputedStyle(element);var x=parseFloat(styles.marginTop||0)+parseFloat(styles.marginBottom||0);var y=parseFloat(styles.marginLeft||0)+parseFloat(styles.marginRight||0);return{width:Number(element.offsetWidth)+y,height:Number(element.offsetHeight)+x};}", "readParentSizeFromDom(dom) {\n\t const oldWidth = this.parentWidth;\n\t const oldHeight = this.parentHeight;\n\t const clientRect = logging.assertExists(dom.parentElement).getBoundingClientRect();\n\t this.parentWidth = clientRect.width;\n\t this.parentHeight = clientRect.height;\n\t return this.parentHeight !== oldHeight || this.parentWidth !== oldWidth;\n\t }", "function restrictWH (parent, child) {\n\t\t\tif (child.x + child.width - parent.x > parent.adjW) {\n\t\t\t\tchild.width = parent.x + parent.adjW - child.x;\n\t\t\t} else if (child.x + child.width < parent.x) {\n\t\t\t\tchild.width = parent.x - child.x;\n\t\t\t}\n\t\t\tif (child.y + child.height - parent.y > parent.adjH) {\n\t\t\t\tchild.height = parent.y + parent.adjH - child.y;\n\t\t\t} else if (child.y + child.height < parent.y) {\n\t\t\t\tchild.height = parent.y - child.y;\n\t\t\t}\n\t\t\tvar result = {width: child.width, height: child.height};\n\t\t\treturn result;\n\t\t}", "inlineStyles () {\n if (this.props.disabled) return 'width:100%'\n if (this.element) {\n this.element.removeAttribute('style')\n var parent = this.element.parentNode\n var parentD = this.getInnerDimensions(parent)\n\n var styles = {}\n if (parentD.ratio > this.props.ratio) {\n styles.width = parentD.width + 'px'\n var elHeight = parentD.width * (this.props.ratio / 100)\n styles.height = elHeight + 'px'\n styles.marginTop = (parentD.height - elHeight) / 2 + 'px'\n } else {\n styles.height = parentD.height + 'px'\n var elWidth = parentD.height / (this.props.ratio / 100)\n styles.width = elWidth + 'px'\n styles.marginLeft = (parentD.width - elWidth) / 2 + 'px'\n }\n \n return inlineStyle(styles)\n }\n }", "function setSvgWidthToParentsWidth() {\n // fit svg size to parents size\n let main = document.getElementsByTagName('main')[0];\n let bounding = main.getBoundingClientRect();\n\n let sideMenuHeight = document.getElementsByTagName('nav')[0].clientHeight;\n d3.select('#heatmaps')\n .attr(\"width\", bounding.width);\n}", "function checkParentResize(baseid) {\n\tlet entry = HNP.entries[baseid];\n\tif (!entry) {\n\t\tconsole.log(\"Error: cannot find data for ID\", baseid);\n\t\treturn;\n\t}\n\tlet container = entry.container;\n\tif (!container) {\n\t\tconsole.log(\"Error: cannot find container for ID\", baseid);\n\t\treturn;\n\t}\n\tlet pluginOptions = entry.options;\n\tif (!pluginOptions) {\n\t\tconsole.log(\"Error: cannot find options for ID\", baseid);\n\t\treturn;\n\t}\n\tlet scale = pluginOptions.scale;\n\tlet previousWidth = parseInt(pluginOptions._currentPageWidth * scale / 100.0);\n\tlet style = window.getComputedStyle(container, null);\n\tlet currentWidth = parseInt(style.getPropertyValue(\"width\"));\n\tif (currentWidth == previousWidth) {\n\t\t// nothing to do\n\t\treturn;\n\t}\n\tif (Math.abs(currentWidth - previousWidth) < 3) {\n\t\t// Safari required hysteresis\n\t\treturn;\n\t}\n\t// console.log(\"UPDATING NOTATION DUE TO PARENT RESIZE FOR\", baseid);\n\t// console.log(\"OLDWIDTH\", previousWidth, \"NEWWIDTH\", currentWidth);\n\tif (!HNP.MUTEX) {\n\t\t// This code is used to stagger redrawing of the updated examples\n\t\t// so that they do not all draw at the same time (given a little\n\t\t// more responsiveness to the UI).\n\t\tHNP.MUTEX = 1;\n\t\tdisplayHumdrum(baseid);\n\t\tHNP.MUTEX = 0;\n\t}\n}", "recalculateDims() {\n const dims = this.dimensionsHelper.getDimensions(this.element);\n this._innerWidth = Math.floor(dims.width);\n if (this.scrollbarV) {\n let height = dims.height;\n if (this.headerHeight)\n height = height - this.headerHeight;\n if (this.footerHeight)\n height = height - this.footerHeight;\n this.bodyHeight = height;\n }\n this.recalculatePages();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[0, 6] is week offset 0. [7, 13] is offset 1. [1, 7] is offset 1.
function weekOffset(dayOffset) { if (dayOffset >= 0) { return Math.floor(dayOffset / 7); } dayOffset = -dayOffset; dayOffset--; return -Math.floor(dayOffset / 7) - 1; }
[ "_startOfWeekOffset(day, dow) {\n // offset of first day corresponding to the day of week in first 7 days (zero origin)\n const weekStart = MathUtil.floorMod(day - dow, 7);\n let offset = -weekStart;\n if (weekStart + 1 > this._weekDef.minimalDaysInFirstWeek()) {\n // The previous week has the minimum days in the current month to be a 'week'\n offset = 7 - weekStart;\n }\n return offset;\n }", "function firstWeekOffset(year, dow, doy) { // 1105\n var // first-week day -- which january is always in the first week (4 for iso, 1 for other) // 1106\n fwd = 7 + dow - doy, // 1107\n // first-week day local weekday -- which local weekday is fwd // 1108\n fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; // 1109\n // 1110\n return -fwdlw + fwd - 1; // 1111\n } // 1112", "function dstWeekOffset(expectedOffset, dt) {\n if (dt.offset === expectedOffset) return dt\n\n dt = dt.minus({ weeks: 1 })\n if (dt.offset === expectedOffset) return dt\n\n return dt.plus({ weeks: 2 })\n}", "function getAnyMonday(offset) {\n var d = new Date();\n var day = d.getDay();\n var diff = d.getDate() - day + (day == 0 ? -6:1);\n var monday = new Date(d.setDate(diff - offset*7));\n monday.setHours(0, 0, 0, 0);\n return monday;\n }", "function startOfIsoWeek (y, w) {\n const dow = isoDow(y, 1, 1);\n const startDay = dow > 4 ? 9 - dow : 2 - dow;\n const startDate = new Date(y, 0, startDay);\n return addDays(startDate, (w - 1) * 7);\n}", "getWeekBounds(date) {\n let start = date.clone().startOf('week'),\n end = start.clone().endOf('week');\n return [start, end];\n }", "function WeekOperation (stack){\n var WEEK = 1000*60*60*24*7;\n this.IDENTIFIER = 'week';\n\n this.calculate_new_offset = function (offset, value){\n return (new Date(new_offset = offset.getTime() + WEEK));\n }\n}", "function offset(date, weeks) {\n date.setDate(date.getDate() + weeks * 7);\n }", "function offset(date, weeks) {\n date.setUTCDate(date.getUTCDate() + weeks * 7);\n }", "function dayOffsetToCellOffset(dayOffset) {\n var day0 = t.visStart.getDay(); // first date's day of week\n dayOffset += day0; // normalize dayOffset to beginning-of-week\n return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks\n + dayToCellMap[ // # of cells from partial last week\n (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets\n ]\n - dayToCellMap[day0]; // adjustment for beginning-of-week normalization\n }", "function weekdayMap(w) {\n let week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n return week[w]\n}", "getCurrentWeekDates() {\n let week = []\n const startOfWeek = DateTime.fromISO(this.today).startOf('week')\n\n // TODO get locale from state\n for (let i = 0; i <= 6; i++) {\n let day = startOfWeek.plus({days: i}).setLocale('de-DE')\n week.push(\n {\n isoDate: day.toISODate(),\n day: day.toFormat('d'),\n weekDay: day.toFormat('ccccc'),\n }\n )\n }\n return week\n }", "function dayOffsetToCellOffset(dayOffset) {\r\n\t\tvar day0 = t.visStart.getDay(); // first date's day of week\r\n\t\tdayOffset += day0; // normalize dayOffset to beginning-of-week\r\n\t\treturn Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks\r\n\t\t\t+ dayToCellMap[ // # of cells from partial last week\r\n\t\t\t\t(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets\r\n\t\t\t]\r\n\t\t\t- dayToCellMap[day0]; // adjustment for beginning-of-week normalization\r\n\t}", "function dayOffsetToCellOffset(dayOffset) {\n\t\tvar day0 = t.visStart.getDay(); // first date's day of week\n\t\tdayOffset += day0; // normalize dayOffset to beginning-of-week\n\t\treturn Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks\n\t\t\t+ dayToCellMap[ // # of cells from partial last week\n\t\t\t\t(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets\n\t\t\t]\n\t\t\t- dayToCellMap[day0]; // adjustment for beginning-of-week normalization\n\t}", "function weeksArray(){\n\treturn ['周日','周一','周二','周三','周四','周五','周六'];\n}", "function getInitialOffset() {\n var offset;\n var now = new Date();\n for (offset = 0; new Date($scope.forecastTimes[offset]) < now; ++offset) { \n }\n \n // offset is such that next forecast will now be shown in position 1 \n return (offset - 4 * ($scope.forecastFreq / $scope.service.forecastFreq));\n }", "function convertTime (startHour1, dayOfWeek1, offset1, offset2) {\n // calculate start hour and day of week using the difference of two GMT offsets\n startHour2 = startHour1 + (offset2 - offset1);\n dayOfWeek2 = dayOfWeek1;\n\n // convert to next Day\n if (startHour2 > 24) {\n dayOfWeek2 = (dayOfWeek1 + 1) % 7;\n startHour2 = startHour2 % 24;\n }\n\n // convert to previous day\n else if (startHour2 < 0) {\n dayOfWeek2 = (dayOfWeek1 - 1) + 7 % 7;\n startHour2 = startHour2 + 24;\n }\n\n // return teacher's start hour and day of week for the school user's timezone\n return [startHour2, dayOfWeek2];\n\n}", "function generateWeekConstraints(date){\r\n\tvar original = new Date(date.year, (date.monthOfYear-1), date.dayOfMonth);\r\n\tbeginWeek = new Date(original.setDate(original.getDate()-original.getDay()));\r\n\tendWeek = new Date(original.setDate(original.getDate()+6));\t\r\n}", "function moveToSunday(fer){\n if(fer==1){\n return 0;\n }\n else{\n return 8-fer;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if an offset/length value is valid. (Throws an exception if check fails)
function checkOffsetOrLengthValue(value, offset) { if (typeof value === 'number') { // Check for non finite/non integers if (!isFiniteInteger(value) || value < 0) { throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); } } else { throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); } }
[ "function checkOffset (offset, ext, length) { // 811\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') // 812\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') // 813\n} // 814", "function check_bounds(buf, offset, len) {\n if (offset < 0 || offset + len > buf.length) {\n throw new RangeError(\"Index out of range\");\n }\n}", "hasOffset (offset) {\n let min = this.offset\n let max = min + this.length\n return offset >= min && offset <= max\n }", "function checkOffset(offset){\n if(offset && offset >= 0){\n return offset;\n }\n else{\n return 0;\n }\n }", "checkForValidInputLength() {\r\n if (this._len <= 0 || this._len > 4) {\r\n return false;\r\n };\r\n return true;\r\n }", "function checkBounds(index, len) {\n if (!(index >= 0 && index < len)) {\n throw new Error(\"Index out of bounds: \" + index);\n }\n }", "function inBounds (view, nbytes, offset) {\n return (offset + nbytes) <= view.byteLength\n}", "function checkBounds(index, len) {\r\n if (!(index >= 0 && index < len)) {\r\n throw new Error(\"Index out of bounds: \" + index);\r\n }\r\n}", "static validatePosition(arrPos) {\n const [x, y] = arrPos\n return (x >= 0 && x < this.width) && (y >= 0 && y < this.height)\n }", "function checkBounds(index, len) {\n if (!(index >= 0 && index < len)) {\n throw new Error(\"Index out of bounds: \" + index);\n }\n}", "function checkBounds(index, len) {\n if (!(index >= 0 && index < len)) {\n throw new Error(\"Index out of bounds: \" + index);\n }\n}", "function substring(someStr, length, offset) {\n if (length < 0 || offset < 0) {\n alert('Both length and offset must be positive.')\n } else if (length > someStr.length || offset > someStr.length) {\n alert('Both length and offset must be sorter than the length of input string.')\n } else if (offset + length > someStr.length) {\n alert('Sum of length and offset must be sorter than the length of input string.')\n }\n else {\n return someStr.substring(offset, offset + length);\n }\n}", "function checkOffset(elm)\n {\n if (elm.offset != undefined) {\n if (typeof elm.offset != 'number') {\n throw 'Offset must be numeric';\n }\n \n elm.top += elm.offset;\n elm.left += elm.offset;\n }\n \n if (elm.offset_left != undefined) {\n if (typeof elm.offset_left != 'number') {\n throw 'Left offset must be numeric';\n }\n \n elm.left += elm.offset_left;\n } \n \n if (elm.offset_top != undefined) {\n if (typeof elm.offset_top != 'number') {\n throw 'Top offset must be numeric';\n }\n \n elm.top += elm.offset_top;\n } \n \n return elm;\n }", "function _checkOffsets() {\n\t\tvar $lines = $('.' + settings.lineWrap);\n\n\t\t$lines.each(function() {\n\t\t\tvar offset = $(this).data('offset');\n\t\t\t$(this).children('span').each(function() {\n\t\t\t\tif ($(this).data('offset') !== offset) {\n\t\t\t\t\t// what do I do with things that don't match?\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function hasValidSampleSize() {\n return offsetSamples.length >= 5;\n }", "_verifyLength() {\n let touched = false;\n const timestampLength = this._timestampLength.getValue();\n\n // min length must have at least the length of current timestamp\n if (this.getConfiguration().getMinLength().getValue() < timestampLength) {\n this.getConfiguration().setMinLength(timestampLength);\n touched = true;\n }\n\n // max length must have at least the length of current timestamp\n // and the max safe integer length\n if (this.getConfiguration().getMaxLength().getValue() < timestampLength) {\n const maxLengthConfig = new Configuration();\n\n maxLengthConfig.setLength(NumberLength.getMaxSafeLength());\n this.getConfiguration().setMaxLength((new RandomNumber(maxLengthConfig)).getValue());\n touched = true;\n }\n\n if (touched) {\n this._calculateLength();\n }\n }", "fits_memory(offset, len) {\n return utils.toNum(offset) + utils.toNum(len) < this.memory.length;\n }", "deleteValueAtOffset(offset) {\n assert('Cannot delete value at offset outside bounds',\n offset >= 0 && offset <= this.length);\n\n let width = 1;\n let code = this.value.charCodeAt(offset);\n if (code >= HIGH_SURROGATE_RANGE[0] && code <= HIGH_SURROGATE_RANGE[1]) {\n width = 2;\n } else if (code >= LOW_SURROGATE_RANGE[0] && code <= LOW_SURROGATE_RANGE[1]) {\n width = 2;\n offset = offset - 1;\n }\n\n const [ left, right ] = [\n this.value.slice(0, offset),\n this.value.slice(offset+width)\n ];\n this.value = left + right;\n\n return width;\n }", "function validate_length(param, length) {\n\treturn (param.length <= length) ? true : false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Before a Carmel Packager can be used, we have to load it into memory.
load () { if (!this.exists) { // We can't load it because it doesn't exist throw new Carmel.Error(Carmel.Error.PACK.NOT_FOUND); } }
[ "static packager(test) {\n // Create an empty Packager with a temporary root directory\n let dir = path.join(test.spec.tmpDir, 'packages');\n let packager = new Carmel.Packager(dir);\n\n // Initialize the Packager\n fs.mkdirsSync(dir);\n test.expect(fs.existsSync(dir)).to.be.true;\n test.expect(packager.exists).to.be.true;\n packager.load();\n\n // Return the newly created and loaded packager\n return packager;\n }", "convertToPackagedRuntime() {\n if (this.storage) {\n throw new Error('convertToPackagedRuntime must be called before attachStorage');\n }\n\n this.isPackaged = true;\n }", "preload() {\n\n\t\t// Get our type based on the key in the manifest\n\t\tlet _type = Object.keys(this.manifest)[this.preloader.package_loaded];\n\n\t\t// Check to see if our total loaded is < our manifest\n\t\tif(this.preloader.package_loaded < Object.keys(this.manifest).length){\n\t\t\tthis.preloader.load(_type, this.manifest[_type]);\n\t\t} else {\n\t\t\tthis.trigger('assets_loaded');\n\t\t}\n\t}", "inflate(archer_part){\n const asset = window.application.assetController.getAsset(archer_part);\n this.graphic = asset.graphic;\n\n this.size = [asset.size[0],asset.size[1]];\n this.localCenter = asset.translate;\n\n this.vector.rotationIsManual = true;\n\n }", "onInitialLoad() {\n return;\n }", "_ensureUnpacked() {\n if (this.packedData) {\n this._unpackData();\n }\n }", "function preload() {\n tarot = loadJSON(`assets/data/tarot_interpretations.json`);\n}", "readImports() {\n let file = this.archive.get('war3map.imp');\n\n if (file) {\n let buffer = file.arrayBuffer();\n\n if (buffer) {\n this.imports.load(buffer);\n }\n }\n }", "loadVPK() {\n this.vpkDir = new vpk(this.config.directory + '/pak01_dir.vpk');\n this.vpkDir.load();\n\n this.vpkFiles = this.vpkDir.files.filter((f) => f.startsWith('resource/flash/econ/stickers'));\n }", "readImports() {\n\n\t\tconst file = this.archive.get( \"war3map.imp\" );\n\n\t\tif ( file ) {\n\n\t\t\tconst buffer = file.arrayBuffer();\n\n\t\t\tif ( buffer )\n\t\t\t\tthis.imports.load( buffer );\n\n\t\t}\n\n\t}", "function prepareProcessedData() {\n // #BUG: Had to add resourcesDirectory for Android...\n state.processedData = JSON.parse(Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + 'common/data-base.json').read().text);\n}", "function load()\n{\n dashcode.setupParts();\n doInit();\n}", "packageSetup() {\n var packages = [];\n for (let i = 0; i < 7; i++) {\n packages.push(this.add.image(-this.packageSize.width / 2, config.height * 0.33, 'pk' + i).setName(i).setInteractive({ draggable: true }));\n }\n\n while (packages.length > 0) {\n var index = Math.floor(Math.random() * packages.length);\n this.packageStacked.push(packages[index]);\n packages.splice(index, 1);\n }\n }", "function load() { \n m_data.load(\"assets/obj/X50Render/X50-Out.json\", load_cb, stageload_cb );\n }", "loadCartridgeRam() {\n const loadCartridgeRamTask = async () => {\n const header = this.cartridgeHeader;\n\n if (!header) {\n throw new Error('Error parsing the cartridge header');\n }\n\n const cartridgeObject = await idbKeyval.get(header);\n\n if (!cartridgeObject || !cartridgeObject.cartridgeRam) {\n return;\n }\n\n // Set the cartridgeRam\n // Don't transfer, because we want to keep a reference to it\n const workerMemoryObject = {};\n workerMemoryObject[MEMORY_TYPE.CARTRIDGE_RAM] = cartridgeObject.cartridgeRam.buffer;\n await this.worker\n .postMessage({\n type: WORKER_MESSAGE_TYPE.SET_MEMORY,\n ...workerMemoryObject\n })\n .then(event => {\n this.loadedCartridgeMemoryState.RAM = true;\n this.cartridgeRam = cartridgeObject.cartridgeRam;\n });\n };\n return loadCartridgeRamTask();\n }", "function LoadManager() {}", "function resetCpakData() {\n pack.zipFile = new JSZip();\n pack.imageCache.length = 0;\n pack.imageWorkerPool.cacheData = undefined;\n pack.imageWorkerPool.initCache();\n $scope.$broadcast(\"selectCard\", {\n position: 0\n });\n }", "initializeLoadOrder() {\n this.loadorder = json.read(\"user/cache/loadorder.json\");\n }", "function GoLoader() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
display Draw the hunter as an ellipse on the canvas with a radius the same size as its current health. Draw the image in the ellipse Draw only if alive
display() { if (this.health > 0) { push(); noStroke(); fill(this.fillColor); this.radius = this.health; ellipse(this.x, this.y, this.radius * 2); image(this.image, this.x, this.y, this.radius, this.radius); pop(); } else { var removed = hunterList.splice(this.index, 1); } }
[ "display() {\n push();\n noStroke();\n this.radius = this.health;\n imageMode(CENTER);\n if (this.radius > 1) {\n image(this.image,this.x, this.y, this.radius * 3, this.radius * 3);\n }\n pop();\n }", "function drawPlayer() {\n fill(250,20,50,playerHealth);\n ellipse(playerX,playerY,playerRadius*2,playerRadius*2);\n}", "display() {\n push();\n // Predator will only have a bright stroke color (no fill)\n noFill();\n strokeWeight(5);\n stroke(this.strokeColor);\n this.radius = this.health;\n // Once the health/radius reaches zero, remove stroke as well\n // so that is disappears entirely\n if (this.radius === 0) {\n strokeWeight(0);\n // Once the health/radius reaches 0, end the game\n gameOver = true;\n gameStart = false;\n // Resetting the predator\n this.reset();\n }\n ellipse(this.x, this.y, this.radius * 2);\n pop();\n }", "display() {\n push();\n noStroke();\n this.radius = this.health;\n // Display Alien as an image only whyle it's alive\n imageMode(CENTER);\n if (this.radius > 0) {\n // map the alpha value to the health of the Alien and use it for display\n let alpha = map(this.health, 0, this.maxHealth, 75, 255);\n tint(255, alpha);\n image(this.alienImage, this.x, this.y, this.radius * 2, this.radius * 2);\n }\n pop();\n }", "function draw(){\n // Draw an ellipse with height based on volume\n \n }", "function drawHealth() {\n ctx.lineWidth = 1\n // Draw empty health circles\n for (let i = hero.maxhealth; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'white', 'black', 0, 2 * Math.PI, [5, 5])\n }\n // Fill health circles\n for (let i = hero.health; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'hotpink', 'black', 0 - frame, 2 * Math.PI + frame, [5, 5])\n }\n}", "function drawPlayer() {\n fill(playerFill,playerHealth);\n ellipse(playerX,playerY,playerRadius*2);\n tint(255,playerHealth);\n image(playerImage, playerX-playerRadius, playerY-playerRadius, playerRadius*2,playerRadius*2);\n}", "display() {\n push();\n noStroke();\n this.radius = this.health;\n // Display Black hole\n if (this.radius > 20) {\n imageMode(CENTER);\n image(this.holeImg, this.x, this.y, this.radius * 2, this.radius * 2);\n }\n pop();\n }", "show(){\n // Make the Goal red\n fill(200, 0, 0);\n ellipse(this.pos.x, this.pos.y, 20, 20);\n }", "function drawPlayer() {\n fill(playerFill,playerHealth);\n ellipse(playerX,playerY,playerRadius*2);\n}", "displayHealth() {\n // The color changes based on the number of health left\n rectMode(CENTER);\n noFill();\n if (this.health < 13.2) {\n fill(255, 0, 0);\n } else if (this.health < 26.4) {\n fill(255, 255, 0);\n } else {\n fill(0, 255, 0);\n }\n rect(this.x, this.y - this.radius * 2, this.health * 4, 20);\n }", "display() {\n if (this.show){\n push();\n rectMode(CENTER);\n ellipseMode(CENTER);\n angleMode(DEGREES);\n stroke(255);\n strokeWeight(2);\n fill(this.color);\n ellipse(this.x, this.y, this.size);\n noStroke();\n fill(255);\n ellipse(this.x, this.y, this.size / 4);\n // if dies, it will shrink\n if (this.dead) {\n this.size -= 0.5;\n this.speed = 0;\n if (this.playOnce){\n Die.play();\n this.playOnce = false;\n }\n if (this.size <= 0) {\n this.animationFinished = true;\n this.show = false;\n // if it dies, the enemy base is no longer under attack\n if (this.theEnemyBase!=null){\n this.theEnemyBase.underAttack = false;\n }\n }\n }\n pop();\n }\n }", "display() {\n // Don't display if not active\n if (!this.active) {\n return;\n }\n\n // Set fill and stroke then draw an ellipse at this agent's position and with its size\n push();\n noStroke();\n fill(this.color);\n ellipse(this.x,this.y,this.size);\n pop();\n }", "function drawPlayer() {\n fill(playerFill, playerHealth);\n ellipse(playerX, playerY, playerRadius * 2);\n}", "function drawEnemy(obj){\n ctx.beginPath();\n ctx.arc(obj.x,obj.y,enemy.diameter,0,Math.PI*2);\n ctx.fillStyle = \"#000000\";\n if (obj.host){\n ctx.fillStyle =\"#000000\"\n }\n ctx.fill();\n ctx.closePath() \n }", "display(){\n fill (0);\n ellipse(this.x, this.y, 4, 4);\n }", "displayHealth() {\n push();\n rectMode(CENTER);\n // Health will be red at critical levels\n if (this.health <= 85) {\n fill(255, 0 , 0);\n }\n // Health will be yellow at medium levels\n else if (this.health <= 168) {\n fill(255, 220, 0);\n }\n // Health is green otherwise\n else {\n fill(0, 255, 0);\n }\n rect(this.x, this.y - this.radius * 2, this.health, 30);\n pop();\n }", "show(){\r\n if(this.dot){\r\n if(!this.eaten){//draw dot if not eaten\r\n fill(255, 255, 0);\r\n noStroke();\r\n ellipse(this.pos.x, this.pos.y, 3, 3);\r\n }\r\n }else if(this.bigDot){\r\n if(!this.eaten){\r\n fill(255, 255, 0);\r\n noStroke();\r\n ellipse(this.pos.x, this.pos.y, 6, 6);\r\n }\r\n }\r\n }", "function drawTarget() {\n push();\n strokeWeight(4);\n fill(targetFill, targetHealth);\n imageMode(CENTER);\n image(target, targetX, targetY, targetRadius * 2, targetRadius * 2);\n // Add a secondary circle as a \"countdown\" to when the target has lost all health\n ellipse(targetX, targetY, targetHealth * 0.8);\n pop();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
external to_int32: t > int32 Provides: ml_z_to_int32 Requires: ml_z_to_int
function ml_z_to_int32(z1) { return ml_z_to_int(z1) }
[ "function ml_z_of_int32(i32) {\n return ml_z_of_int(i32);\n}", "function ml_z_to_int32(z1) {\n return bigInt(z1).toJSNumber();\n}", "function ml_z_of_int32(i32) {\n return bigInt(i32);\n}", "function ml_z_fits_int32(z1) {\n return ml_z_fits_int(z1);\n}", "function ToInt32(v) { return v >> 0; }", "function ml_z_of_nativeint(z) {\n return ml_z_of_int(z)\n}", "function ml_z_to_nativeint(z1) { return ml_z_to_int(z1) }", "function toInt32(n) {\n return n | 0;\n }", "function ml_z_to_int(z1) {\n if (z1 == (z1 | 0)) return z1 | 0;\n caml_raise_constant(caml_named_value(\"ml_z_overflow\"));\n}", "function ml_z_of_nativeint(z1, z2) {\n\n}", "function ml_z_fits_nativeint(z1) {\n return ml_z_fits_int(z1);\n}", "function ml_z_to_int64(z1) {\n z1 = bigInt(z1)\n if(!ml_z_fits_int64(z1)) {\n caml_raise_constant(caml_named_value(\"ml_z_overflow\"));\n }\n var mask = bigInt(0xffffffff)\n var lo = z1.and(mask).toJSNumber();\n var hi = z1.shiftRight(32).and(mask).toJSNumber();\n var x = caml_int64_create_lo_hi(lo, hi);\n return x;\n}", "function opaqueAllTypesClz32(argument) {\n return Math.clz32(argument);\n}", "function ml_z_to_int(z1) {\n return bigInt(z1).toJSNumber();\n}", "function i32(a,o) {\n return iC(a,o,4);\n}", "function ftoi_low32(val) {\r\n f64_buf[0] = val;\r\n return BigInt(u32_buf[0]);\r\n}", "function ml_z_to_nativeint(z1) {\n return bigInt(z1).toJSNumber();\n}", "function int32ToFloat(i) {\n i32[0] = i;\n return f32[0];\n}", "function toInt32s(arr) {\n for (let i = 0; i < arr.length; ++i) {\n arr[i] = arr[i] & 0xFFFFFFFF;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the signal exception handler.
function setExceptionHandler(handler) { var old = Private.exceptionHandler; Private.exceptionHandler = handler; return old; }
[ "function setExceptionHandler(handler) {\n var old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }", "function setExceptionHandler(handler) {\n var old = Private$4.exceptionHandler;\n Private$4.exceptionHandler = handler;\n return old;\n }", "function setExceptionHandler(handler) {\n var old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }", "static set actionOnDotNetUnhandledException(value) {}", "_initExceptionHandler() {\n process.on('uncaughtException', this._exceptionHandler.bind(this));\n }", "configureErrorHandler() {\n process.on('uncaughtException', (error) => {\n logger.debug('Uncaught Exception', 'An Uncaught Exception was throwed', {\n error\n });\n console.log(error);\n });\n\n this.server.on('restifyError', errorHandler.handle.bind(errorHandler));\n }", "function exceptionHandler(){\n\n\tvar me = this;\n\n\tme.error = function(msg){\n\n\t\tthrow new Error(msg);\n\t};\n}", "setExceptionHandler(namespace) {\n this.set('exceptionHandlerNamespace', namespace);\n return this;\n }", "function _installGlobalUnhandledRejectionHandler() {\n window.onunhandledrejection = _traceKitWindowOnUnhandledRejection;\n }", "function _installGlobalUnhandledRejectionHandler() {\n window.onunhandledrejection = _traceKitWindowOnUnhandledRejection;\n }", "function _installGlobalUnhandledRejectionHandler() {\r\n window.onunhandledrejection = _traceKitWindowOnUnhandledRejection;\r\n }", "function loadSignalHandlers() {\n\n process.on('uncaughtException', function(e) {\n global.logger.log('error', e.toString());\n });\n\n process.on('SIGINT', function() {\n global.logger.log('info', 'Received sigint. Relaying to exit');\n self.saveViews(function(err) {\n if (err) {\n global.logger.error('SIGINT saveViews', err);\n }\n process.exit(128 + 2);\n });\n });\n\n process.on('SIGTERM', function() {\n global.logger.log('info', 'Received sigterm. Relaying to exit');\n self.saveViews(function(err) {\n if (err) {\n global.logger.error('SIGTERM saveViews', err);\n }\n process.exit(128 + 15);\n });\n });\n\n process.on('exit', function() {\n global.logger.log('info', 'rtdb (' + self._identity._pjson.version + ') is exiting.');\n });\n }", "function installGlobalUnhandledRejectionHandler() {\n if (_onUnhandledRejectionHandlerInstalled === true) {\n return;\n }\n\n _oldOnunhandledrejectionHandler = window.onunhandledrejection;\n window.onunhandledrejection = traceKitWindowOnUnhandledRejection;\n _onUnhandledRejectionHandlerInstalled = true;\n }", "function installGlobalUnhandledRejectionHandler() {\n if (_onUnhandledRejectionHandlerInstalled === true) {\n return;\n }\n _oldOnunhandledrejectionHandler = window$1.onunhandledrejection;\n window$1.onunhandledrejection = traceKitWindowOnUnhandledRejection;\n _onUnhandledRejectionHandlerInstalled = true;\n }", "function installGlobalUnhandledRejectionHandler() {\r\n if (_onUnhandledRejectionHandlerInstalled === true) {\r\n return;\r\n }\r\n _oldOnunhandledrejectionHandler = window$1.onunhandledrejection;\r\n window$1.onunhandledrejection = traceKitWindowOnUnhandledRejection;\r\n _onUnhandledRejectionHandlerInstalled = true;\r\n }", "function setErrorHandler(value) {\n assertType(typeof value === \"function\" || value === undefined, \"The error handler must be a function or undefined, but got %o.\", value);\n currentErrorHandler = value;\n}", "static set logObjCUncaughtExceptions(value) {}", "function initUncaughtExceptionHandler() {\n Alloy.Globals.logLifecycleEvent('Adding uncaughtException handler');\n\n // NEW (iOS, Android): Catch uncaught exceptions\n Ti.App.addEventListener('uncaughtException', function (e) {\n console.error('[uncaughtException ' + JSON.stringify(e, null, 2));\n\n // in development on iOS the red error screen will prevent our alert\n // from showing so we wait until the screen has been closed by the user.\n if (OS_IOS && !ENV_PROD && $ && $.otherWin) {\n $.otherWin.addEventListener('focus', function onFocus() {\n $.otherWin.removeEventListener('focus', onFocus);\n if (Alloy.Globals.lib) {\n Alloy.Globals.lib.showError(e, '[uncaughtException]');\n }\n });\n\n } else {\n try {\n Ti.API.error(e);\n } catch(E) {\n }\n //}\n }\n });\n}", "onSetSignalsResult(err) {\r\n _notifyOnError('onSetSignalsResult', err);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contact lens power measured in diopters (0.25 units).
get power() { return this.__power; }
[ "get power() {\n return this.intensity * 4 * Math.PI;\n }", "get power() {\n return this.intensity * Math.PI;\n }", "get arousePower() {\n return this.charisma + this.dexterity * 0.25\n }", "function panel_power(mesh, direction, sun_v, time){\r\n\r\n var panel_v = new THREE.Vector3(0, 1, 0);\r\n \r\n var z_vector = new THREE.Vector3(0, 0, 1);\r\n panel_v.applyAxisAngle(z_vector, mesh.rotation._z);\r\n\r\n var y_vector = new THREE.Vector3(0, 1, 0);\r\n panel_v.applyAxisAngle(y_vector, degrees_to_radians(roof_orientation_deg));\r\n\r\n panel_v.normalize();\r\n\r\n // dot product of n and d = cosine of angle a in solar radiation euqation\r\n var sun_factor = sun_v.dot(panel_v);\r\n // console.log('dot product', sun_factor);\r\n\r\n var panel_potential = panel[mesh.userData.type].watt_capacity;\r\n\r\n // var power = sun_factor * panel_factor * panel_area;\r\n var power = sun_factor * panel_potential;\r\n // if (direction < 0) power = -power;\r\n if (power < 0) power = 0;\r\n \r\n mesh.userData.power = power;\r\n \r\n mesh.userData.percent_of_potential = power / panel_potential;\r\n\r\n if (time){\r\n\r\n if (mesh.userData.roof_id == \"Left\") {\r\n // month_data_left[month] += power;\r\n month_data_left[time.month] += (power / 1000);\r\n }\r\n else {\r\n month_data_right[time.month] += (power / 1000);\r\n }\r\n }\r\n\r\n mesh.userData.total_energy += power;\r\n\r\nreturn power;\r\n}", "get power (){\n return this._power; \n }", "get DOTMASK_STRENGTH() { return 0.3; }", "get numberOfPowerMeters() {\n return this.numberOfAccessories\n }", "function kelilingDiameter(d) {\n return (22 / 7) * d;\n}", "function getLineWidth(power){\n return Math.min(Math.round(getBaseLog(4.2, Math.abs(power))), 6);\n}", "get power() { return this.voltage * this.current; }", "get basePower() {\n const leverage = this.weapon.leverage;\n let power = this.weapon.power;\n if (leverage) {\n power = Math.round(power + this.char.body * leverage);\n }\n\n return power;\n }", "calcPowerGenerated() {\n this.pPanel = this.eSunRoof > 0 ? this.panelEfficiency * this.pSun\n * this.roofArea * Math.sin(this.eSunRoof * (Math.PI / 180)) : 0;\n }", "function find_prop_rpm(dia,pitch,K,power){\n\tvar prop_rpm = 0.0;\n// prop absorbed power(watts) = K P D^4 RPM^3 x 5.33e(-15)\n// prop static thrust(oz) = K P_eff D^3 RPM^2 x 1.1e(-10)\n\n// rearrange power equation to get:\n//prop rpm^3 = power/(K P D^4 x 5.33e(-15); take cube root of RHS to get rpm at which this prop absorbs this much power.\n\tvar rpm_cubed = power/(K*pitch*dia*dia*dia*dia*5.33e-15);\n\tprop_rpm = Math.pow(rpm_cubed,0.333333333333);\n\treturn prop_rpm;\n}", "function charge(d) {\r\n\t\t\t\t\t return -Math.pow(d.radius, 2.0) * forceStrength;\r\n\t\t\t\t\t }", "get wheelDampingRate() {}", "getDragCoefficient() {\n var dragco;\n var dragCam0Thk5, dragCam5Thk5, dragCam10Thk5, dragCam15Thk5, dragCam20Thk5;\n var dragCam0Thk10,\n dragCam5Thk10,\n dragCam10Thk10,\n dragCam15Thk10,\n dragCam20Thk10;\n var dragCam0Thk15,\n dragCam5Thk15,\n dragCam10Thk15,\n dragCam15Thk15,\n dragCam20Thk15;\n var dragCam0Thk20,\n dragCam5Thk20,\n dragCam10Thk20,\n dragCam15Thk20,\n dragCam20Thk20;\n var dragThk5, dragThk10, dragThk15, dragThk20;\n var dragCam0, dragCam5, dragCam10, dragCam15, dragCam20;\n var camd = this.getCamber();\n var thkd = this.getThickness();\n var alfd = this.getAngle();\n\n dragCam0Thk5 =\n -9e-7 * Math.pow(alfd, 3) +\n 0.0007 * Math.pow(alfd, 2) +\n 0.0008 * alfd +\n 0.015;\n dragCam5Thk5 =\n 4e-8 * Math.pow(alfd, 5) -\n 7e-7 * Math.pow(alfd, 4) -\n 1e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0033 * alfd +\n 0.0301;\n dragCam10Thk5 =\n -9e-9 * Math.pow(alfd, 6) -\n 6e-8 * Math.pow(alfd, 5) +\n 5e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) -\n 0.0001 * Math.pow(alfd, 2) -\n 0.0025 * alfd +\n 0.0615;\n dragCam15Thk5 =\n 8e-10 * Math.pow(alfd, 6) -\n 5e-8 * Math.pow(alfd, 5) -\n 1e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) -\n 0.0027 * alfd +\n 0.0612;\n dragCam20Thk5 =\n 8e-9 * Math.pow(alfd, 6) +\n 1e-8 * Math.pow(alfd, 5) -\n 5e-6 * Math.pow(alfd, 4) +\n 6e-6 * Math.pow(alfd, 3) +\n 0.001 * Math.pow(alfd, 2) -\n 0.001 * alfd +\n 0.1219;\n\n dragCam0Thk10 =\n -1e-8 * Math.pow(alfd, 6) +\n 6e-8 * Math.pow(alfd, 5) +\n 6e-6 * Math.pow(alfd, 4) -\n 2e-5 * Math.pow(alfd, 3) -\n 0.0002 * Math.pow(alfd, 2) +\n 0.0017 * alfd +\n 0.0196;\n dragCam5Thk10 =\n 3e-9 * Math.pow(alfd, 6) +\n 6e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) +\n 0.0038 * alfd +\n 0.0159;\n dragCam10Thk10 =\n -5e-9 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) +\n 1e-5 * Math.pow(alfd, 3) +\n 0.0004 * Math.pow(alfd, 2) -\n 3e-5 * alfd +\n 0.0624;\n dragCam15Thk10 =\n -2e-9 * Math.pow(alfd, 6) -\n 2e-8 * Math.pow(alfd, 5) -\n 5e-7 * Math.pow(alfd, 4) +\n 8e-6 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0034 * alfd +\n 0.0993;\n dragCam20Thk10 =\n 2e-9 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) +\n 2e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.0023 * alfd +\n 0.1581;\n\n dragCam0Thk15 =\n -5e-9 * Math.pow(alfd, 6) +\n 7e-8 * Math.pow(alfd, 5) +\n 3e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) -\n 7e-5 * Math.pow(alfd, 2) +\n 0.0017 * alfd +\n 0.0358;\n dragCam5Thk15 =\n -4e-9 * Math.pow(alfd, 6) -\n 8e-9 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) -\n 9e-7 * Math.pow(alfd, 3) +\n 0.0002 * Math.pow(alfd, 2) +\n 0.0031 * alfd +\n 0.0351;\n dragCam10Thk15 =\n 3e-9 * Math.pow(alfd, 6) +\n 3e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 1e-5 * Math.pow(alfd, 3) +\n 0.0009 * Math.pow(alfd, 2) +\n 0.004 * alfd +\n 0.0543;\n dragCam15Thk15 =\n 3e-9 * Math.pow(alfd, 6) +\n 5e-8 * Math.pow(alfd, 5) -\n 2e-6 * Math.pow(alfd, 4) -\n 3e-5 * Math.pow(alfd, 3) +\n 0.0008 * Math.pow(alfd, 2) +\n 0.0087 * alfd +\n 0.1167;\n dragCam20Thk15 =\n 3e-10 * Math.pow(alfd, 6) -\n 3e-8 * Math.pow(alfd, 5) -\n 6e-7 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0006 * Math.pow(alfd, 2) +\n 0.0008 * alfd +\n 0.1859;\n\n dragCam0Thk20 =\n -3e-9 * Math.pow(alfd, 6) +\n 2e-8 * Math.pow(alfd, 5) +\n 2e-6 * Math.pow(alfd, 4) -\n 8e-6 * Math.pow(alfd, 3) -\n 4e-5 * Math.pow(alfd, 2) +\n 0.0003 * alfd +\n 0.0416;\n dragCam5Thk20 =\n -3e-9 * Math.pow(alfd, 6) -\n 7e-8 * Math.pow(alfd, 5) +\n 1e-6 * Math.pow(alfd, 4) +\n 3e-5 * Math.pow(alfd, 3) +\n 0.0004 * Math.pow(alfd, 2) +\n 5e-5 * alfd +\n 0.0483;\n dragCam10Thk20 =\n 1e-8 * Math.pow(alfd, 6) +\n 4e-8 * Math.pow(alfd, 5) -\n 6e-6 * Math.pow(alfd, 4) -\n 2e-5 * Math.pow(alfd, 3) +\n 0.0014 * Math.pow(alfd, 2) +\n 0.007 * alfd +\n 0.0692;\n dragCam15Thk20 =\n 3e-9 * Math.pow(alfd, 6) -\n 9e-8 * Math.pow(alfd, 5) -\n 3e-6 * Math.pow(alfd, 4) +\n 4e-5 * Math.pow(alfd, 3) +\n 0.001 * Math.pow(alfd, 2) +\n 0.0021 * alfd +\n 0.139;\n dragCam20Thk20 =\n 3e-9 * Math.pow(alfd, 6) -\n 7e-8 * Math.pow(alfd, 5) -\n 3e-6 * Math.pow(alfd, 4) +\n 4e-5 * Math.pow(alfd, 3) +\n 0.0012 * Math.pow(alfd, 2) +\n 0.001 * alfd +\n 0.1856;\n\n if (liftAnalisis == 2) {\n dragco = 0;\n } else {\n if (-20.0 <= camd && camd < -15.0) {\n dragThk5 =\n (camd / 5 + 4) * (dragCam15Thk5 - dragCam20Thk5) + dragCam20Thk5;\n dragThk10 =\n (camd / 5 + 4) * (dragCam15Thk10 - dragCam20Thk10) + dragCam20Thk10;\n dragThk15 =\n (camd / 5 + 4) * (dragCam15Thk15 - dragCam20Thk15) + dragCam20Thk15;\n dragThk20 =\n (camd / 5 + 4) * (dragCam15Thk20 - dragCam20Thk20) + dragCam20Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-15.0 <= camd && camd < -10.0) {\n dragThk5 =\n (camd / 5 + 3) * (dragCam10Thk5 - dragCam15Thk5) + dragCam15Thk5;\n dragThk10 =\n (camd / 5 + 3) * (dragCam10Thk10 - dragCam15Thk10) + dragCam15Thk10;\n dragThk15 =\n (camd / 5 + 3) * (dragCam10Thk15 - dragCam15Thk15) + dragCam15Thk15;\n dragThk20 =\n (camd / 5 + 3) * (dragCam10Thk20 - dragCam15Thk20) + dragCam15Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-10.0 <= camd && camd < -5.0) {\n dragThk5 =\n (camd / 5 + 2) * (dragCam5Thk5 - dragCam10Thk5) + dragCam10Thk5;\n dragThk10 =\n (camd / 5 + 2) * (dragCam5Thk10 - dragCam10Thk10) + dragCam10Thk10;\n dragThk15 =\n (camd / 5 + 2) * (dragCam5Thk15 - dragCam10Thk15) + dragCam10Thk15;\n dragThk20 =\n (camd / 5 + 2) * (dragCam5Thk20 - dragCam10Thk20) + dragCam10Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (-5.0 <= camd && camd < 0) {\n dragThk5 =\n (camd / 5 + 1) * (dragCam0Thk5 - dragCam5Thk5) + dragCam5Thk5;\n dragThk10 =\n (camd / 5 + 1) * (dragCam0Thk10 - dragCam5Thk10) + dragCam5Thk10;\n dragThk15 =\n (camd / 5 + 1) * (dragCam0Thk15 - dragCam5Thk15) + dragCam5Thk15;\n dragThk20 =\n (camd / 5 + 1) * (dragCam0Thk20 - dragCam5Thk20) + dragCam5Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (0 <= camd && camd < 5) {\n dragThk5 = (camd / 5) * (dragCam5Thk5 - dragCam0Thk5) + dragCam0Thk5;\n dragThk10 =\n (camd / 5) * (dragCam5Thk10 - dragCam0Thk10) + dragCam0Thk10;\n dragThk15 =\n (camd / 5) * (dragCam5Thk15 - dragCam0Thk15) + dragCam0Thk15;\n dragThk20 =\n (camd / 5) * (dragCam5Thk20 - dragCam0Thk20) + dragCam0Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (5 <= camd && camd < 10) {\n dragThk5 =\n (camd / 5 - 1) * (dragCam10Thk5 - dragCam5Thk5) + dragCam5Thk5;\n dragThk10 =\n (camd / 5 - 1) * (dragCam10Thk10 - dragCam5Thk10) + dragCam5Thk10;\n dragThk15 =\n (camd / 5 - 1) * (dragCam10Thk15 - dragCam5Thk15) + dragCam5Thk15;\n dragThk20 =\n (camd / 5 - 1) * (dragCam10Thk20 - dragCam5Thk20) + dragCam5Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (10 <= camd && camd < 15) {\n dragThk5 =\n (camd / 5 - 2) * (dragCam15Thk5 - dragCam10Thk5) + dragCam10Thk5;\n dragThk10 =\n (camd / 5 - 2) * (dragCam15Thk10 - dragCam10Thk10) + dragCam10Thk10;\n dragThk15 =\n (camd / 5 - 2) * (dragCam15Thk15 - dragCam10Thk15) + dragCam10Thk15;\n dragThk20 =\n (camd / 5 - 2) * (dragCam15Thk20 - dragCam10Thk20) + dragCam10Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n } else if (15 <= camd && camd <= 20) {\n dragThk5 =\n (camd / 5 - 3) * (dragCam20Thk5 - dragCam15Thk5) + dragCam15Thk5;\n dragThk10 =\n (camd / 5 - 3) * (dragCam20Thk10 - dragCam15Thk10) + dragCam15Thk10;\n dragThk15 =\n (camd / 5 - 3) * (dragCam20Thk15 - dragCam15Thk15) + dragCam15Thk15;\n dragThk20 =\n (camd / 5 - 3) * (dragCam20Thk20 - dragCam15Thk20) + dragCam15Thk20;\n\n if (1.0 <= thkd && thkd <= 5.0) {\n dragco = dragThk5;\n } else if (5.0 < thkd && thkd <= 10.0) {\n dragco = (thkd / 5 - 1) * (dragThk10 - dragThk5) + dragThk5;\n } else if (10.0 < thkd && thkd <= 15.0) {\n dragco = (thkd / 5 - 2) * (dragThk15 - dragThk10) + dragThk10;\n } else if (15.0 < thkd && thkd <= 20.0) {\n dragco = (thkd / 5 - 3) * (dragThk20 - dragThk15) + dragThk15;\n }\n }\n\n var cldin = this.getLiftCoefficient();\n\n var reynolds = this.getReynolds();\n\n /**\n * The following is for the reynolds number correction\n */\n if (reCorrection == true)\n dragco = dragco * Math.pow(50000 / reynolds, 0.11);\n\n /**\n * The following is for the induced drag option\n */\n if (induced == true)\n dragco = dragco + (cldin * cldin) / (3.1415926 * aspr * 0.85);\n\n /**\n * If the velocity is 0 then the dragCoefficient will be 0\n */\n\n if (this.getVelocity() == 0) dragco = 0;\n }\n\n return dragco;\n }", "calcEnergy(){\r\n this.kineticE=this.mass*(Math.pow(this.speed.x,2)+Math.pow(this.speed.y,2));\r\n this.totalE=this.kineticE+this.heatE;\r\n }", "function CalculatePower(params) \n{\n // calculate the forces on the rider.\n var forces = CalculateForces(params);\n var totalforce = forces.Fgravity + forces.Frolling + forces.Fdrag;\n\n // calculate necessary wheelpower\n var wheelpower = totalforce * params.Speed;// * 1000.0 / 3600.0);\n\n // calculate necessary legpower\n var legpower = wheelpower / (1.0 - (params.DriveDrainLoss/100.0));\n\n return { Leg: legpower, Wheel: wheelpower};\n}", "get power(){\n return this._power;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disallowModify(input_object[,message[,true]]) Checks a form field for a value different than defaultValue. Optionally alerts and focuses
function disallowModify(obj) { var msg; var dofocus; if (arguments.length>1) { msg = arguments[1]; } if (arguments.length>2) { dofocus = arguments[2]; } else { dofocus=false; } if (getInputValue(obj) != getInputDefaultValue(obj)) { if (!isBlank(msg)) { alert(msg); } if (dofocus) { obj.select(); obj.focus(); } setInputValue(obj,getInputDefaultValue(obj)); return true; } return false; }
[ "function disallowModify(obj){\r\n\tvar msg=(arguments.length>1)?arguments[1]:\"\";\r\n\tvar dofocus=(arguments.length>2)?arguments[2]:false;\r\n\tif (getInputValue(obj)!=getInputDefaultValue(obj)){\r\n\t\tif(!isBlank(msg)){alert(msg);}\r\n\t\tif(dofocus){\r\n\t\t\tif (isArray(obj) && (typeof(obj.type)==\"undefined\")) {obj=obj[0];}\r\n\t\t\tif(obj.type==\"text\"||obj.type==\"textarea\"||obj.type==\"password\") { obj.select(); }\r\n\t\t\tobj.focus();\r\n\t\t\t}\r\n\t\tsetInputValue(obj,getInputDefaultValue(obj));\r\n\t\treturn true;\r\n\t\t}\r\n\treturn false;\r\n\t}", "function disallowModify(obj){\n\tvar msg=(arguments.length>1)?arguments[1]:\"\";\n\tvar dofocus=(arguments.length>2)?arguments[2]:false;\n\tif (getInputValue(obj)!=getInputDefaultValue(obj)){\n\t\tif(!isBlank(msg)){alert(msg);}\n\t\tif(dofocus){\n\t\t\tif (isArray(obj) && (typeof(obj.type)==\"undefined\")) {obj=obj[0];}\n\t\t\tif(obj.type==\"text\"||obj.type==\"textarea\"||obj.type==\"password\") { obj.select(); }\n\t\t\tobj.focus();\n\t\t\t}\n\t\tsetInputValue(obj,getInputDefaultValue(obj));\n\t\treturn true;\n\t\t}\n\treturn false;\n\t}", "function disallowBlank(obj){\r\n\tvar msg=(arguments.length>1)?arguments[1]:\"\";\r\n\tvar dofocus=(arguments.length>2)?arguments[2]:false;\r\n\tif (isBlank(getInputValue(obj))){\r\n\t\tif(!isBlank(msg)){alert(msg);}\r\n\t\tif(dofocus){\r\n\t\t\tif (isArray(obj) && (typeof(obj.type)==\"undefined\")) {obj=obj[0];}\r\n\t\t\tif(obj.type==\"text\"||obj.type==\"textarea\"||obj.type==\"password\") { obj.select(); }\r\n\t\t\tobj.focus();\r\n\t\t\t}\r\n\t\treturn true;\r\n\t\t}\r\n\treturn false;\r\n\t}", "function disallowBlank(obj){\n\tvar msg=(arguments.length>1)?arguments[1]:\"\";\n\tvar dofocus=(arguments.length>2)?arguments[2]:false;\n\tif (isBlank(getInputValue(obj))){\n\t\tif(!isBlank(msg)){alert(msg);}\n\t\tif(dofocus){\n\t\t\tif (isArray(obj) && (typeof(obj.type)==\"undefined\")) {obj=obj[0];}\n\t\t\tif(obj.type==\"text\"||obj.type==\"textarea\"||obj.type==\"password\") { obj.select(); }\n\t\t\tobj.focus();\n\t\t\t}\n\t\treturn true;\n\t\t}\n\treturn false;\n\t}", "function disallowBlank(obj)\n{\n\tvar msg=(arguments.length>1)?arguments[1]:\"\";\n\tvar dofocus=(arguments.length>2)?arguments[2]:false;\n\tif (isBlank(getInputValue(obj))){\n\t\tif(!isBlank(msg)){alert(msg);}\n\t\tif(dofocus){\n\t\t\tif (isArray(obj) && (typeof(obj.type)==\"undefined\")) {obj=obj[0];}\n\t\t\tif(obj.type==\"text\"||obj.type==\"textarea\"||obj.type==\"password\") { obj.select(); }\n\t\t\tobj.focus();\n\t\t\t}\n\t\treturn true;\n\t\t}\n\treturn false;\n}", "function isChanged(obj){return(getInputValue(obj)!=getInputDefaultValue(obj));}", "function MUD_set_msg_novalue(el_input) {\n const has_novalue = !el_input.value;\n add_or_remove_class(el_input, \"border_bg_invalid\", has_novalue);\n\n const fldName = get_attr_from_el(el_input, \"data-field\");\n const el_MUD_msg = document.getElementById(\"id_MUD_msg_\" + fldName);\n if (el_MUD_msg){\n const cpt = (loc.err_userdata[fldName]) ? loc.err_userdata[fldName] : \"-\";\n el_MUD_msg.innerText = (has_novalue) ? cpt + loc.err_userdata.cannot_be_blank : null;\n add_or_remove_class(el_MUD_msg, \"text-danger\", has_novalue);\n };\n\n if (has_novalue){\n if(!mod_MUD_dict.err_list.includes(fldName)){\n mod_MUD_dict.err_list.push(fldName);\n };\n } else {\n if(mod_MUD_dict.err_list.includes(fldName)){\n b_remove_item_from_array(mod_MUD_dict.err_list, fldName);\n };\n };\n\n }", "function warnControlledUsage(params) {\n if (true) {\n var componentId = params.componentId, componentName = params.componentName, defaultValueProp = params.defaultValueProp, props = params.props, oldProps = params.oldProps, onChangeProp = params.onChangeProp, readOnlyProp = params.readOnlyProp, valueProp = params.valueProp;\n // This warning logic closely follows what React does for native <input> elements.\n var oldIsControlled = oldProps ? Object(_controlled__WEBPACK_IMPORTED_MODULE_1__[\"isControlled\"])(oldProps, valueProp) : undefined;\n var newIsControlled = Object(_controlled__WEBPACK_IMPORTED_MODULE_1__[\"isControlled\"])(props, valueProp);\n if (newIsControlled) {\n // onChange (or readOnly) must be provided if value is provided\n var hasOnChange = !!props[onChangeProp];\n var isReadOnly = !!(readOnlyProp && props[readOnlyProp]);\n if (!(hasOnChange || isReadOnly) && !warningsMap.valueOnChange[componentId]) {\n warningsMap.valueOnChange[componentId] = true;\n Object(_warn__WEBPACK_IMPORTED_MODULE_0__[\"warn\"])(\"Warning: You provided a '\" + valueProp + \"' prop to a \" + componentName + \" without an '\" + onChangeProp + \"' handler. \" +\n (\"This will render a read-only field. If the field should be mutable use '\" + defaultValueProp + \"'. \") +\n (\"Otherwise, set '\" + onChangeProp + \"'\" + (readOnlyProp ? \" or '\" + readOnlyProp + \"'\" : '') + \".\"));\n }\n // value and defaultValue are mutually exclusive\n var defaultValue = props[defaultValueProp];\n if (defaultValue !== undefined && defaultValue !== null && !warningsMap.valueDefaultValue[componentId]) {\n warningsMap.valueDefaultValue[componentId] = true;\n Object(_warn__WEBPACK_IMPORTED_MODULE_0__[\"warn\"])(\"Warning: You provided both '\" + valueProp + \"' and '\" + defaultValueProp + \"' to a \" + componentName + \". \" +\n (\"Form fields must be either controlled or uncontrolled (specify either the '\" + valueProp + \"' prop, \") +\n (\"or the '\" + defaultValueProp + \"' prop, but not both). Decide between using a controlled or uncontrolled \") +\n (componentName + \" and remove one of these props. More info: https://fb.me/react-controlled-components\"));\n }\n }\n // Warn if switching between uncontrolled and controlled. (One difference between this implementation\n // and React's <input> is that if oldIsControlled is indeterminate and newIsControlled true, we don't warn.)\n if (oldProps && newIsControlled !== oldIsControlled) {\n var oldType = oldIsControlled ? 'a controlled' : 'an uncontrolled';\n var newType = oldIsControlled ? 'uncontrolled' : 'controlled';\n var warnMap = oldIsControlled ? warningsMap.controlledToUncontrolled : warningsMap.uncontrolledToControlled;\n if (!warnMap[componentId]) {\n warnMap[componentId] = true;\n Object(_warn__WEBPACK_IMPORTED_MODULE_0__[\"warn\"])(\"Warning: A component is changing \" + oldType + \" \" + componentName + \" to be \" + newType + \". \" +\n (componentName + \"s should not switch from controlled to uncontrolled (or vice versa). \") +\n \"Decide between using controlled or uncontrolled for the lifetime of the component. \" +\n \"More info: https://fb.me/react-controlled-components\");\n }\n }\n }\n}", "function warnControlledUsage(params) {\n if (true) {\n var componentId = params.componentId, componentName = params.componentName, defaultValueProp = params.defaultValueProp, props = params.props, oldProps = params.oldProps, onChangeProp = params.onChangeProp, readOnlyProp = params.readOnlyProp, valueProp = params.valueProp;\n // This warning logic closely follows what React does for native <input> elements.\n var oldIsControlled = oldProps ? (0,_controlled__WEBPACK_IMPORTED_MODULE_0__.isControlled)(oldProps, valueProp) : undefined;\n var newIsControlled = (0,_controlled__WEBPACK_IMPORTED_MODULE_0__.isControlled)(props, valueProp);\n if (newIsControlled) {\n // onChange (or readOnly) must be provided if value is provided\n var hasOnChange = !!props[onChangeProp];\n var isReadOnly = !!(readOnlyProp && props[readOnlyProp]);\n if (!(hasOnChange || isReadOnly) && !warningsMap.valueOnChange[componentId]) {\n warningsMap.valueOnChange[componentId] = true;\n (0,_warn__WEBPACK_IMPORTED_MODULE_1__.warn)(\"Warning: You provided a '\" + valueProp + \"' prop to a \" + componentName + \" without an '\" + onChangeProp + \"' handler. \" +\n (\"This will render a read-only field. If the field should be mutable use '\" + defaultValueProp + \"'. \") +\n (\"Otherwise, set '\" + onChangeProp + \"'\" + (readOnlyProp ? \" or '\" + readOnlyProp + \"'\" : '') + \".\"));\n }\n // value and defaultValue are mutually exclusive\n var defaultValue = props[defaultValueProp];\n if (defaultValue !== undefined && defaultValue !== null && !warningsMap.valueDefaultValue[componentId]) {\n warningsMap.valueDefaultValue[componentId] = true;\n (0,_warn__WEBPACK_IMPORTED_MODULE_1__.warn)(\"Warning: You provided both '\" + valueProp + \"' and '\" + defaultValueProp + \"' to a \" + componentName + \". \" +\n (\"Form fields must be either controlled or uncontrolled (specify either the '\" + valueProp + \"' prop, \") +\n (\"or the '\" + defaultValueProp + \"' prop, but not both). Decide between using a controlled or uncontrolled \") +\n (componentName + \" and remove one of these props. More info: https://fb.me/react-controlled-components\"));\n }\n }\n // Warn if switching between uncontrolled and controlled. (One difference between this implementation\n // and React's <input> is that if oldIsControlled is indeterminate and newIsControlled true, we don't warn.)\n if (oldProps && newIsControlled !== oldIsControlled) {\n var oldType = oldIsControlled ? 'a controlled' : 'an uncontrolled';\n var newType = oldIsControlled ? 'uncontrolled' : 'controlled';\n var warnMap = oldIsControlled ? warningsMap.controlledToUncontrolled : warningsMap.uncontrolledToControlled;\n if (!warnMap[componentId]) {\n warnMap[componentId] = true;\n (0,_warn__WEBPACK_IMPORTED_MODULE_1__.warn)(\"Warning: A component is changing \" + oldType + \" \" + componentName + \" to be \" + newType + \". \" +\n (componentName + \"s should not switch from controlled to uncontrolled (or vice versa). \") +\n \"Decide between using controlled or uncontrolled for the lifetime of the component. \" +\n \"More info: https://fb.me/react-controlled-components\");\n }\n }\n }\n}", "function prefSetterOppositeOfDefault(prefName, defaultValue) {\n if (possibly_missing_preferences.has(prefName)) {\n return;\n }\n this[prefName].set({value: !defaultValue},\n chrome.test.callbackPass(function() {\n this[prefName].get({}, expectControlled(prefName, !defaultValue));\n }.bind(this)));\n}", "function checkDefault(boxObj, setfocus)\n{\n boxObj.hasFocus = setfocus;\n \n if (boxObj.hasFocus && boxObj.value == boxObj.defaultValue) \n boxObj.value = \"\";\n else if (!boxObj.hasFocus && boxObj.value == \"\")\n boxObj.value = boxObj.defaultValue;\n}", "function checkDefault(boxObj, setfocus)\n{\n boxObj.hasFocus = setfocus;\n\n if (boxObj.hasFocus && boxObj.value == boxObj.defaultValue) \n boxObj.value = \"\";\n else if (!boxObj.hasFocus && boxObj.value == \"\")\n boxObj.value = boxObj.defaultValue;\n}", "function MaskedEditSetMessage(value,msg)\n{\n value.errormessage = msg;\n value.innerHTML = msg;\n}", "function KeepFieldSet( field, originalValue, id )\r\n{\r\n\tif ( field.value != '' )\r\n\t{\r\n\t\talert( localMessages.youCanTEnterTextInByHandUseTheButtonToTheRight );\r\n\t\tfield.value = originalValue.value;\r\n\t}\r\n}", "function getInputDefaultValue(obj){return getInputValue(obj,true);}", "function disableFormFields() {\n\tvar modifyButton = $(modifyButtonName);\n\tvar saveButton = $(saveButtonName);\n\tvar backButton = $(backButtonName);\n\n\tif (modifyButton) {\n\t\tif (modifyButton.oldOnclick) {\n\t\t\t//Transform the cancel back to modify button\n\t\t\tmodifyButton.onclick = modifyButton.oldOnclick;\n\t\t\tmodifyButton.value = modifyLabel;\n\t\t\tmodifyButton.oldOnclick = null;\n\t\t}\n\t}\n\tif (saveButton) {\n\t\tdisableField(saveButton);\n\t}\n\t\n\t//The additional arguments are field names we don't want to touch.\n\tvar keep = $A(arguments);\n\tif (modifyButton) {\n\t\tkeep.push(elementId(modifyButton));\n\t}\n\tif (backButton) {\n\t\tkeep.push(elementId(backButton));\n\t}\n\n\t//Process each field\n\tprocessFields(this, keep, disableField);\n}", "function preventInputBlur(e) {\n e.preventDefault();\n}", "function setUnchanged(){\n\tformModified = false;\n}", "function skipValidation() { \n unsaved = false;\n checkChange(unsaved);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolves Preload config per destination
static async resolveDestinationPreloadConfig(router, destination) { const requests = []; await new Tasks_1.default() .add(...router.preloadRequests.options) .onTaskDone((result) => { requests.push(...result.map(r => ({ ...r, destination }))); }) .resolve(); return { requests, }; }
[ "static async resolvePreloadConfig(router) {\n const preloadRequests = [];\n const tasks = new Tasks_1.default();\n const destinations = router.getDestinations();\n // Compile all the requests and options across all destinations\n if (!Object.keys(destinations).length) {\n tasks.add(PreloadRequests.resolveDestinationPreloadConfig(router, 'default'));\n }\n else {\n for (let d in destinations) {\n tasks.add(PreloadRequests.resolveDestinationPreloadConfig(destinations[d], d));\n }\n }\n await tasks\n .onTaskDone(({ requests }) => {\n preloadRequests.push(...requests);\n })\n .resolve();\n return {\n requests: preloadRequests,\n concurrency: config_1.default.get('prerenderConcurrency', null),\n };\n }", "createPreloadConfig() {\n return PreloadRequests_1.default.resolvePreloadConfig(this);\n }", "async _mapLoadToResolve(resolveResults, onProgress) {\n const resolveArray = Object.values(resolveResults), resolveKeys = Object.keys(resolveResults);\n this._backgroundLoader.active = !1;\n const loadedAssets = await this.loader.load(resolveArray, onProgress);\n this._backgroundLoader.active = !0;\n const out = {};\n return resolveArray.forEach((resolveResult, i2) => {\n const asset = loadedAssets[resolveResult.src], keys = [resolveResult.src];\n resolveResult.alias && keys.push(...resolveResult.alias), out[resolveKeys[i2]] = asset, Cache.set(keys, asset);\n }), out;\n }", "normalizeDataSources(config, path) {\n config.sources = config.sources || {};\n\n for (let source of Utils.values(config.sources)) {\n source.url = Utils.addBaseURL(source.url, path);\n }\n\n return config;\n }", "function fnLoadConfig(){\n // if there's a \"config.json\" file, try to read from it\n if (fs.existsSync(`${CFG}/config.json`)){\n try {\n const raw = fs.readFileSync(`${CFG}/config.json`, \"utf8\");\n const parsed = JSON.parse(raw);\n return { config: parsed, rawConfig: raw, sourceConfig: `${CFG}/config.json` };\n }\n catch (error){\n return { config: false, rawConfig: false, sourceConfig: false };\n }\n }\n // otherwise, try to read from \"remote-api.config.json\",\n // in case \"config.gen.js\" is missing and Remote API is running\n else if (fs.existsSync(`${CFG}/config.gen.js`) !== true && fnIsRunning(\"node /startup/remote-api/index.js\")) {\n try {\n const raw = fs.readFileSync(`${CFG}/remote-api.config.json`, \"utf8\");\n const parsed = JSON.parse(raw);\n return { config: parsed, rawConfig: raw, sourceConfig: `${CFG}/remote-api.config.json` };\n }\n catch (error){\n return { config: false, rawConfig: false, sourceConfig: false };\n }\n }\n\n return { config: false, rawConfig: false, sourceConfig: false };\n}", "loadConfig (configPath, another, folder) {\n const options = Object.assign(getConfig(configPath, { startFrom: folder }))\n if (another) {\n Object.assign(options, getConfig(another, { startFrom: folder }))\n }\n return options\n }", "function loadConfigs() {\n grunt.file.expandMapping(settings.configs, '', {\n flatten: true,\n ext: ''\n }).forEach(function(configFile) {\n var config = {};\n config[configFile.dest] = grunt.file.readJSON(configFile.src[0]);\n grunt.config.merge(config);\n });\n}", "function init() {\n return {\n loaders: [ new LocalLoader() ],\n fetch: function(dep_name, targetConfig) {\n var output;\n this.loaders.forEach(function(l) {\n if (!output && l.match(dep_name)) {\n output = l.load(dep_name, targetConfig);\n }\n });\n return output;\n }\n };\n}", "async loadProperties() {\n this.resolveProperties(await this.globalConfig.read(), this.localConfig && (await this.localConfig.read()));\n ConfigAggregator.encrypted = false;\n }", "loadConfig() {\n this.loadPlugin();\n super.loadConfig();\n }", "resolveCacheLoaderOptions () {\n Object.assign(this, (getCacheLoaderOptions(this.siteConfig, this.options, this.cwd, this.isProd)))\n }", "resolve() {\n return new ResolvedConfig(this.resolveData());\n }", "fetchOrigin() {\n this.possibleOrigins = this.airService.getAirports(AIRPORT_TYPE.ORIGIN, this.destinationAirport);\n }", "function resolve(base, configuration)\n{\n\tconfiguration.forEach(function(s, index)\n\t{\n\t\tif (typeof s === \"string\")\n\t\t{\n\t\t\ts = configuration[index] = { path: s };\n\t\t}\n\n\t\t// If the service is a package on the disk we need to load it\n\t\tif (s.hasOwnProperty(\"path\"))\n\t\t{\n\t\t\tvar servicePath = path.join(base, s.path);\n\t\t\tvar initializer = require(servicePath);\n\n\t\t\ts.isLocal = true;\n\t\t\ts.initializer = initializer;\n\t\t\ts.dependencies = initializer.$dependencies || [];\n\t\t\ts.dependenciesLeft = s.dependencies.slice();\n\t\t}\n\n\t\t// Set helper properties\n\t\ts.isLocal = s.isLocal || false;\n\t\ts.isMultiBound = s.multibinder ? true : false;\n\t\ts.isMapBound = s.mapbinder ? true : false;\n\t\ts.name = s.name || s.external || deriveNameFromPath(s.path);\n\n\t\t// Set proper mapbinder data\n\t\tif (s.isMapBound)\n\t\t{\n\t\t\tvar name = s.name;\n\t\t\tvar mapbinder = s.mapbinder;\n\n\t\t\ts.name = mapbinder;\n\t\t\ts.mapbinder = name;\n\t\t}\n\n\t\t// Set proper multibinder data\n\t\tif (s.isMultiBound)\n\t\t{\n\t\t\ts.name = s.multibinder;\n\t\t}\n\t});\n\n\treturn configuration;\n}", "Load(CdoConfigSource, string) {\n\n }", "function preload(key, config) {\n // 如果未同时传入键名和配置参数,将终止执行本次预加载过程\n if (!angular.isDefined(key) || !angular.isDefined(config)) return;\n // 分支判断,目前仅仅支持数据字典与下拉选单的预加载过程\n switch (key) {\n case 'dict':\n loadingDictionary(config, PhoebeDict, dataProvider, broadcastEvent);\n break;\n case 'options':\n loadingOptionData(config, PhoebeResource, $q, dataProvider, resoure, broadcastEvent);\n break;\n }\n }", "async preload (path) {\n const { route, match } = this.findRoute(path)\n if (!match) return\n\n // fetch component(bundle).\n const Component = await route.Component.load()\n // fetch initialProps of component.\n await getInitialPropsFromComponent(Component, path, { match })\n }", "_loadConfigs() {\n\n let pattern = path.join(this._envValOptions.CONFIG_DIR, '/**/*.js');\n\n glob.sync(pattern).map(file => { // eslint-disable-line array-callback-return\n const {values, schema} = require(file);\n this._schemas.push(schema);\n Object.assign(this.configStore, values);\n });\n }", "fetchDestination() {\n this.possibleDestinations = this.airService.getAirports(AIRPORT_TYPE.DEST, this.originAirport);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iv. Fill input value whose element id firstname using javascript.
function first(){ var firstname=document.getElementById('first-name'); firstname.nodeValue="mushi"; }
[ "function updateNameSurname() {\n nameSurname = document.getElementById(\"name-surname\").value;\n}", "function update_primary(){\n $('input#person_primary_salutation').val($('select#person_primary_title_id').find('option:selected').html()\n + \" \" + $('input#person_first_name').val()\n + \" \" + $('input#person_family_name').val());\n }", "updateFirstName(Fname) {\n\n\t\tlet driver = this.driver_; \n\n\t\ttry{\n\n\t\t\treturn this.getFirstNameElement()\n\t\t\t\t.then(function(element){\n\n\t\t\t\t\telement.sendKeys(Fname);\n\n\t\t\t\t});\n\t\t}catch(e){\n\n\t\t\tconsole.log(\"error\", e)\n\t\t}\n\n\t}", "function setFirst(first) {\n console.info(\"Setting the Current First Name: \", first);\n $('#edit_first').val(first);\n }", "get latNameTextField() { return $(\"//input[@name='lastName' and @type='text']\")}", "function details(){\n var firstname = document.getElementById(\"firstname\").value;\n var surname = document.getElementById(\"surname\").value;\n var full_name = firstname + \" \" + surname;\n\n document.getElementById(\"full_name\").innerHTML = full_name;\n}", "function autofillLogin() {\n var dLogin = document.getElementById(\"desired_login\");\n var dEmail = document.getElementById(\"desired_email\");\n\n var fname = document.getElementById(\"fname\");\n var lname = document.getElementById(\"lname\");\n dLogin.value = fname.value + \".\" + lname.value;\n dEmail.value = fname.value + \".\" + lname.value + \"@cambridgecollege.edu\";\n}", "async fillFirstName(firstName) {\n const firstNameElement = await this.components.firstNameInput()\n await firstNameElement.type(firstName)\n }", "function getFirstName() {\n if (typeof document.registration.firstname === \"undefined\") {\n return \"\";\n }\n return document.registration.firstname.value;\n}", "function ReferidoGPT(){\r\nif(document.getElementsByName(\"referrerid\").item(0)){\r\ndocument.getElementsByName(\"referrerid\").item(0).value = Referido;\r\n}}", "function populateVerName() {\r\n\r\n\tvar fName = document\r\n\t\t\t.getElementsByName('partAGEN1.personalInfo.assesseeName.firstName')[0].value;\r\n\tvar mName = document\r\n\t\t\t.getElementsByName('partAGEN1.personalInfo.assesseeName.middleName')[0].value;\r\n\tvar lName = document\r\n\t\t\t.getElementsByName('partAGEN1.personalInfo.assesseeName.surNameOrOrgName')[0].value;\r\n\r\n\tvar verName;\r\n\r\n\tif (fName != '' && mName != '') {\r\n\t\tverName = fName + ' ' + mName + ' ' + lName;\r\n\t}\r\n\r\n\telse if (fName == '' && mName != '') {\r\n\t\tverName = mName + ' ' + lName;\r\n\t}\r\n\r\n\telse if (fName != '' && mName == '') {\r\n\t\tverName = fName + ' ' + lName;\r\n\t} else {\r\n\t\tverName = lName;\r\n\t}\r\n\tdocument.getElementsByName('verification.declaration.assesseeVerName')[0].value = verName;\r\n\r\n}", "function populateVerName(){\r\n\t\r\n\tvar fName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.firstName')[0].value;\r\n\tvar mName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.middleName')[0].value;\r\n\tvar lName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.surNameOrOrgName')[0].value;\r\n\t\r\n\tvar verName;\r\n\t\r\n\tif(fName !='' && mName!='' ){\r\n\tverName=fName+ ' '+ mName +' '+lName ;\r\n\t}\r\n\t\r\n\telse if(fName =='' && mName!='' ){\r\n\t\tverName= mName +' '+lName ;\r\n\t\t}\r\n\t\r\n\telse if(fName !='' && mName =='' ){\r\n\t\tverName=fName+ ' '+lName ;\r\n\t\t}\r\n\telse{\r\n\t\tverName=lName;\r\n\t}\r\n\tdocument.getElementsByName('verification.declaration.assesseeVerName')[0].value=verName;\r\n\t\r\n}", "function getFirstName() {\n if ($.first_name) {\n return $.first_name.getValue().trim();\n }\n }", "function autoFillUser() {\t\n\tvar i=0;\n\tt = document.forms[0];\n\tif (t) {\t\t\t\t\t\n\t\tvar count = t.elements.length - 1;\t\n\t\tvar data = false;\n\t\twhile( i < count )\n\t\t{\t\t\t\n\t\t\t// Last name:\n\t\t\tif (t.elements[i].name==\"id1\" ) {\n\t\t\t\tt.elements[i].value = lastName;\n\t\t\t\tdata = true;\n\t\t\t}\n\t\t\tif (t.elements[i].name==\"id0\" ) {\n\t\t\t\tt.elements[i].value = cardNumber;\n\t\t\t\tdata = true;\n\t\t\t}\t\t\t\n\t\t\ti++;\n\t\t} // while\n\t\t\n\t\tif (data) {\n\t\t\tif (!cardNumber || !lastName) {\n\t\t\t\talert(\"autoFillUser is on, but cardNumber & lastname are not defined. Open script and define them.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tt.submit();\t\n\t\t}\n\t} \n\n}", "function generateUsername() {\r\n\tvar forename = document.getElementById(\"forname\").value;\r\n\tvar surname = document.getElementById(\"surname\").value;\r\n\tforename = forename.toLowerCase();\r\n\tsurname = surname.toLowerCase();\r\n\t// Concatenate the surname and only the fisr character from the forename\r\n\tvar username = surname + forename.charAt(0);\r\n\tdocument.getElementById(\"username\").value = username;\r\n}", "function fill_contact_number_name()\n{\n\tvar i1 = contact_number.length;\n\tvar to_check, to_check_val, to_write, first_name, last_name, full_name;\n\tfor(var i=0;i<i1;i++)\n\t{\n\t\tto_check = contact_number[i] + \"_number_owner\";\n\t\t//to_check_val = eval(\"docF.\"+to_check+\".value\");\n\t\tto_check_val = document.getElementById(to_check).value;\n\t\tto_write = contact_number[i] + \"_owner_name\";\n\t\tif(to_check_val == \"1\" || to_check_val == \"2\")\n\t\t{\n\t\t\tfirst_name = docF.fname_user.value;\n\t\t\tlast_name = docF.lname_user.value;\n\t\t\tif(first_name && last_name)\n\t\t\t\tfull_name = first_name + \" \" + last_name;\n\t\t\telse if(first_name)\n\t\t\t\tfull_name = first_name;\n\t\t\telse if(last_name)\n\t\t\t\tfull_name = last_name;\n\t\t\telse\n\t\t\t\tfull_name = \"\";\n\n\t\t\tdocument.getElementById(to_write).value = full_name;\n\t\t\t//eval(\"docF.\"+to_write+\".value = full_name\");\n\t\t}\n\t\telse\n\t\t\tdocument.getElementById(to_write).value = '';\n\t\t\t//eval(\"docF.\"+to_write+\".value = ''\");\n\t}\n}", "function inputName(){\n\t\t\tuserdata.nameInput =getName.value;\n\t\t}", "function getPersona(persona){\n\t\n\tdocument.getElementById(\"nombre\").value = persona.nombre;\n\tdocument.getElementById(\"apellido\").value = persona.apellido;\n\tdocument.getElementById(\"edad\").value = persona.edad;\n}", "function nameInfo(){\n let firstName = document.getElementById('firstName').value;\n let middleName = document.getElementById('middleName').value;\n let lastName = document.getElementById('lastName').value;\n \n let fullName = firstName + ' ' + middleName + ' ' + lastName;\n \n document.getElementById(\"fullName\").innerHTML = fullName;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a mutation batch and the associated document mutations.
function removeMutationBatch(txn, userId, batch) { var mutationStore = txn.store(DbMutationBatch.store); var indexTxn = txn.store(DbDocumentMutation.store); var promises = []; var range = IDBKeyRange.only(batch.batchId); var numDeleted = 0; var removePromise = mutationStore.iterate({ range: range }, function (key, value, control) { numDeleted++; return control.delete(); }); promises.push(removePromise.next(function () { assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' + batch.batchId); })); var removedDocuments = []; for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) { var mutation = _a[_i]; var indexKey = DbDocumentMutation.key(userId, mutation.key.path, batch.batchId); promises.push(indexTxn.delete(indexKey)); removedDocuments.push(mutation.key); } return PersistencePromise.waitFor(promises).next(function () { return removedDocuments; }); }
[ "function removeMutationBatch(txn, userId, batch) {\n var mutationStore = txn.store(DbMutationBatch.store);\n var indexTxn = txn.store(DbDocumentMutation.store);\n var promises = [];\n var range = IDBKeyRange.only(batch.batchId);\n var numDeleted = 0;\n var removePromise = mutationStore.iterate({ range: range }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId);\n }));\n var removedDocuments = [];\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(function () { return removedDocuments; });\n}", "function removeMutationBatch(txn, userId, batch) {\n var mutationStore = txn.store(DbMutationBatch.store);\n var indexTxn = txn.store(DbDocumentMutation.store);\n var promises = [];\n var range = IDBKeyRange.only(batch.batchId);\n var numDeleted = 0;\n var removePromise = mutationStore.iterate({\n range: range\n }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' + batch.batchId);\n }));\n var removedDocuments = [];\n\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n\n return PersistencePromise.waitFor(promises).next(function () {\n return removedDocuments;\n });\n}", "function removeMutationBatch(txn,userId,batch){var mutationStore=txn.store(DbMutationBatch.store);var indexTxn=txn.store(DbDocumentMutation.store);var promises=[];var range=IDBKeyRange.only(batch.batchId);var numDeleted=0;var removePromise=mutationStore.iterate({range:range},function(key,value,control){numDeleted++;return control.delete();});promises.push(removePromise.next(function(){assert(numDeleted===1,'Dangling document-mutation reference found: Missing batch '+batch.batchId);}));var removedDocuments=[];for(var _i=0,_a=batch.mutations;_i<_a.length;_i++){var mutation=_a[_i];var indexKey=DbDocumentMutation.key(userId,mutation.key.path,batch.batchId);promises.push(indexTxn.delete(indexKey));removedDocuments.push(mutation.key);}return PersistencePromise.waitFor(promises).next(function(){return removedDocuments;});}", "batchDelete(batch, firestore, id) {\n let ref;\n if (!id) {\n ref = firestore.collection('org').doc(this.orgId).collection(this.docName).doc(this.id);\n }\n else {\n ref = firestore.collection('org').doc(this.orgId).collection(this.docName).doc(id);\n }\n batch.delete(ref);\n }", "async destroyMany({ request, response }) {\n\t\tconst { ids } = request.params;\n\t\tconst result = await Taxonomy.query()\n\t\t\t.whereIn('id', ids)\n\t\t\t.delete();\n\t\tif (!result) {\n\t\t\treturn response\n\t\t\t\t.status(400)\n\t\t\t\t.send(\n\t\t\t\t\terrorPayload(\n\t\t\t\t\t\terrors.RESOURCE_DELETED_ERROR,\n\t\t\t\t\t\trequest.antl('error.resource.resourceDeletedError'),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t}\n\t\treturn response.status(200).send({ success: true });\n\t}", "deleteProblem(server, response, accountID, problemID) {\n let self = this;\n //is problem deletable by user\n let unassembledLink = problemID.split('/');\n let correctLink = unassembledLink.reduce((assembler, part) => assembler + \"\\\\\" + part);\n let problemReference;\n try {\n problemReference = this.session.collection(\"problems\").doc(correctLink)\n } catch (error) {\n console.error(\"============ Error =============\");\n console.error(\"Error with gettting problem in deleteProblem\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n return server.respondWithError(response, 400, 'text/plain', \"Error 400: Invalid Problem Link\");\n }\n\n problemReference.get()\n .then(doc => {\n if (!doc.exists) {\n return server.respondWithError(response, 404, \"Error 404: Problem not found\");\n }\n\n let problem = doc.data();\n if (problem.creatorAccountID !== accountID) {\n return server.respondWithError(response, 403, \"Error 403: Invalid Authorization to delete problem\")\n }\n\n //make deletes atomic\n let batch = self.session.batch();\n //remove problem from lessons that it exists in\n problem.ownerLessons.forEach(lessonID => {\n let lessonReference = self.session.collection(\"lessons\").doc(lessonID);\n batch.update(lessonReference, {\n creations: self.admin.firestore.FieldValue.arrayRemove(\"problems/\" + correctLink)\n });\n });\n\n //remove problem from list of account's creations\n let accountReference = self.session.collection(\"accounts\").doc(accountID);\n batch.update(accountReference, {\n problems: self.admin.firestore.FieldValue.arrayRemove(correctLink)\n });\n\n //remove problem\n batch.delete(doc.ref);\n\n //commit all deletes/updates\n batch.commit()\n .then(result => {\n return server.respondWithData(response, 200, 'text/plain', problemID + \" deleted successfully\");\n })\n .catch(error => {\n console.error(\"============ Error =============\");\n console.error(\"Error with comitting batch delete in deleteProblem()\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n return server.respondWithError(response, 500, 'Error 500: Internal Server Error');\n });\n })\n\n .catch(error => {\n console.error(\"============ Error =============\");\n console.error(\"Error with getting problem in deleteProblem())\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n return server.respondWithError(response, 500, \"Error 500: Internal Server Error\");\n });\n }", "deleteElementMutation(params) {\n this.store.commit('deleteElementMutation', params)\n }", "async deleteBulk ({ request, response, auth }) {\n const result = await ArticleService.deleteBulk(request, auth);\n return response.status(result.status).send(result.data);\n }", "static squash(document, mutations) {\n var squashed = mutations.reduce((result, mutation) => result.concat(...mutation.mutations), []);\n return new Mutation({\n mutations: squashed\n });\n }", "static squash(document, mutations) {\n const squashed = mutations.reduce((result, mutation) => result.concat(...mutation.mutations), []);\n return new Mutation({\n mutations: squashed\n });\n }", "async destroyMany({ request, response }) {\n\t\tconst { ids } = request.params;\n\n\t\tconst result = await User.query()\n\t\t\t.whereIn('id', ids)\n\t\t\t.delete();\n\n\t\tif (!result) {\n\t\t\treturn response\n\t\t\t\t.status(400)\n\t\t\t\t.send(\n\t\t\t\t\terrorPayload(\n\t\t\t\t\t\terrors.RESOURCE_DELETED_ERROR,\n\t\t\t\t\t\trequest.antl('error.resource.resourceDeletedError'),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t}\n\t\treturn response.status(200).send({ success: true });\n\t}", "async deletePatient ({ commit }, id) {\n await PatientDataService.delete(id)\n .then(res => {\n console.log(res)\n console.log(res.data)\n commit('REMOVE_PATIENT', id)\n })\n .catch(err => {\n console.log('Network error when delete 1 patient')\n console.log(err)\n })\n }", "async DeleteBatch(req, res) {\n console.log(req.params.batchId);\n await Batch.findOne({ batchId: req.params.batchId }).then(batch => {\n // console.log(batch);\n if (batch.students.length > 0) {\n return res.status(Httpstatus.INTERNAL_SERVER_ERROR).json({ message: 'Please delete all the students of batch before deleting batch.' })\n }\n Batch.deleteOne({ batchId: batch.batchId }).then(result => {\n console.log(result);\n return res.status(Httpstatus.OK).json({ message: 'Batch Delete Successfully..' });\n }).catch(err => {\n return res.status(Httpstatus.INTERNAL_SERVER_ERROR).json({ message: err });\n });\n }).catch(err => {\n return res.status(Httpstatus.INTERNAL_SERVER_ERROR).json({ message: err });\n });\n }", "deleteContent(deletions) {\n return __awaiter(this, void 0, void 0, function* () {\n const schema = yield this.getResolvedSchema(deletions.schema);\n if (schema) {\n const resolvedSchemaLocation = this.resolveJSONSchemaToSection(schema.schema, deletions.path);\n if (typeof resolvedSchemaLocation === 'object') {\n delete resolvedSchemaLocation[deletions.key];\n }\n yield this.saveSchema(deletions.schema, schema.schema);\n }\n });\n }", "deleteLesson(server, response, accountID, lessonID) {\n let self = this;\n try {\n //is lesson deletable by user\n let unassembledLink = lessonID.split('/');\n let correctLink = unassembledLink.reduce((assembler, part) => assembler + \"\\\\\" + part);\n this.session.collection(\"lessons\").doc(correctLink).get()\n .then(doc => {\n if (!doc.exists) {\n return server.respondWithError(response, 404, \"Error 404: Problem not found\");\n }\n let lesson = doc.data()\n if (accountID !== lesson.creatorAccountID) {\n return server.respondWithError(response, 403, \"Error 403: User does not have permission to delete file\");\n }\n \n let splitArrays = self.splitCreationsIntoArrays(lesson.creations);\n if(splitArrays === null) {\n return server.respondWithError(response, 400, \"Error 400: Lesson creation data not formatted correctly\");\n } else {\n //make deletes atomic\n let batch = self.session.batch();\n \n //update ownerLessons for each lesson that it has\n splitArrays.lessons.forEach(databaseLink => {\n let problemReference = self.session.collection(\"lessons\").doc(databaseLink);\n return batch.update(problemReference, {\n ownerLessons: self.admin.firestore.FieldValue.arrayRemove(correctLink)\n });\n });\n \n //update ownerLessons for each problem that it has\n splitArrays.problems.forEach(databaseLink => {\n let problemReference = self.session.collection(\"problems\").doc(databaseLink);\n return batch.update(problemReference, {\n ownerLessons: self.admin.firestore.FieldValue.arrayRemove(correctLink)\n });\n });\n \n //remove lesson from lessons that it exists in\n lesson.ownerLessons.forEach(ownerLessonID => {\n let lessonReference = self.session.collection(\"lessons\").doc(ownerLessonID);\n batch.update(lessonReference, {\n creations: self.admin.firestore.FieldValue.arrayRemove(\"lessons/\" + correctLink)\n });\n });\n \n //remove lesson from list of account's creations\n let accountReference = self.session.collection(\"accounts\").doc(accountID);\n batch.update(accountReference, {\n lessons: self.admin.firestore.FieldValue.arrayRemove(correctLink)\n });\n \n //remove lesson\n batch.delete(doc.ref);\n \n //commit batched deletes/updates\n batch.commit()\n .then(result => {\n server.respondWithData(response, 200, 'text/plain', lessonID + \" deleted successfully\");\n })\n .catch(error => {\n console.error(\"============ Error =============\");\n console.error(\"Error in batch deleting lesson info\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n server.respondWithError(response, 500, 'Error 500: Internal Server Error');\n })\n\n }\n })\n .catch(error => {\n console.error(\"============ Error =============\");\n console.error(\"Error in batch deleting lesson info\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n server.respondWithError(response, 500, \"Error 500: Internal Server Error\");\n })\n } catch (error) {\n console.error(\"============ Error =============\");\n console.error(\"Error inside deleteLesson\");\n console.error(error);\n console.error(\"==========End of Error =========\");\n server.respondWithError(response, 400, 'text/plain', \"Error 400: Invalid Link\");\n }\n\n\n }", "function useDeleteCartMutation(_a) {\n var onError = _a.onError, onSuccess = _a.onSuccess;\n var client = react_query_1.useQueryClient();\n var mutate = react_query_1.useMutation(deleteCartMutation_1.deleteCartMutation, {\n onSuccess: function () {\n client.invalidateQueries(\"one-time-token\");\n client.invalidateQueries(\"all-cart-lists\");\n onSuccess();\n },\n onError: onError,\n retry: 0,\n }).mutate;\n return mutate;\n}", "async deleteMany(ctx) {\n const { model } = ctx.params;\n const contentManagerService = strapi.plugins['content-manager'].services.contentmanager;\n\n ctx.body = await contentManagerService.deleteMany({ model }, ctx.request.query);\n }", "delete() {\n const currentOp = buildCurrentOp(this.bulkOperation);\n return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 }));\n }", "bulkDelete() {\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traite toutes les collisions
function collisions() { collisonBords(ballon); equipes.forEach((eq) => { eq.joueurs.forEach((e) => { // Touche le cote droit collisonBords(e); }); }); let collision = false; // Pour toutes les equipes equipes.forEach((e) => { // Pour chaque joueur de chaque équipe e.joueurs.forEach((j) => { if (GestionnaireCollision.cercleCercle(j, ballon, j.rayon(), ballon.rayon())) { gererCollision(j, ballon); collision = true; } // Pour chaque équipe equipes.forEach((e2) => { // Chaque joueur de chaque équipe e2.joueurs.forEach((j2) => { if (j.x === j2.x && j.y === j2.y) { return; } if (GestionnaireCollision.cercleCercle(j, j2, j.rayon(), j2.rayon())) { collision = true; gererCollision(j, j2); } }); }); }); }); if (collision) { soundsManager.collisionJoueurs(); } if (GestionnaireCollision.pointDansRectangle(map.cageGauche, ballon.centre())) { score.DROITE += 1; reset(); soundsManager.but(); } else if (GestionnaireCollision.pointDansRectangle(map.cageDroite, ballon.centre())) { score.GAUCHE += 1; reset(); soundsManager.but(); } }
[ "resolveCollisions() {\r\n this.narrowPhaseCollision(this.broadPhaseCollision());\r\n }", "function collisionsCleaner(){\n rightcollision=false;\n leftcollision=false;\n bottomcollision=false;\n topcollision=false;\n }", "updateCollisions() {\n this.model.scene.forEach(\n /** @arg a {Celestial} */\n (a) =>\n this.model.scene.forEach(\n /** @arg b {Celestial} */\n (b) =>\n a !== b &&\n this.checkIntersection(a, b) &&\n a.collisions.push({\n time: +new Date(),\n who: b,\n })\n )\n );\n }", "collision(){ \n if (\n Rat_obj.x <= (Cheese_obj.x + 32)\n && Cheese_obj.x <= (Rat_obj.x + 32)\n && Rat_obj.y <= (Cheese_obj.y + 32)\n && Cheese_obj.y <= (Rat_obj.y + 32)\n ) {\n ++CheesesCaught;\n Cheese_obj.reset();\n Rat_obj.reset();\n }\n }", "function onCollision(entity, entity2) {}", "function collisionDetection() {\n bullets.forEach((bullet, b) => {\n if (b === 0) {\n nul = null;\n } else {\n cats.forEach((cat, c) => {\n if (c === 0) {\n nul = null;\n } else {\n const bulletX = bullet.getPosition().x;\n const bulletY = bullet.getPosition().y;\n const catX = cat.getPosition().x;\n const catY = cat.getPosition().y;\n if (bulletX < catX + 100 &&\n bulletX + 15 > catX &&\n bulletY < catY + 59 &&\n 30 + bulletY > catY) {\n bullet.removeBullet();\n bullets.splice(b, 1);\n cat.removeCat();\n cats.splice(c, 1);\n $('#scores').html($('#scores').html() - (-5));\n }\n }\n });\n }\n });\n }", "_collision() {\n\n // obstacles to player\n this._do_collision(\n this.obstacleModels.slice(0), // don't remove when collision\n this.optionalPlayerModel,\n ObstacleAndPlayerCollisionDetector.INSTANCE,\n this._sounds.get(SOUND_EXPLOSION_PLAYER)\n );\n\n // player shots to enemies\n this._do_collision(\n this.playerShotModels,\n this.enemyModels,\n ShotAndTargetCollisionDetector.INSTANCE,\n this._sounds.get(SOUND_EXPLOSION_ENEMY)\n );\n\n // enemy shots to player\n this._do_collision(\n this.enemyShotModels,\n this.optionalPlayerModel,\n ShotAndTargetCollisionDetector.INSTANCE,\n this._sounds.get(SOUND_EXPLOSION_PLAYER)\n );\n }", "function collision() {\n console.log(\"hit\");\n }", "handleCollision(climber) {\n\n // distance\n //\n // to calculate the distance between the avalanche and climber\n let d = dist(this.x, this.y, climber.x, climber.y);\n\n // dist()\n //\n // To keep track of the avalanche and the avatar are in contact\n if (d < this.width / 2 + climber.width / 2) {\n // this is to push the climber down\n climber.vy += 2;\n\n }\n }", "handleCollision() {\n\n for (let i = 0; i < this.balls.length; i++) {\n\n this.balls[i].collideWithTable(this.table); //looks if collided with border\n this.balls[i].handlePocketCollision();\n\n for (let j = i + 1; j < this.balls.length; j++) {\n\n const ball1 = this.balls[i];\n const ball2 = this.balls[j];\n\n ball1.collideWithBall(ball2);\n }\n }\n }", "checkCollisionBetweenObjects() {\n for (let i = 0; i < this.objects.length; i++) {\n const obj1 = this.objects[i];\n if (!(obj1 instanceof Collidable)) continue;\n\n for (let j = i + 1; j < this.objects.length; j++) {\n const obj2 = this.objects[j];\n if (!(obj2 instanceof Collidable)) continue;\n obj1.checkCollision(obj2);\n }\n }\n }", "detectCollision(){\n\t\tfor(var i = 1;i<=land1.platforms*2;i++){\n\t\t\tif(this.position[0]+50>=land1.terrainX[i] && this.position[0]+50 <= land1.terrainX[i+1] && abs(this.position[1]-50 -rocket1.height/2) >= land1.terrainY[i]){\n\n\t\t\t\t\tthis.landed = true;\n\t\t\t\t\ttranslate(this.position[0],-this.position[1]);\n\t\t\t\t\tif(abs(this.velocity[0])>.6 || abs(this.velocity[1])>.6){\n\t\t\t\t\t\tthis.crashed = true;\n\t\t\t\t\t}\n\n\t\t\t\t//print(abs(this.position[1])+ \" \" + land1.terrainY[i]);\n\t\t\t\t//print(this.position[0] + \" \" + land1.terrainX[i] + \" \" + land1.terrainX[i+1]);\n\t\t\t}\n\t\t\ti++ ;\n\t\t}\n\t}", "function collisonBords(e) {\n let collision = false;\n\n if (GestionnaireCollision.cercleDansCarre(e, map.cageDroite)) {\n if (e.x + e.width >= map.cageDroite.x + map.cageDroite.width) {\n e.x = (map.cageDroite.x + map.cageDroite.width) - e.width;\n e.inverserVx();\n\n collision = true;\n }\n if (e.y <= map.cageDroite.y) {\n e.y = map.cageDroite.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.cageDroite.y + map.cageDroite.height) {\n e.y = (map.cageDroite.y + map.cageDroite.height) - e.height;\n e.inverserVy();\n\n collision = true;\n }\n // S'il y a collision avec la cage gauche\n } else if (GestionnaireCollision.cercleDansCarre(e, map.cageGauche)) {\n if (e.x <= map.cageGauche.x) {\n e.x = map.cageGauche.x;\n e.inverserVx();\n\n collision = true;\n }\n if (e.y <= map.cageGauche.y) {\n e.y = map.cageGauche.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.cageGauche.y + map.cageGauche.height) {\n e.y = (map.cageGauche.y + map.cageGauche.height) - e.height;\n e.inverserVy();\n\n collision = true;\n }\n } else if (e.x <= map.x) {\n e.x = map.x;\n e.inverserVx();\n\n collision = true;\n } else if (e.x + e.width >= map.x + map.width) {\n e.x = (map.x + map.width) - e.width;\n e.inverserVx();\n\n collision = true;\n } else if (e.y <= map.y) {\n e.y = map.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.y + map.height) {\n e.y = (map.y + map.height) - e.height;\n e.inverserVy();\n collision = true;\n }\n\n if (collision) {\n soundsManager.collisionBords();\n }\n }", "onCollision(otherObjects) {}", "function collisionCheck(){\n\n}", "collide(obj){\n this.hitBoxes.forEach(hitBox =>{\n if (hitBox.shape === 'circle'){\n if (obj.shape === 'circle'){\n if (collideCircleCircle(hitBox.x + this.pos.x,hitBox.y + this.pos.y,hitBox.sizeX,hitBox.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n obj.collision();\n this.collision(obj)\n return true \n }\n }\n if (obj.shape === 'rect'){\n if (collideRectCircle(obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY,hitBox.x + this.pos.x,hitBox.y + this.pos.y,hitBox.sizeX,hitBox.sizeY)){\n obj.collision();\n this.collision(obj)\n return true \n }\n }\n }\n if (hitBox.shape === 'rect'){\n if (obj.shape === 'rect'){\n if (collideRectRect(hitBox.x + this.pos.x,hitBox.y + this.pos.y,hitBox.sizeX,hitBox.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n obj.collision();\n this.collision(obj)\n return true \n }\n }\n if (obj.shape === 'circle'){\n if (collideRectCircle(hitBox.x + this.pos.x,hitBox.y + this.pos.y,hitBox.sizeX,hitBox.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n obj.collision();\n this.collision(obj)\n return true \n }\n }\n }\n })\n\n // old collision code \n\n // if (this.shape === 'circle'){\n // // check if player bullet collided with this enemy \n // if (obj.shape === 'circle'){\n // if (collideCircleCircle(this.pos.x,this.pos.y,this.sizeX,this.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n // console.log('collided with horz enemy')\n // obj.collision();\n // this.collision(obj)\n // return true \n // }\n // }else if(obj.shape === 'rect'){\n // if (collideRectCircle(this.pos.x,this.pos.y,this.sizeX,this.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n // console.log('collided with horz enemy')\n // obj.collision();\n // this.collision(obj)\n // return true \n // }\n // }\n // }\n // if (this.shape === 'rect'){\n // // check if player bullet collided with this enemy \n // if (obj.shape === 'circle'){\n // if (collideRectCircle(this.pos.x,this.pos.y,this.sizeX,this.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n // console.log('collided with horz enemy')\n // obj.collision();\n // this.collision(obj)\n // return true \n // }\n // }else if(obj.shape === 'rect'){\n // if (collideRectRect(this.pos.x,this.pos.y,this.sizeX,this.sizeY,obj.pos.x,obj.pos.y,obj.sizeX,obj.sizeY)){\n // obj.collision();\n // this.collision(obj)\n // return true \n // }\n // }\n // }\n }", "function detectCollisions() {\n // alien ships with player and player lasers \n alienShipManager.ships.forEach(ship => {\n if(Collisions.detectCircleCollision(ship, spaceShip)) {\n playerHit();\n ship.crash();\n particleSystemManager.createUFOExplosion(ship.center.x, ship.center.y); \n }\n spaceShipLasers.lasers.forEach(laser => {\n if(!laser.isDead && Collisions.detectCircleCollision(ship, laser)) {\n ship.crash(); \n laser.isDead = true; \n particleSystemManager.createUFOExplosion(ship.center.x, ship.center.y); \n } \n })\n });\n\n // alien lasers with player ship\n alienLasers.lasers.forEach(laser => {\n if(Collisions.detectCirclePointCollision(spaceShip, laser)) {\n laser.isDead = true; \n playerHit(); \n }\n }); \n\n // asteroids with player ship and player lasers\n asteroidManager.asteroids.forEach(asteroid => {\n spaceShipLasers.lasers.forEach(laser =>{\n if(!laser.isDead && Collisions.detectCirclePointCollision(asteroid, laser)) {\n asteroidManager.explode(asteroid, particleSystemManager); \n laser.isDead = true; \n }\n })\n if(Collisions.detectCircleCollision(spaceShip, asteroid)) {\n playerHit(); \n }\n }); \n }", "collision(a) {\n if (a == this) {return;}\n // a is a moveable object or a player\n // top side\n if (a.pos.y + a.h > this.pos.y && a.pos.y + a.h < this.pos.y + 1 + a.vel.y && a.pos.x + a.w > this.pos.x && a.pos.x < this.pos.x + this.w) {\n a.grounded = true;\n a.friction = this.friction;\n a.vel.y = 0;\n a.pos.y = this.pos.y - a.h;\n }\n // bottom side\n if (a.pos.y < this.pos.y + this.h && a.pos.y > this.pos.y + this.h - 1 + a.vel.y && a.pos.x + a.w > this.pos.x && a.pos.x < this.pos.x + this.w) {\n a.vel.y = 1;\n a.pos.y = this.pos.y + this.h;\n }\n // right side\n if (a.pos.x < this.pos.x + this.w && a.pos.x > this.pos.x + this.w + a.vel.x - 10 && a.pos.y < this.pos.y + this.h && a.pos.y + a.h > this.pos.y) {\n this.vel.x = a.vel.x;\n a.pos.x = this.pos.x + this.w;\n a.animation = \"Pushing\";\n }\n // left side\n if (a.pos.x + a.w > this.pos.x && a.pos.x + a.w < this.pos.x + a.vel.x + 10 && a.pos.y < this.pos.y + this.h && a.pos.y + a.h > this.pos.y) {\n this.vel.x = a.vel.x;\n a.pos.x = this.pos.x - a.w;\n a.animation = \"Pushing\";\n }\n }", "function targetsCollision() {\n targets.forEach((t) => {\n if (((t.x + t.w) > w)) {\n t.vx = -t.vx;\n t.x = w - t.w;\n t.sprite = new Sprite(\"left\");\n t.extractSprites(assets.spriteSheetLeft);\n t.action = \"left\";\n }\n\n if (t.x < 0) {\n t.vx = -t.vx;\n t.x = 0\n t.sprite = new Sprite(\"right\");\n t.extractSprites(assets.spriteSheetRight);\n t.action = \"right\";\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the type specification from the directive meta. This type is inserted into .d.ts files to be consumed by upstream compilations.
function createDirectiveType(meta) { const typeParams = createDirectiveTypeParams(meta); return expressionType(importExpr(Identifiers$1.DirectiveDefWithMeta, typeParams)); }
[ "function createDirectiveType(meta) {\n const typeParams = createDirectiveTypeParams(meta);\n return expressionType(importExpr(Identifiers.DirectiveDeclaration, typeParams));\n}", "function createDirectiveType(meta) {\n var typeParams = createBaseDirectiveTypeParams(meta); // Directives have no NgContentSelectors slot, but instead express a `never` type\n // so that future fields align.\n\n typeParams.push(NONE_TYPE);\n typeParams.push(expressionType(literal(meta.isStandalone)));\n return expressionType(importExpr(Identifiers.DirectiveDeclaration, typeParams));\n} // Define and update any view queries", "function compileDeclareDirectiveFromMetadata(meta) {\n var definitionMap = createDirectiveDefinitionMap(meta);\n var expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);\n var type = createDirectiveType(meta);\n return {\n expression: expression,\n type: type,\n statements: []\n };\n}", "function compileDeclareDirectiveFromMetadata(meta) {\n const definitionMap = createDirectiveDefinitionMap(meta);\n const expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);\n const type = createDirectiveType(meta);\n return { expression, type, statements: [] };\n}", "function createDirectiveDefinitionMap(meta) {\n var definitionMap = new DefinitionMap();\n definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$5));\n definitionMap.set('version', literal('14.2.12')); // e.g. `type: MyDirective`\n\n definitionMap.set('type', meta.internalType);\n\n if (meta.isStandalone) {\n definitionMap.set('isStandalone', literal(meta.isStandalone));\n } // e.g. `selector: 'some-dir'`\n\n\n if (meta.selector !== null) {\n definitionMap.set('selector', literal(meta.selector));\n }\n\n definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));\n definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));\n definitionMap.set('host', compileHostMetadata(meta.host));\n definitionMap.set('providers', meta.providers);\n\n if (meta.queries.length > 0) {\n definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));\n }\n\n if (meta.viewQueries.length > 0) {\n definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));\n }\n\n if (meta.exportAs !== null) {\n definitionMap.set('exportAs', asLiteral(meta.exportAs));\n }\n\n if (meta.usesInheritance) {\n definitionMap.set('usesInheritance', literal(true));\n }\n\n if (meta.lifecycle.usesOnChanges) {\n definitionMap.set('usesOnChanges', literal(true));\n }\n\n definitionMap.set('ngImport', importExpr(Identifiers.core));\n return definitionMap;\n}", "function createDirectiveDefinitionMap(meta) {\n const definitionMap = new DefinitionMap();\n definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$1));\n definitionMap.set('version', literal('12.0.2'));\n // e.g. `type: MyDirective`\n definitionMap.set('type', meta.internalType);\n // e.g. `selector: 'some-dir'`\n if (meta.selector !== null) {\n definitionMap.set('selector', literal(meta.selector));\n }\n definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));\n definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));\n definitionMap.set('host', compileHostMetadata(meta.host));\n definitionMap.set('providers', meta.providers);\n if (meta.queries.length > 0) {\n definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));\n }\n if (meta.viewQueries.length > 0) {\n definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));\n }\n if (meta.exportAs !== null) {\n definitionMap.set('exportAs', asLiteral(meta.exportAs));\n }\n if (meta.usesInheritance) {\n definitionMap.set('usesInheritance', literal(true));\n }\n if (meta.lifecycle.usesOnChanges) {\n definitionMap.set('usesOnChanges', literal(true));\n }\n definitionMap.set('ngImport', importExpr(Identifiers.core));\n return definitionMap;\n}", "function createDirectiveDefinitionMap(meta) {\n const definitionMap = new DefinitionMap();\n definitionMap.set('version', literal('11.1.2'));\n // e.g. `type: MyDirective`\n definitionMap.set('type', meta.internalType);\n // e.g. `selector: 'some-dir'`\n if (meta.selector !== null) {\n definitionMap.set('selector', literal(meta.selector));\n }\n definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));\n definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));\n definitionMap.set('host', compileHostMetadata(meta.host));\n definitionMap.set('providers', meta.providers);\n if (meta.queries.length > 0) {\n definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));\n }\n if (meta.viewQueries.length > 0) {\n definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));\n }\n if (meta.exportAs !== null) {\n definitionMap.set('exportAs', asLiteral(meta.exportAs));\n }\n if (meta.usesInheritance) {\n definitionMap.set('usesInheritance', literal(true));\n }\n if (meta.lifecycle.usesOnChanges) {\n definitionMap.set('usesOnChanges', literal(true));\n }\n definitionMap.set('ngImport', importExpr(Identifiers$1.core));\n return definitionMap;\n}", "function createDirectiveDefinitionMap(meta) {\n const definitionMap = new DefinitionMap();\n definitionMap.set('version', literal('11.2.14'));\n // e.g. `type: MyDirective`\n definitionMap.set('type', meta.internalType);\n // e.g. `selector: 'some-dir'`\n if (meta.selector !== null) {\n definitionMap.set('selector', literal(meta.selector));\n }\n definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));\n definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));\n definitionMap.set('host', compileHostMetadata(meta.host));\n definitionMap.set('providers', meta.providers);\n if (meta.queries.length > 0) {\n definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));\n }\n if (meta.viewQueries.length > 0) {\n definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));\n }\n if (meta.exportAs !== null) {\n definitionMap.set('exportAs', asLiteral(meta.exportAs));\n }\n if (meta.usesInheritance) {\n definitionMap.set('usesInheritance', literal(true));\n }\n if (meta.lifecycle.usesOnChanges) {\n definitionMap.set('usesOnChanges', literal(true));\n }\n definitionMap.set('ngImport', importExpr(Identifiers$1.core));\n return definitionMap;\n}", "function toR3DirectiveMeta(metaObj, code, sourceUrl) {\n var typeExpr = metaObj.getValue('type');\n var typeName = typeExpr.getSymbolName();\n if (typeName === null) {\n throw new fatal_linker_error_1.FatalLinkerError(typeExpr.expression, 'Unsupported type, its name could not be determined');\n }\n return {\n typeSourceSpan: createSourceSpan(typeExpr.getRange(), code, sourceUrl),\n type: util_1.wrapReference(typeExpr.getOpaque()),\n typeArgumentCount: 0,\n internalType: metaObj.getOpaque('type'),\n deps: null,\n host: toHostMetadata(metaObj),\n inputs: metaObj.has('inputs') ? metaObj.getObject('inputs').toLiteral(toInputMapping) : {},\n outputs: metaObj.has('outputs') ?\n metaObj.getObject('outputs').toLiteral(function (value) { return value.getString(); }) :\n {},\n queries: metaObj.has('queries') ?\n metaObj.getArray('queries').map(function (entry) { return toQueryMetadata(entry.getObject()); }) :\n [],\n viewQueries: metaObj.has('viewQueries') ?\n metaObj.getArray('viewQueries').map(function (entry) { return toQueryMetadata(entry.getObject()); }) :\n [],\n providers: metaObj.has('providers') ? metaObj.getOpaque('providers') : null,\n fullInheritance: false,\n selector: metaObj.has('selector') ? metaObj.getString('selector') : null,\n exportAs: metaObj.has('exportAs') ?\n metaObj.getArray('exportAs').map(function (entry) { return entry.getString(); }) :\n null,\n lifecycle: {\n usesOnChanges: metaObj.has('usesOnChanges') ? metaObj.getBoolean('usesOnChanges') : false,\n },\n name: typeName,\n usesInheritance: metaObj.has('usesInheritance') ? metaObj.getBoolean('usesInheritance') : false,\n };\n }", "getDirectiveMetadata(ref) {\n const clazz = ref.node;\n const def = this.reflector.getMembersOfClass(clazz).find(field => field.isStatic && (field.name === 'ɵcmp' || field.name === 'ɵdir'));\n if (def === undefined) {\n // No definition could be found.\n return null;\n }\n else if (def.type === null || !ts.isTypeReferenceNode(def.type) ||\n def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {\n // The type metadata was the wrong shape.\n return null;\n }\n const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));\n const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));\n return Object.assign(Object.assign({ ref, name: clazz.name.text, isComponent: def.name === 'ɵcmp', selector: readStringType(def.type.typeArguments[1]), exportAs: readStringArrayType(def.type.typeArguments[2]), inputs,\n outputs, queries: readStringArrayType(def.type.typeArguments[5]) }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), { baseClass: readBaseClass(clazz, this.checker, this.reflector), isPoisoned: false });\n }", "function createComponentType(meta) {\n const typeParams = createDirectiveTypeParams(meta);\n typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));\n return expressionType(importExpr(Identifiers$1.ComponentDefWithMeta, typeParams));\n}", "getDirectiveMetadata(ref) {\n const clazz = ref.node;\n const def = this.reflector.getMembersOfClass(clazz).find(field => field.isStatic && (field.name === 'ɵcmp' || field.name === 'ɵdir'));\n if (def === undefined) {\n // No definition could be found.\n return null;\n }\n else if (def.type === null || !ts.isTypeReferenceNode(def.type) ||\n def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {\n // The type metadata was the wrong shape.\n return null;\n }\n const isComponent = def.name === 'ɵcmp';\n const ctorParams = this.reflector.getConstructorParameters(clazz);\n // A directive is considered to be structural if:\n // 1) it's a directive, not a component, and\n // 2) it injects `TemplateRef`\n const isStructural = !isComponent && ctorParams !== null && ctorParams.some(param => {\n return param.typeValueReference.kind === 1 /* IMPORTED */ &&\n param.typeValueReference.moduleName === '@angular/core' &&\n param.typeValueReference.importedName === 'TemplateRef';\n });\n const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));\n const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));\n return Object.assign(Object.assign({ type: MetaType.Directive, ref, name: clazz.name.text, isComponent, selector: readStringType(def.type.typeArguments[1]), exportAs: readStringArrayType(def.type.typeArguments[2]), inputs,\n outputs, queries: readStringArrayType(def.type.typeArguments[5]) }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), { baseClass: readBaseClass(clazz, this.checker, this.reflector), isPoisoned: false, isStructural });\n }", "function createComponentType(meta) {\n var typeParams = createBaseDirectiveTypeParams(meta);\n typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));\n typeParams.push(expressionType(literal(meta.isStandalone)));\n return expressionType(importExpr(Identifiers.ComponentDeclaration, typeParams));\n}", "function createComponentType(meta) {\n const typeParams = createDirectiveTypeParams(meta);\n typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));\n return expressionType(importExpr(Identifiers.ComponentDeclaration, typeParams));\n}", "function DirectiveType() {}", "function TypeDef() {\n}", "function DirectiveType(){}", "function DirectiveType() { }", "function compileDeclarePipeFromMetadata(meta) {\n var definitionMap = createPipeDefinitionMap(meta);\n var expression = importExpr(Identifiers.declarePipe).callFn([definitionMap.toLiteralMap()]);\n var type = createPipeType(meta);\n return {\n expression: expression,\n type: type,\n statements: []\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print all the cookies whose value contain one of the names in PI store. Only fields with tags "usernameXXX" and "emailXXX" are checked.
function print_cookies_with_values_containing_usernames(domain) { var cb_cookies = (function(domain, event_name) { return function(all_cookies) { var tot_hostonly = 0; var tot_httponly = 0; var tot_secure = 0; var tot_session = 0; var detected_usernames = {}; var pi_usernames = get_all_usernames(true); console.log("APPU DEBUG: Printing all cookies containing usernames for: " + domain); for (var i = 0; i < all_cookies.length; i++) { for (var j = 0; j < all_cookies.length; j++) { if (all_cookies[i].value.indexOf(pi_usernames[j]) != -1) { detected_usernames[pi_usernames[j]] = true; var cookie_str = ""; var cookie_name = all_cookies[i].name; var cookie_domain = all_cookies[i].domain; var cookie_path = all_cookies[i].path; var cookie_protocol = (all_cookies[i].secure) ? "https://" : "http://"; var cookie_key = cookie_protocol + cookie_domain + cookie_path + ":" + cookie_name; cookie_str += "Cookie Key: " + cookie_key; cookie_str += ", HostOnly: '" + all_cookies[i].hostOnly + "'"; cookie_str += ", Secure: '" + all_cookies[i].secure + "'"; cookie_str += ", HttpOnly: '" + all_cookies[i].httpOnly + "'"; cookie_str += ", Session: '" + all_cookies[i].session + "'"; cookie_str += ", Value: '" + all_cookies[i].value + "'"; cookie_str += ", Expiration: '" + all_cookies[i].expirationDate + "'"; if (all_cookies[i].hostOnly) { tot_hostonly += 1; } if (all_cookies[i].secure) { tot_secure += 1; } if (all_cookies[i].httpOnly) { tot_httponly += 1; } if (all_cookies[i].session) { tot_session += 1; } console.log("APPU DEBUG: " + cookie_str); break; } } } console.log("APPU DEBUG: Total HostOnly Cookies: " + tot_hostonly); console.log("APPU DEBUG: Total HTTPOnly Cookies: " + tot_httponly); console.log("APPU DEBUG: Total Secure Cookies: " + tot_secure); console.log("APPU DEBUG: Total Session Cookies: " + tot_session); console.log("APPU DEBUG: Total number of cookies: " + all_cookies.length); console.log("APPU DEBUG: Detected usernames: " + JSON.stringify(Object.keys(detected_usernames))); } })(domain); get_all_cookies(domain, cb_cookies); }
[ "function checkForOurCookiesValue() {\n var allTheCookies = document.cookie;\n\n console.log(allTheCookies);\n\n if(allTheCookies.includes(this_cookies_value)) {\n jQuery(\".exampleSection\").css(\"opacity\",1);\n } else {\n jQuery(\".exampleSection\").css(\"opacity\",0);\n };\n\n }", "function logCookies() {\n chrome.cookies.getAll(\n {},\n function(cookieList) {\n for (var i = 0; i < cookieList.length; i++) {\n var cookie = cookieList[i];\n console.log(cookie.name + \"::\" + cookie.value + \"::\" + cookie.domain);\n }\n }\n );\n}", "function traceCookies()\n{\n var cookies = AnyBalance.getCookies();\n var str = \"\";\n for (var i=0; i<cookies.length; i++)\n str += cookies[i].name + \"=\" + cookies[i].value + \"\\n\";\n AnyBalance.trace(str,\"Cookies\");\n}", "function eachFilteredCookies(host, fn) {\n if (db === null) initDB();\n \n var doc = db.getDocument(host);\n var props = doc.properties || {};\n \n Object.keys(props).forEach(function (name) {\n if (specials.indexOf(name) < 0) fn(props[name], name);\n });\n }", "function checkCookie(cookiename) {\n //reworked to turn document.cookie into object\n\n // get document.cookie and store in var\n var cookies = document.cookie;\n //convert into array\n var cookiearr = cookies.split('; ');\n //get length of array items\n var arrlen = cookiearr.length;\n\n //declare object to store cookie details in\n var cookieobj = {};\n //declare holding array for name and values\n var holdingarr = [];\n\n //loop through and split into JS object\n for (var i = 0; i < arrlen; i++) {\n //split array item into name and value and store in holding array at 0 for name and 1 for value\n holdingarr = cookiearr[i].split('=');\n //store in key value pair in object\n cookieobj[holdingarr[0]] = holdingarr[1];\n }\n\n //check if cookie name exists as key in object\n if (cookiename in cookieobj) {\n //if does exist return cookie value\n return cookieobj[cookiename];\n } else {\n return false;\n }\n}", "function getUserdata(){\n let cookieElements = splitCookies();\n for(let i =0; i<cookieElements.length; i++){\n if(cookieElements[i].includes(\"username\")){\n return cookieElements[i].substring(cookieElements[i].indexOf(\"=\") + 1).split(\",\");\n }\n }\n return [\"\", \"\", \"\"];\n}", "function getLoginCookies() {\n\n\n}", "function wptouchListCookies() {\n var theCookies = document.cookie.split(';');\n var aString = '';\n for (var i = 1 ; i <= theCookies.length; i++) {\n aString += i + ' ' + theCookies[i-1] + \"\\n\";\n }\n return aString;\n}", "function getAllCookies() {\r\n\t\tvar cookies = { };\r\n\t\tif (document.cookie && document.cookie != '') {\r\n\t\t\tvar split = document.cookie.split(';');\r\n\t\t\tfor (var i = 0; i < split.length; i++) {\r\n\t\t\t\tvar name_value = split[i].split(\"=\");\r\n\t\t\t\tname_value[0] = name_value[0].replace(/^ /, '');\r\n\t\t\t\tif(decodeURIComponent(name_value[0]).match(\"^\"+cookieName)){\r\n\t\t\t\t\tcookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn cookies;\r\n\t}", "function checkCookies() {\n username = decrypt(getCookie(\"username\"));\n password = decrypt(getCookie(\"password\"));\n}", "function logCookies(cookies) \n\t\t{\n\t\t\tif (cookies === undefined || cookies.length == 0) {\n\t\t\t\tconsole.log(\"No cookies found!\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvar j = 1;\n\t\t\t\tfor (let cookie of cookies) \n\t\t\t\t{\n\t\t\t\t//console.log(cookie);\n\t\t\t\tconsole.log(\"#\" + j);\n\t\t\t\t\tconsole.log(cookie);\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function getCookies() {\n var cookie = document.cookie;\n console.log(cookie);\n checkUserStatus(cookie);\n}", "function get_selective_account_cookies(current_url, cookie_names) {\n var domain = get_domain(current_url.split(\"/\")[2]);\n var cs = pii_vault.aggregate_data.session_cookie_store[domain];\n var account_cookies = {};\n\n for (var i = 0; i < cookie_names.length; i++) {\n\tfor (c in cs.cookies) {\n\t if (cs.cookies[c].cookie_class == 'during' &&\n\t\tc.split(\":\")[2] == cookie_names[i]) {\n\t\taccount_cookies[c] = {};\n\t\taccount_cookies[c].hashed_value = cs.cookies[c].hashed_cookie_val; \n\t\tbreak;\n\t }\n\t}\n }\n \n return account_cookies;\n}", "function print_expand_state_cookies(domain, only_present) {\n var cs = pii_vault.aggregate_data.session_cookie_store[domain];\n var account_cookies = [];\n\n only_present = (only_present == undefined) ? true : only_present;\n\n for (c in cs.cookies) {\n\tif (cs.cookies[c].cookie_class == 'during') {\n\t continue;\n\t}\n\tif (cs.cookies[c].is_part_of_account_cookieset == true) {\n\t if (only_present && cs.cookies[c].current_state == \"absent\") {\n\t\tcontinue;\n\t }\n\t account_cookies.push(c);\n\t}\n }\n print_cookie_values(domain, account_cookies);\n}", "function getCookies(tab) {\n\n var url = new URL(tab.url)\n console.log(\"Getting cookies for: \" + url.hostname);\n\n var cookie_url = url.protocol + url.hostname;\n\n var cookies = [\n {\n url: cookie_url,\n name: \"FedAuth\"\n },\n {\n url: cookie_url,\n name: \"rtFa\"\n },\n ];\n\n var promises = [];\n\n for (var i = 0; i < cookies.length; ++i) {\n promises.push(browser.cookies.get(cookies[i]));\n }\n\n Promise.all(promises).then(function(cookies){\n\n var str = construct_davfsconf_str(cookies);\n\n console.log(\"Cookie line: \" + str);\n\n send_to_content(tab, str);\n });\n}", "_isPageInCookie(pageDevName){const cookieValue=this._getCookie(FLEXIPAGE_SAVE_COOKIE);if(cookieValue!=null){const values=cookieValue.split(\",\");const index=values.indexOf(pageDevName);if(index>-1){return true;}else{return false;}}return false;}", "function checkCookies() {\n apiPort.postMessage({topic: 'social.cookies-get'});\n}", "get cookies() {\n let cookies = [];\n let enumerator = Services.cookies.enumerator;\n while (enumerator.hasMoreElements()) {\n let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);\n if (cookie.host.hasRootDomain(\n AboutPermissions.domainFromHost(this.host))) {\n cookies.push(cookie);\n }\n }\n return cookies;\n }", "ListenToLoginCookie() {\n chrome.cookies.onChanged.addListener(info => {\n if (!this.excludeCookies.contains(info.cookie.name)) {\n console.log(info);\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
utility to convert the indexed member of args to a Boolean. alters args and returns it too. defaults to changing the last member in args.
function jum_arg_to_boolean(args, ind) { if (typeof ind == 'undefined' || ind == null) ind = args.length - 1; args[ind] = eval(args[ind]) ? true : false; return args; }
[ "_parseBooleanArg(value) {\n return Array.isArray(value) ? value.pop() : value;\n }", "function getBooleanValues(args, config) {\n function getBooleanValues(argsAndLastOption, arg) {\n var _a = getParamConfig(arg, config), argOptions = _a.argOptions, argName = _a.argName, argValue = _a.argValue;\n if (isBoolean(argOptions) && argValue != null && argName != null) {\n argsAndLastOption.partial[argName] = convertType(argValue, argOptions);\n }\n else if (argsAndLastOption.lastName != null &&\n isBoolean(argsAndLastOption.lastOption) &&\n booleanValue.some(function (boolValue) { return boolValue === arg; })) {\n argsAndLastOption.partial[argsAndLastOption.lastName] = convertType(arg, argsAndLastOption.lastOption);\n }\n return { partial: argsAndLastOption.partial, lastName: argName, lastOption: argOptions };\n }\n return args.reduce(getBooleanValues, { partial: {} }).partial;\n}", "function getBooleanArgument(node) {\n return node.arguments.length >= 2 &&\n [node.arguments[0], node.arguments[1]]\n .find(arg => arg.type === \"Literal\" && (arg.value === true || arg.value === false));\n }", "function removeBooleanValues(args, config) {\n function removeBooleanArgs(argsAndLastValue, arg) {\n var _a = getParamConfig(arg, config), argOptions = _a.argOptions, argValue = _a.argValue;\n if (isBoolean(argsAndLastValue.lastOption) && booleanValue.some(function (boolValue) { return boolValue === arg; })) {\n var args_1 = argsAndLastValue.args.concat();\n args_1.pop();\n return { args: args_1 };\n }\n else if (isBoolean(argOptions) && argValue != null) {\n return { args: argsAndLastValue.args };\n }\n else {\n return { args: __spreadArrays(argsAndLastValue.args, [arg]), lastOption: argOptions };\n }\n }\n return args.reduce(removeBooleanArgs, { args: [] }).args;\n}", "_bool(val) {\n if (arguments.length === 1) {\n this._boolFlag = val;\n return this;\n }\n const ret = this._boolFlag;\n this._boolFlag = 'and';\n return ret;\n }", "function ToBoolean(argument) { // eslint-disable-line no-unused-vars\n\t\treturn Boolean(argument);\n\t}", "function ToBoolean(argument) { // eslint-disable-line no-unused-vars\n\treturn Boolean(argument);\n}", "function preCheck (args) {\n return args !== null && args.length !== 0 && isFlag(args[0]) === true\n}", "function ToBoolean(argument) { // eslint-disable-line no-unused-vars\n return Boolean(argument);\n }", "function boolSetOp (e, pushIfLess, pushIfGtr, pushIfEq) {\n var e1 = e[1];\n var e2 = e[2];\n var args1 = e1.slice(1);\n var args2 = e2.slice(1);\n var i = 0;\n var j = 0;\n var c;\n var result = [];\n while (i < args1.length && j < args2.length) {\n\tc = compare(args1[i], args2[j]);\n\tif (c < 0) {\n\t if (pushIfLess) {\n\t\tresult.push(args1[i]);\n\t }\n\t i++;\n\t}\n\telse if (c > 0) {\n\t if (pushIfGtr) {\n\t\tresult.push(args2[j]);\n\t }\n\t j++;\n\t}\n\telse { // they're equal\n\t if (pushIfEq) {\n\t\tresult.push(args1[i]);\n\t }\n\t i++;\n\t j++;\n\t}\n }\n // at most one of these two loops does something.\n if (pushIfLess) {\n\twhile (i < args1.length) {\n\t result.push(args1[i++]);\n\t}\n }\n if (pushIfGtr) {\n\twhile (j < args2.length) {\n\t result.push(args2[j++]);\n\t}\n }\n result.unshift(\"Set\");\n return result;\n}", "asBoolean() {\n this.validate();\n const val = this._captured[this.idx];\n if ((0, type_1.getType)(val) === 'boolean') {\n return val;\n }\n this.reportIncorrectType('boolean');\n }", "function __evaluateBoolConditions(method, object, args)\n{\n\tfor (var idx = 0; idx < method.whereas_precompiled.length; idx ++) {\n\t\tvar miniFunc = method.whereas_precompiled[idx];\n\n\t\ttry {\n\t\t\tif (!miniFunc.apply(object, args)) {\n\t\t\t\tif (traceEvals && (miniFunc.toSource != undefined)) console.log(\"Failed bool\", miniFunc.toSource());\n\t\t\t\tif (traceEvals && (miniFunc.toSource == undefined)) console.log(\"Failed bool\", miniFunc);\t\t\t\t\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\t\n\t\t} catch(e) {\n\t\t\tconsole.log(\"ERROR: \", e);\n\t\t\t\n\t\t\tif (miniFunc.toSource != undefined)\n\t\t\t\tconsole.log(\"Evaluation failed:\", miniFunc.toSource());\n\t\t\telse\n\t\t\t\tconsole.log(\"Evaluation failed:\", console.log(miniFunc));\n\t\t\t\t\n\t\t\tconsole.log(\"Of Method:\", method);\n\t\t\tconsole.log(\"On object: \", object);\n\t\t\tconsole.log(\"Called with:\", args);\n\t\t\tconsole.trace();\n\t\t\t\n\t\t\treturn -1;\n\t\t}\n\n\t}\n\n\treturn method.whereas_precompiled.length;\n}", "function isBoolean(arg) {\n\treturn typeof(arg) == typeof(true);\n}", "function set ()\n{\n var result = {};\n\n for (var i = 0; i < arguments.length; i++)\n result[arguments[i]] = true;\n\n return result;\n}", "function FALSE(arg) {\n return !arg ? null : _Message(\"Equivalent to\", false, arg);\n}", "function GetFlagValue(oArgs, flag, default_val)\n{\n for(var arg_i = 0; arg_i < oArgs.length; arg_i++) {\n if (oArgs.item(arg_i) == flag) {\n return true;\n }\n }\n return default_val;\n}", "function argsEmptyOrSetTo(name) {\n if (typeof argv.task === 'undefined') {\n return true;\n }\n else if (typeof argv.task === 'string') {\n return argv.task == name;\n }\n else if (argv.task instanceof Array) {\n return argv.task.indexOf(name) >= 0;\n }\n else {\n return true;\n }\n}", "function isBoolean(arg) {\n return (typeof arg === \"boolean\");\n}", "function isBoolean(arg) {\n return typeof arg === \"boolean\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fill the filtered books depending on categories
function filterByCat( categ ){ filteredBooks = []; for (let i = 0; i < allBooks.length; i++) { if (allBooks[i].categories == categ ) { filteredBooks.push(allBooks[i]); } } }
[ "filterBooks(category) {\n this.currentCategory = category;\n if (this.currentCategory == \"Todos\") {\n this.currentBooks = this.books;\n } else {\n this.currentBooks = this.books.filter(this.applyFilter);\n }\n }", "filterBooksByRating(rating) {\r\n let category, objCategory, searchResult, prop, objBook;\r\n for(category in this.categories){\r\n \r\n // store current category in a variable\r\n objCategory = this.categories[category];\r\n searchResult= [];\r\n\r\n // loop through books and find the search input\r\n for(prop in objCategory.books){\r\n objBook = objCategory.books[prop];\r\n if(objBook.Rating > rating ){\r\n // if the search input exists, push to results array\r\n searchResult.push(objBook);\r\n }\r\n }\r\n // if there are results\r\n if(searchResult.length > 0) {\r\n objCategory.books = [];\r\n objCategory.books = searchResult;\r\n // add category to filtered data\r\n this.filteredData.push(objCategory);\r\n }\r\n } \r\n }", "async getBooksByCategory() {\r\n let objBook;\r\n try {\r\n // read data from cache\r\n var cacheCategories = lscache.get(global.constants.cacheKey_categoriesData);\r\n\r\n // if cache is empty, go to database\r\n if( cacheCategories === undefined || cacheCategories === null){\r\n\r\n // getting categories from database\r\n await this.getCategories(); \r\n } else { \r\n //getting categories from cache\r\n this.categories = cacheCategories;\r\n }\r\n\r\n // read books data from cache\r\n let cacheBooks = lscache.get(global.constants.cacheKey_booksData); \r\n // if cache is empty, go to database \r\n if( cacheBooks === undefined || cacheBooks === \"undefined\" || cacheBooks === null){\r\n // getting books from database\r\n await this.getBooks();\r\n } else { \r\n //getting books from cache \r\n this.books = cacheBooks;\r\n }\r\n\r\n //Iterate through each category and get books for it\r\n for(let category in this.categories){ \r\n let objCategory = this.categories[category];\r\n \r\n let bookListForCategory = [];\r\n for(let prop in this.books){\r\n // set local variable for books\r\n objBook = this.books[prop];\r\n\r\n // check if book has the category\r\n if(objBook['Category'].indexOf(objCategory.Name) > -1){\r\n\r\n // if book has the category, add book to the category arrary\r\n bookListForCategory.push(objBook);\r\n }\r\n }\r\n \r\n // if category has books, add to it\r\n if(bookListForCategory.length > 0){\r\n this.categories[category].books = bookListForCategory;\r\n }\r\n } \r\n\r\n // get data to get displayed for filter functionality\r\n this.filterData.initializeFilter(this.categories);\r\n } catch (error) {\r\n alert(error);\r\n }\r\n }", "async getBooksBySearchKey(key) { \r\n // initialize variables\r\n let objBook, searchResult;\r\n this.filteredData = [];\r\n\r\n try {\r\n // get categories data\r\n await this.getBooksByCategory();\r\n \r\n // loop through categories data\r\n for(let category in this.categories){\r\n // store current category in a variable\r\n let objCategory = this.categories[category];\r\n searchResult= [];\r\n\r\n // loop through books and find the search input\r\n for(let prop in objCategory.books){\r\n objBook = objCategory.books[prop];\r\n if(objBook[global.constants.searchKey_Title].toLowerCase().indexOf(key) > -1 ||\r\n objBook[global.constants.searchKey_Author].toLowerCase().indexOf(key) > -1){\r\n // if the search input exists, push to results array\r\n searchResult.push(objBook);\r\n }\r\n }\r\n // if there are results\r\n if(searchResult.length > 0) {\r\n objCategory.books = [];\r\n objCategory.books = searchResult;\r\n // add category to filtered data\r\n this.filteredData.push(objCategory);\r\n }\r\n } \r\n } \r\n catch (error) {\r\n alert(error);\r\n }\r\n }", "function filterSearch(text, category){\n for (index in bookDOM){\n switch (category){\n case \"title\":\n if (booklist[index].Title.toUpperCase().includes(text.toUpperCase())){\n $(\"#results-table\").append(bookDOM[index]);\n\n }\n break;\n case \"author\":\n if (booklist[index].Author.toUpperCase().includes(text.toUpperCase())){\n $(\"#results-table\").append(bookDOM[index]);\n }\n break;\n case \"ISBN\":\n if (booklist[index].ISBN.includes(text)){\n $(\"#results-table\").append(bookDOM[index]);\n }\n break;\n case \"professor\":\n if (booklist[index].Professor.toUpperCase().includes(text.toUpperCase())){\n $(\"#results-table\").append(bookDOM[index]);\n }\n break;\n case \"class\":\n if (booklist[index].Class.toUpperCase().includes(text.toUpperCase())){\n $(\"#results-table\").append(bookDOM[index]);\n }\n break;\n case \"CRN\":\n if (String(booklist[index].CRN).includes(text)){\n $(\"#results-table\").append(bookDOM[index]);\n }\n break;\n }\n }\n}", "static getBooksByAuthor(author, category) {\n let tempArray = []\n\n for (let i = 0; i < books.length; i++) {\n if (books[i].bookAuthors.includes(author) && books[i].bookCategory == category) {\n tempArray.push(books[i])\n }\n }\n return tempArray\n }", "static getBooksByTag(tag, category) {\n let tempArray = []\n\n for (let i = 0; i < books.length; i++) {\n if (books[i].bookTags.includes(parseInt(tag)) && books[i].bookCategory == category) {\n tempArray.push(books[i])\n }\n }\n return tempArray\n }", "function getBooksInCategory(category) {\n// var db = ScriptDb.getMyDb();\n// var db_categories = ParseDb.getMyDb(applicationId, restApiKey, \"list_categories\");\n var db_gen = ParseDb.getMyDb(applicationId, restApiKey, \"book_generic\");\n \n var books = [];\n \n var query = db_gen.query({});\n while (query.hasNext()) {\n var book = query.next();\n if (category == \"\" || category == null || book.category == category) {\n books.push(book); \n }\n }\n \n return books;\n}", "function filterByCategory() {\n let category = $scope.currentCategory ? $scope.currentCategory.name : \"\";\n dataService.getRecipesByCategory(category, function (res) {\n $scope.recipes = res.data;\n });\n }", "function addCategoryBooks(category, index){\n createCategory(category)\n fetch(`https://www.googleapis.com/books/v1/volumes?q=subject:${category}`)\n .then(response => {return response.json()})\n .then(data => {\n data.items.forEach(element => { \n if (element.volumeInfo.hasOwnProperty('imageLinks') \n && element.volumeInfo.hasOwnProperty('authors')\n && element.volumeInfo.hasOwnProperty('description')){\n let cover = element.volumeInfo.imageLinks.thumbnail\n let name = element.volumeInfo.title\n let author = element.volumeInfo.authors[0]\n let bookId = element.id\n if(name.length > 35){\n name = name.slice(0, 35) + \"...\" \n }\n if(author.length > 25){\n author = author.slice(0, 25) + \"...\"\n }\n createBookContainer1(cover,name,author,index,bookId)\n } \n })\n })\n}", "filterBooks() {\r\n let currentlyReading = this.state.allBooks.filter(book => book.shelf === \"currentlyReading\");\r\n let wantToRead = this.state.allBooks.filter(book => book.shelf === \"wantToRead\");\r\n let read = this.state.allBooks.filter(book => book.shelf === \"read\");\r\n\r\n this.bookShelves[0].bookCollection = currentlyReading\r\n this.bookShelves[1].bookCollection = wantToRead\r\n this.bookShelves[2].bookCollection = read\r\n\r\n }", "function handleFilterBooks(genre){\n const filteredBooks = fullBookList.filter(book => book.genre.toLowerCase() === genre.toLowerCase() )\n setBookList(filteredBooks)\n }", "function initializeCategoryFilter() {\n var $filterCategoryItems = $(checkBox).click(function(){\n $('.categories').hide();\n var $selected = $(checked).map(function (index, element) {\n return '.' + $(element).val()\n });\n var categories = $.makeArray($selected).join(',');\n categories ? $(categories).show() : $('.categories').show();\n });\n}", "filterBooks(res) {\n //a new array with the filtered search result that maintain the status\n const filteredResult =\n !res.error &&\n res.map(\n (resBook) =>\n //if the a book in the search matches a book in the library, return it, if not, keep search item\n this.state.books.find((book) => book.id === resBook.id) || resBook\n );\n return filteredResult;\n }", "function getBookCategories() {\n\t\t\tbookCategoryService.getBookCategories().then(function(categories) {\n\t\t\t\t$scope.categories = categories\n\t\t\t\t\n\t\t\t\t$scope.selectedCategory = $scope.categories[0];\n\t\t\t});\n\t\t}", "function renderBooks(data) {\n // Capture book categories\n let categories = [];\n data.forEach(book => {\n if(!categories.includes(book.status))\n categories.push(book.status);\n })\n\n let shelves = categories.map(cat => {\n // return books whose category match current category\n let books = data.filter(book => book.status === cat);\n return <Shelf title={cat} books={books} />\n })\n\n return shelves;\n}", "handleFilter() {\n const bookAttr = ['bookId', 'bookName', 'author', 'isbn', 'storage', 'price']\n const filteredBooks = filter(this.state.sortedBooks, [bookAttr[this.state.filterBy]], [this.state.filterKey])\n this.setState({\n filteredBooks\n })\n }", "function initCategoryFilter() {\n _.each(vm.categoriesForFilter, function(value, key) {\n vm.categoriesForFilter[key].categorySelected = false;\n });\n }", "function prepareCategories() {\n var categories = {},\n page,\n pagesData;\n\n // iterator to build categories\n for (page in pages) {\n pagesData = pages[page].data;\n\n if (pages.hasOwnProperty(page) && pagesData.title !== undefined) {\n // check if already defined with category or not\n if(categories[pagesData.category] === undefined){\n categories[pagesData.category] = { list: [] };\n }\n\n // build pages list for each category\n listItemsforCategory(categories[pagesData.category], pagesData);\n }\n }\n\n // return the categories\n return categories;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buildCompactText Compact box with labelicon to the left
function buildCompactText( options ){ var $result = $(); options.title = options.title || (options.label ? options.label.text : null); $result = $result.add( $._bsCreateIcon( {icon: options.label ? options.label.icon : 'fas fa_'}, null, options.title, 'part-of-compact-text fa-fw text-center flex-grow-0 align-self-center' ) ); var $content = $('<div/>') ._bsAddHtml( options ) .addClass('flex-grow-1'); if (options.title) $content.i18n(options.title, 'title'); return $result.add( $content ); }
[ "get short_text () {\n return new IconData(0xe261, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "get label_outline () {\n return new IconData(0xe893, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "get wrap_text () {\n return new IconData(0xe25b, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "function createCompactNodeLabel(node) {\n if (node.name.length) { // only display a label for named nodes\n var labelText = new PointText(new Point(node.bounds.x + node.bounds.width/2,\n node.bounds.bottom+viewProperties.lineHeight));\n labelText.content = node.name || '';\n labelText.characterStyle = {\n fontSize: viewProperties.fontSize,\n fillColor: viewProperties.nodeForegroundColor\n };\n labelText.paragraphStyle.justification = 'center';\n labelText.name = \"labelText\";\n return labelText;\n }\n return null;\n}", "renderLabeledBox(text, content, options) {\n let label = this.container.text(0, 0, lodash__WEBPACK_IMPORTED_MODULE_1___default().flatten([text])).addClass(`${this.type}-label`),\n box = this.container.rect().addClass(`${this.type}-box`).attr({\n rx: 3,\n ry: 3\n });\n options = lodash__WEBPACK_IMPORTED_MODULE_1___default().defaults(options || {}, {\n padding: 0\n });\n this.container.prepend(label);\n this.container.prepend(box);\n return this.deferredStep().then(() => {\n let labelBox = label.getBBox(),\n contentBox = content.getBBox(),\n boxWidth = Math.max(contentBox.width + options.padding * 2, labelBox.width),\n boxHeight = contentBox.height + options.padding * 2;\n label.transform(Snap.matrix().translate(0, labelBox.height));\n box.transform(Snap.matrix().translate(0, labelBox.height)).attr({\n width: boxWidth,\n height: boxHeight\n });\n content.transform(Snap.matrix().translate(boxWidth / 2 - contentBox.cx, labelBox.height + options.padding));\n });\n }", "function createCompactNodeBodyLabel(node) {\n var bounds = node.bounds;\n var pos = new Point(bounds.x+bounds.width/2,\n bounds.y+bounds.height/2+viewProperties.symbolSize/2*viewProperties.zoomFactor);\n var symbolText = new PointText(pos);\n symbolText.fillColor = viewProperties.nodeForegroundColor;\n symbolText.content = node.symbol;\n symbolText.fontSize = viewProperties.symbolSize*viewProperties.zoomFactor;\n symbolText.paragraphStyle.justification = 'center';\n pos.x += 1 * viewProperties.zoomFactor;\n pos.y -= 5 * viewProperties.zoomFactor;\n gatefuncHint = new PointText(pos);\n gatefuncHint.content = '';\n gatefuncHint.fillColor = viewProperties.nodeForegroundColor;\n gatefuncHint.fontSize = viewProperties.fontSize*viewProperties.zoomFactor;\n var non_standard_gatefunc = [];\n for (var g in node.gates){\n if(node.gates[g].gatefunction && node.gates[g].gatefunction != 'identity'){\n if(non_standard_gatefunc.indexOf(node.gates[g].gatefunction) < 0){\n non_standard_gatefunc.push(node.gates[g].gatefunction);\n }\n }\n }\n if(non_standard_gatefunc.length > 0){\n if(non_standard_gatefunc.length == 1){\n gatefuncHint.content = gatefunction_icons[non_standard_gatefunc[0]];\n } else {\n gatefuncHint.content = '*';\n }\n }\n if(gatefuncHint.content){\n symbolText.point.x -= 3 * viewProperties.zoomFactor;\n symbolText.fontSize = viewProperties.fontSize*viewProperties.zoomFactor;\n }\n var g = new Group([symbolText, gatefuncHint]);\n return g;\n}", "get add_box () {\n return new IconData(0xe146,{fontFamily:'MaterialIcons'})\n }", "function displayTextAlignIcon() {\n if (textAlign === \"center\") {\n return (\n <FiAlignCenter />\n )\n } else if (textAlign === \"left\") {\n return (\n <FiAlignLeft />\n )\n } else {\n return (\n <FiAlignRight />\n )\n }\n }", "renderLabeledBox(text, content, options) {\n let label = this.container.text(0, 0, _.flatten([text]))\n .addClass(`${this.type}-label`),\n box = this.container.rect()\n .addClass(`${this.type}-box`)\n .attr({\n rx: 3,\n ry: 3\n });\n\n options = _.defaults(options || {}, {\n padding: 0\n });\n\n this.container.prepend(label);\n this.container.prepend(box);\n\n return this.deferredStep()\n .then(() => {\n let labelBox = label.getBBox(),\n contentBox = content.getBBox(),\n boxWidth = Math.max(contentBox.width + options.padding * 2, labelBox.width),\n boxHeight = contentBox.height + options.padding * 2;\n\n label.transform(Snap.matrix()\n .translate(0, labelBox.height));\n\n box\n .transform(Snap.matrix()\n .translate(0, labelBox.height))\n .attr({\n width: boxWidth,\n height: boxHeight\n });\n\n content.transform(Snap.matrix()\n .translate(boxWidth / 2 - contentBox.cx, labelBox.height + options.padding));\n });\n }", "function atomLabel(ctx,A,i,ax,ay) {\n var label = element(A,\"symbol\");\n var fontsize = 14;\n var x = parseFloat(ax);\n var y = parseFloat(ay) + fontsize/2;\n var molecule = Mol();\n var show = showstyle();\n var color = element(A,\"label\")\n if(show.type==\"line\"){\n color = \"rgb(255,255,255)\";\n }\n ctx.lineWidth = 1.0;\n ctx.textAlign = \"center\";\n ctx.font = \"normal \" + fontsize + \"px sans-serif\";\n ctx.fillStyle = color;\n ctx.beginPath();\n ctx.fillText(label,x,y);\n\n var w = 10.0 / molecule[0].AtomScale;\n ctx.fillRect(x,y,w*1.5,w);\n ctx.closePath();\n}", "get label () {\n return new IconData(0xe892, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }", "function ELEMENT_TEXT$static_(){IconWithTextBEMEntities.ELEMENT_TEXT=( IconWithTextBEMEntities.BLOCK.createElement(\"text\"));}", "label() {\n if(this.props.columnType === Constants.getIn(['columnTypes', 'SIDEBAR'])) {\n return null\n }\n\n let labelLines = this.labelLines()\n\n // Clip long names, and append an ellipsis\n if (labelLines.length > 3) {\n labelLines = [labelLines[0], labelLines[1], labelLines[2]]\n labelLines[2] += '…'\n }\n\n const labelLengthExceed = labelLines.length * Constants.get('singleLineCategoryLabelHeight') > this.props.height\n\n let labelClassName = 'inactiveCategoryLabels'\n\n if(labelLengthExceed === true && this.checkHoverState() === false && this.filterboxActive() === false) {\n return null\n }\n\n if(this.checkHoverState() === true) {\n labelClassName = 'activeCategoryLabels'\n }\n\n let currentY = (this.props.height/2)\n let lineCount = 0\n currentY += (1 - (labelLines.length/2)) * \n Constants.get('singleLineCategoryLabelHeight')\n\n // Decrement just before it's increcemented inside the map.\n currentY -= Constants.get('singleLineCategoryLabelHeight')\n\n return <g>\n <text\n >\n {labelLines.map((line) => {\n currentY += Constants.get('singleLineCategoryLabelHeight')\n lineCount += 1\n return <tspan fill={this.fill} className={labelClassName} \n key={this.props.categoryName + 'CategoryLabelLine' + lineCount}\n y={currentY}\n x={this.props.width + Constants.get('categoryLabelOffset')}>\n {line}\n </tspan>\n })}\n </text>\n { this.filterbox(currentY) }\n </g>\n }", "function setLabelPos() {\r\n $(\".codeLabel\").css(\"left\", $(\".codeContainer\").width()/2);\r\n}", "get format_align_left () {\n return new IconData(0xe236,{fontFamily:'MaterialIcons'})\n }", "function build_label(ct) {\n // Note: we must add the label div to the document (along with text content and max-width\n // setting) _before_ the clipping is applied. Otherwise the clipping can't be calculated\n // because the size of the label div is unknown.\n ct.label_div = $(\"<div>\").addClass(\"canvas-topic-label\").text(ct.label)\n ct.label_div.css({\"max-width\": LABEL_MAX_WIDTH})\n ct.label_div.mouseup(mouseup) // to not block mouse gestures when mouse-up over the label div\n $(\"#canvas-panel\").append(ct.label_div)\n ct.label_div.css(label_position_css(ct))\n // Note: we must add the label div as a canvas sibling. As a canvas child element it doesn't appear.\n }", "function circle_add_label(l){\n circle.html('')\n circle.css({ width: \"80px\", height: \"80px\"})\n circle.html(\"<small class='text-white'>\" + l + \"</small>\")\n \n }", "function createLabelFlags()\n{\n\tlet digits = amountUserFlags.toString().length + amountFlags.toString().length\n\n\tlet padding = 20 + digits * 10 \n\n\t$flagIcon.removeClass('fa fa-flag')\n\t$flagIcon.empty()\n\n\t$flagsCheck.empty()\n\n\t$flagsCheck = $('<div>').css('display','inline-block').css('position','absolute').css('padding-left','10px')\n\t$flagsCheck.append('<i>').html(amountUserFlags + '/' + amountFlags) \n\n\t$flagIcon = $('<div>').css('display','inline-block').css('position','absolute').css('padding-left',padding + 'px').\n\t\tcss('padding-top','2px')\n\n\t$flagIcon.append('<i>').addClass('fa fa-flag')\n\n\t$('body').append($flagsCheck)\n\t$('body').append($flagIcon)\n\n\t//disable context menu when use right click \n\t$('#field').on(\"contextmenu\",function () {\n\t \treturn false;\n\t}); \n}", "function circle_add_label(l){\n\t\tcircle.innerHTML \t= '';\n\t\tcircle.style.width \t= \"80px\";\n\t\tcircle.style.height = \"80px\";\n\t\tcircle.innerHTML \t= \"<small class='text-white'>\" + l + \"</small>\";\n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a local path from a plugin folder to a full path relative to the webserver's main views folder. Allows a plugin to bundle views/layouts and make them available to the webserver's renderer.
getLocalView(path_to_view) { if (this.webserver) { return path.relative(path.join(this.webserver.get('views')), path_to_view); } else { throw new Error('Cannot get local view when webserver is disabled'); } }
[ "function basepath(uri) {\n\t\t\treturn 'dist/views/' + uri;\n\t\t}", "function pluginPath()\n{\n var path = MSPluginManager.mainPluginsFolderURL();\n\n path = [path absoluteString]\n path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]\n path = [path stringByReplacingOccurrencesOfString:@\"file://\" withString:@\"\"]\n\n return path\n}", "function getMyBasepath(uri) {\r\n return 'app/views/appViews/' + uri;\r\n}", "function get_path_to_rendered_template(path_to_file, path_to_layout, destination) {\n\n // remove src (options.src) from beginning of path\n var path_to_rendered_template = path_to_file.replace(path_to_layout, \"\");\n\n // add destination (options.dest) to beginning of path\n path_to_rendered_template = destination + path_to_rendered_template;\n\n return path_to_rendered_template; \n \n }", "get viewsPath() {\n return path.resolve(this.rootPath, this.paths.views || '../views');\n }", "directory (name) {\n const plugin = this.plugins.get(name)\n if (plugin) core.application.directory(`${this.folder}/${plugin.path}`)\n }", "function basepath(uri) {\r\n return 'app/views/' + uri;\r\n }", "plugin() {\n return (function () {\n return {\n rootPath: configAPI.getPluginFolder()\n }\n }())\n }", "function basepath(uri) {\r\n return 'app/views/' + uri;\r\n }", "function basepath(uri) {\n return 'app/views/' + uri;\n }", "function templatesPath(dir) {\n return path.join(dir, '_layouts');\n}", "function basepath(uri) {\n return App.path + '/views/' + uri;\n }", "function basepath(uri) {\n return 'app/views/' + uri;\n }", "function ignitePluginPath () { return pluginPath }", "mainPath(path) {\n\t\treturn this.siteDir + this.#formatPath(path);\n\t}", "function output(relative){\n return 'app' + relative;\n}", "function buildPublicPath(filename) {\n return path.join(ROOT, 'views', filename);\n}", "function build_theme_layout() {\n \"use strict\";\n\n return gulp.src([\"./components/**/layout/**/*.liquid\", \"./layouts/**/layout/**/*.liquid\"])\n .pipe(plumber({\n errorHandler: function (err) {\n notify.onError({\n \"title\": \"Theme layout error.\",\n \"message\": \"<%= error.message %>\",\n \"icon\": failurePic\n })(err);\n this.emit('end');\n }\n }))\n .pipe(rename(function (thispath) {\n var split = thispath.dirname.split(path.sep);\n thispath.dirname = split.slice(2).join(path.sep);\n\n return thispath;\n }))\n .pipe(gulp.dest(\"./theme_files/layout\"))\n .pipe(notify({\n \"title\": \"Theme layout compiled.\",\n \"message\": \"Compiled <%= file.relative %>\",\n \"icon\": successPic\n }));\n}", "getpath(){ return `${globals.VERSION}/plugins/${this.prefix}/` ; }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unload a model's relationships payload.
unload(modelName, id) { var modelClass = this._store._modelFor(modelName); var relationshipsByName = Ember.get(modelClass, 'relationshipsByName'); relationshipsByName.forEach((_, relationshipName) => { var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false); if (relationshipPayloads) { relationshipPayloads.unload(modelName, id, relationshipName); } }); }
[ "unload(modelName, id) {\n var modelClass = this._store.modelFor(modelName);\n var relationshipsByName = Ember.get(modelClass, 'relationshipsByName');\n relationshipsByName.forEach((_, relationshipName) => {\n var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false);\n if (relationshipPayloads) {\n relationshipPayloads.unload(modelName, id, relationshipName);\n }\n });\n }", "unload(modelName, id, relationshipName) {\n this._flushPending();\n\n if (this._isLHS(modelName, relationshipName)) {\n delete this.lhs_payloads.delete(modelName, id);\n } else {\n (true && !(this._isRHS(modelName, relationshipName)) && Ember.assert(`${modelName}:${relationshipName} is not either side of this relationship, ${this._relInfo.lhs_baseModelName}:${this._relInfo.lhs_relationshipName}<->${this._relInfo.rhs_baseModelName}:${this._relInfo.rhs_relationshipName}`, this._isRHS(modelName, relationshipName)));\n\n delete this.rhs_payloads.delete(modelName, id);\n }\n }", "unload(modelName, id, relationshipName) {\n this._flushPending();\n\n if (this._isLHS(modelName, relationshipName)) {\n this.lhs_payloads.delete(modelName, id);\n } else {\n (true && !(this._isRHS(modelName, relationshipName)) && Ember.assert(`${modelName}:${relationshipName} is not either side of this relationship, ${this._relInfo.lhs_baseModelName}:${this._relInfo.lhs_relationshipName}<->${this._relInfo.rhs_baseModelName}:${this._relInfo.rhs_relationshipName}`, this._isRHS(modelName, relationshipName)));\n\n this.rhs_payloads.delete(modelName, id);\n }\n }", "function destroyRelationship(rel){rel.internalModelDidDematerialize();if(rel._inverseIsSync()){ // disconnect the graph so that the sync inverse relationship does not\n// prevent us from cleaning up during `_cleanupOrphanedInternalModels`\nrel.removeAllInternalModelsFromOwn();rel.removeAllCanonicalInternalModelsFromOwn();}} // this (and all heimdall instrumentation) will be stripped by a babel transform", "_resetRelationships() {\n for (let attr in this._relationships) {\n if (this._relationships.hasOwnProperty(attr)) {\n delete this._relationships[attr];\n }\n }\n }", "function destroyRelationship(rel) {\n rel.internalModelDidDematerialize();\n\n if (rel._inverseIsSync()) {\n // disconnect the graph so that the sync inverse relationship does not\n // prevent us from cleaning up during `_cleanupOrphanedInternalModels`\n rel.removeAllInternalModelsFromOwn();\n rel.removeAllCanonicalInternalModelsFromOwn();\n }\n }", "function destroyRelationship(rel) {\n rel.internalModelDidDematerialize();\n\n if (rel._inverseIsSync()) {\n // disconnect the graph so that the sync inverse relationship does not\n // prevent us from cleaning up during `_cleanupOrphanedInternalModels`\n rel.removeAllInternalModelsFromOwn();\n rel.removeAllCanonicalInternalModelsFromOwn();\n }\n}", "clear() {\n var models = this._models;\n this._models = [];\n\n for (var i = 0; i < models.length; i++) {\n var model = models[i];\n model.unloadRecord();\n }\n\n this._metadata = null;\n }", "clear() {\n if (this._models) {\n let models = this._models;\n this._models = [];\n\n for (let i = 0; i < models.length; i++) {\n let model = models[i];\n model.unloadRecord();\n }\n }\n\n this._metadata = null;\n }", "clear() {\n var models = this._models;\n this._models = [];\n\n for (var i = 0; i < models.length; i++) {\n var model = models[i];\n model.unloadRecord();\n }\n\n this._metadata = null;\n }", "removeAll() {\n if (!this.isMany) {\n throw new Error('Cannot delete to-one relationships, you must use `remove`');\n }\n\n const adapter = this.parent.model.adapter;\n const id = this.parent.id;\n const field = this.field;\n\n return new Promise((resolve, reject) => {\n adapter.deleteRelationship(this.parent.model, id, field)\n .then(success => {\n this.child.removeAll();\n return resolve(true);\n })\n .catch(err => {\n return reject(err);\n });\n });\n }", "clear() {\n var internalModels = this._models;\n this._models = [];\n\n for (var i = 0; i < internalModels.length; i++) {\n var internalModel = internalModels[i];\n internalModel.unloadRecord();\n }\n\n this._metadata = null;\n }", "_disassociateFromDependents() {\n this._schema.dependentAssociationsFor(this.modelName).forEach(association => {\n association.disassociateAllDependentsFromTarget(this);\n });\n }", "async clearRelationship(property) {\n this._errorIfNothasOneReln(property, \"clearRelationship\");\n if (!this.get(property)) {\n console.warn(`Call to clearRelationship(${property}) on model ${this.modelName} but there was no relationship set. This may be ok.`);\n return;\n }\n const mps = this.db.multiPathSet(\"/\");\n this._relationshipMPS(mps, this.get(property), property, null, new Date().getTime());\n this.dispatch(this._createRecordEvent(this, index_1.FMEvents.RELATIONSHIP_REMOVED_LOCALLY, mps.payload));\n await mps.execute();\n this.dispatch(this._createRecordEvent(this, index_1.FMEvents.RELATIONSHIP_REMOVED, this.data));\n }", "destroy() {\n if (this.isSaved()) {\n this._disassociateFromDependents();\n\n let collection = this._schema.toInternalCollectionName(this.modelName);\n\n this._schema.db[collection].remove(this.attrs.id);\n }\n }", "_deleteFromRelation() {\n const relation = this._truck.relation\n const collection = this._truck.collection\n\n if (!relation && !collection) {\n return\n }\n\n // hasMany / collection\n if (relation instanceof HasManyRelation || collection) {\n collection.delete(this)\n }\n // hasOne\n else if (relation instanceof HasOneRelation) {\n relation.model = null\n }\n }", "detach() {\n if (this.valid()) {\n // Remove from current world\n for (const name in this.data) {\n if (name === 'entity') continue\n this.world.entities.removeFromIndex(this, name)\n }\n this.world.entities.entities.delete(this._id)\n this._id = undefined\n this.world = undefined\n }\n }", "async dropAllModels() {\n var i, len, model, ref;\n ref = this._getModelNamesByAssociationOrder();\n for (i = 0, len = ref.length; i < len; i++) {\n model = ref[i];\n await this.models[model].drop();\n }\n }", "async removeAllCropRelationships() {\n\t\tconst relationships = await this.getAllCropRelationships();\n\t\tawait this.removeCropRelationships(ApiClient.getIds(relationships));\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test helpers: sendMin(), sendTXSelf() send the minimum amount
async sendMin({ to, value }) { const txHash = await this.send({ to: to, value: 1000000000000 }) console.log("TX:", txHash) return true }
[ "async ensureMinimumEther(dest,toWrio) { //TODO: add ethereum queue for adding funds, to prevent multiple funds transfer\n var ethBalance = await this.getEtherBalance(dest)/wei;\n logger.debug(\"Ether:\",ethBalance);\n if (ethBalance < min_amount) {\n logger.info(\"Adding minium ether amount\",ethBalance);\n await this.etherTransfer(dest,min_amount);\n\n var feed = new EtherFeed();\n await feed.create(dest,min_amount,toWrio);\n\n if (!(await this.waitForEther(dest))) {\n logger.error(\"Failed to wait for ether to arrive\");\n }\n\n } else {\n logger.verbose(\"Account has minimum ether, cancelling\");\n }\n }", "function sendAll(from, to) {\n\n var balance = eth.getBalance(from);\n var gas = new BigNumber(21000);\n var gasPrice = web3.eth.gasPrice;\n\n var cost = gas.mul(gasPrice);\n var sendAmount = balance.sub(cost);\n\n time = new Date();\n\n if (sendAmount < 0) {\n console.log(\"Insufficient funds, you need atleast '\", cost, \"' wei\");\n } else {\n\n console.log(\"Sending wei:\", sendAmount, \"at GasPrice\", gasPrice);\n\n //tx = eth.getTransactionReceipt(eth.sendTransaction({from: from, to: to, gas: gas, gasPrice: gasPrice, value: sendAmount}));\n console.log(\"eth.sendTransaction({ from:\", from, \", to:\", to, \", value:\", sendAmount.toString(), \", gas: '21000', })\")\n txHash = eth.sendTransaction({ from: from, to: to, value: sendAmount.toString(), gas: \"21000\", });\n i = setInterval(waitForConfirmation, 5000);\n }\n}", "async function send({ address, amount, tokenAddress }) {\n assert(senderAccount != null, 'Please provide SENDER_ACCOUNT in .env file if you send')\n if (tokenAddress) {\n const erc20ContractJson = require('./build/contracts/ERC20Mock.json')\n erc20 = new web3.eth.Contract(erc20ContractJson.abi, tokenAddress)\n const tokenBalance = new BigNumber(await erc20.methods.balanceOf(senderAccount).call())\n const tokenDecimals = await erc20.methods.decimals().call()\n const tokenSymbol = await erc20.methods.symbol().call()\n const toSend = new BigNumber(amount).times(BigNumber(10).pow(tokenDecimals))\n if (tokenBalance.lt(toSend)) {\n console.error(\"You have\",tokenBalance.div(BigNumber(10).pow(tokenDecimals)).toString(),tokenSymbol,\", you can't send more than you have\")\n process.exit(1);\n }\n const encodeTransfer = erc20.methods.transfer(address, toSend).encodeABI()\n await generateTransaction(tokenAddress, encodeTransfer)\n console.log('Sent',amount,tokenSymbol,'to',address);\n } else {\n const balance = new BigNumber(await web3.eth.getBalance(senderAccount));\n assert(balance.toNumber() !== 0, \"You have 0 balance, can't send transaction\")\n if (amount) {\n toSend = new BigNumber(amount).times(BigNumber(10).pow(18))\n if (balance.lt(toSend)) {\n console.error(\"You have\",balance.div(BigNumber(10).pow(18)),netSymbol+\", you can't send more than you have.\")\n process.exit(1);\n }\n } else {\n console.log('Amount not defined, sending all available amounts')\n const gasPrice = new BigNumber(await fetchGasPrice());\n const gasLimit = new BigNumber(21000);\n if (netId == 1 || netId == 5) {\n const priorityFee = new BigNumber(await gasPrices(3));\n toSend = balance.minus(gasLimit.times(gasPrice.plus(priorityFee)));\n } else {\n toSend = balance.minus(gasLimit.times(gasPrice));\n }\n }\n await generateTransaction(address, null, toSend)\n console.log('Sent',toSend.div(BigNumber(10).pow(18)).toString(),netSymbol,'to',address);\n }\n}", "function genAndSendMinMessage (values){\n var message = {\n \"concept\": msg.concept,\n \"person\": msg.patient,\n \"obsDatetime\": msg.obsDatetime,\n \"encounter\": msg.encounter,\n \"value\": min(values)\n }\n pipeMessage(client,message);\n}", "async sendTx(...args) {\n // wait to acquire lock\n while (lock != null) {\n // eslint-disable-line no-unmodified-loop-condition\n await lock\n }\n\n try {\n // send and unlock when done\n lock = doSend(...args)\n // wait for doSend to finish\n let res = await lock\n return res\n } catch (error) {\n throw error\n } finally {\n // get rid of lock whether doSend throws or succeeds\n lock = null\n }\n }", "async sendTx(...args) {\n // wait to acquire lock\n while (lock != null) {\n // eslint-disable-line no-unmodified-loop-condition\n await lock\n }\n\n try {\n // send and unlock when done\n lock = doSend(...args)\n // wait for doSend to finish\n let res = await lock\n return res\n } finally {\n // get rid of lock whether doSend throws or succeeds\n lock = null\n }\n }", "async sendOrders()\n\t{\n\t\tvar currentBlock = await EtherMiumApi.getCurrentBlockNumber();\n\t\ttry {\n\t\t\tfor (let token of this.tokensList)\n\t\t\t{\n\t\t\t\tvar found_buy_order = false;\n\t\t\t\tvar found_sell_order = false;\n\n\t\t\t\t// check if there active orders\n\t\t\t\tvar orders = await EtherMiumApi.getMyTokenOrders(token[0]);\n\n\t\t\t\tfor (let order of orders)\n\t\t\t\t{\n\t\t\t\t\tif (order.is_buy)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_buy_order = true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_sell_order = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (found_buy_order && found_sell_order) continue;\n\n\t\t\t\t// get the latest ticker for the token\n\t\t\t\tvar ticker = await EtherMiumApi.getTickers(token[0], this.ethAddress);\n\n\t\t\t\tif (!found_buy_order)\n\t\t\t\t{\n\t\t\t\t\tvar balance = await EtherMiumApi.getMyBalance(this.ethAddress);\n\t\t\t\t\tif (balance.decimal_adjusted_balance - balance.decimal_adjusted_in_orders < 0.2)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.error(`[updateOrders] Insufficient balance to place BUY order`);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar highestBid = ticker.highestBid;\n\n\t\t\t\t\tvar orderPrice = new BigNumber(highestBid).times(1-this.buyOrderMarkUp);\n\t\t\t\t\tvar amount = new BigNumber(this.orderEthValue).div(orderPrice).toFixed(8);\n\n\t\t\t\t\tvar result = await EtherMiumApi.placeLimitOrder(\n\t\t\t\t\t\t'BUY', \n\t\t\t\t\t\torderPrice.toFixed(0), \n\t\t\t\t\t\tamount, \n\t\t\t\t\t\ttoken[0], \n\t\t\t\t\t\ttoken[1], \n\t\t\t\t\t\tthis.ethAddress, \n\t\t\t\t\t\t18, \n\t\t\t\t\t\tcurrentBlock+this.orderLife\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!found_sell_order)\n\t\t\t\t{\n\t\t\t\t\tvar balance = await EtherMiumApi.getMyBalance(token[0]);\n\t\t\t\t\tvar lowestAsk = ticker.lowestAsk;\n\t\t\t\t\tif ((balance.decimal_adjusted_balance - balance.decimal_adjusted_in_orders)*lowestAsk < 0.2)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.error(`[updateOrders] Insufficient balance to place SELL order`);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar orderPrice = new BigNumber(lowestAsk).times(1+this.sellOrderMarkUp);\n\t\t\t\t\tvar amount = new BigNumber(this.orderEthValue).div(orderPrice).toFixed(8);\n\n\t\t\t\t\tvar result = await EtherMiumApi.placeLimitOrder(\n\t\t\t\t\t\t'SELL', \n\t\t\t\t\t\torderPrice.toFixed(0), \n\t\t\t\t\t\tamount, \n\t\t\t\t\t\ttoken[0], \n\t\t\t\t\t\ttoken[1], \n\t\t\t\t\t\tthis.ethAddress, \n\t\t\t\t\t\t18, \n\t\t\t\t\t\tcurrentBlock+this.orderLife\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (error)\n\t\t{\n\t\t\tconsole.error(`[updateOrders] Error=${error.message}`);\n\t\t}\n\t}", "async function sendWei( sender, receiver, privkey, value, gasprice=1, mined=false, rawdata ) {\n var signonce = await web3.eth.getTransactionCount(sender);\n var chain = await web3.eth.getChainId();\n var tx = {\n \"nonce\" : signonce,\n \"from\" : sender, \n \"value\" : value, \n \"gasPrice\" : gasprice,\n \"to\" : receiver,\n \"chainId\" : chain\n }\n tx[\"gas\"] = (await web3.eth.estimateGas(tx)); // should be 21000\n if (rawdata) {\n tx[\"data\"] = rawdata;\n // Add Gas for data\n databytes = (rawdata.length - 2 ) / 2;\n extragas = 68 * databytes;\n tx[\"gas\"] += extragas;\n }\n\n try {\n var signed = await web3.eth.accounts.signTransaction(tx, privkey);\n } catch (e) {\n throw(e);\n }\n\n // What to return? Mined tx or tx hash?\n if (mined) {\n // Return a promise that fires on tx receipt available \n return new Promise ((resolve, reject) => {\n web3.eth.sendSignedTransaction(signed.rawTransaction)\n .on('receipt', (r) => {return resolve(r);})\n .on('error', (e) => {return reject(e);});\n })\n } \n else {\n // Return a promise that fires on tx hash available\n return new Promise ((resolve, reject) => {\n web3.eth.sendSignedTransaction(signed.rawTransaction, \n (err, txHash) => {\n return !err ? resolve(txHash) : reject(err)\n })\n })\n }\n}", "async function test(){\n\t\t\t\n\t\t\tawait newContractInstance.methods.enter().send({\n \t\t\tfrom: accounts[8],\n\t\t\tvalue: 25\n \t \t\t});\n\n\t\t await newContractInstance.methods.enter().send({\n \t\t\tfrom: accounts[9],\n\t\t\tvalue: 28\n \t\t\t});\n \t\t\t\n\t\t\tvar LowestBidder = await newContractInstance.methods.pickLowestBidder().call({\n \t\t\tfrom: accounts[8]\n \t\t\t});\n\t\t\t\n\t\t\tconsole.log('Attorney bids are:'+'\\n');\n\t\t\tconsole.log('Attorney 1: 25'+'\\n');\n\t\t\tconsole.log('Attorney 2: 28' + '\\n');\n\t\t\tconsole.log('Lowest Bidder is at index '+LowestBidder);\n\t\t}", "async simpleSend (amount, addresses, distribution, confirm = true, feeRate = 0.000004, fees) {\n const balance = await this.getBalance()\n if (amount > balance) throw new Error('insufficient funds.')\n\n // if distribution is unspecified, equally distribute funds to addresses\n distribution = distribution || []\n const leftoverAddresses = addresses.slice(distribution.length)\n\n // if fewer distributed amounts than addresses are specified,\n // remaining funds are equally distributed among the remaining addresses\n if (leftoverAddresses.length > 0) {\n const allocatedAmount = distribution.reduce((acc, val) => acc + val, 0)\n const toLeftover = (amount - allocatedAmount) / leftoverAddresses.length\n const remainingAmounts = leftoverAddresses.map(address => toLeftover)\n distribution = distribution.concat(remainingAmounts)\n }\n\n if (distribution.reduce((acc, val) => acc + val, 0) > amount) throw new Error ('amounts to transfer exceed amount available')\n\n // select inputs for the transaction\n const inputs = selectTxInputs(this.unspent, amount)\n\n // create outputs\n const outputs = addresses.map(mapToOutput)\n // generate a change address and format input data for rpc\n const changeAddress = await this.newAddress()\n\n if (!fees) {\n const txSize = await this.calculateTxSize(inputs, outputs, changeAddress, feeRate)\n fees = txSize * feeRate\n }\n\n const rpcInput = rpcFormat(inputs, outputs, changeAddress, fees)\n\n // send and confirm (unless instructed not to) transaction\n const txid = await this.send(...rpcInput)\n if (confirm) await this.confirm()\n\n return {\n inputs,\n outputs,\n changeAddress,\n txid\n }\n\n // map addresses and amounts to formatted outputs\n function mapToOutput (address, index) {\n const output = {}\n\n output[address] = castToValidBTCFloat(distribution[index])\n return output\n }\n }", "async function buyPCT() {\n\t\t// Converts integer as Eth to Wei,\n\t\tlet amount = await ethers.utils.parseEther(transAmount.toString());\n\t\ttry {\n\t\t\tawait erc20.buyToken(transAmount, {value: amount});\n\t\t\t// Listens for event on blockchain\n\t\t\tawait erc20.on(\"PCTBuyEvent\", (from, to, amount) => {\n\t\t\t\tsetPendingFrom(from.toString());\n\t\t\t\tsetPendingTo(to.toString());\n\t\t\t\tsetPendingAmount(amount.toString());\n\t\t\t\tsetIsPending(true);\n\t\t\t})\n\t\t} catch(err) {\n\t\t\tif(typeof err.data !== 'undefined') {\n\t\t\t\tsetErrMsg(\"Error: \"+ err.data.message);\n\t\t\t} \n\t\t\tsetIsError(true);\n\t\t} \t\n\t}", "async function sendCoins() {\n if (typeof window.ethereum !== 'undefined') {\n await requestAccount()\n const provider = new ethers.providers.Web3Provider(window.ethereum);\n const signer = provider.getSigner();\n const contract = new ethers.Contract(bvgTokenAddress, BVGToken.abi, signer);\n // We parse the amount to be sent. eg : amount of BVG to be sent = ethers.utils.parseEther(amount BVG written on the UI)\n // since BVG and Ether has the same decimal 18\n // For a token with another value of the decimal, we should update our parse method\n const parsedAmount = ethers.utils.parseEther(amount);\n const transation = await contract.transfer(userAccount, parsedAmount);\n await transation.wait();\n console.log(`${ethers.utils.formatEther(parsedAmount)} BVG successfully sent to ${userAccount}`);\n }\n }", "function sendtx(src, tgtaddr, amount, strData) {\n\t\t\n\tchain3.mc.sendTransaction(\n\t\t{\n\t\t\tfrom: src,\n\t\t\tvalue:chain3.toSha(amount,'mc'),\n\t\t\tto: tgtaddr,\n\t\t\tgas: \"22000\",//min 1000\n\t\t\tgasPrice: chain3.mc.gasPrice,\n\t\t\tdata: strData\n\t\t}, function (e, transactionHash){\n if (!e) {\n console.log('Transaction hash: ' + transactionHash);\n }\n });\n\t\t\n\tconsole.log('sending from:' + \tsrc + ' to:' + tgtaddr + ' amount:' + amount + ' with data:' + strData);\n\n}", "function minOrders(q, id, order) {\n console.log(order.order_time);\n if(q.isEmpty()) {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n return;\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n } else {\n while(order.qty != 0) {\n var pos = getMinPriceOrder(q,order.qty,order.minq, order.mindis);\n if(pos === -1) {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n } else if (order.type === 0 && order.category === 0 && q.elements[pos].price > order.price) {\n qb.enqueue(order);\n msg = \"Order waiting! No sellers at this price\\n\"\n return;\n } else if (order.type === 0 && order.category === 1 && q.elements[pos].price < order.price) {\n qb.enqueue(order);\n msg = \"Order waiting! No buyers at this price\\n\"\n return;\n } else if(q.elements[pos].qty >= order.qty) {\n //trade executes\n if(order.category === 0) {\n acceptOrder(id, q.elements[pos].order_id, q.elements[pos].price, order.qty);\n } else {\n acceptOrder(q.elements[pos].order_id, id, q.elements[pos].price, order.qty);\n }\n msg = \"Order executed!\"\n updateAcceptStatus(id);\n //update qty\n q.elements[pos].qty -= order.qty;\n if(q.elements[pos].qty === 0 ) {\n if(q.elements[pos].description === 3) {\n if(q.elements[pos].left > 0) {\n if(q.elements[pos].left < q.elements[pos].mindis) {\n q.elements[pos].qty = q.elements[pos].left;\n q.elements[pos].left = 0;\n } else {\n q.elements[pos].qty = q.elements[pos].mindis;\n q.elements[pos].left -= q.elements[pos].mindis;\n }\n }\n }\n if(q.elements[pos].qty === 0 ){\n updateAcceptStatus(q.elements[pos].order_id);\n q.elements[pos].category = -1;\n if(pos === 0) {\n q.dequeue();\n }\n }\n }\n if (q.elements[pos].description === 2) {\n q.elements[pos].minq = 1;\n }\n order.qty=0;\n } else if((q.elements[pos].qty >= mindis && minq === 0)|| minq === 1){\n //execute partial order\n if(order.category === 0) {\n acceptOrder(id, q.elements[pos].order_id, q.elements[pos].price, order.qty);\n } else {\n acceptOrder(q.elements[pos].order_id, id, q.elements[pos].price, order.qty);\n }\n msg = \"Partial order executed!\\n\"\n //updateAcceptStatus(q.elements[pos].order_id);\n //update qty\n order.qty-=q.elements[pos].qty;\n q.elements[pos].qty = 0;\n if(q.elements[pos].description === 3) {\n if(q.elements[pos].left > 0) {\n if(q.elements[pos].left < q.elements[pos].mindis) {\n q.elements[pos].qty = q.elements[pos].left;\n q.elements[pos].left = 0;\n } else {\n q.elements[pos].qty = q.elements[pos].mindis;\n q.elements[pos].left -= q.elements[pos].mindis;\n }\n }\n }\n if(q.elements[pos].qty === 0 ){\n updateAcceptStatus(q.elements[pos].order_id);\n q.elements[pos].category = -1;\n if(pos === 0) {\n q.dequeue();\n }\n }\n order.minq = 1;\n } else {\n if(order.order_type === 1) {\n rejectOrder(id);\n msg += \"Order rejected!\\n\";\n } else {\n qb.enqueue(order);\n if(order.category === 0)\n msg = \"Order waiting! No sellers\\n\"\n else\n msg = \"Order waiting! No buyers\\n\"\n }\n return;\n }\n }\n }\n}", "mineCoins(web3, contractData , minerEthAddress)\n {\n\n var solution_number = web3utils.randomHex(32) //solution_number like bitcoin\n\n var challenge_number = contractData.challengeNumber;\n var target = contractData.miningTarget;\n\n var digest = web3utils.soliditySha3( challenge_number , minerEthAddress, solution_number )\n\n\n // console.log(web3utils.hexToBytes('0x0'))\n var digestBytes32 = web3utils.hexToBytes(digest)\n var digestBigNumber = web3utils.toBN(digest)\n\n var miningTarget = web3utils.toBN(target) ;\n\n\n\n // console.log('digestBigNumber',digestBigNumber.toString())\n // console.log('miningTarget',miningTarget.toString())\n\n if ( digestBigNumber.lt(miningTarget) )\n {\n\n if(this.testMode){\n console.log(minerEthAddress)\n console.log('------')\n console.log(solution_number)\n console.log(challenge_number)\n console.log(solution_number)\n console.log('------')\n console.log( web3utils.bytesToHex(digestBytes32))\n\n //pass in digest bytes or trimmed ?\n\n\n this.mining = false;\n\n this.networkInterface.checkMiningSolution( minerEthAddress, solution_number , web3utils.bytesToHex( digestBytes32 ),challenge_number,miningTarget,\n function(result){\n console.log('checked mining soln:' ,result)\n })\n }else {\n console.log('submit mined solution with challenge ', challenge_number)\n\n\n this.submitNewMinedBlock( minerEthAddress, solution_number, web3utils.bytesToHex( digestBytes32 ) , challenge_number);\n }\n }\n\n\n }", "async function netTransaction(callback){\n \n if(offChainBalanceUserA<=onChainBalanceUserA){\n amount=await Web3.utils.fromWei((onChainBalanceUserA-offChainBalanceUserA).toString(), 'ether')\n \n recipient= userB\n sender= userA\n }\n else{\n amount=await Web3.utils.fromWei((onChainBalanceUserB-offChainBalanceUserB).toString(), 'ether')\n \n recipient= userA\n sender= userB\n\n }\n\n callback()\n }", "function nfyLPBuyOrder() {\n if ($('#price-buy-lp').val() <= 0) {\n alert('Price needs to be more than 0!');\n return;\n }\n\n nfyToken.methods\n .allowance(accounts[0], tradingPlatformAddress)\n .call()\n .then(function (res) {\n if (res == 0) {\n nfyToken.methods\n .approve(tradingPlatformAddress, BigInt(maxAllowance).toString())\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n } else {\n var lpToBuyVal = $('#quantity-buy-lp').val();\n var lpPriceVal = $('#price-buy-lp').val();\n\n var lpToBuy = web3.utils.toWei(lpToBuyVal, 'ether');\n var lpPrice = web3.utils.toWei(lpPriceVal, 'ether');\n\n tradingPlatform.methods\n .createLimitOrder('nfylp', lpToBuy, lpPrice, 0)\n .send()\n\n .on('transactionHash', function (hash) {\n console.log(hash);\n })\n\n .on('confirmation', function (confirmationNr) {\n console.log(confirmationNr);\n })\n\n .on('receipt', function (receipt) {\n console.log(receipt);\n });\n }\n });\n}", "function execSendCoinCall() {\n var txDataToSend = {\n address: $scope.sendCoin.address,\n amount: $scope.sendCoin.amount,\n note: $scope.sendCoin.note\n };\n if (Number($scope.sendCoin.fee) !== Number(coinsInfo[$scope.activeCoin].relayFee) /*&& Number($scope.sendCoin.fee) !== 0.00001*/ && Number($scope.sendCoin.fee) !== 0) {\n $api.setTxFee($scope.activeCoin, $scope.sendCoin.fee)\n .then(function(response) {\n $api.sendToAddress($scope.activeCoin, txDataToSend)\n .then(function(response) {\n if (response.length === 64) {\n $scope.sendCoin.success = true;\n }\n // revert pay fee\n $api.setTxFee($scope.activeCoin, coinsInfo[$scope.activeCoin].relayFee)\n .then(function(response) {\n // do nothing\n }, function(reason) {\n if (dev.showConsoleMessages && dev.isDev)\n console.log('request failed: ' + reason);\n // TODO: show error\n });\n }, function(reason) {\n $message.ngPrepMessageModal($filter('lang')('MESSAGE.TRANSACTION_ERROR'), 'red');\n // revert pay fee\n $api.setTxFee($scope.activeCoin, coinsInfo[$scope.activeCoin].relayFee)\n .then(function(response) {\n // do nothing\n }, function(reason) {\n if (dev.showConsoleMessages && dev.isDev)\n console.log('request failed: ' + reason);\n // TODO: show error\n });\n });\n }, function(reason) {\n $message.ngPrepMessageModal($filter('lang')('MESSAGE.TRANSACTION_ERROR'), 'red');\n if (dev.showConsoleMessages && dev.isDev)\n console.log('request failed: ' + reason);\n });\n } else {\n $api.sendToAddress($scope.activeCoin, txDataToSend)\n .then(function(response) {\n if (response.length === 64) {\n $scope.sendCoin.success = true;\n } else {\n $message.ngPrepMessageModal($filter('lang')('MESSAGE.TRANSACTION_ERROR'), 'red');\n }\n }, function(reason) {\n $message.ngPrepMessageModal($filter('lang')('MESSAGE.TRANSACTION_ERROR'), 'red');\n if (dev.showConsoleMessages && dev.isDev)\n console.log('request failed: ' + reason);\n });\n }\n }", "function checkMinimumOrder(value, { req })\r\n{\r\n brownies = (parseInt(req.body.brownies) > 0 ? req.body.brownies : 0);\r\n blueberryMuffins = (parseInt(req.body.blueberryMuffins) > 0 ? req.body.blueberryMuffins : 0);\r\n chocolateCookies = (parseInt(req.body.chocolateCookies) > 0 ? req.body.chocolateCookies : 0);\r\n macarons = (parseInt(req.body.macarons) > 0 ? req.body.macarons : 0);\r\n cheeseCakes = (parseInt(req.body.cheeseCakes) > 0 ? req.body.cheeseCakes : 0);\r\n croissants = (parseInt(req.body.croissants) > 0 ? req.body.croissants : 0);\r\n //check whether input quantity is 0\r\n if (brownies == 0 && blueberryMuffins == 0 && chocolateCookies == 0 && macarons == 0 &&\r\n cheeseCakes == 0 && croissants == 0) \r\n {\r\n throw new Error(\"***Please select atleast an item for checkout***\");\r\n }\r\n else \r\n {\r\n //getting the total\r\n total = calculateTotal();\r\n if (total < 10) \r\n {\r\n throw new Error(\"***Sorry you dont have a minimum purchase of $10.Please add few more items***\");\r\n }\r\n else \r\n {\r\n return true;\r\n }\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the tabs scrollers to show or not, dependent on the tabs count and width
function setScrollers(container, state) { if (!state) state = $.data(container, 'tabs'); var opts = state.options; var header = state.dc.header; var tool = header.children('div.tabs-tool'); var sLeft = header.children('div.tabs-scroller-left'); var sRight = header.children('div.tabs-scroller-right'); var wrap = state.dc.wrap; // set the tool height tool._outerHeight(header.outerHeight() - (opts.plain ? 2 : 0)); var tabsWidth = 0; $('ul.tabs li', header).each(function () { tabsWidth += $(this).outerWidth(true); }); var cWidth = header.width() - tool.outerWidth(); if (tabsWidth > cWidth) { sLeft.show(); sRight.show(); tool.css('right', sRight.outerWidth()); wrap.css({ marginLeft: sLeft.outerWidth(), marginRight: sRight.outerWidth() + tool.outerWidth(), left: 0, width: cWidth - sLeft.outerWidth() - sRight.outerWidth() }); } else { sLeft.hide(); sRight.hide(); tool.css('right', 0); wrap.css({ marginLeft: 0, marginRight: tool.outerWidth(), left: 0, width: cWidth }); wrap.scrollLeft(0); } }
[ "function setScrollers(container) {\n\t\tvar header = $('>div.tabs-header', container);\n\t\tvar tabsWidth = 0;\n\t\t$('ul.tabs li', header).each(function(){\n\t\t\ttabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\t\n\t\tif (tabsWidth > header.width()) {\n\t\t\t$('.tabs-scroller-left', header).css('display', 'block');\n\t\t\t$('.tabs-scroller-right', header).css('display', 'block');\n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling');\n\t\t\t\n//\t\t\tif ($.boxModel == true) {\n//\t\t\t\t$('.tabs-wrap', header).css('left',2);\n//\t\t\t} else {\n//\t\t\t\t$('.tabs-wrap', header).css('left',0);\n//\t\t\t}\n//\t\t\tvar width = header.width()\n//\t\t\t\t- $('.tabs-scroller-left', header).outerWidth()\n//\t\t\t\t- $('.tabs-scroller-right', header).outerWidth();\n//\t\t\t$('.tabs-wrap', header).width(width);\n//\t\t\t\n//\t\t} else {\n//\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\n//\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\n//\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0);\n//\t\t\t$('.tabs-wrap', header).width(header.width());\n//\t\t\t$('.tabs-wrap', header).css('left',0);\n//\t\t\t\n\t\t}\n\t}", "function setScrollers(container) {\r\n\t\tvar header = $('>div.tabs-header', container);\r\n\t\tvar tabsWidth = 0;\r\n\t\t$('ul.tabs li', header).each(function() {\r\n\t\t\t\t\ttabsWidth += $(this).outerWidth(true);\r\n\t\t\t\t});\r\n\r\n\t\tif (tabsWidth > header.width()) {\r\n\t\t\t$('.tabs-scroller-left', header).css('display', 'block');\r\n\t\t\t$('.tabs-scroller-right', header).css('display', 'block');\r\n\t\t\t$('.tabs-wrap', header).addClass('tabs-scrolling');\r\n\r\n\t\t\tif ($.boxModel == true) {\r\n\t\t\t\t$('.tabs-wrap', header).css('left', 2);\r\n\t\t\t} else {\r\n\t\t\t\t$('.tabs-wrap', header).css('left', 0);\r\n\t\t\t}\r\n\t\t\tvar width = header.width()\r\n\t\t\t\t\t- $('.tabs-scroller-left', header).outerWidth()\r\n\t\t\t\t\t- $('.tabs-scroller-right', header).outerWidth();\r\n\t\t\t$('.tabs-wrap', header).width(width);\r\n\r\n\t\t} else {\r\n\t\t\t$('.tabs-scroller-left', header).css('display', 'none');\r\n\t\t\t$('.tabs-scroller-right', header).css('display', 'none');\r\n\t\t\t$('.tabs-wrap', header).removeClass('tabs-scrolling').scrollLeft(0);\r\n\t\t\t$('.tabs-wrap', header).width(header.width());\r\n\t\t\t$('.tabs-wrap', header).css('left', 0);\r\n\r\n\t\t}\r\n\t}", "function setScrollers(container) {\n\t\tvar opts = $.data(container, 'tabs').options;\n\t\tif (opts.tabPosition == 'left' || opts.tabPosition == 'right'){return}\n\t\t\n\t\tvar header = $(container).children('div.tabs-header');\n\t\tvar tool = header.children('div.tabs-tool');\n\t\tvar sLeft = header.children('div.tabs-scroller-left');\n\t\tvar sRight = header.children('div.tabs-scroller-right');\n\t\tvar wrap = header.children('div.tabs-wrap');\n\t\t\n\t\t// set the tool height\n\t\ttool._outerHeight(header.outerHeight() - (opts.plain ? 2 : 0));\n\t\t\n\t\tvar tabsWidth = 0;\n\t\t$('ul.tabs li', header).each(function(){\n\t\t\ttabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\tvar cWidth = header.width() - tool._outerWidth();\n\t\t\n\t\tif (tabsWidth > cWidth) {\n\t\t\tsLeft.show();\n\t\t\tsRight.show();\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: sLeft.outerWidth(),\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth() + tool._outerWidth(),\n\t\t\t\t\tmarginRight: sRight._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: sRight.outerWidth()\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth(),\n\t\t\t\t\tmarginRight: sRight.outerWidth() + tool._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tsLeft.hide();\n\t\t\tsRight.hide();\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: 0,\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: tool._outerWidth(),\n\t\t\t\t\tmarginRight: 0,\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: 0\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: 0,\n\t\t\t\t\tmarginRight: tool._outerWidth(),\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t}\n//\t\t\twrap.scrollLeft(0);\n\t\t}\n\t}", "function setScrollers(container) {\n\t\tvar opts = $.data(container, 'tabs').options;\n\t\tif (opts.tabPosition == 'left' || opts.tabPosition == 'right'){return}\n\t\t\n\t\tvar header = $(container).children('div.tabs-header');\n\t\tvar tool = header.children('div.tabs-tool');\n\t\tvar sLeft = header.children('div.tabs-scroller-left');\n\t\tvar sRight = header.children('div.tabs-scroller-right');\n\t\tvar wrap = header.children('div.tabs-wrap');\n\t\t\n\t\t// set the tool height\n\t\tvar tHeight = header.outerHeight();\n\t\tif (opts.plain){\n\t\t\ttHeight -= tHeight - header.height();\n\t\t}\n\t\ttool._outerHeight(tHeight);\n\t\t\n\t\tvar tabsWidth = 0;\n\t\t$('ul.tabs li', header).each(function(){\n\t\t\ttabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\tvar cWidth = header.width() - tool._outerWidth();\n\t\t\n\t\tif (tabsWidth > cWidth) {\n\t\t\tsLeft.add(sRight).show()._outerHeight(tHeight);\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: sLeft.outerWidth(),\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth() + tool._outerWidth(),\n\t\t\t\t\tmarginRight: sRight._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: sRight.outerWidth()\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth(),\n\t\t\t\t\tmarginRight: sRight.outerWidth() + tool._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tsLeft.add(sRight).hide();\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: 0,\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: tool._outerWidth(),\n\t\t\t\t\tmarginRight: 0,\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: 0\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: 0,\n\t\t\t\t\tmarginRight: tool._outerWidth(),\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}", "function setScrollers(container) {\r\n\t\tvar opts = $.data(container, 'tabs').options;\r\n\t\tif (opts.tabPosition == 'left' || opts.tabPosition == 'right' || !opts.showHeader){return}\r\n\t\t\r\n\t\tvar header = $(container).children('div.tabs-header');\r\n\t\tvar tool = header.children('div.tabs-tool');\r\n\t\tvar sLeft = header.children('div.tabs-scroller-left');\r\n\t\tvar sRight = header.children('div.tabs-scroller-right');\r\n\t\tvar wrap = header.children('div.tabs-wrap');\r\n\t\t\r\n\t\t// set the tool height\r\n\t\tvar tHeight = header.outerHeight();\r\n\t\tif (opts.plain){\r\n\t\t\ttHeight -= tHeight - header.height();\r\n\t\t}\r\n\t\ttool._outerHeight(tHeight);\r\n\t\t\r\n\t\tvar tabsWidth = 0;\r\n\t\t$('ul.tabs li', header).each(function(){\r\n\t\t\ttabsWidth += $(this).outerWidth(true);\r\n\t\t});\r\n\t\tvar cWidth = header.width() - tool._outerWidth();\r\n\t\t\r\n\t\tif (tabsWidth > cWidth) {\r\n\t\t\tsLeft.add(sRight).show()._outerHeight(tHeight);\r\n\t\t\tif (opts.toolPosition == 'left'){\r\n\t\t\t\ttool.css({\r\n\t\t\t\t\tleft: sLeft.outerWidth(),\r\n\t\t\t\t\tright: ''\r\n\t\t\t\t});\r\n\t\t\t\twrap.css({\r\n\t\t\t\t\tmarginLeft: sLeft.outerWidth() + tool._outerWidth(),\r\n\t\t\t\t\tmarginRight: sRight._outerWidth(),\r\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\ttool.css({\r\n\t\t\t\t\tleft: '',\r\n\t\t\t\t\tright: sRight.outerWidth()\r\n\t\t\t\t});\r\n\t\t\t\twrap.css({\r\n\t\t\t\t\tmarginLeft: sLeft.outerWidth(),\r\n\t\t\t\t\tmarginRight: sRight.outerWidth() + tool._outerWidth(),\r\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tsLeft.add(sRight).hide();\r\n\t\t\tif (opts.toolPosition == 'left'){\r\n\t\t\t\ttool.css({\r\n\t\t\t\t\tleft: 0,\r\n\t\t\t\t\tright: ''\r\n\t\t\t\t});\r\n\t\t\t\twrap.css({\r\n\t\t\t\t\tmarginLeft: tool._outerWidth(),\r\n\t\t\t\t\tmarginRight: 0,\r\n\t\t\t\t\twidth: cWidth\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\ttool.css({\r\n\t\t\t\t\tleft: '',\r\n\t\t\t\t\tright: 0\r\n\t\t\t\t});\r\n\t\t\t\twrap.css({\r\n\t\t\t\t\tmarginLeft: 0,\r\n\t\t\t\t\tmarginRight: tool._outerWidth(),\r\n\t\t\t\t\twidth: cWidth\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function showHideTabs() {\n $.each(tabArray, function (index, value) {\n if (((index < firstVisibleTabIndex) || (index > lastVisibleTabIndex)) && index != partialShowTabIndex) {\n value.hide();\n } else {\n value.show();\n }\n });\n\n // If the first and/or last tab is visible, hide the appropriate scroll button(s).\n firstVisibleTabIndex == 0 ? $(\"#leftScroll\").addClass(\"tabScrollButtonDisabled\") : $(\"#leftScroll\").removeClass(\"tabScrollButtonDisabled\");\n lastVisibleTabIndex == tabArray.length - 1 ? $(\"#rightScroll\").addClass(\"tabScrollButtonDisabled\") : $(\"#rightScroll\").removeClass(\"tabScrollButtonDisabled\");\n\n expandTabsToFill();\n }", "adjustTabs() {\n var tabs = $('#phase-tabs')[0];\n if(tabs != undefined && tabs.scrollWidth > tabs.clientWidth && !this.state.overflowTabs) {\n this.setState({\n overflowTabs: true\n });\n }\n else if(tabs != undefined && tabs.scrollWidth <= tabs.clientWidth && this.state.overflowTabs) {\n this.setState({\n overflowTabs: false\n });\n }\n }", "function setScrollers(container) {\n\t\tvar opts = $.data(container, 'wizardtabs').options;\n\t\tif (opts.tabPosition == 'left' || opts.tabPosition == 'right'){return}\n\t\t\n\t\tvar header = $(container).children('div.wizardtabs-header');\n\t\tvar tool = header.children('div.wizardtabs-tool');\n\t\tvar sLeft = header.children('div.wizardtabs-scroller-left');\n\t\tvar sRight = header.children('div.wizardtabs-scroller-right');\n\t\tvar wrap = header.children('div.wizardtabs-wrap');\n\t\t\n\t\t// set the tool height\n\t\tvar tHeight = header.outerHeight();\n\t\tif (opts.plain){\n\t\t\ttHeight -= tHeight - header.height();\n\t\t}\n\t\ttool._outerHeight(tHeight);\n\t\t\n\t\tvar wizardtabsWidth = 0;\n\t\t$('ul.wizardtabs li', header).each(function(){\n\t\t\twizardtabsWidth += $(this).outerWidth(true);\n\t\t});\n\t\tvar cWidth = header.width() - tool._outerWidth();\n\t\t\n\t\tif (wizardtabsWidth > cWidth) {\n\t\t\tsLeft.add(sRight).show()._outerHeight(tHeight);\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: sLeft.outerWidth(),\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth() + tool._outerWidth(),\n\t\t\t\t\tmarginRight: sRight._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: sRight.outerWidth()\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: sLeft.outerWidth(),\n\t\t\t\t\tmarginRight: sRight.outerWidth() + tool._outerWidth(),\n\t\t\t\t\twidth: cWidth - sLeft.outerWidth() - sRight.outerWidth()\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tsLeft.add(sRight).hide();\n\t\t\tif (opts.toolPosition == 'left'){\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: 0,\n\t\t\t\t\tright: ''\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: tool._outerWidth(),\n\t\t\t\t\tmarginRight: 0,\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttool.css({\n\t\t\t\t\tleft: '',\n\t\t\t\t\tright: 0\n\t\t\t\t});\n\t\t\t\twrap.css({\n\t\t\t\t\tmarginLeft: 0,\n\t\t\t\t\tmarginRight: tool._outerWidth(),\n\t\t\t\t\twidth: cWidth\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}", "function setScrollTabs() {\r\n\tvar scrollers = $$('*[scroller]');\r\n\tif(!scrollers[0]) return;\r\n\tvar scroller = scrollers[0].get('scroller');\r\n\tvar current_tab;\r\n\r\n\tvar page_scroll = new Fx.Scroll(scroller, {\r\n\t\twait: false,\r\n\t\tduration:1000,\r\n\t\ttransition: Fx.Transitions.Quad.easeInOut,\r\n\t\toffset: {\r\n\t\t\tx: -72,\r\n\t\t\ty: 0\r\n\t\t}\r\n\t});\r\n\r\n\tscrollers.each(function(el,i) {\r\n\t\t\tel.addEvents({\r\n\t\t\t\t\t'mouseover' : function(e) {\r\n\t\t\t\t\t\tthis.addClass('tab_selected');\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'mouseout' : function(e) {\r\n\t\t\t\t\t\tif(current_tab != this) this.removeClass('tab_selected');\r\n\t\t\t\t\t},\r\n\t\t\t\t\t'click' : function(e) {\r\n\t\t\t\t\t\tpage_scroll.toElement(this.get('target'));\r\n\t\t\t\t\t\t//console.log($(el.get('target')).getSize().y);\r\n\t\t\t\t\t\tvar fixHeight = new Fx.Morph($(el.get('target')).getParent(), {duration: 500});\r\n\t\t\t\t\t\tfixHeight.start({height:$(this.get('target')).getSize().y+160});\r\n\t\t\t\t\t\tthis.addClass('tab_selected');\r\n\t\t\t\t\t\tif(current_tab) current_tab.removeClass('tab_selected');\r\n\t\t\t\t\t\tcurrent_tab = this;\r\n\t\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tif(i==0) {\r\n\t\t\t\tel.fireEvent('click');\r\n\t\t\t}\r\n\t});\r\n}", "function ShowHideScrollImages()\n{\n\t/*setting the visiblity of previous and next images. \n\tAlso attaching the mouse scroll if number of tabs is more then visible tabs.*/\n if ($size > $visible) {\n if ($index > 0)\n $prev.show();\n if ($index < $size - $visible)\n $next.show();\n } else { // has not more tabs to show\n /* fix of the rest of menu tabs which do not use this custom menu */\n $tabs.css(\"width\",\"auto !important\");\n $ul.css(\"width\",\"auto !important\");\n /* fix of the rest of menu tabs which do not use this custom menu */\n }\n}", "_setTabsAndTabWidth() {\n this.tabsWidth = this.$el.width();\n this.tabWidth = Math.max(this.tabsWidth, this.el.scrollWidth) / this.$tabLinks.length;\n }", "function setTabAreaWidth() {\n $(\".tabs\").css(\"max-width\", ($(window).innerWidth() - (2 * $(\".tabScrollButton\").outerWidth(true))) + \"px\");\n }", "_checkOverflowScroll() {\n const that = this,\n tabsHeaderSection = that.$tabsHeaderSection,\n tabStrip = that.$.tabStrip,\n overflow = that.overflow;\n\n if (overflow === 'hidden') {\n return;\n }\n\n let overflowing, showNear, showFar;\n\n if (!(that.tabPosition === 'left' || that.tabPosition === 'right')) {\n const scrollLeft = Math.abs(that._getScrollLeft());\n\n overflowing = Math.round(tabStrip.scrollWidth) > Math.round(tabStrip.offsetWidth);\n\n if (that.rightToLeft) {\n showFar = Math.round(scrollLeft) > 0;\n showNear = Math.round(tabStrip.offsetWidth + scrollLeft) < Math.round(tabStrip.scrollWidth);\n }\n else {\n showNear = Math.round(scrollLeft) > 0;\n showFar = Math.round(tabStrip.offsetWidth + scrollLeft) < Math.round(tabStrip.scrollWidth);\n }\n }\n else {\n overflowing = Math.round(tabStrip.scrollHeight) > Math.round(tabStrip.offsetHeight);\n showNear = Math.round(tabStrip.scrollTop) > 0;\n showFar = Math.round(tabStrip.offsetHeight + tabStrip.scrollTop) < Math.round(tabStrip.scrollHeight);\n }\n\n if (overflow === 'scroll') {\n tabsHeaderSection.addClass('scroll-buttons-shown');\n that.$scrollButtonNear.removeClass('smart-hidden');\n that.$scrollButtonFar.removeClass('smart-hidden');\n }\n\n if (overflowing) {\n if (overflow === 'auto') {\n if (!tabsHeaderSection.hasClass('scroll-buttons-shown')) {\n tabsHeaderSection.addClass('scroll-buttons-shown');\n }\n\n if (showNear) {\n that.$scrollButtonNear.removeClass('smart-hidden');\n }\n else {\n that.$scrollButtonNear.addClass('smart-hidden');\n }\n\n if (showFar) {\n that.$scrollButtonFar.removeClass('smart-hidden');\n }\n else {\n that.$scrollButtonFar.addClass('smart-hidden');\n }\n\n if ((showNear && showFar) === false) {\n tabsHeaderSection.addClass('one-button-shown');\n }\n else {\n tabsHeaderSection.removeClass('one-button-shown');\n }\n\n if (!that.disabled) {\n that.$.scrollButtonNear.disabled = false;\n that.$.scrollButtonFar.disabled = false;\n }\n }\n else {\n tabsHeaderSection.removeClass('one-button-shown');\n\n if (that.disabled) {\n that.$.scrollButtonNear.disabled = true;\n that.$.scrollButtonFar.disabled = true;\n }\n else {\n that.$.scrollButtonNear.disabled = !showNear;\n that.$.scrollButtonFar.disabled = !showFar;\n }\n }\n }\n else if (!overflowing && overflow === 'auto' && tabsHeaderSection.hasClass('scroll-buttons-shown')) {\n tabsHeaderSection.removeClass('scroll-buttons-shown');\n tabsHeaderSection.removeClass('one-button-shown');\n that.$scrollButtonNear.addClass('smart-hidden');\n that.$scrollButtonFar.addClass('smart-hidden');\n }\n else if (!overflowing && overflow === 'scroll') {\n that.$.scrollButtonNear.disabled = true;\n that.$.scrollButtonFar.disabled = true;\n }\n }", "scrollable() {\n return this.tabs.length > this.swipeThreshold || !this.ellipsis;\n }", "updateScrollButtons(useTabmixButtons) {\r\n let tabstrip = this.tabBar.mTabstrip;\r\n tabstrip._scrollButtonDown = useTabmixButtons ?\r\n tabstrip._scrollButtonDownRight :\r\n tabstrip._scrollButtonDownLeft || // fall back to original\r\n document.getAnonymousElementByAttribute(tabstrip, \"anonid\", \"scrollbutton-down\");\r\n this.tabBar._animateElement = tabstrip._scrollButtonDown;\r\n\r\n tabstrip._scrollButtonUp = useTabmixButtons ?\r\n tabstrip._scrollButtonUpRight :\r\n tabstrip._scrollButtonUpLeft || // fall back to original\r\n document.getAnonymousElementByAttribute(tabstrip, \"anonid\", \"scrollbutton-up\");\r\n tabstrip._updateScrollButtonsDisabledState();\r\n\r\n if (!Tabmix.isVersion(320, 270)) {\r\n let overflow = this.overflow;\r\n tabstrip._scrollButtonUp.collapsed = !overflow;\r\n tabstrip._scrollButtonDown.collapsed = !overflow;\r\n }\r\n }", "function clickScrollTab() {\n\t$(\".wrap-tab-link ul\").scrollTo(\"li.active\", 800);\n\tlet numberTab = $(\".tabslet-tab li\").length;\n\tlet countNumber = 1;\n\tif (numberTab > 2) {\n\t\t$(\".tabslet-tab\").wrap('<div class=\"number-tab-wrap\"></div>');\n\t\t$(\".number-tab-wrap\").append(\n\t\t\t'<div class=\"icon-next\"><div class=\"next\"><em class=\"material-icons\">navigate_next</em></div></div>'\n\t\t);\n\t\t$(\".icon-next\").click(function () {\n\t\t\tif (countNumber < numberTab - 1) {\n\t\t\t\t$(this)\n\t\t\t\t\t.parent()\n\t\t\t\t\t.find(\".tabslet-tab\")\n\t\t\t\t\t.scrollTo(\"li:eq(\" + countNumber + \")\", 800);\n\t\t\t\tcountNumber++;\n\t\t\t} else {\n\t\t\t\tcountNumber = 1;\n\t\t\t\t$(this).parent().find(\".tabslet-tab\").scrollTo(\"li:eq(0)\", 800);\n\t\t\t}\n\t\t});\n\t}\n}", "function initTabbar() {\n _debug();\n if ($('#tabbar').length > 0) {\n _debug(' #tabbar exists');\n\n // Find current class or 1st page in #jqt & the last stylesheet\n var firstPageID = '#' + ($('#jqt > .current').length === 0 ? $('#jqt > *:first') : $('#jqt > .current:first')).attr('id'),\n sheet = d.styleSheets[d.styleSheets.length - 1];\n\n // pad .s-scrollpane\n $('.s-scrollpane').css('padding-bottom', '1px');\n\n // Make sure that the tabbar is not visible while its being built\n $('#tabbar').hide();\n $('#tabbar-pane').height($('#tabbar').height());\n _debug(' #tabbar height = ' + $('#tabbar').height() + 'px');\n _debug(' #tabbar-pane height = ' + $('#tabbar-pane').height() + 'px');\n _debug(' #tabbar-pane <ul>/<table> height = ' + $('#tabbar-pane ul').height() + 'px');\n $('#tabbar a').each(function (index) {\n var $me = $(this);\n\n // Enummerate the tabbar anchor tags\n $me.attr('id', 'tabbar_' + index);\n\n // If this is the button for the page with the current class then enable it\n if ($me.attr('href') === firstPageID) {\n $me.addClass('enabled');\n }\n\n // Put page animation, if any, into data('animation')\n $me.data('animation', $me.attr('animation'));\n\n // Put href target into data('default_target') and void href\n if ($me.data('default_target') === null || typeof ($me.data('default_target')) === 'undefined') {\n $me.data('default_target', $me.attr('href'));\n $me.attr('href', 'javascript:void(0);');\n }\n\n // Create css masks from the anchor's mask property\n sheet.insertRule(\"a#tabbar_\" + index + \"::after, a#tabbar_\" + index + \"::before {-webkit-mask-image:url('\" + $(this).attr('mask') + \"')}\", sheet.cssRules.length);\n\n // tabbar touches\n $(this).click(function () {\n var $me = $(this),\n animation,\n animations = ':fade:pop:slideup:',\n target;\n\n if (!$me.hasClass('enabled')) {\n animation = animations.indexOf(':' + $me.data('animation') + ':') > -1 ? $me.data('animation') : '';\n target = $me.data('default_target');\n\n jQT.goTo(target, animation);\n $('#tabbar a').each(function () {\n $(this).toggleClass('enabled', ($me.get(0) === $(this).get(0)));\n });\n }\n });\n });\n\n // Hide tabbar when page has a form or any form element except when the page's parent div has the keep_tabbar class\n $('#jqt > div, #jqt > form').has('button, datalist, fieldset, form, keygen, label, legend, meter, optgroup, option, output, progress, select, textarea').each(function () {\n\n // Hide when in a form\n $(this).bind('pageAnimationEnd', function (e, data) {\n if ($(':input', this).length !== $(':input:hidden', this).length) {\n if (data.direction === 'in' && !$(this).hasClass('keep_tabbar') && !$(this).children().hasClass('keep_tabbar')) {\n $('#tabbar').hide(function () {\n _debug('\\nHide tabbar');\n setPageHeight();\n });\n }\n }\n });\n\n // Show when starting to leave a form\n $(this).bind('pageAnimationStart', function (e, data) {\n if (data.direction === 'out' && $('#tabbar:hidden').length) {\n $('#tabbar').show(function () {\n _debug('\\nShow tabbar');\n setPageHeight();\n });\n }\n });\n });\n\n // Scroll to enabled tab on rotation\n $('#jqt').bind('turn', function (e, data) {\n var scroll = $('#tabbar').data('iscroll');\n if (scroll !== null && typeof (scroll) !== 'undefined') {\n setTimeout(function () {\n if ($('.enabled').offset().left + $('.enabled').width() >= win.innerWidth) {\n scroll.scrollToElement('#' + $('.enabled').attr('id'), '0ms');\n }\n },\n 0);\n }\n });\n\n // Show tabbar now that it's been built\n $('#tabbar').show(function () {\n setPageHeight();\n setBarWidth();\n });\n }\n }", "function enableViewTypeTabs(){\n tabsFrame.setTabEnabled(\"page0\", true);\n tabsFrame.setTabEnabled(\"page1\", true);\n tabsFrame.setTabEnabled(\"page2\", false);\n tabsFrame.setTabEnabled(\"page3\", false);\n tabsFrame.setTabEnabled(\"page4\", false);\n tabsFrame.setTabEnabled(\"page5\", false);\n tabsFrame.setTabEnabled(\"page6\", false);\n tabsFrame.setTabEnabled(\"page7\", false);\n}", "function hideOverflowTabs($tabSet) {\n //hide each tab until the width is greater than or equal to the shownTab\n //we can know when to reverse the array if the tab is greater than the middle\n var $allTabs = $tabSet.find(\".tab\");\n var $visibleTabs = $allTabs.filter(\":visible\");\n var maximumWidth = getMaximumWidthForTabSet.call($tabSet,true);\n var options = $tabSet.data(\"tabData\").options;\n var $selectedTab = ($allTabs.filter(\".active\").length === 1) ? $allTabs.filter(\".active\") : $allTabs.eq(options.activeTab);\n var selectedTabHidden = $selectedTab.is(\":hidden\");\n var $cTab = $lastTab = $currentlyVisibleTabs = findCenterTab($selectedTab, $visibleTabs);\n $allTabs.hide();\n $cTab.show();\n var $oldTab = null;\n //filter tabs left and right from the selectedTab until we don't fit, then break loop\n var numOfTabs = $allTabs.length;\n for (var i = 0; i < numOfTabs; i++){\n $oldTab = $cTab;\n if ($lastTab.prev(\".tab\").is(\":hidden\") && i % 2 === 1) {\n $cTab = $lastTab.prev(\".tab\");\n }\n if ($lastTab.next(\".tab\").is(\":hidden\") && i % 2 === 0) {\n $cTab = $lastTab.next(\".tab\");\n }\n if ($oldTab[0] === $cTab[0]) {\n $cTab = $lastTab.prev(\".tab\").length === 0 ? $cTab.next(\".tab\") : $cTab.prev(\".tab\"); \n $oldTab = $lastTab;\n }\n $cTab.show();\n $currentlyVisibleTabs = $currentlyVisibleTabs.add($cTab);\n if (getTotalWidthOfTabs($currentlyVisibleTabs) > maximumWidth) {\n $cTab.hide();\n break;\n }\n $lastTab = $oldTab;\n }\n enableDisableNavTabs($allTabs);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the width of the given rule from the css style.
function getWidth(ruleName){ var mysheet=document.styleSheets[0]; var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules let targetrule; for (let i = 0; i < myrules.length; i++){ if(myrules[i].selectorText.toLowerCase() == ruleName){ targetrule=myrules[i]; break; } } let str_width = targetrule.style.width; return parseInt(str_width.slice(0, -2)); }
[ "function getWidth( elem ) {\n // Gets the computed CSS value and parses out a usable number\n return parseInt( getStyle( elem, 'width') );\n}", "function getWidth(elem) {\n return parseInt(getStyle(elem, \"width\"));\n }", "function getWidth (node) {\n return parseInt(window.getComputedStyle(node).width, 10);\n }", "function getElementWidth(element) {\n // Optimization: Check style.width first as we probably set it already before reading\n // offsetWidth which triggers layout.\n return coercePixelsFromCssValue(element.style.width) || element.offsetWidth;\n }", "function getStyleLength(node) {\n\t\tvar s;\n\t\tvar styleLength = 0;\n\n\t\tif (!node) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (!node.style) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t// some browsers support .length on styles\n\t\tif (typeof node.style.length !== 'undefined') {\n\t\t\treturn node.style.length;\n\t\t}\n\n\t\t/*jslint forin: true*/ //not sure whether node.style.hasOwnProperty is valid\n\t\tfor (s in node.style) {\n\t\t\tif (node.style[s] && node.style[s] !== 0 && node.style[s] !== 'false') {\n\t\t\t\tstyleLength++;\n\t\t\t}\n\t\t}\n\t\t/*jslint forin: false*/\n\n\t\treturn styleLength;\n\t}", "function getStyle (cssrule) {\n for (var i in document.styleSheets) {\n var styleRules = (document.styleSheets[i].rules) ? document.styleSheets[i].rules :\n (document.styleSheets[i].cssRules) ? document.styleSheets[i].cssRules : [];\n for (var j=0; j<styleRules.length; j++){\n if (styleRules[j].selectorText.toUpperCase() == cssrule.toUpperCase()) {\n return styleRules[j];\n }\n }\n }\n return null;\n}", "function getStyle(rule, prop) {\n try {\n return rule.style.getPropertyValue(prop);\n } catch (err) {\n // IE may throw if property is unknown.\n return '';\n }\n }", "function elem_width(elem) {\n var styles;\n try {\n styles = window.getComputedStyle(elem);\n return elem.clientWidth + parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);\n } catch (err) {\n console.warn(err);\n }\n return 0;\n }", "function getTextWidth( text, cssStyle, cssFile )\n{\n var timeForId = new Date().getTime();\n var divTextToGetWidthId = \"divToGetWidth_\" + timeForId;\n $( \"#\" + divTextToGetWidthId ).remove();\n var fontSize = getStyleSheetsPropertyValue( cssStyle, \"fontSize\", cssFile );\n var fontWeight = getStyleSheetsPropertyValue( cssStyle, \"fontWeight\", cssFile );\n var fontFamily = getStyleSheetsPropertyValue( cssStyle, \"fontFamily\", cssFile );\n var divTextToGetWidth = $( \"<span id='\" + divTextToGetWidthId + \"' style='visibility:hidden; font-size:\" + fontSize + \";font-weight:\" + fontWeight + \";font-family:\" + fontFamily + \"'>\" + text + \"</span>\" );\n $( \"body\" ).append( divTextToGetWidth );\n var textWidth = divTextToGetWidth.width();\n $( \"#\" + divTextToGetWidthId ).remove();\n return textWidth;\n}", "function getCssWidth(childSelector) {\n return 100 * $(childSelector).width() / $(childSelector).offsetParent().width();\n}", "function getWidth(elem) {\n return parseInt(elem.style.width) \n}", "async function getElementWidth(selector) {\n const elementStyle = await page.evaluate(sel => {\n const element = document.querySelector(sel);\n return JSON.parse(JSON.stringify(getComputedStyle(element)));\n }, selector);\n return parseInt(elementStyle.width);\n }", "function widthOf(node) {\n return valOf(node, `.size.width`) * valOf(node, `.scale.x`);\n}", "function xGetCSSRules(ss) { return ss.rules ? ss.rules : ss.cssRules; }", "function getWidth(element) {\n return element[0].offsetWidth;\n }", "function evaluateStyleRule(styleProperty_)\n{\n\treturn styleProperty_.name + \": \" + styleProperty_.value;\n}", "function getWidth(obj,tag){\r\n\t\tif(!obj) return 0;\r\n\t\tvar children = eXo.core.DOMUtil.findDescendantsByTagName(obj,tag);\r\n\t\tvar w = 0;\r\n\t\tvar i = children.length;\r\n\t\twhile(i--){\r\n\t\t\tw += children[i].offsetWidth;\r\n\t\t}\r\n\t\treturn w;\r\n\t}", "function getDivElementWidth(element) {\n var style = getComputedStyle(element[0]);\n if (style)\n return style.width;\n else\n return \"0\";\n }", "function getDivElementWidth(element) {\n var style = window.getComputedStyle(element);\n if (style)\n return style.width;\n else\n return \"0\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get room data array Add map to the array Broadcast map
function map(msg) { var thisData = getRoom(msg["room"]); thisData.push(msg["mapURL"]); web.io.emit("servermessage", { "room": msg["room"], "command": "send_map", "mapURL": msg["mapURL"] }); }
[ "processRoomMaping(response) {\n const rooms = {};\n let room;\n if (typeof response.result !== 'object') {\n return false;\n }\n\n for (let r in response.result) {\n room = response.result[r];\n rooms[room[1]] = room[0];\n }\n adapter.getChannelsOf('rooms', function(err, roomObjs) {\n for (let r in roomObjs) {\n let roomObj = roomObjs[r];\n let extRoomId = roomObj._id.split('.').pop();\n if (extRoomId.indexOf('manual_') === -1) {\n room = rooms[extRoomId];\n if (!room) {\n adapter.setStateChanged(roomObj._id + '.mapIndex', i18n.notAvailable, true, (err,id,notChanged) => {\n if (!notChanged){\n adapter.log.info('room: ' + extRoomId + ' not mapped');\n adapter.setState(roomObj._id + '.state', i18n.notAvailable, true);\n }\n });\n } else {\n room= parseInt(room,10);\n adapter.setStateChanged(roomObj._id + '.mapIndex', room, true, (err,id,notChanged) => {\n if (!notChanged){\n adapter.log.info('room: ' + extRoomId + ' mapped with index ' + room);\n adapter.setObjectNotExists(roomObj._id + '.roomClean', roomManager.stateRoomClean); // in former time this dp was deleted, so try to create if needed\n adapter.setObjectNotExists(roomObj._id + '.state', roomManager.stateRoomStatus);\n adapter.setState(roomObj._id + '.state', '', true);\n }\n });\n delete rooms[extRoomId];\n }\n }\n }\n for (let extRoomId in rooms) {\n adapter.getObject('rooms.' + extRoomId, function (err, roomObj) {\n if (roomObj)\n adapter.setStateChanged(roomObj._id + '.mapIndex', rooms[extRoomId], true);\n else\n roomManager.createRoom(extRoomId, rooms[extRoomId]);\n });\n }\n });\n }", "function getRoomData(roomId, cb) {\n socket.on(\"viewRoom\", (v) => cb(null, v));\n socket.emit(\"getViewRoom\", roomId);\n}", "function sendMap() {\n console.log(\"Sending map...\");\n socket.emit(\"sendMap\", wallArray);\n }", "getData(playerId){\n let square=this.props.squareConfig.squares;\n let squareOwner = [];\n\n square.map((sq,i) => {\n if(sq.owner == playerId) {\n squareOwner.push({id:i, ...sq});\n }\n });\n\n return squareOwner;\n }", "addMap() {\n let data = new Object();\n data.name = \"\";\n data.description = \"\";\n data.list = [];\n this.allMaps.push(data);\n }", "static getPickYourTabletData(stationId) {\n var station = globalStations[stationId];\n var res = []\n if (station != undefined) {\n station.servers.map(server => {\n var item = {id: server.id, key: server.tabletId}\n res.push(item)\n })\n }\n return res\n }", "function getDataForMap() {\n google.maps.event.addListener(map, 'idle', function() {\n boundingBox = getBoundingBox();\n if (activitySelector.value === 'all') {\n // Only load data between these zoom levels\n if (map.getZoom() >= 3 && map.getZoom() <= 11) {\n $.ajax({\n url: '/getData',\n type: 'POST',\n data: JSON.stringify(boundingBox),\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n success: function(data) {\n addPlacesToMap(data);\n }\n });\n }\n }\n });\n}", "buildMap() {\n // Daventry map starts at room 31 but room 31 is stored in position 30.\n for (let room=0; room<48; room++) {\n let roomX = (room % 8) + 8;\n let roomY = ~~(room / 8) + 6;\n this.rooms[room + 30] = [\n 0, \n ((roomY % 6) * 8) + ((roomX - 1) % 8) + 31, // Left\n ((roomY % 6) * 8) + ((roomX + 1) % 8) + 31, // Right\n (((roomY + 1) % 6) * 8) + (roomX % 8) + 31, // Down\n (((roomY - 1) % 6) * 8) + (roomX % 8) + 31, // Up\n ];\n }\n }", "function getRoom(room)\r\n{\r\n if (!(room in roomObj))\r\n {\r\n roomObj[room] = roomData.length;\r\n roomData.push([]);\r\n console.log(\"===> Room \" + room + \" created on \" + new Date());\r\n console.log(\"Current rooms:\" );\r\n console.log(roomObj);\r\n }\r\n return roomData[roomObj[room]];\r\n}", "static getPickYourStationData() {\n var stations = getGlobalStations();\n var res = []\n stations.map(station => {\n var item = {id:station.id, name:station.name, stationkey:station.key}\n res.push(item)\n })\n return res\n }", "function initializeRoomData() {\n\tvar rooms = JSONData.rooms;\n\tfor (var i = 0; i < rooms.length; i++) {\n\t\tvar newRoom = {};\n\t\tnewRoom[\"_id\"] = generateUUID();\n\t\tnewRoom.title = rooms[i].prefix + \" \" + rooms[i].number;\n\t\tnewRoom.classes = [];\n\t\troomData.push(newRoom);\n\t}\n}", "function DataFromGps(id, lat, lon, time){\n var myDevice = new device(id, lat, lon, time);\n var recievedTable = [];\n recievedTable.push(myDevice);\n localTable = updateLocalTable(recievedTable,localTable);\n}", "function broadcastToPhones(data){\n console.log(\"to phones\");\n phones.forEach(phone => {\n phone.emit(\"location_request\", data);\n });\n}", "get playerData() {\n let pd = new Map();\n\n this._playerData.forEach((player, id, map) => {\n pd.set(id, {id: id, name: player.name, pieces: player.pieces});\n });\n\n return pd;\n }", "function getMapData(allData, mapTopLeft, mapBottomRight, numBlocks){\n //Initiialize the block array. Let me know if there's a better way to do this.\n var blockArray = new Array(numBlocks[0]);\n for (i = 0; i < blockArray.length; i++) {\n blockArray[i] = new Array(numBlocks[1]);\n }\n\n for (dataNum = 0; dataNum < data.length; dataNum ++) {\n dataEntry = allData[dataNum];\n dataLoc = dataEntry.coordinates;\n // Use this function to get where the entry belongs in the block array\n arrayLoc = getArrayLoc(dataLoc, mapTopLeft, mapBottomRight, numBlocks);\n // Add the entry to the appropriate location in the block array\n blockArray[arrayLoc[0]][arrayLoc[1]] = dataEntry;\n }\n return blockArray;\n}", "function getAllPlayers(data) {\n var room = io.sockets.adapter.rooms[data.gameId];\n var playersInRoom = [];\n\n for(var i = 0; i < players.length; i++) {\n if(room.sockets[players[i].socketId]==true) {\n playersInRoom.push(players[i]);\n }\n }\n var imgSubmitted;\n this.emit('playersInRoom', playersInRoom);\n this.broadcast.to(data.gameId).emit('newPlayerEntered', data);\n this.broadcast.to(data.gameId).emit('timerIs', data.timer);\n \n}", "static get_broadcasts()\n {\n try\n {\n const broadcastArray = []\n const keys = localStorage\n if (keys.length > 0) {\n for (let i = 0; i < keys.length; i++) {\n let key = localStorage.key(i)\n let pair = localStorage.getItem(key)\n let jsonPair = JSON.parse(pair)\n broadcastArray.push(jsonPair)\n }\n }\n \n return broadcastArray;\n }\n catch(e)\n {\n console.error('Error has occured',e);\n return [];\n }\n }", "function addmessagestoarray(data) {\n if (filteredmessages.length !== 0) {\n messagestore = filteredmessages\n }\n messagestore.push(data)\n setchats([messagestore])\n scrollmessages();\n }", "function getOplogWebsocketsData() {\n // Get all the requied data from ParkingData sensor in all devices \n for (let i = 0; i < devices.length; ++i) {\n let device = devices[i];\n let sensorIndex = _.findIndex(device.sensors, {id: \"ParkingData\"});\n\n // Setup if sensor exists \n if (sensorIndex !== -1) {\n let sensor = device.sensors[sensorIndex];\n let collection = sensor.collection;\n let dbName = sensor.dbName;\n let mongoUri = sensor.mongoAddress + '/' + dbName;\n let parkingData = monk(mongoUri);\n let oplog = MongoOplog('mongodb://' + mongoUri + '/local', { ns: dbName + '.' + collection}).tail();\n\n // Set configured to true\n sensor.configured = true;\n \n oplogHolder[i] = oplog;\n parkingDataHolder[i] = parkingData;\n collectionHolder[i] = collection;\n websocketportHolder[i] = sensor.WebSocketPort;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the parent key. If the key is toplevel, return null. mkey String Examples: > parent("alpha") null > parent("alpha>beta") "alpha" > parent("alpha>beta|gamma") "alpha>beta" Returns String or null.
function keyParent(mkey) { var path = keyToPath(mkey) , pathLen = path.length return pathLen === 1 ? null : path[pathLen - 2] }
[ "get parentChangeKey()\n\t{\n\t\tif (!this._parentChangeKey) {\n\t\t\tthis._parentChangeKey = this.getAttributeByTag(\"t:ParentFolderId\", \"ChangeKey\", null);\n\t\t}\n\t\treturn this._parentChangeKey;\n\t}", "function rawGetParentKey(parent, childkey, separator, allow_empty)\n{\n\tif(!rawIsSafeString(childkey)){\n\t\treturn null;\n\t}\n\tvar\tchild_hierarchy_arr = rawExpandHierarchyArray(parent, childkey, separator, allow_empty);\n\tif(null === child_hierarchy_arr || !(child_hierarchy_arr instanceof Array) || 0 === child_hierarchy_arr.length){\n\t\treturn null;\n\t}\n\tif(1 === child_hierarchy_arr.length){\n\t\t// there is no parent, the array is only childkey(or parent)\n\t\treturn null;\n\t}\n\treturn child_hierarchy_arr[child_hierarchy_arr.length - 2];\n}", "get parent() { return this.getParentKey(); }", "_parentKey(key){\n return key\n .split(\".\")\n .reduce((parentKey, subKey, idx, arr) =>\n parentKey + ((idx !== arr.length -1) ?`.${subKey}` : \"\"), \"\")\n .replace(/^\\./,\"\");\n }", "parent() {\n if (this.level === 0) {\n throw new Error(\"Cannot get the parent of the root tile key\");\n }\n // tslint:disable-next-line:no-bitwise\n return TileKey.fromRowColumnLevel(this.row >>> 1, this.column >>> 1, this.level - 1);\n }", "parent(root, path) {\n var parentPath = Path.parent(path);\n var p = Node$1.get(root, parentPath);\n\n if (Text.isText(p)) {\n throw new Error(\"Cannot get the parent of path [\".concat(path, \"] because it does not exist in the root.\"));\n }\n\n return p;\n }", "parent(root, path) {\n var parentPath = Path.parent(path);\n var p = Node.get(root, parentPath);\n\n if (Text.isText(p)) {\n throw new Error(\"Cannot get the parent of path [\".concat(path, \"] because it does not exist in the root.\"));\n }\n\n return p;\n }", "function getParent()/*:MetadataTreeNode*/ {\n return this.parent$pjKk;\n }", "function findParent(id) {\n var arrExp = id.split('_');\n var parent = '';\n if(arrExp.length > 1) {\n arrExp.pop();\n var parent = arrExp.join('_');\n }\n\n return parent;\n}", "function getCurrentParentID(){\r\n\t\t\r\n\t\tvar parentID = null;\r\n\t\tif(g_temp.is_edit_group_mode == true)\r\n\t\t\tparentID = g_temp.edit_group_id;\r\n\t\t\r\n\t\treturn(parentID);\r\n\t}", "getParentId(input) {\n if (input == undefined) {\n return this.defaultParentId;\n }\n\n return input;\n }", "get parentRef() {\n /* get string before {id} */\n return this._db.ref( this.path.split('{id}').shift() );\n // return this._db.ref( this.path ).parent < should work too?\n }", "function findParent(callback) {\n\t\t var path = this;\n\t\t while (path = path.parentPath) {\n\t\t if (callback(path)) return path;\n\t\t }\n\t\t return null;\n\t\t}", "function parent() {\n return this[0] ? this[0].parent : null;\n}", "getParentKey(notebook, nodeIndex, nodeID) {\n var currentID;\n if (!nodeID) {\n currentID = Object.keys(notebook.subnotes)[nodeIndex];\n } else {\n currentID = nodeID;\n }\n\n var indexTopLevel = notebook.topLevelSubnotes.indexOf(currentID);\n if (indexTopLevel !== -1) { //return 0 for parentID of a top level node\n return 0;\n }\n\n for (var key in notebook.subnotes) { //go through each subnote\n if (!notebook.subnotes.hasOwnProperty(key)) continue;\n var node = notebook.subnotes[key];\n if (\"childSubnotes\" in node) { //if node has children\n for (var i = 0; i < node.childSubnotes.length; i++) { //search through each child\n if (currentID === node.childSubnotes[i]) { //if we find a match, return that id\n return key;\n }\n }\n }\n }\n return 0; //if no match was found, return 0 (there was an invalid currentID)\n }", "get parentItem() {\n const item = (\n getParentItem(this.rootItem, this.dataPath, this.nested) ||\n null\n )\n return item !== this.item ? item : null\n }", "get_parent_node(){\n return this.fc.get_fragment_by_id(this.parent_node[0]).get_node_by_id(this.parent_node[1])\n }", "function node_parent_pks(node) {\n return node_relationship_pks(node, 'pa');\n}", "get _parentFolderId()\n {\n let folderId = this._folderIdForParent;\n let isLocal = helpers.mediaId.isLocal(folderId);\n if(!isLocal)\n return null;\n\n // Go to the parent of the item that was clicked on. \n let parentFolderId = LocalAPI.getParentFolder(folderId);\n\n // If the user right-clicked a thumbnail and its parent is the folder we're\n // already displaying, go to the parent of the folder instead (otherwise we're\n // linking to the page we're already on). This makes the parent button make\n // sense whether you're clicking on an image in a search result (go to the\n // location of the image), while viewing an image (also go to the location of\n // the image), or in a folder view (go to the folder's parent).\n let currentlyDisplayingId = LocalAPI.getLocalIdFromArgs(helpers.args.location);\n if(parentFolderId == currentlyDisplayingId)\n parentFolderId = LocalAPI.getParentFolder(parentFolderId);\n\n return parentFolderId;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Synthesize and validate a single stack
synthesizeStack(stackName) { const stack = this.getStack(stackName); // first, validate this stack and stop if there are errors. const errors = stack.validateTree(); if (errors.length > 0) { const errorList = errors.map(e => `[${e.source.path}] ${e.message}`).join('\n '); throw new Error(`Stack validation failed with the following errors:\n ${errorList}`); } const account = stack.env.account || 'unknown-account'; const region = stack.env.region || 'unknown-region'; const environment = { name: `${account}/${region}`, account, region }; const missing = Object.keys(stack.missingContext).length ? stack.missingContext : undefined; return { name: stack.id, environment, missing, template: stack.toCloudFormation(), metadata: this.collectMetadata(stack) }; }
[ "function IsStackValid() {\n if (!isNaN(stackVal) && isFinite(stackVal)) { return (true); } return (false);\n }", "async validateStacks(stacks) {\n stacks.processMetadataMessages({\n ignoreErrors: this.props.ignoreErrors,\n strict: this.props.strict,\n verbose: this.props.verbose,\n });\n }", "function checkStack(input){\n if(sequenceStack.length != 0 && !(input == sequenceStack.pop())){\n lossSequence();\n }\n if(sequenceStack == 0){\n simonTurn();\n }\n}", "function Stack() {}", "checkEmptyStack(numstack)\n {\n return (this.posting[numstack-1].length===0 || this.posting[numstack-1].length===null)\n }", "canPush() {\n return this.stackControl.length !== this.MAX_SIZE;\n }", "pop(){\r\n const stacklist = _stacklist.get(this);\r\n if(stacklist.length === 0){\r\n throw new Error(\"Empty Stack\");\r\n }else{\r\n stacklist.pop();\r\n }\r\n }", "function isStack(s) {\n var pattern = /type\\s=\\sclass\\sstd::stack.*/;\n return pattern.test(s);\n}", "function Assign_Stack_Stack() {\r\n}", "function MinStack() {}", "function MinStack() {\n this.stack = [];\n this.minStack = [];\n}", "stack() {\n return new SMTStack();\n }", "function Stack_A() {\r\n}", "function Stack() {\n this.stack = [new Scope()];\n}", "function countStack(stack){\n \n}", "function Stack() {\n this.list = new LinkedList_1.default();\n }", "function Stack_A_A() {\r\n}", "function Assign_Stack_Other() {\r\n}", "function Stack_R() {\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates date input. Returns whether validation succeeded and either the parsed and normalized value or a message the bot can use to ask the user again.
static validateDate(input) { // Try to recognize the input as a date-time. This works for responses such as "11/14/2018", "today at 9pm", "tomorrow", "Sunday at 5pm", and so on. // The recognizer returns a list of potential recognition results, if any. try { const results = Recognizers.recognizeDateTime(input, Recognizers.Culture.English); const now = new Date(); const earliest = now.getTime() let output; results.forEach(result => { // result.resolution is a dictionary, where the "values" entry contains the processed input. if (results[0].resolution.values.length>1 ){ // The processed input contains a "value" entry if it is a date-time value, or "start" and // "end" entries if it is a date-time range. const datevalue = results[0].resolution.values[1].value; // If only time is given, assume it's for today. const datetime = results[0].resolution.values[1].type === 'time' ? new Date(`${ now.toLocaleDateString() } ${ datevalue }`) : new Date(datevalue); if (datetime && earliest < datetime.getTime()) { output = { success: true, date: datetime.toLocaleDateString('en-US',{month:'long', year:'numeric', day:'numeric'}), date2: datetime}; return; } else { const date1 = datevalue; const parts = date1.split('-'); const date2 = parts[0] + '-' + parts[2] + '-' + parts[1]; const datevalue2 = date2; const datetime2 = resolution.type === 'time' ? new Date(`${ now.toLocaleDateString() } ${ datevalue2 }`) : new Date(datevalue2); if (datetime2 && earliest < datetime2.getTime()) { output = { success: true, date: datetime2.toLocaleDateString('en-US',{month:'long', year:'numeric', day:'numeric'})}; return; } } } else { result.resolution.values.forEach(resolution => { // The processed input contains a "value" entry if it is a date-time value, or "start" and // "end" entries if it is a date-time range. const datevalue = resolution.value || resolution.start; // If only time is given, assume it's for today. const datetime = resolution.type === 'time' ? new Date(`${ now.toLocaleDateString() } ${ datevalue }`) : new Date(datevalue); if (datetime && earliest < datetime.getTime()) { output = { success: true, date: datetime.toLocaleDateString('en-US',{month:'long', year:'numeric', day:'numeric'})}; return; } else if (datetime && (earliest - datetime.getTime()< (23*60*60*1000))){ output = { success: true, date: datetime.toLocaleDateString('en-US',{month:'long', year:'numeric', day:'numeric'})}; return; } else { const date1 = datevalue; const parts = date1.split('-'); const date2 = parts[0] + '-' + parts[2] + '-' + parts[1]; const datevalue2 = date2; const datetime2 = resolution.type === 'time' ? new Date(`${ now.toLocaleDateString() } ${ datevalue2 }`) : new Date(datevalue2); if (datetime2 && earliest < datetime2.getTime()) { output = { success: true, date: datetime2.toLocaleDateString('en-US',{month:'long', year:'numeric', day:'numeric'})}; return; } } }); } }); return output || { success: false, message: "I'm sorry, please enter a date at least an hour out." }; } catch (error) { return { success: false, message: "I'm sorry, I could not interpret that as an appropriate date. Please enter a date at least an hour out." }; } }
[ "function dateValidation(input) {\n if(!DateValidation.isDate(input)) {\n return SURVEY_CLIENT.MESSAGES.INVALID_DATE;\n }\n\n return null;\n}", "function dateValidation(date) {\n\tif (!date) {\n\t\treturn true;\n\t}\n\n\tvar currentDate = getCurrentDate();\n\n\tvar year = +date.substring(0, 4);\n\tvar month = +date.substring(5, 7);\n\tvar day = +date.substring(8, 10);\n\n\tif (date.length < 10 || date.substring(4,5) != '-' || date.substring(7,8) != '-') {\n\t\treturn 'Please enter your date in the format YYYY-MM-DD';\n\t\t//\t\t document.getElementById(dt).style.background ='#e35152';\n\n\t}\n\n\t if ( month > 12 || month < 1 || day > 31 || month < 1 || year > 2050 ) {\n\t\treturn 'You must enter a valid date. Please try again.';\n\t\t //\t\t document.getElementById(dt).style.background ='#e35152';\n\n\t}\n\telse if (year < currentDate['year'] || (month < currentDate['month'] && year == currentDate['year'])\n\t\t|| (month == currentDate['month'] && year == currentDate['year'] && day < currentDate['date'])) {\n\t\t return 'You cannot enter a date that is in the past.';\n\t\t // document.getElementById(dt).style.background ='#e35152';\n\n\t} \n\n\treturn true;\n}", "function validate_date(date) {\n var regex = /^[0-9]{2}\\/[0-9]{2}\\/[0-9]{4}$/;\n if (date.match(regex) === null) {\n return {pass: false, message: \"Wrong format\"};\n }\n\n\n // Validates if month is between 1 and 12 months inclusive\n var dateSplit = date.split('/');\n if (parseInt(dateSplit[0]) <= 0 || parseInt(dateSplit[0]) > 12) {\n return {pass: false, message: \"Month not in range\"};\n }\n\n // Validates if there are correct amount of days in months\n // Takes into account leap years for February\n var longMonths = [\"01\", \"03\", \"05\", \"07\", \"08\", \"10\", \"12\"];\n if (dateSplit[0] === \"02\") {\n if ((parseInt(dateSplit[2]) % 4 === 0) &&\n ((parseInt(dateSplit[1]) > 29) ||\n (parseInt(dateSplit[1]) <= 0))) {\n return {pass: false, message: \"Day not in range\"};\n } else if (parseInt(dateSplit[1]) > 28 || parseInt(dateSplit[1] <= 0)) {\n return {pass: false, message: \"Day not in range\"};\n }\n } else if (longMonths.includes(dateSplit[0])) {\n if (parseInt(dateSplit[1]) > 31 || parseInt(dateSplit[1]) < 0) {\n return {pass: false, message: \"Day not in range\"};\n }\n } else {\n if (parseInt(dateSplit[1]) > 30 || parseInt(dateSplit[1]) < 0) {\n return {pass: false, message: \"Day not in range\"};\n }\n }\n\n // Validates if the year is now or in the future\n var now = new Date();\n if (dateSplit[2] < now.getFullYear()) {\n return {pass: false, message: \"Year not in range\"};\n }\n\n return {pass: true, message: \"Success!\"};\n}", "static validate (fieldValue, message, resolve, reject) {\n if (moment(fieldValue, 'YYYY-MM-DD').isValid()) {\n resolve('Value is a valid non-empty date')\n } else {\n reject(message)\n }\n }", "validateStartDate() {\n const startDate = this.state.startDate;\n const yesterday = moment().subtract(1, 'days').format('MM-DD-YYYY hh:mm a');\n if (moment(startDate).isAfter(yesterday)) return 'success';\n else if(!this.state.startDate) return; //otherwise the form shows an error before the user inputs a date\n else return 'error';\n }", "function validDate(value) {\n\t return check.date(value) &&\n\t check.number(Number(value));\n\t }", "function isFailValidateDateformat(usrdate){\n \n // User doesn't specify the date or all white space\n \n if(typeof String.prototype.trim !== 'function') {\n String.prototype.trim = function() {\n usrdate = usrdate.replace(/^\\s+|\\s+$/g, '').leng; \n }\n }else {\n usrdate = usrdate.trim()\n \n }\n \n if (usrdate.length === 0)\n return false;\n \n\n \n var dateArray = usrdate.split(\"/\");\n\n if(dateArray.length === 3)\n {\n \n // Case 1: 1/1/ (no year) or no date /5/2000\n // Not necessary , check isNum instead\n //if (dateArray[0].length === 0 || dateArray[1].length === 0 || dateArray[2].length === 0)\n // return true;\n \n // Case 1: User inputs character 01/Feb/2000\n if (!(isNum(dateArray[0]) && isNum(dateArray[1]) && isNum(dateArray[2])))\n return true;\n \n // Case 2: Mount is not in 1-12\n if(dateArray[1]>12 || dateArray[1]<1)\n return true;\n // Case 3: If month in rage 1-12 , check date\n else {\n \n var maxdate = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];\n \n // Leap years\n if(dateArray[2] % 400 === 0 || (dateArray[2] % 100 !== 0 && dateArray[2] % 4 === 0))\n {\n maxdate[1] = 29;\n }\n \n \n if (dateArray[0] > maxdate[dateArray[1]-1]){\n return true;\n }\n } \n }else{\n // Date user input doesn't have date , month and year\n return true;\n }\n \n return false; //Doesn't match all bad cases\n \n}", "function isInputDateTypeValid() {\n let overallValidity = true;\n\n let inputDate = document.getElementById('travelDay');\n let travelDate = new Date((inputDate.value).replace(/-/g,'\\/'));\n\n if (!inputDate.value) {\n document.getElementById('travelDayWarning').style.visibility = 'visible';\n return false;\n }\n\n let validityOfDate = validateTodaysDateWith(travelDate);\n\n if (!validityOfDate) overallValidity = false;\n return overallValidity;\n}", "function checkBirthdayFormat() {\n var tbBirthday = document.getElementById(\"picked-day\").value; // value of birthday\n var myDate = Date.parse(tbBirthday);\n var now = Date.parse(Date());\n var errorBirthday = document.getElementById(\"error-birthday\");\n\n if (myDate > now) {\n errorBirthday.innerHTML = \"Birthday must be on or before today\";\n return false;\n } else {\n errorBirthday.innerHTML = \"\";\n return true;\n }\n}", "function validate_date(year, month, day, hour, minute, second, millisecond, pastdateok, futuredateok, fulldatetime) {\n var returnvalue = \"\";\n var testdate;\n var months = new Array('', \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\");\n if (year.length < 4) {\n return (\"You must enter a 4 digit year.\");\n }\n if ((day < 1) || (day > 31)) {\n return (\"You have entered an invalid day.\");\n }\n if ((month < 1) || (month > 12)) {\n return (\"You have entered an invalid month.\");\n }\n switch (month) {\n case 4:\n case \"4\":\n case \"04\":\n case 6:\n case \"6\":\n case \"06\":\n case 9:\n case \"9\":\n case \"09\":\n case 11:\n case \"11\":\n if (day > 30) {\n returnvalue = \"Invalid day (31st) for the month of \" + months[month] + \".\";\n }\n break;\n case 2:\n case \"2\":\n case \"02\":\n if (isleapyear(year)) {\n returnvalue = (day > 29) ? \"Cannot have more than 29 days in February of \" + year + \".\" : \"\";\n }\n else {\n returnvalue = (day > 28) ? \"Cannot have more than 28 days in February of \" + year + \".\" : \"\";\n }\n break;\n default:\n if (day > 31) {\n returnvalue = \"Cannot have more than 31 days in the month of \" + months[month] + \".\";\n }\n }\n if (returnvalue != \"\") {\n // we do a return here because the following is invalid if we've determined we have an invalid date.\n return (returnvalue);\n }\n testdate = new Date(year, month-1, day, hour, minute, second, millisecond);\n today = new Date();\n if (!(fulldatetime)) {\n today = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0,0,0,0);\n }\n if ( (!(pastdateok)) && (testdate.getTime() < today.getTime() ) ) {\n returnvalue = \"You have selected a date from the past and the system will not accept past dates.\";\n }\n if ( (!(futuredateok)) && (testdate.getTime() > today.getTime() ) ) {\n returnvalue = \"You have selected a date from the future and the system will not accept future dates.\";\n }\n return (returnvalue);\n}", "processBirthDay() {\n let input = this.birthDate.day\n resetError(input)\n\n if(!(input.value === '')){\n if (smallerThan(input, 1)) {\n this.valid = false;\n } else if (biggerThan(input, 31)) {\n this.valid = false;\n } else {\n input.success = true;\n this.changed = true;\n }\n }\n }", "function datevalidation(date,flag_alert) \n{\n\n\t\t\tdatearrayentry = date.split(\"-\");\n\t\t\tday = datearrayentry[0];\n\t\t\tmonth = datearrayentry[1];\n\t\t\tyear = datearrayentry[2];\n\t\t\t\n\t\t\tif (date.match(\"^[0-9]{2}-[0-9]{2}-[0-9]{4}$\") == null)\n\t\t\t{\n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\t\talert(\"You have specified an Invalid Date Format\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\tif ((month==4 || month==6 || month==9 || month==11) && day==31) \n\t\t\t{\n\t\t\t\tif(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"April\";\n\t\t\t\t}\n\t\t\t\telse if(month==6)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"June\";\n\t\t\t\t}\n\t\t\t\telse if(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"September\";\n\t\t\t\t}\n\t\t\t\telse if(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"November\";\n\t\t\t\t}\n\n\t\t\t\tif(flag_alert=='1')\n\t\t\t\t{\n\t\t\t\t\talert(\"Month \"+month_desc+\" doesn't have 31 days!\");\n\t\t\t\t}\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tif (month == 2) \n\t\t\t{ // check for february 29th\n\t\t\t\tvar isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));\n\t\t\t\tif (day>29 || (day==29 && !isleap)) \n\t\t\t\t{\n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"February \" + year + \" doesn't have \" + day + \" days!\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null; \n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (month < 1 || month > 12) // check month range\n\t\t\t{ \n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"Month must be between 1 and 12.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (day < 1 || day > 31) // check date range\n\t\t\t{\n\t\t\t\tif(flag_alert=='1')\n\t\t\t\t{\n\t\t\t\t\talert(\"Day must be between 1 and 31.\");\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\treturn \"dateisvalid\";\n\t\t\t\t\t\t\n}", "function dateValidator() {\n var dateFormat = /^\\d{2}\\/\\d{2}\\/\\d{4}$/;\n var now = new Date(Date.now()); //get currents date\n if (!dateFormat.test(this.value)) {\n alert(\"You put invalid date format\");\n return false;\n }\n //check date\n if (this.value.substring(0, 2) != now.getDate()) {\n alert(\"You put not current day.\");\n return false;\n }\n //check month\n else if (this.value.substring(3, 5) != now.getMonth() + 1) {\n alert(\"You put not current month.\");\n return false;\n }\n //check year\n else if (this.value.substring(6, 10) != now.getFullYear()) {\n alert(\"You put not current year.\");\n return false;\n }\n return true;\n }", "function validate_date(input_date) {\n\tvar dateFormat = /^\\d{1,4}[\\.|\\/|-]\\d{1,2}[\\.|\\/|-]\\d{1,4}$/;\n\tif (dateFormat.test(input_date)) {\n\t\ts = input_date.replace(/0*(\\d*)/gi, \"$1\");\n\t\tvar dateArray = input_date.split(/[\\.|\\/|-]/);\n\t\tdateArray[1] = dateArray[1] - 1;\n\t\tif (dateArray[2].length < 4) {\n\t\t\tdateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);\n\t\t}\n\t\tvar testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);\n\t\tif (testDate.getDate() != dateArray[0] || testDate.getMonth() != dateArray[1] || testDate.getFullYear() != dateArray[2]) {\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\telse {\n\t\treturn false;\n\t}\n}", "function checkValidDate() {\n let dateRef = document.getElementById(\"date\")\n let date = dateRef.value;\n let todayDate = new Date();\n // Convert user entered date to Date object\n let selectedDate = new Date(date);\n\n let output = `Cannot book flight for previous dates.\n \\n\\nPlease enter a valid date.`;\n\n // Alert user if selected date is invalid\n // Compare if year of selected date is < current year\n if (selectedDate.getFullYear() < todayDate.getFullYear()) {\n alert(output);\n dateRef.value = \"\";\n }\n // Compare if month of selected date is < current month\n else if (selectedDate.getMonth() < todayDate.getMonth()) {\n alert(output);\n dateRef.value = \"\";\n }\n // Compare if date of selected date is < current date\n else if (selectedDate.getDate() < todayDate.getDate()) {\n alert(output);\n dateRef.value = \"\";\n }\n}", "function validator() {\n if ((Number(day) < 0 || Number(day) > 31) || (Number(month) < 0 || Number(month) > 12)) {\n alert(\"Enter valid day or month\")\n }\n }", "processBirthDay() {\n let input = this.birthDate.day\n resetError(input)\n\n if (isEmpty(input)) {\n this.valid = false\n } else if (smallerThan(input, 1)) {\n this.valid = false\n } else if (biggerThan(input, 31)) {\n this.valid = false\n } else {\n input.success = true\n }\n }", "function checkDateInput() {\n\tlet input = document.createElement( 'input' );\n\tinput.type = 'date';\n\n\tconst invalidDate = 'invalid-date';\n\tinput.value = invalidDate;\n\n\treturn invalidDate !== input.value;\n}", "function dateIsValid(req, res, next) {\n const { reservation_date } = req.body.data;\n const date = Date.parse(reservation_date);\n if (date && date > 0) {\n return next();\n } else {\n return next({\n status: 400,\n message: `reservation_date field formatted incorrectly: ${reservation_date}.`,\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate a 32bit thumb instruction. Returns nonzero if the instruction is not legal.
function disas_thumb2_insn(/* CPUARMState * */ env, /* DisasContext * */ s, /* uint16_t */ insn_hw1) { var /* uint32_t */ insn, imm, shift, offset, addr; var /* uint32_t */ rd, rn, rm, rs; var op; var shiftop; var conds; var logic_cc; if (!(arm_feature(env, ARM_FEATURE_THUMB2) || arm_feature (env, ARM_FEATURE_M))) { /* Thumb-1 cores may need to tread bl and blx as a pair of 16-bit instructions to get correct prefetch abort behavior. */ insn = insn_hw1; if ((insn & (1 << 12)) == 0) { /* Second half of blx. */ offset = ((insn & 0x7ff) << 1); gen_movl_T0_reg(s, 14); gen_op_movl_T1_im(offset); gen_op_addl_T0_T1(); gen_op_movl_T1_im(0xfffffffc); gen_op_andl_T0_T1(); addr = s.pc >>> 0; gen_op_movl_T1_im(addr | 1); gen_movl_reg_T1(s, 14); gen_bx(s); return 0; } if (insn & (1 << 11)) { /* Second half of bl. */ offset = ((insn & 0x7ff) << 1) | 1; gen_movl_T0_reg(s, 14); gen_op_movl_T1_im(offset); gen_op_addl_T0_T1(); addr = s.pc; gen_op_movl_T1_im(addr | 1); gen_movl_reg_T1(s, 14); gen_bx(s); return 0; } if ((s.pc & ~~((1 << 10) - 1)) == 0) { /* Instruction spans a page boundary. Implement it as two 16-bit instructions in case the second half causes an prefetch abort. */ offset = ( insn << 21) >> 9; addr = s.pc + 2 + offset; gen_op_movl_T0_im(addr); gen_movl_reg_T0(s, 14); return 0; } /* Fall through to 32-bit decode. */ } insn = lduw_code(s.pc); s.pc += 2; insn |= insn_hw1 << 16; if ((insn & 0xf800e800) != 0xf000e800) { if (!arm_feature(env, ARM_FEATURE_THUMB2)) return 1; } rn = (insn >> 16) & 0xf; rs = (insn >> 12) & 0xf; rd = (insn >> 8) & 0xf; rm = insn & 0xf; switch ((insn >> 25) & 0xf) { case 0: case 1: case 2: case 3: /* 16-bit instructions. Should never happen. */ abort(); case 4: if (insn & (1 << 22)) { /* Other load/store, table branch. */ if (insn & 0x01200000) { /* Load/store doubleword. */ if (rn == 15) { gen_op_movl_T1_im(s.pc & ~3); } else { gen_movl_T1_reg(s, rn); } offset = (insn & 0xff) * 4; if ((insn & (1 << 23)) == 0) offset = -offset; if (insn & (1 << 24)) { gen_op_addl_T1_im(offset); offset = 0; } if (insn & (1 << 20)) { /* ldrd */ do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); gen_movl_reg_T0(s, rs); gen_op_addl_T1_im(4); do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); gen_movl_reg_T0(s, rd); } else { /* strd */ gen_movl_T0_reg(s, rs); do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); gen_op_addl_T1_im(4); gen_movl_T0_reg(s, rd); do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); } if (insn & (1 << 21)) { /* Base writeback. */ if (rn == 15) return 1; gen_op_addl_T1_im(offset - 4); gen_movl_reg_T1(s, rn); } } else if ((insn & (1 << 23)) == 0) { /* Load/store exclusive word. */ gen_movl_T0_reg(s, rd); gen_movl_T1_reg(s, rn); if (insn & (1 << 20)) { do { s.is_mem = 1; if ((s.user)) gen_op_ldlex_user(); else gen_op_ldlex_kernel(); } while (0); } else { do { s.is_mem = 1; if ((s.user)) gen_op_stlex_user(); else gen_op_stlex_kernel(); } while (0); } gen_movl_reg_T0(s, rd); } else if ((insn & (1 << 6)) == 0) { /* Table Branch. */ if (rn == 15) { gen_op_movl_T1_im(s.pc); } else { gen_movl_T1_reg(s, rn); } gen_movl_T2_reg(s, rm); gen_op_addl_T1_T2(); if (insn & (1 << 4)) { /* tbh */ gen_op_addl_T1_T2(); do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0); } else { /* tbb */ do { s.is_mem = 1; if ((s.user)) gen_op_ldub_user(); else gen_op_ldub_kernel(); } while (0); } gen_op_jmp_T0_im(s.pc); s.is_jmp = 1; } else { /* Load/store exclusive byte/halfword/doubleword. */ op = (insn >> 4) & 0x3; gen_movl_T1_reg(s, rn); if (insn & (1 << 20)) { switch (op) { case 0: do { s.is_mem = 1; if ((s.user)) gen_op_ldbex_user(); else gen_op_ldbex_kernel(); } while (0); break; case 1: do { s.is_mem = 1; if ((s.user)) gen_op_ldwex_user(); else gen_op_ldwex_kernel(); } while (0); break; case 3: do { s.is_mem = 1; if ((s.user)) gen_op_ldqex_user(); else gen_op_ldqex_kernel(); } while (0); gen_movl_reg_T1(s, rd); break; default: return 1; } gen_movl_reg_T0(s, rs); } else { gen_movl_T0_reg(s, rs); switch (op) { case 0: do { s.is_mem = 1; if ((s.user)) gen_op_stbex_user(); else gen_op_stbex_kernel(); } while (0); break; case 1: do { s.is_mem = 1; if ((s.user)) gen_op_stwex_user(); else gen_op_stwex_kernel(); } while (0); break; case 3: gen_movl_T2_reg(s, rd); do { s.is_mem = 1; if ((s.user)) gen_op_stqex_user(); else gen_op_stqex_kernel(); } while (0); break; default: return 1; } gen_movl_reg_T0(s, rm); } } } else { /* Load/store multiple, RFE, SRS. */ if (((insn >> 23) & 1) == ((insn >> 24) & 1)) { /* Not available in user mode. */ if (!(s.user)) return 1; if (insn & (1 << 20)) { /* rfe */ gen_movl_T1_reg(s, rn); if (insn & (1 << 24)) { gen_op_addl_T1_im(4); } else { gen_op_addl_T1_im(-4); } /* Load CPSR into T2 and PC into T0. */ do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); gen_op_movl_T2_T0(); gen_op_addl_T1_im(-4); do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); if (insn & (1 << 21)) { /* Base writeback. */ if (insn & (1 << 24)) gen_op_addl_T1_im(8); gen_movl_reg_T1(s, rn); } gen_rfe(s); } else { /* srs */ op = (insn & 0x1f); if (op == (env.uncached_cpsr & (0x1f))) { gen_movl_T1_reg(s, 13); } else { gen_op_movl_T1_r13_banked(op); } if ((insn & (1 << 24)) == 0) { gen_op_addl_T1_im(-8); } gen_movl_T0_reg(s, 14); do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); gen_op_movl_T0_cpsr(); gen_op_addl_T1_im(4); do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); if (insn & (1 << 21)) { if ((insn & (1 << 24)) == 0) { gen_op_addl_T1_im(-4); } else { gen_op_addl_T1_im(4); } if (op == (env.uncached_cpsr & (0x1f))) { gen_movl_reg_T1(s, 13); } else { gen_op_movl_r13_T1_banked(op); } } } } else { var i; /* Load/store multiple. */ gen_movl_T1_reg(s, rn); offset = 0; for (i = 0; i < 16; i++) { if (insn & (1 << i)) offset += 4; } if (insn & (1 << 24)) { gen_op_addl_T1_im(-offset); } for (i = 0; i < 16; i++) { if ((insn & (1 << i)) == 0) continue; if (insn & (1 << 20)) { /* Load. */ do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); if (i == 15) { gen_bx(s); } else { gen_movl_reg_T0(s, i); } } else { /* Store. */ gen_movl_T0_reg(s, i); do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); } gen_op_addl_T1_im(4); } if (insn & (1 << 21)) { /* Base register writeback. */ if (insn & (1 << 24)) { gen_op_addl_T1_im(-offset); } /* Fault if writeback register is in register list. */ if (insn & (1 << rn)) return 1; gen_movl_reg_T1(s, rn); } } } break; case 5: /* Data processing register constant shift. */ if (rn == 15) gen_op_movl_T0_im(0); else gen_movl_T0_reg(s, rn); gen_movl_T1_reg(s, rm); op = (insn >> 21) & 0xf; shiftop = (insn >> 4) & 3; shift = ((insn >> 6) & 3) | ((insn >> 10) & 0x1c); conds = (insn & (1 << 20)) != 0; logic_cc = (conds && thumb2_logic_op(op)); if (shift != 0) { if (logic_cc) { gen_shift_T1_im_cc[shiftop](shift); } else { gen_shift_T1_im[shiftop](shift); } } else if (shiftop != 0) { if (logic_cc) { gen_shift_T1_0_cc[shiftop](); } else { gen_shift_T1_0[shiftop](); } } if (gen_thumb2_data_op(s, op, conds, 0)) return 1; if (rd != 15) gen_movl_reg_T0(s, rd); break; case 13: /* Misc data processing. */ op = ((insn >> 22) & 6) | ((insn >> 7) & 1); if (op < 4 && (insn & 0xf000) != 0xf000) return 1; switch (op) { case 0: /* Register controlled shift. */ gen_movl_T0_reg(s, rm); gen_movl_T1_reg(s, rn); if ((insn & 0x70) != 0) return 1; op = (insn >> 21) & 3; if (insn & (1 << 20)) { gen_shift_T1_T0_cc[op](); gen_op_logic_T1_cc(); } else { gen_shift_T1_T0[op](); } gen_movl_reg_T1(s, rd); break; case 1: /* Sign/zero extend. */ gen_movl_T1_reg(s, rm); shift = (insn >> 4) & 3; /* ??? In many cases it's not neccessary to do a rotate, a shift is sufficient. */ if (shift != 0) gen_op_rorl_T1_im(shift * 8); op = (insn >> 20) & 7; switch (op) { case 0: gen_op_sxth_T1(); break; case 1: gen_op_uxth_T1(); break; case 2: gen_op_sxtb16_T1(); break; case 3: gen_op_uxtb16_T1(); break; case 4: gen_op_sxtb_T1(); break; case 5: gen_op_uxtb_T1(); break; default: return 1; } if (rn != 15) { gen_movl_T2_reg(s, rn); if ((op >> 1) == 1) { gen_op_add16_T1_T2(); } else { gen_op_addl_T1_T2(); } } gen_movl_reg_T1(s, rd); break; case 2: /* SIMD add/subtract. */ op = (insn >> 20) & 7; shift = (insn >> 4) & 7; if ((op & 3) == 3 || (shift & 3) == 3) return 1; gen_movl_T0_reg(s, rn); gen_movl_T1_reg(s, rm); gen_thumb2_parallel_addsub[op][shift](); gen_movl_reg_T0(s, rd); break; case 3: /* Other data processing. */ op = ((insn >> 17) & 0x38) | ((insn >> 4) & 7); if (op < 4) { /* Saturating add/subtract. */ gen_movl_T0_reg(s, rm); gen_movl_T1_reg(s, rn); if (op & 2) gen_op_double_T1_saturate(); if (op & 1) gen_op_subl_T0_T1_saturate(); else gen_op_addl_T0_T1_saturate(); } else { gen_movl_T0_reg(s, rn); switch (op) { case 0x0a: /* rbit */ gen_op_rbit_T0(); break; case 0x08: /* rev */ gen_op_rev_T0(); break; case 0x09: /* rev16 */ gen_op_rev16_T0(); break; case 0x0b: /* revsh */ gen_op_revsh_T0(); break; case 0x10: /* sel */ gen_movl_T1_reg(s, rm); gen_op_sel_T0_T1(); break; case 0x18: /* clz */ gen_op_clz_T0(); break; default: return 1; } } gen_movl_reg_T0(s, rd); break; case 4: case 5: /* 32-bit multiply. Sum of absolute differences. */ op = (insn >> 4) & 0xf; gen_movl_T0_reg(s, rn); gen_movl_T1_reg(s, rm); switch ((insn >> 20) & 7) { case 0: /* 32 x 32 -> 32 */ gen_op_mul_T0_T1(); if (rs != 15) { gen_movl_T1_reg(s, rs); if (op) gen_op_rsbl_T0_T1(); else gen_op_addl_T0_T1(); } gen_movl_reg_T0(s, rd); break; case 1: /* 16 x 16 -> 32 */ gen_mulxy(op & 2, op & 1); if (rs != 15) { gen_movl_T1_reg(s, rs); gen_op_addl_T0_T1_setq(); } gen_movl_reg_T0(s, rd); break; case 2: /* Dual multiply add. */ case 4: /* Dual multiply subtract. */ if (op) gen_op_swap_half_T1(); gen_op_mul_dual_T0_T1(); /* This addition cannot overflow. */ if (insn & (1 << 22)) { gen_op_subl_T0_T1(); } else { gen_op_addl_T0_T1(); } if (rs != 15) { gen_movl_T1_reg(s, rs); gen_op_addl_T0_T1_setq(); } gen_movl_reg_T0(s, rd); break; case 3: /* 32 * 16 -> 32msb */ if (op) gen_op_sarl_T1_im(16); else gen_op_sxth_T1(); gen_op_imulw_T0_T1(); if (rs != 15) { gen_movl_T1_reg(s, rs); gen_op_addl_T0_T1_setq(); } gen_movl_reg_T0(s, rd); break; case 5: case 6: /* 32 * 32 -> 32msb */ gen_op_imull_T0_T1(); if (insn & (1 << 5)) gen_op_roundqd_T0_T1(); else gen_op_movl_T0_T1(); if (rs != 15) { gen_movl_T1_reg(s, rs); if (insn & (1 << 21)) { gen_op_addl_T0_T1(); } else { gen_op_rsbl_T0_T1(); } } gen_movl_reg_T0(s, rd); break; case 7: /* Unsigned sum of absolute differences. */ gen_op_usad8_T0_T1(); if (rs != 15) { gen_movl_T1_reg(s, rs); gen_op_addl_T0_T1(); } gen_movl_reg_T0(s, rd); break; } break; case 6: case 7: /* 64-bit multiply, Divide. */ op = ((insn >> 4) & 0xf) | ((insn >> 16) & 0x70); gen_movl_T0_reg(s, rn); gen_movl_T1_reg(s, rm); if ((op & 0x50) == 0x10) { /* sdiv, udiv */ if (!arm_feature(env, ARM_FEATURE_DIV)) return 1; if (op & 0x20) gen_op_udivl_T0_T1(); else gen_op_sdivl_T0_T1(); gen_movl_reg_T0(s, rd); } else if ((op & 0xe) == 0xc) { /* Dual multiply accumulate long. */ if (op & 1) gen_op_swap_half_T1(); gen_op_mul_dual_T0_T1(); if (op & 0x10) { gen_op_subl_T0_T1(); } else { gen_op_addl_T0_T1(); } gen_op_signbit_T1_T0(); gen_op_addq_T0_T1(rs, rd); gen_movl_reg_T0(s, rs); gen_movl_reg_T1(s, rd); } else { if (op & 0x20) { /* Unsigned 64-bit multiply */ gen_op_mull_T0_T1(); } else { if (op & 8) { /* smlalxy */ gen_mulxy(op & 2, op & 1); gen_op_signbit_T1_T0(); } else { /* Signed 64-bit multiply */ gen_op_imull_T0_T1(); } } if (op & 4) { /* umaal */ gen_op_addq_lo_T0_T1(rs); gen_op_addq_lo_T0_T1(rd); } else if (op & 0x40) { /* 64-bit accumulate. */ gen_op_addq_T0_T1(rs, rd); } gen_movl_reg_T0(s, rs); gen_movl_reg_T1(s, rd); } break; } break; case 6: case 7: case 14: case 15: /* Coprocessor. */ if (((insn >> 24) & 3) == 3) { /* Translate into the equivalent ARM encoding. */ insn = (insn & 0xe2ffffff) | ((insn & (1 << 28)) >> 4); if (disas_neon_data_insn(env, s, insn)) return 1; } else { if (insn & (1 << 28)) return 1; if (disas_coproc_insn (env, s, insn)) return 1; } break; case 8: case 9: case 10: case 11: if (insn & (1 << 15)) { /* Branches, misc control. */ if (insn & 0x5000) { /* Unconditional branch. */ /* signextend(hw1[10:0]) -> offset[:12]. */ offset = (insn << 5) >> 9 & ~0xfff; /* hw1[10:0] -> offset[11:1]. */ offset |= (insn & 0x7ff) << 1; /* (~hw2[13, 11] ^ offset[24]) -> offset[23,22] offset[24:22] already have the same value because of the sign extension above. */ offset ^= ((~insn) & (1 << 13)) << 10; offset ^= ((~insn) & (1 << 11)) << 11; addr = s.pc; if (insn & (1 << 14)) { /* Branch and link. */ gen_op_movl_T1_im(addr | 1); gen_movl_reg_T1(s, 14); } addr += offset; if (insn & (1 << 12)) { /* b/bl */ gen_jmp(s, addr); } else { /* blx */ addr &= ~2; gen_op_movl_T0_im(addr); gen_bx(s); } } else if (((insn >> 23) & 7) == 7) { /* Misc control */ if (insn & (1 << 13)) return 1; if (insn & (1 << 26)) { /* Secure monitor call (v6Z) */ return 1; /* not implemented. */ } else { op = (insn >> 20) & 7; switch (op) { case 0: /* msr cpsr. */ if (arm_feature(env, ARM_FEATURE_M)) { gen_op_v7m_msr_T0(insn & 0xff); gen_movl_reg_T0(s, rn); gen_lookup_tb(s); break; } /* fall through */ case 1: /* msr spsr. */ if (arm_feature(env, ARM_FEATURE_M)) return 1; gen_movl_T0_reg(s, rn); if (gen_set_psr_T0(s, msr_mask(env, s, (insn >> 8) & 0xf, op == 1), op == 1)) return 1; break; case 2: /* cps, nop-hint. */ if (((insn >> 8) & 7) == 0) { gen_nop_hint(s, insn & 0xff); } /* Implemented as NOP in user mode. */ if ((s.user)) break; offset = 0; imm = 0; if (insn & (1 << 10)) { if (insn & (1 << 7)) offset |= (1 << 8); if (insn & (1 << 6)) offset |= (1 << 7); if (insn & (1 << 5)) offset |= (1 << 6); if (insn & (1 << 9)) imm = (1 << 8) | (1 << 7) | (1 << 6); } if (insn & (1 << 8)) { offset |= 0x1f; imm |= (insn & 0x1f); } if (offset) { gen_op_movl_T0_im(imm); gen_set_psr_T0(s, offset, 0); } break; case 3: /* Special control operations. */ op = (insn >> 4) & 0xf; switch (op) { case 2: /* clrex */ gen_op_clrex(); break; case 4: /* dsb */ case 5: /* dmb */ case 6: /* isb */ /* These execute as NOPs. */ if (!arm_feature(env, ARM_FEATURE_V7)) return 1; break; default: return 1; } break; case 4: /* bxj */ /* Trivial implementation equivalent to bx. */ gen_movl_T0_reg(s, rn); gen_bx(s); break; case 5: /* Exception return. */ /* Unpredictable in user mode. */ return 1; case 6: /* mrs cpsr. */ if (arm_feature(env, ARM_FEATURE_M)) { gen_op_v7m_mrs_T0(insn & 0xff); } else { gen_op_movl_T0_cpsr(); } gen_movl_reg_T0(s, rd); break; case 7: /* mrs spsr. */ /* Not accessible in user mode. */ if ((s.user) || arm_feature(env, ARM_FEATURE_M)) return 1; gen_op_movl_T0_spsr(); gen_movl_reg_T0(s, rd); break; } } } else { /* Conditional branch. */ op = (insn >> 22) & 0xf; /* Generate a conditional jump to next instruction. */ s.condlabel = gen_new_label(); gen_test_cc[op ^ 1](s.condlabel); s.condjmp = 1; /* offset[11:1] = insn[10:0] */ offset = (insn & 0x7ff) << 1; /* offset[17:12] = insn[21:16]. */ offset |= (insn & 0x003f0000) >> 4; /* offset[31:20] = insn[26]. */ offset |= (/* (int32_t) */((insn << 5) & 0x80000000)) >> 11; /* offset[18] = insn[13]. */ offset |= (insn & (1 << 13)) << 5; /* offset[19] = insn[11]. */ offset |= (insn & (1 << 11)) << 8; /* jump to the offset */ addr = s.pc + offset; gen_jmp(s, addr); } } else { /* Data processing immediate. */ if (insn & (1 << 25)) { if (insn & (1 << 24)) { if (insn & (1 << 20)) return 1; /* Bitfield/Saturate. */ op = (insn >> 21) & 7; imm = insn & 0x1f; shift = ((insn >> 6) & 3) | ((insn >> 10) & 0x1c); if (rn == 15) gen_op_movl_T1_im(0); else gen_movl_T1_reg(s, rn); switch (op) { case 2: /* Signed bitfield extract. */ imm++; if (shift + imm > 32) return 1; if (imm < 32) gen_op_sbfx_T1(shift, imm); break; case 6: /* Unsigned bitfield extract. */ imm++; if (shift + imm > 32) return 1; if (imm < 32) gen_op_ubfx_T1(shift, (1/* u */ << imm) - 1); break; case 3: /* Bitfield insert/clear. */ if (imm < shift) return 1; imm = imm + 1 - shift; if (imm != 32) { gen_movl_T0_reg(s, rd); gen_op_bfi_T1_T0(shift, ((1/* u*/ << imm) - 1) << shift); } break; case 7: return 1; default: /* Saturate. */ gen_movl_T1_reg(s, rn); if (shift) { if (op & 1) gen_op_sarl_T1_im(shift); else gen_op_shll_T1_im(shift); } if (op & 4) { /* Unsigned. */ gen_op_ssat_T1(imm); if ((op & 1) && shift == 0) gen_op_usat16_T1(imm); else gen_op_usat_T1(imm); } else { /* Signed. */ gen_op_ssat_T1(imm); if ((op & 1) && shift == 0) gen_op_ssat16_T1(imm); else gen_op_ssat_T1(imm); } break; } gen_movl_reg_T1(s, rd); } else { imm = ((insn & 0x04000000) >> 15) | ((insn & 0x7000) >> 4) | (insn & 0xff); if (insn & (1 << 22)) { /* 16-bit immediate. */ imm |= (insn >> 4) & 0xf000; if (insn & (1 << 23)) { /* movt */ gen_movl_T0_reg(s, rd); gen_op_movtop_T0_im(imm << 16); } else { /* movw */ gen_op_movl_T0_im(imm); } } else { /* Add/sub 12-bit immediate. */ if (rn == 15) { addr = s.pc & ~3; if (insn & (1 << 23)) addr -= imm; else addr += imm; gen_op_movl_T0_im(addr); } else { gen_movl_T0_reg(s, rn); gen_op_movl_T1_im(imm); if (insn & (1 << 23)) gen_op_subl_T0_T1(); else gen_op_addl_T0_T1(); } } gen_movl_reg_T0(s, rd); } } else { var shifter_out = 0; /* modified 12-bit immediate. */ shift = ((insn & 0x04000000) >> 23) | ((insn & 0x7000) >> 12); imm = (insn & 0xff); switch (shift) { case 0: /* XY */ /* Nothing to do. */ break; case 1: /* 00XY00XY */ imm |= imm << 16; break; case 2: /* XY00XY00 */ imm |= imm << 16; imm <<= 8; break; case 3: /* XYXYXYXY */ imm |= imm << 16; imm |= imm << 8; break; default: /* Rotated constant. */ shift = (shift << 1) | (imm >> 7); imm |= 0x80; imm = imm << (32 - shift); shifter_out = 1; break; } gen_op_movl_T1_im(imm); rn = (insn >> 16) & 0xf; if (rn == 15) gen_op_movl_T0_im(0); else gen_movl_T0_reg(s, rn); op = (insn >> 21) & 0xf; if (gen_thumb2_data_op(s, op, (insn & (1 << 20)) != 0, shifter_out)) return 1; rd = (insn >> 8) & 0xf; if (rd != 15) { gen_movl_reg_T0(s, rd); } } } break; case 12: /* Load/store single data item. */ { var postinc = 0; var writeback = 0; if ((insn & 0x01100000) == 0x01000000) { if (disas_neon_ls_insn(env, s, insn)) return 1; break; } if (rn == 15) { /* PC relative. */ /* s.pc has already been incremented by 4. */ imm = s.pc & 0xfffffffc; if (insn & (1 << 23)) imm += insn & 0xfff; else imm -= insn & 0xfff; gen_op_movl_T1_im(imm); } else { gen_movl_T1_reg(s, rn); if (insn & (1 << 23)) { /* Positive offset. */ imm = insn & 0xfff; gen_op_addl_T1_im(imm); } else { op = (insn >> 8) & 7; imm = insn & 0xff; switch (op) { case 0: case 8: /* Shifted Register. */ shift = (insn >> 4) & 0xf; if (shift > 3) return 1; gen_movl_T2_reg(s, rm); if (shift) gen_op_shll_T2_im(shift); gen_op_addl_T1_T2(); break; case 4: /* Negative offset. */ gen_op_addl_T1_im(-imm); break; case 6: /* User privilege. */ gen_op_addl_T1_im(imm); break; case 1: /* Post-decrement. */ imm = -imm; /* Fall through. */ case 3: /* Post-increment. */ gen_op_movl_T2_im(imm); postinc = 1; writeback = 1; break; case 5: /* Pre-decrement. */ imm = -imm; /* Fall through. */ case 7: /* Pre-increment. */ gen_op_addl_T1_im(imm); writeback = 1; break; default: return 1; } } } op = ((insn >> 21) & 3) | ((insn >> 22) & 4); if (insn & (1 << 20)) { /* Load. */ if (rs == 15 && op != 2) { if (op & 2) return 1; /* Memory hint. Implemented as NOP. */ } else { switch (op) { case 0: do { s.is_mem = 1; if ((s.user)) gen_op_ldub_user(); else gen_op_ldub_kernel(); } while (0); break; case 4: do { s.is_mem = 1; if ((s.user)) gen_op_ldsb_user(); else gen_op_ldsb_kernel(); } while (0); break; case 1: do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0); break; case 5: do { s.is_mem = 1; if ((s.user)) gen_op_ldsw_user(); else gen_op_ldsw_kernel(); } while (0); break; case 2: do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0); break; default: return 1; } if (rs == 15) { gen_bx(s); } else { gen_movl_reg_T0(s, rs); } } } else { /* Store. */ if (rs == 15) return 1; gen_movl_T0_reg(s, rs); switch (op) { case 0: do { s.is_mem = 1; if ((s.user)) gen_op_stb_user(); else gen_op_stb_kernel(); } while (0); break; case 1: do { s.is_mem = 1; if ((s.user)) gen_op_stw_user(); else gen_op_stw_kernel(); } while (0); break; case 2: do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0); break; default: return 1; } } if (postinc) gen_op_addl_T1_im(imm); if (writeback) gen_movl_reg_T1(s, rn); } break; default: return 1; } return 0; }
[ "function castToI32(lctx) {\n const currentType = currentTempType(lctx);\n if (currentType === 'i32') {\n return '';\n }\n\n if (currentType === 'i1') {\n const currentName = currentTempName(lctx);\n const castedName = nextTempName(lctx);\n const castBlock = TAB() + castedName + ' = zext i1 ' + currentName + ' to i32 ;cast i1 to i32' + LF();\n return castBlock; \n }\n\n /*\n if (currentType === 'i8*') {\n const castedName = nextTempName(lctx);\n const castBlock = TAB() + castedName + ' = or i32 255, 255 ;-- dummy value for casting i8* to i32 --' + LF();\n return castBlock;\n }\n */\n\n if (currentType === 'void') {\n const castedName = nextTempName(lctx);\n const castBlock = TAB() + castedName + ' = or i32 254, 254 ;-- dummy value for casting void to i32 --' + LF();\n return castBlock;\n }\n\n println('-- ERROR: unknown type in castToI32() ---');\n printObj(currentType);\n abort();\n}", "function toUnit32(key) {\n return Math.floor(Math.abs(Number(key)) % Math.pow(2, 32))\n}", "function int32LE(i) {\n return String.fromCharCode(\n i & 0xFF,\n i >>> 8 & 0xFF,\n i >>> 16 & 0xFF,\n i >>> 24 & 0xFF\n );\n }", "function ROTR32 (x, y) {\n return (x >>> y) ^ (x << (32 - y))\n }", "function Low32Bits(n) {\n var result = n & 0x7fffffff;\n\n if (n & 0x80000000) {\n result += 0x80000000;\n }\n\n return result;\n}", "function add32(a, b) {\n return ((a + b) & ~0) >>> 0;\n}", "load32(offset) {\n const rotate = (offset & 3) << 3;\n const mem = this.view.getInt32(offset & this.mask32, true);\n return (mem >>> rotate) | (mem << (32 - rotate));\n }", "function u32(a,o) {\n return i32(a,0);\n}", "function ROTR32 (x, y) {\n return (x >>> y) ^ (x << (32 - y))\n}", "function I_MOVES_32(p) { /* >= 68010 */\n\t\tif (regs.s) {\n\t\t\tvar args = coreNext16();\n\t\t\t//SAEF_log((\"I_MOVES.L %04x\", args));\n\t\t\tif (args & 0x800) {\n\t\t\t\tvar s = (args & 0x8000) ? regs.a[(args >> 12) & 7] : regs.d[(args >> 12) & 7];\n\t\t\t\tstEA32tab[p.ea](s);\n\t\t\t} else {\n\t\t\t\tif (args & 0x8000) regs.a[(args >> 12) & 7] = ldEA32tab[p.ea]();\n\t\t\t\telse regs.d[(args >> 12) & 7] = ldEA32tab[p.ea]();\n\t\t\t}\n\t\t\t//ccna\n\t\t\tcoreSyncPC();\n\t\t\treturn p.cyc;\n\t\t} else {\n\t\t\t//SAEF_log(\"I_MOVES PRIVILIG VIOLATION\");\n\t\t\t//coreClrPC();\n\t\t\treturn coreException(8);\n\t\t}\n\t}", "function unsigned32Add(){\n\treturn Array.from(arguments).reduce(function (a, b){\n\t\treturn ((a >>> 0) + (b >>> 0)) >>> 0;\n\t}, 0);\n}", "function muls32(x, y) {\n var neg = false;\n if (x < 0) {\n x = -x;\n neg = true;\n }\n if (y < 0) {\n y = -y;\n neg = !neg;\n }\n\n var res = mul32(x, y);\n\n if (neg)\n res = neg64(res);\n\n return res;\n }", "function ToInt32(v) { return v >> 0; }", "function swap32(val) {\r\n return (((val & 0xFF) << 24)\r\n | ((val & 0xFF00) << 8)\r\n | ((val >> 8) & 0xFF00)\r\n | ((val >> 24) & 0xFF)) >>> 0;\r\n}", "function CRC32Step(old, ch) {\n return CRC32.table[(old ^ ch) & 0xff] ^ (old >>> 8);\n}", "function ToUint32(v) { return v >>> 0; }", "function iptoInt32(ip){\n \n}", "function swap32(val) {\n return ((val & 0xFF) << 24)\n | ((val & 0xFF00) << 8)\n | ((val >> 8) & 0xFF00)\n | ((val >> 24) & 0xFF);\n }", "function readInt32() {\n const result =\n (readByte() << 24)\n + (readByte() << 16)\n + (readByte() << 8)\n + readByte()\n return result\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event for when the user alters the theme selector.
function themeSelectChange(event) { Common.setTheme(event.target.value); }
[ "function themeChangedEventListener(event)\r\n{ \r\n\tchangeThemeColor();\r\n}", "function onThemeSelected(){\n setTheme(dropdown.value);\n}", "function themeSelectMenu() {\n $(\"#zenTheme\").on('change', function() {\n setTheme($(this).val());\n });\n }", "function themeChanged() { if (extSearchUI) extSearchUI.themeChanged(true); }", "function themeSelector() {\r\n\tstopUpdateFunction();\r\n\t$.mobile.changePage(\r\n\t\t\"themeselector.html#themeselectpage\",\r\n\t {\r\n\t transition \t: 'pop',\r\n\t reverse\t\t\t: true\r\n\t }\r\n\t);\r\n\tresetCanvas();\r\n}", "function handleThemeChange(e) {\n dispatch(changeTheme());\n }", "function themeChange() {\n if (document.documentElement.hasAttribute('theme')) {\n document.documentElement.removeAttribute('theme');\n }\n else {\n document.documentElement.setAttribute('theme', 'adult');\n }\n}", "applySavedTheme() {\n if (this.savedTheme) {\n this.body.setAttribute('data-bs-theme', this.savedTheme);\n if (this.savedTheme === 'dark') {\n this.toggleBtn.checked = true;\n }\n }\n\n this.toggleBtn.addEventListener('change', () => {\n this.toggleTheme()\n });\n\n this.toggleBtn.addEventListener('keydown', ( keyboardEvent ) => {\n switch (keyboardEvent.key) {\n case 'Enter':\n case 'Space':\n keyboardEvent.preventDefault();\n this.toggleTheme()\n break;\n }\n });\n }", "function setTheme() {\n // get the data template of the active note\n const activeNoteTemplate = document.querySelector('.active-note').dataset.template\n\n // set the value of the select element in the toolbar to the current theme\n if (activeNoteTemplate == 'undefined') {\n selectTheme.value = 'reset';\n } else {\n selectTheme.value = activeNoteTemplate;\n }\n}", "[osThemeUpdateHandler]() {\n const info = this.generateSystemThemeInfo();\n this.arcApp.wm.notifyAll('system-theme-changed', info);\n }", "function themeChanger(theme) {\n setTheme(theme)\n setAppearanceDisplay(!appearanceDisplay)\n }", "function onThemeLabelChanged() {\n\n //Find the current theme level, if any\n var level = $rootScope.level; //set in drawoverlays\n\n if(!level) return; //no theme\n\n var layer = overlays_dictionary[\"gadm\" + level];\n\n if (layer) {\n redrawThemeLayers(layer);\n }\n\n }", "function resetThemeSelection(){\n\n $(\"#color option\").css('display','none');\n $('#color').val('first');\n\n}", "_onNewThemePurchased() {\n const themeSelector = this.shadowRoot.getElementById('theme-select');\n const e = new CustomEvent('color-purchased', {\n detail: {\n selectedColor: themeSelector.value,\n },\n bubbles: true,\n composed: true,\n });\n this.dispatchEvent(e);\n }", "ChangeThemeTagShow() {\n $('#Theme option[value=' + _Value_.GetTheme() + ']').attr(\"selected\", true);\n }", "function onThemeSelect () {\n $('#selectTheme').on('change', event => {\n currentTheme = event.target.value;\n\n initQuestionsView();\n openQuestionsView();\n\n });\n}", "changeTheme() {\n let isDay = this.isDay()\n if (isDay === this.wasDay) return\n\n if (isDay) {\n this.scheduleThemeUpdate(['atom-material-ui',\n 'atom-material-syntax-light'])\n } else {\n this.scheduleThemeUpdate(['atom-material-ui',\n 'atom-material-syntax'])\n }\n\n this.wasDay = isDay\n }", "nextTheme() {\n this.currentTheme = (this.currentTheme + 1) % this.themes.length;\n\n document.dispatchEvent(new CustomEvent('ThemeChanged', {\n detail: window.themePresets[this.themes[this.currentTheme]],\n }));\n }", "function changeTheme(name) {\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
func: delete_load desc: Deletes load w/ load_id
function delete_load (load_id) { const l_key = datastore.key( ['LOAD', parseInt(load_id, 10)] ); // Create key for ds entity deletion return datastore.delete(l_key); // Delete entity and return to calling function }
[ "function delete_load(load_id) {\n if (typeof(load_id) == \"string\")\n load_id = parseInt(load_id);\n var key = datastore.key([LOAD, load_id]);\n return datastore.delete(key).then(\n (entity) => { return {}; }\n );\n}", "function delete_loadFromBoat(boat_id, load_id){\n const loadKey = datastore.key([LOAD, parseInt(load_id,10)]);\n const boatKey = datastore.key([BOAT, parseInt(boat_id,10)]);\n return datastore.get(loadKey)\n .then( (load) => {\n if ( load[0].carrier === boat_id ) {\n load[0].carrier = null;\n }\n return datastore.get(boatKey)\n .then ( (boat) => {\n if ( boat[0].loads[0].includes(load_id) ) {\n boat[0].loads = null;\n }\n return datastore.save({\"key\":loadKey, \"data\":load[0]})\n .then(datastore.save({\"key\":boatKey, \"data\":boat[0]}));\n });\n });\n}", "async function remove_load(boat_id, load_id) {\n boat = await get_item_by_id(boat_id, BOAT);\n // remove the load from the boat.loads array\n for (var i = boat.loads.length - 1; i >= 0; i--) {\n if (boat.loads[i].key === load_id) {\n boat.loads.splice(i, 1);\n }\n }\n return boat.loads;\n}", "function remove_a_load(bid,lid){\n const key = datastore.key([LOADS, parseInt(lid,10)]);\n const q = datastore.createQuery(LOADS).filter('__key__','=', key);\n return datastore.runQuery(q).then( (entities) => {\n const loads = (entities[0].map(fromDatastore));\n if(loads[0].carrier === bid){\n const load_info ={'weight':loads[0].weight,'carrier':null, 'content':loads[0].content, 'delivery_date':loads[0].delivery_date};\n return datastore.update({\"key\":key, \"data\":load_info}).then(()=>{\n return key\n })\n }\n else{\n return null;\n }\n})\n}", "function delete_load_carrier(b_id, l_id){\r\n const l_key = datastore.key([LOAD, parseInt(l_id,10)]);\r\n const b_key = datastore.key([BOAT, parseInt(b_id,10)]);\r\n console.log(\"delete_load_carrier: b_id\" + JSON.stringify(b_id) + \"l_id\" + JSON.stringify(l_id))\r\n return datastore.get(l_key)\r\n .then( (load) => {\r\n console.log (\"delete_load_carrier: before deletion \"+JSON.stringify(load[0].carrier.id))\r\n load[0].carrier.id = null;\r\n console.log (\"delete_load_carrier . then after deletion load[0].carrier.id) \"+JSON.stringify(load[0].carrier.id))\r\n console.log (\"delete_load_carrier . then after deletion load[0]\"+JSON.stringify(load[0]))\r\n console.log (\"delete_load_carrier . then after deletion load\"+JSON.stringify(load))\r\n return datastore.save({\"key\":l_key, \"data\":load[0]});\r\n });\r\n\r\n}", "function delete_boat_load(b_id, l_id){\r\n const l_key = datastore.key([LOAD, parseInt(l_id,10)]);\r\n const b_key = datastore.key([BOAT, parseInt(b_id,10)]);\r\n console.log(\"delete_boat_load: b_id\" + JSON.stringify(b_id) + \"l_id\" + JSON.stringify(l_id))\r\n return datastore.get(b_key)\r\n .then( (boat) => {\r\n if( typeof(boat[0].loads) === 'undefined'){\r\n boat[0].loads = [];\r\n }\r\n boat[0].loads.push(l_id);\r\n console.log (\"delete_boat_load: boat[0].load \"+ boat[0].loads)\r\n const array = boat[0].loads;\r\n const valueToRemove = l_id;\r\n const filteredItems = array.filter((item) => item !== valueToRemove)\r\n boat[0].loads = filteredItems;\r\n console.log (\"delete_boat_load: boat[0].loads after deleting load \"+ boat[0].loads) \r\n return datastore.save({\"key\":b_key, \"data\":boat[0]});\r\n });\r\n}", "function delete_load_carrier(b_id, l_id){\r\n const l_key = datastore.key([LOAD, parseInt(l_id,10)]);\r\n const b_key = datastore.key([BOAT, parseInt(b_id,10)]);\r\n console.log(\"delete_load_carrier: b_id\" + JSON.stringify(b_id) + \"l_id\" + JSON.stringify(l_id))\r\n return datastore.get(l_key)\r\n .then( (load) => {\r\n console.log (\"delete_load_carrier: before deletion \"+JSON.stringify(load[0].carrier.id))\r\n load[0].carrier.id = null;\r\n console.log (\"delete_load_carrier . then after deletion load[0].carrier.id) \"+JSON.stringify(load[0].carrier.id))\r\n console.log (\"delete_load_carrier . then after deletion load[0]\"+JSON.stringify(load[0]))\r\n console.log (\"delete_load_carrier . then after deletion load\"+JSON.stringify(load[0]))\r\n return datastore.save({\"key\":l_key, \"data\":load[0]});\r\n }).catch((error)=>{\r\n console.log('In delete_load_carrier ' + error); \r\n res.status(404).send({\"Error\": \"Delete of carrier did not work\"});\r\n }); \r\n\r\n}", "removeLoad(loadEvent) {\n this._removeEvent(loadEvent, this.loadEvents);\n }", "function FinishLoad(loader, load) {\n var loaderData = GetLoaderInternalData(loader);\n\n //> 1. Let name be load.[[Name]].\n var name = load.name;\n\n //> 2. If name is not undefined, then\n if (name !== undefined) {\n //> 1. Assert: There is no Record {[[key]], [[value]]} p that is\n //> an element of loader.[[Modules]], such that p.[[key]] is\n //> equal to load.[[Name]].\n Assert(!callFunction(std_Map_has, loaderData.modules, name));\n\n //> 2. Append the Record {[[key]]: load.[[Name]], [[value]]:\n //> load.[[Module]]} as the last element of loader.[[Modules]].\n callFunction(std_Map_set, loaderData.modules, name, load.module);\n }\n\n //> 3. If load is an element of the List loader.[[Loads]], then\n var name = load.name;\n if (name !== undefined) {\n let currentLoad =\n callFunction(std_Map_get, loaderData.loads, name);\n if (currentLoad === load) {\n //> 1. Remove load from the List loader.[[Loads]].\n callFunction(std_Map_delete, loaderData.loads, name);\n }\n }\n\n //> 4. For each linkSet in load.[[LinkSets]],\n var linkSets = SetToArray(load.linkSets);\n for (var i = 0; i < linkSets.length; i++) {\n //> 1. Remove load from linkSet.[[Loads]].\n callFunction(std_Set_delete, linkSets[i].loads, load);\n }\n\n //> 5. Remove all elements from the List load.[[LinkSets]].\n callFunction(std_Set_clear, load.linkSets);\n}", "async deleteFlow (id) {\n await client.resource('arrow').remove(id)\n this.props.rehydrate()\n }", "async deleteRecord(recordId){if(!recordId){throw new Error(\"recordId must be provided\");}await _makeServerCall.call(this,recordId,\"RecordUiController.deleteRecord\",{recordId});const recordCacheKey=new RecordCacheKeyBuilder().setRecordId(recordId).build();this._ldsCache.evictAndDeleteObservable(recordCacheKey).then(()=>{this._ldsCache.clearDependencies(recordCacheKey);});}", "delete(id) {\n dbPouch.get(JSON.stringify(id)).then(function (doc) {\n dbPouch.remove(doc);\n db.loadAll();\n });\n\n\n }", "async function remove_carrier(lid){\r\n const lkey = datastore.key([LOAD, parseInt(lid, 10)]);\r\n\r\n const [load] = await datastore.get(lkey); \r\n\r\n // Remove boat information on load\r\n load.carrier = []; \r\n\r\n return datastore.save({\"key\":lkey, \"data\": load});\r\n}", "function clearLoadErrors (loader, load) {\n var state = loader[REGISTER_INTERNAL];\n\n // clear from loads\n if (state.records[load.key] === load)\n delete state.records[load.key];\n\n var link = load.linkRecord;\n\n if (!link)\n return;\n\n if (link.dependencyInstantiations)\n link.dependencyInstantiations.forEach(function (depLoad, index) {\n if (!depLoad || depLoad instanceof ModuleNamespace)\n return;\n\n if (depLoad.linkRecord) {\n if (depLoad.linkRecord.error) {\n // provides a circular reference check\n if (state.records[depLoad.key] === depLoad)\n clearLoadErrors(loader, depLoad);\n }\n\n // unregister setters for es dependency load records that will remain\n if (link.setters && depLoad.importerSetters) {\n var setterIndex = depLoad.importerSetters.indexOf(link.setters[index]);\n depLoad.importerSetters.splice(setterIndex, 1);\n }\n }\n });\n}", "function deleteRecord(id) {\n\t\ttaskTable.get(id).deleteRecord();\n\t}", "delete(arg) {\n return this.httpClient\n .url(`/ip_policies/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }", "delete(arg) {\n return this.httpClient\n .url(`/ip_policy_rules/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }", "function clearLoadErrors (loader, load) {\n // clear from loads\n if (loader[REGISTER_REGISTRY][load.key] === load)\n loader[REGISTER_REGISTRY][load.key] = undefined;\n\n var link = load.linkRecord;\n\n if (!link)\n return;\n\n if (link.dependencyInstantiations)\n link.dependencyInstantiations.forEach(function (depLoad, index) {\n if (!depLoad || depLoad instanceof Module)\n return;\n\n if (depLoad.linkRecord) {\n if (depLoad.linkRecord.error) {\n // provides a circular reference check\n if (loader[REGISTER_REGISTRY][depLoad.key] === depLoad)\n clearLoadErrors(loader, depLoad);\n }\n\n // unregister setters for es dependency load records that will remain\n if (link.setters && depLoad.importerSetters) {\n var setterIndex = depLoad.importerSetters.indexOf(link.setters[index]);\n depLoad.importerSetters.splice(setterIndex, 1);\n }\n }\n });\n}", "delete(arg) {\n return this.httpClient\n .url(`/ip_whitelist/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lumen price in terms of btc
function getLumenPrice() { return Promise.all([ rp('https://poloniex.com/public?command=returnTicker') .then(data => { return parseFloat(JSON.parse(data).BTC_STR.last); }) .catch(() => { return null; }) , rp('https://bittrex.com/api/v1.1/public/getticker?market=BTC-XLM') .then(data => { return parseFloat(JSON.parse(data).result.Last); }) .catch(() => { return null; }) , rp('https://api.kraken.com/0/public/Ticker?pair=XLMXBT') .then(data => { return parseFloat(JSON.parse(data).result.XXLMXXBT.c[0]); }) .catch(() => { return null; }) ]) .then(allPrices => { return _.round(_.mean(_.filter(allPrices, price => price !== null)), 8); }) }
[ "async function price() {\n const obj = await wallet.lcd.market.swapRate(new Terra.Coin('uluna', '1000000'), 'uusd');\n return parseFloat(obj.toData().amount) / DIVISOR;\n}", "function ltcDollar() {\n requestify.get('https://min-api.cryptocompare.com/data/price?fsym=LTC&tsyms=USD')\n .then(function(response) {\n var dol = response.getBody();\n answer.coinToDollar = dol.USD;\n done();\n }\n );\n }", "async btcPrice() {\n \n const response = await this.ctx.curl('https://api.coinmarketcap.com/v1/ticker/bitcoin/', {\n dataType: 'json',\n timeout: 1000 * 60\n });\n const data = response.data;\n const price = data[0] && data[0].price_usd || '--';\n return price;\n }", "function getLumenPrice() {\n return Promise.all([\n rp('https://poloniex.com/public?command=returnTicker')\n .then(data => {\n return parseFloat(JSON.parse(data).BTC_STR.last);\n })\n .catch(() => {\n return null;\n })\n ,\n rp('https://bittrex.com/api/v1.1/public/getticker?market=BTC-XLM')\n .then(data => {\n return parseFloat(JSON.parse(data).result.Last);\n })\n .catch(() => {\n return null;\n })\n ,\n rp('https://api.kraken.com/0/public/Ticker?pair=XLMXBT')\n .then(data => {\n return parseFloat(JSON.parse(data).result.XXLMXXBT.c[0]);\n })\n .catch(() => {\n return null;\n }),\n ])\n .then(allPrices => {\n let xlmPrice = _.round(_.mean(_.filter(allPrices, price => price !== null)), 8);\n TickerLogger.log('Phase 1: XLM price ' + xlmPrice + ' XLM/BTC');\n return xlmPrice;\n });\n}", "function btcDollar() {\n requestify.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')\n .then(function(response) {\n var dol = response.getBody();\n answer.coinToDollar = dol.USD;\n done();\n }\n );\n }", "function convertToBTCPrice(priceUSD){\n let BTCPrice = cmcArrayDict['btc'.toUpperCase()]['quote']['USD']['price'];\n return priceUSD / BTCPrice;\n}", "function getLPPrice() {\n var lpPrice;\n\n LPTokens.methods\n .totalSupply()\n .call()\n .then(function (lpTotal) {\n lpTotal = lpTotal / 1000000000000000000;\n\n wEth.methods\n .balanceOf(lpAddress)\n .call()\n .then(function (eth) {\n eth = eth / 1000000000000000000;\n\n lpPrice = ((2 * eth) / lpTotal).toFixed(5);\n\n $('#price-sell-lp').attr('value', lpPrice);\n $('#price-buy-lp').attr('value', lpPrice);\n });\n });\n}", "function convertToETHPrice(priceUSD){\n let ETHPrice = cmcArrayDict['eth'.toUpperCase()]['quote']['USD']['price'];\n return priceUSD / ETHPrice;\n}", "async getCurrentLokiPriceInUSD() {\n try {\n const response = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=loki-network&vs_currencies=usd');\n return response.data['loki-network'].usd;\n } catch (e) {\n log.debug(e);\n throw new PriceFetchFailed();\n }\n }", "function getPrice() {\n if (result.Prijs.Koopprijs && !result.Prijs.Huurprijs) {\n return '<strong>€ ' + numberWithPeriods(result.Prijs.Koopprijs) + ' <abbr title=\"Kosten Koper\">k.k.</abbr></strong>';\n } else {\n return '<strong>€ ' + numberWithPeriods(result.Prijs.Huurprijs) + ' <abbr title=\"Per maand\">/mnd</abbr></strong>';\n }\n }", "async function getEthPriceInUSD() {\n try {\n const { data } = await CoinGeckoClient.simple.price({\n ids: 'ethereum',\n vs_currencies:'usd',\n });\n const ethPriceInUSD = data['ethereum'].usd;\n return ethPriceInUSD;\n }\n catch(err) {\n console.log(err);\n }\n}", "function getBtc(){\n request('https://coinbase.com/api/v1/prices/spot_rate', function(error, response, body){\n if(!error && response.statusCode == 200){\n var btc = JSON.parse(body);\n bot.say(config.channels[0], \"The price of bitcoin is \" + btc.amount +\" \"+ btc.currency);\n }\n });\n}", "async ethPrice() {\n\n const response = await this.ctx.curl('https://api.coinmarketcap.com/v1/ticker/ethereum/', {\n dataType: 'json',\n timeout: 1000 * 60 \n });\n const data = response.data;\n const price = data[0] && data[0].price_usd || '--';\n return price;\n }", "function getNFYPrice() {\n var nfyPrice;\n\n wEth.methods\n .balanceOf(lpAddress)\n .call()\n .then(function (eth) {\n eth = eth / 1000000000000000000;\n\n nfyToken.methods\n .balanceOf(lpAddress)\n .call()\n .then(function (nfy) {\n nfy = nfy / 1000000000000000000;\n\n nfyPrice = (eth / nfy).toFixed(5);\n\n $('#price-sell-nfy').attr('value', nfyPrice);\n $('#price-buy-nfy').attr('value', nfyPrice);\n });\n });\n}", "getPrice() {\n\t\tconst balances = aa_state.getUpcomingBalances()[this.#oswap_aa];\n\t\treturn balances[this.#stable_asset] / balances[this.#interest_asset]; \n\t}", "specialRateCalculate(price){\n let specialRatePrice = price - (price*0.2);\n return specialRatePrice;\n }", "async btcEthRate() {\n\n const btc = await this.btcPrice();\n const eth = await this.ethPrice();\n if (btc === '--' || eth === '--' || !btc || !eth) {\n return 10;\n }\n\n return btc / eth;\n }", "get priceInDollars () {\n return self.priceInSatoshis && self.bitcoinPrice\n ? numeral(self.priceInSatoshis)\n .multiply(self.bitcoinPrice)\n .divide(100000000)\n .format('$0.00000')\n : null\n }", "function VAT(price){\n return price * 0.21;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function returns all techs used in a project
function getProjectTechs (req, res) { // var techss = [] PROJECTTECHS.findAll({ where: { ProjectId: req.params.id } }).then(techs => { resolveTechs(techs, res) // res.send(techs) }).catch(err => { console.log(err) res.send(false) }) }
[ "function getUsingTechs() {\n if (getUsingTechs.vals) return getUsingTechs.vals;\n\n var lang = getProp('lang');\n var type = getProp('type');\n var level = getProp('level');\n \n var techNames = getLangSet('tech');\n var urlPointer = lang+'-'+type;\n var usingCriteria = getUsingCriteria();\n var usingTechs = [];\n \n for (i = 0; i < usingCriteria.length; i++) {\n var criteria = usingCriteria[i][1];\n if (gRelTechsAndCriteria[criteria] == null) continue;\n for (j = 0; j < gRelTechsAndCriteria[criteria].length; j++) {\n var url = gUrlbase['tech'][urlPointer];\n var each = gRelTechsAndCriteria[criteria][j];\n \n // Techniques for WCAG 2.1 has directory\n if (type == 'wcag21' && lang == 'en') {\n var dir = each.charAt(0)+each.charAt(1);\n if (['M', 'L', 'V', 'C'].indefOf(each.charAt(1)) < 0) {\n dir = dir.charAt(0);\n }\n url += gTechDirAbbr[dir]+'/'+each;\n } else {\n url += each+'.html';\n }\n\n usingTechs.push([criteria, gRelTechsAndCriteria[criteria][j], techNames[each], url]);\n }\n }\n \n getUsingTechs.vals = usingTechs;\n \n return usingTechs;\n}", "function getTechButtons() {\n const technologies = [];\n projectList.forEach((p) => {\n p.technologies.forEach((tech) => {\n let check = false;\n for (let i = 0; i < technologies.length; i++) {\n if (technologies[i] === tech) check = true;\n }\n if (check === false) technologies.push(tech);\n });\n });\n return technologies.map((tech, i) => {\n return (\n <button key={i} onClick={handleClick} tech={tech} className=\"yellow1\">\n {tech}\n </button>\n );\n });\n }", "function listTech(){\n let techs = [];\n techs.push(\"Node.js\");\n techs.push(\"Ruby\");\n response[\"status\"] = 200;\n response[\"message\"] = \"The list of supported technologies\";\n response[\"body\"] = techs;\n\n return response;\n}", "function listTechnologies(){\n let available = [];\n for (k in supportedTechs) {\n available.push(k.charAt(0).toUpperCase() + k.slice(1));\n }\n let response = constant.getMessageStructure();\n response.status = constant.SUCCESS;\n response.message = \"The list of supported technologies\";\n response.data.body = available;\n\n return response;\n}", "function GetTechnologies(){\n log(\"Inside function GetTechnologies\", DEBUG);\n var data=AjaxHelper.gettechnologies(\"/events/list-technologies\",\"\");\n log(\"returned from Ajax Helper : gettechnologies\", DEBUG);\n log(JSON.stringify(data), DEBUG);\n if(data){\n _alltechnologies = data.technologies;\n return _alltechnologies;\n }\n}", "async function getTechnologies() {\n // fetch asynchrone\n const response = await fetch(\"api/technologies\");\n const data = await response.json();\n return data.technologies;\n}", "getAll() {\n return tools;\n }", "function getTechs(charId) {\n let rawTechs = filterObjs(function(obj) {\n if(obj.get('_type') == 'attribute' &&\n (!charId || obj.get('_characterid') == charId) &&\n obj.get('name').indexOf('repeating_techs') > -1) {\n return true;\n }\n return false;\n });\n \n let techs = [];\n rawTechs.forEach(function(rawTech) {\n let techName = rawTech.get('name');\n let techId = techName.split('_')[2];\n \n let oldTech = techs.find(function(s) {\n return s.id == techId\n });\n \n if(techName.indexOf('tech_name') > -1) {\n if(oldTech) {\n oldTech.name = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), name: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_core') > -1 && \n techName.indexOf('tech_core_') == -1) {\n if(oldTech) {\n oldTech.core = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), core: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_stat') > -1) {\n if(oldTech) {\n oldTech.stat = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), stat: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_cost') > -1) {\n let cost = parseInt(rawTech.get('current'));\n if(cost != cost) {\n cost = 0;\n }\n \n if(oldTech) {\n oldTech.cost = cost;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), cost: cost});\n }\n } else if(techName.indexOf('tech_limit_st') > -1) {\n let limitSt = parseInt(rawTech.get('current'));\n if(limitSt != limitSt) {\n limitSt = 0;\n }\n \n if(oldTech) {\n oldTech.limitSt = limitSt;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), limitSt: limitSt});\n }\n } else if(techName.indexOf('tech_limits') > -1) {\n let limits = rawTech.get('current').split('\\n');\n \n if(oldTech) {\n oldTech.limits = limits;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), limits: limits});\n }\n } else if(techName.indexOf('tech_mods') > -1) {\n let mods = rawTech.get('current').split('\\n');\n \n if(oldTech) {\n oldTech.mods = mods;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), mods: mods});\n }\n } else if(techName.indexOf('tech_micro_summary') > -1) {\n if(oldTech) {\n oldTech.summary = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), summary: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_is_mimic') > -1) {\n if(oldTech) {\n oldTech.isMimic = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), isMimic: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_mimic_target') > -1) {\n if(oldTech) {\n oldTech.mimicTarget = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), mimicTarget: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_core_level') > -1) {\n let coreLevel = parseInt(rawTech.get('current'));\n if(coreLevel != coreLevel) {\n coreLevel = 0;\n }\n if(oldTech) {\n oldTech.coreLevel = coreLevel;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), coreLevel: coreLevel});\n }\n } else if(techName.indexOf('tech_level') > -1) {\n let techLevel = parseInt(rawTech.get('current'));\n if(techLevel != techLevel) {\n techLevel = 0;\n }\n if(oldTech) {\n oldTech.techLevel = techLevel;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), techLevel: techLevel});\n }\n } else if(techName.indexOf('tech_tech_stat') > -1) {\n if(oldTech) {\n oldTech.techStat = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), techLevel: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_granted_skills') > -1) {\n if(oldTech) {\n oldTech.grantedSkills = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), grantedSkills: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_has_skills') > -1) {\n let hasSkills = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.hasSkills = hasSkills;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), hasSkills: hasSkills});\n }\n } else if(techName.indexOf('tech_inflicted_flaws') > -1) {\n if(oldTech) {\n oldTech.inflictedFlaws = rawTech.get('current');\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), inflictedFlaws: rawTech.get('current')});\n }\n } else if(techName.indexOf('tech_has_flaws') > -1) {\n let hasFlaws = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.hasFlaws = hasFlaws;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), hasFlaws: hasFlaws});\n }\n } else if(techName.indexOf('tech_digDeep') > -1) {\n let digDeep = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.digDeep = digDeep;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), digDeep: digDeep});\n }\n } else if(techName.indexOf('tech_overloadLimits') > -1) {\n let overloadLimits = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.overloadLimits = overloadLimits;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), overloadLimits: overloadLimits});\n }\n } else if(techName.indexOf('tech_empowerAttack') > -1) {\n let empowerAttack = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.empowerAttack = empowerAttack;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), empowerAttack: empowerAttack});\n }\n } else if(techName.indexOf('tech_resoluteStrike') > -1) {\n let resoluteStrike = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.resoluteStrike = resoluteStrike;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), resoluteStrike: resoluteStrike});\n }\n } else if(techName.indexOf('tech_reroll') > -1) {\n let reroll = rawTech.get('current') == 'on';\n if(oldTech) {\n oldTech.reroll = reroll;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), reroll: reroll});\n }\n } else if(techName.indexOf('tech_shield_type') > -1) {\n let shieldType = rawTech.get('current');\n if(oldTech) {\n oldTech.shieldType = shieldType;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), shieldType: shieldType});\n }\n log(techs);\n } else if(techName.indexOf('custom_cost') > -1) {\n let customCost = parseInt(rawTech.get('current'));\n if(customCost != customCost) {\n customCost = 0;\n }\n if(oldTech) {\n oldTech.customCost = customCost;\n } else {\n techs.push({ id: techId, charId: rawTech.get('_characterid'), customCost: customCost});\n }\n }\n });\n \n return techs;\n}", "function getProjectTechnology() {\n\n\t\t\t\treturn new Promise((resolve, reject) => {\n\n\t\t\t\t\tinquirer\n\t\t\t\t\t\t.prompt(\n\t\t\t\t\t\t\t[{\n\t\t\t\t\t\t\t\tmessage: 'What technology do you want to use?',\n\t\t\t\t\t\t\t\ttype: 'list',\n\t\t\t\t\t\t\t\tname: 'technology',\n\t\t\t\t\t\t\t\tchoices: ['NodeJS', 'PHP']\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t).then(answers => resolve(answers.technology));\n\n\t\t\t\t});\n\n\t\t\t}", "getDevelopers() {\n\t\t\t\tlet names = '',\n\t\t\t\t\t\tthat = this;\n\t\t\t\tfor ( let i = 0; i < this.developers.length; i++ ) {\n\t\t\t\t\tnames += that.developers[i].name + ' ';\n\t\t\t\t};\n\t\t\t\treturn names\n\t\t\t}", "async function getTechWebTech(url){\n let result = await request(`http://${hostServerApi}:${portServerApi}/api/v1/enumeration/webtech?url=${url}`)\n return result.body\n}", "function _filterByTechnologies(project) {\n for (let currentFilter of filters.filterByTechnology) {\n if (project.technologies.includes(currentFilter)) {\n return true;\n }\n }\n }", "function getSoftwareList() {\n \"use strict\";\n}", "function getProjectData()\n{\n\tlet tags = [];\n\tlet projects = [];\n\t// Iterate over each project...\n\tfor( let i = 0; i < data.projects.length; i++)\n\t{\n\t\t// Store each project.\n\t\tlet project = data.projects[i];\n\t\tprojects.push(project);\n\t\t// Iterate over each tag within the project...\n\t\tfor( let e = 0; e < project.tags.length; e++)\n\t\t{\n\t\t\t// Store each tag.\n\t\t\tlet tag = project.tags[e];\n\t\t\tif(!contains(tags, tag))\n\t\t\t\ttags.push(tag);\n\t\t}\n\t}\n\t// Sort the tags alphabetically.\n\ttags.sort();\n\t// Create project data which will enable us to build our menus.\n\tlet project_data = [];\n\tfor( let i = 0; i < tags.length; i++)\n\t\tproject_data.push(createTagArray(tags[i], projects));\n\t\n\t// Debug.\n\t//for( let i = 0; i < project_data.length; i++)\n\t\t//for( let e = 1; e < project_data[i].length; e++)\n\t\t\t//console.log(\"Tag[\"+project_data[i][0]+\"]: \" + project_data[i][e]);\n\t\n\treturn project_data;\n}", "getProjectLibNames(framework) {\n let projectLibraries = [];\n const frameworkConfig = this.config.stepByStep && this.config.stepByStep[framework.id];\n if (frameworkConfig && frameworkConfig.projTypes && frameworkConfig.projTypes.length) {\n frameworkConfig.projTypes.forEach(x => {\n const projLib = framework.projectLibraries.find(p => p.projectType === x);\n if (projLib) {\n projectLibraries.push(projLib.name);\n }\n });\n }\n if (!projectLibraries.length) {\n // no config or wrong projTypes array:\n projectLibraries = this.templateManager.getProjectLibraryNames(framework.id);\n }\n return projectLibraries;\n }", "function getProjects(){\n\n }", "function createMarkupForTechnologies() {\n if (project.technologiesList) {\n return {\n __html: project.technologiesList,\n };\n } else {\n return;\n }\n }", "async function loadTech () {\n\tlet count = 0;\n\n\tfor await (const tech of techData) {\n\t\t// techTreeDebugger(tech);\n\t\ttechTree[count] = new Technology(tech);\n\t\tcount++;\n\t}\n\n\ttechTreeDebugger(`${count} technology loaded into tech tree...`);\n\treturn `${count} technology loaded into tech tree...`;\n}", "function renderTechs(techs) {\n return techs.map((tech) => \n <li key={tech}>{tech}</li>\n )\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the player buys or sells an item, this method determines whether an inspection occurs. Returns true if no inspection is performed. If an inspection is performed and the player is caught, the player's contraband cargo is confiscated, the player is fined, and their standing with the market's faction is decreased. The method then sends a notification of the fine.
transactionInspection(item, amount, player) { if (!player || !this.faction.isContraband(item, player)) return true; // the relative level of severity of trading in this item const contraband = data_1.default.resources[item].contraband || 0; // FastMath.abs() is used because amount is negative when selling to market, // positive when buying from market. Fine is per unit of contraband. const fine = FastMath.abs(contraband * amount * this.inspectionFine(player)); const rate = this.inspectionRate(player); for (let i = 0; i < contraband; ++i) { if (util.chance(rate)) { const totalFine = Math.min(player.money, fine); const csnFine = util.csn(totalFine); const csnAmt = util.csn(amount); // fine the player player.debit(totalFine); // decrease standing player.decStanding(this.faction.abbrev, contraband); // confiscate contraband let verb; if (amount < 0) { player.ship.cargo.set(item, 0); verb = 'selling'; } else { this.stock.dec(item, amount); verb = 'buying'; } // trigger notification const msg = `Busted! ${this.faction.abbrev} agents were tracking your movements and observed you ${verb} ${csnAmt} units of ${item}. ` + `You have been fined ${csnFine} credits and your standing wtih this faction has decreased by ${contraband}.`; window.game.notify(msg, true); return false; } } return true; }
[ "function handleAffliction(affliction, monId) {\n // Afflictions that take a Tick of Hit Points\n if (affliction == \"Burned\" || affliction == \"Poisoned\") {\n\n // Calculating max_hp\n var max_hp = gm_data[\"pokemon\"][monId]['level'] + gm_data[\"pokemon\"][monId]['hp'] * 3 + 10;\n\n // Subtract health\n gm_data[\"pokemon\"][monId][\"health\"] -= Math.floor(max_hp * 0.1);\n\n // Show message\n if (affliction == \"Burned\")\n doToast(gm_data[\"pokemon\"][monId][\"name\"] + \" was damaged by their burn\");\n else if (affliction == \"Poisoned\")\n doToast(gm_data[\"pokemon\"][monId][\"name\"] + \" was damaged from poison\");\n\n // Check if fainted\n if (gm_data[\"pokemon\"][monId][\"health\"] <= 0) {\n doToast(gm_data[\"pokemon\"][monId][\"name\"] + \" fainted!\");\n gm_data[\"pokemon\"][monId][\"health\"] = 0;\n }\n\n // Update health bar\n var w = Math.floor((gm_data[\"pokemon\"][monId]['health'] / max_hp) * 100);\n\n $(\"[data-name='\"+monId+\"']\").find(\".progress-bar\").css(\"width\", w + \"%\");\n\n // Update Player client\n sendMessage(battle[monId][\"client_id\"], JSON.stringify({\n \"type\": \"health\",\n \"value\": gm_data[\"pokemon\"][monId]['health']\n }));\n }\n // Frozen save check\n else if (affliction == \"Frozen\") {\n // TODO: weather bonuses (+4 sunny, -2 hail)\n\n // Save check roll\n var check = roll(1, 20, 1);\n\n // If rolled higher than 16, or 11 for Fire types, cure of Frozen\n if (check >= 16 || (check >= 11 && (gm_data[\"pokemon\"][monId][\"type\"] == \"Fire\" ||\n $.inArray(\"Fire\", gm_data[\"pokemon\"][monId][\"type\"].split(\" / \")) >= 0))) {\n\n deleteAffliction(\"Frozen\", monId);\n\n return true;\n }\n\n return false;\n }\n // Confused save check\n else if (affliction == \"Confused\") {\n // Save check roll\n var check_cf = roll(1, 20, 1);\n\n // If rolled higher than 16, cure of Confusion\n if (check_cf <= 8) {\n doPhysicalStruggle(monId);\n doToast(gm_data[\"pokemon\"][monId][\"name\"] + \" hurt itself in confusion!\");\n\n return false;\n }\n else if (check_cf >= 16)\n deleteAffliction(\"Confused\", monId);\n }\n\n return true;\n}", "function canAfford(item) {\n if (item.cost <= Cash.quantity) {\n return true;\n }\n\n return false;\n}", "function buy (item) {\n if (blacksmith.fire === false) {\n if (item === 'ore' && blacksmith.gold >= settings.oreCost) {\n blacksmith.ore++\n blacksmith.gold -= settings.oreCost\n return `You have purchased 1 piece of ore.`\n } else if (item === 'wood' && blacksmith.gold >= settings.woodCost) {\n blacksmith.wood++\n blacksmith.gold -= settings.woodCost\n return `You have purchased 1 piece of wood`\n } else {\n return `You cannot purchase a ${item}.`\n }\n } else {\n return `You must put out the fire.`\n }\n}", "function willBuyDrink(isHotOutside, moneyInPocket) {\n return isHotOutside && moneyInPocket > 10.50;\n}", "function checkItemInCart() {\n\t\tlet itemCount = c.cart.item_count;\n\t\tconst items = c.cart.items;\n\n\t\tif (itemCount > 0) {\n\t\t\titems.forEach((item) => {\n\t\t\t\tif (item.handle === c.product.handle) {\n\t\t\t\t\titemCount -= 1;\n\t\t\t\t\t// eslint-disable-next-line\n\t\t\t\t\tif (item.properties._giveaway) {\n\t\t\t\t\t\tc.inCart = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tobserveCart();\n\t}", "fight(item) {\r\n if (item === this.weapon) {\r\n this.isalive = false;\r\n return true;\r\n }\r\n return false;\r\n }", "function willBuyDrink(isHotOutside, moneyInPocket) {\n return isHotOutside && moneyInPocket > 10.50 \n}", "function checkForGiftItem(itemDiscountInfo) {\n if (itemDiscountInfo && itemDiscountInfo.length) {\n for (var i=0; i < itemDiscountInfo.length; i++) {\n if (itemDiscountInfo[i].giftWithPurchaseDiscountInfo && itemDiscountInfo[i].giftWithPurchaseDiscountInfo.length) {\n return true;\n }\n }\n }\n return false;\n }", "function checkForGiftItem(itemDiscountInfo) {\n if (itemDiscountInfo && itemDiscountInfo.length) {\n for (var i=0; i < itemDiscountInfo.length; i++) {\n if (itemDiscountInfo[i].giftWithPurchaseDiscountInfo && itemDiscountInfo[i].giftWithPurchaseDiscountInfo.length) {\n return true;\n }\n }\n }\n return false;\n }", "function buy (item) {\n if (game.fire === false) {\n if (item === 'ore' && game.gold >= settings.oreCost){\n game.ore += 1\n game.gold -= settings.oreCost\n return \"You bought 1 piece of ore!\" \n } else if(item === 'wood' && game.gold >= settings.woodCost){\n game.wood += 1\n game.gold -= settings.woodCost\n return \"You bought 1 piece of wood!\"\n } else {\n return `You cannot buy ${item}`\n }\n } else {\n return \"You must put out the fire.\"\n }\n }", "function willBuyDrink (isHotOutside, moneyInPocket) {\n return ((isHotOutside) && (moneyInPocket > 10.50));\n}", "checkFruit(player=false) {\n if (!this.crashWith(fruit)) // didn't catch fruit\n return false;\n\n // Catched the fruit!\n this.score++;\n while (players[\"me\"].crashWith(fruit) || players[\"you\"].crashWith(fruit))\n fruit.newPos(true); // generate new position of fruit\n\n if (!blocks.sp && players) // send message about me catching the fruit to the opponent\n websocket.send(JSON.stringify({\n event:\"game\",\n data: {\n type: \"scored\",\n score: this.score,\n fruitX: fruit.x,\n fruitY: fruit.y\n }\n }));\n\n if (this.score < blocks.maxScore) // game not over yet\n return true;\n\n if (!blocks.sp) // send info about game over to opponent\n websocket.send(JSON.stringify({event: \"game\", data: {type: \"gameOver\", score: this.score}}));\n // Game over!\n blocks.gameOver(player);\n }", "function itemEffect(item, comp, answer) {\n if (item === 'use_repairkit') {\n player.useItem(useableItemLookUp[item]);\n player.health = player.health + 30;\n if (player.health > player.maxHealth) {\n player.health = player.maxHealth;\n }\n player.status2 = undefined;\n return console.log(`Your health has been restored! You currently have ${player.health} HP!\\n`);\n } else if (item === 'use_particlebattery') {\n player.useItem(useableItemLookUp[item]);\n player.damageBase = player.damageBase + 2;\n return console.log(`You have upgraded your Particle Beam! It now hits harder than ever!\\n`);\n } else if (item === 'use_carboncoating') {\n player.useItem(useableItemLookUp[item]);\n player.maxHealth = player.maxHealth + 10;\n player.health = player.health + 10;\n return console.log(`You have increased your maximum HP by 10 points!\\n`);\n } else if (item === 'use_grenade') {\n player.useItem(useableItemLookUp[item]);\n if (comp !== undefined) {\n comp.health = comp.health - 20;\n return console.log(`You threw a Plasma Grenade! It dealt 20 damage to ${comp.name}!\\n`)\n } else {\n return console.log(`You throw a Plasma Grenade!\\nThe blast was impressive, but would have been more useful in a fight...\\n`)\n }\n } else if (item === 'use_shield') {\n player.useItem(useableItemLookUp[item]);\n if (comp !== undefined) {\n player.status2 = 'shield';\n return console.log(`You generate a temporary shield that can absorb damage!\\n`);\n } else {\n return console.log(`You generate a temporary shield! Too bad you aren't being attacked...\\n`)\n }\n } else if (item === 'use_bomb') {\n player.useItem(useableItemLookUp[item]);\n if (comp !== undefined) {\n comp.status = 'smoke';\n return console.log(`You throw a Smoke Bomb! It will be harder for ${comp.name} to hit you!\\n`)\n } else {\n return console.log(`You throw a Smoke Bomb! Gee golly that was exciting!\\n`);\n }\n } else if (item === 'use_rboxw') {\n if (answer === 'WET') {\n player.useItem(useableItemLookUp[item]);\n player.inventory.push('Office Keycard West');\n return console.log('You solved the riddle! There was a Keycard to the West tower inside!\\n')\n } else {\n return console.log(`That's a tough riddle, gonna have to think about that one...\\n`)\n }\n } else if (item === 'use_rboxe') {\n if (answer === 'SILENCE') {\n player.useItem(useableItemLookUp[item]);\n player.inventory.push('Office Keycard East');\n return console.log('You solved the riddle! There was a Keycard to the East tower inside!\\n')\n } else {\n return console.log(`That's a tough riddle, gonna have to think about that one...\\n`)\n }\n } else if (item === 'use_heatray') {\n player.useItem(useableItemLookUp[item]);\n if (comp !== undefined) {\n comp.health = comp.health - 40;\n return console.log(`You fired the Nuclear Heat Ray! It dealt 40 damage to ${comp.name}!\\n`)\n } else {\n return console.log(`You fired the Nuclear Heat Ray! That hole in the wall would have been\\nmore impressive if it was through a robot instead...\\n`);\n }\n }\n}", "function C999_Common_VibratingEgg_Contract() {\n\tif (!Common_PlayerChaste) {\n\t\tif (PlayerGetSkillLevel(\"Sports\") >= 1) {\n\t\t\tPlayerUnlockInventory(\"VibratingEgg\");\n\t\t\tPlayerAddInventory(\"VibratingEgg\", 1);\n\t\t\tC999_Common_VibratingEgg_CurrentStage = 0;\n\t\t\tC999_Common_VibratingEgg_HasLooseEgg = true;\n\t\t\tOverridenIntroText = GetText(\"ContractSuccess\");\n\t\t}\n\t}\n\telse OverridenIntroText = GetText(\"ContractBelt\");\n}", "function stay()\n{\n if(bust) alert(\"you already lost\");\n else if(showDealersHand) alert(\"this round is already over\");\n else\n {\n runDealer();\n updateVictoryGui();\n updateGui();\n }\n}", "function willBuyDrink(isHotOutside, moneyInPocket){\n if(isHotOutside && (moneyInPocket > 10.50)){\n return true;\n }\n return false;\n}", "static async canFulfilIngredients(memberID, itemCode, qty) {\n let craftable = false;\n\n const ingredients = this.CRAFTABLES[itemCode].ingredients;\n const ingredList = Object.keys(this.CRAFTABLES[itemCode].ingredients);\n const ownedIngredients = await Promise.all(\n ingredList.map(ingred => COOP.ITEMS.getUserItem(memberID, ingred)\n ));\n\n // Check ingredients are sufficient.\n const sufficiencyChecks = ownedIngredients.map(ingred => {\n // Filter out unowned items.\n if (!ingred) return false;\n\n // Check sufficiency\n const req = ingredients[ingred.item_code] * qty;\n const owned = ingred.quantity;\n\n // Declare insufficient.\n if (owned < req) return false;\n else return true;\n });\n\n // Check all ingredients sufficient.\n if (sufficiencyChecks.every(sufficient => sufficient)) \n craftable = true;\n\n // TODO: Improve.\n // Otherwise pull out the ones that aren't, into an error message:\n\n // Return a more helpful result.\n // const manifest = { sufficient: false, checks: sufficiencyChecks };\n // return manifest;\n\n return craftable;\n }", "useItem(currArea, item) {\n if (this.checkIfItemExists(item) && currArea.overcomeHazard(item)) {\n console.log(\"You have overcome this hazard!\");\n this.removeItemFromInventory(item);\n return true;\n }\n else {\n console.log(\"You cannot overcome this hazard with this item.\");\n return false;\n }\n }", "function checkInventory(){\n\tconsole.log(\"Confirming availability...\\n\");\n\tconnection.query(\"SELECT * FROM products WHERE item_id=\"+buyIt, function(err, res) {\n\t\tif (err) throw err;\n\t\t// \tif not...insufficient quantity messages\n\t\tif (res[0].stock_quantity<thisQuant){\n\t\t\tconsole.log(\"Your order could not be fulfilled because we don't have enough of '\"+res[0].product_name+\"' available.\");\n\t\t}\n\t\t// \tif yes...fulfil the customer order\n\t\telse {\n\t\t\t//decrements remaining quantity\n\t\t\tconnection.query(\"UPDATE products SET stock_quantity=\"+(res[0].stock_quantity-thisQuant)+\" WHERE item_id=\"+buyIt);\n\t\t\t//display the customer total order cost\n\t\t\tconsole.log(\"Your order has been fulfilled. You owe $\"+(res[0].price*thisQuant)+\" to Bamazon's receivable department. They will contact you shortly.\");\n\t\t\tconnection.query(\"SELECT * FROM products WHERE item_id=\"+buyIt, function(err, res){\n\t\t\t\tif (err) throw err;\n\t\t\t\tconsole.log(\"The store now has: \"+res[0].stock_quantity+\" of \"+res[0].product_name+\" remaining in inventory.\");\t\t\n\t\t\t});\n\t\t}\n\t\t//close out the database connection\n\t\tconnection.end();\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aligns nodes by depth or by link weight
function alignNodes() { graph.style.align = !graph.style.align applyScale(data.tree) update(data.tree) applyScaleText() addNodeStyle() addLinkStyle() updateInternalLabels(graph.style.parentLabels) if (graph.style.barChart) { graph.element.selectAll('.leafLabelIsolates text').remove() graph.element.selectAll('circle').each(d => addBarCharts(d)) addLeafLabelsNotIsolates() } }
[ "function node_weight(d) {\r\n d.weight = links.filter(function(l) {\r\n return l.source.index == d.index // || l.target.index == d.index \r\n }).length\r\n return d.weight\r\n }", "function justify(node, n) {\n return node.sourceLinks.length ? node.depth : n - 1;\n}", "function computeNodeDepths(graph) {\n var nodes, next, x;\n for ((nodes = graph.nodes, next = [], x = 0); nodes.length; (++x, nodes = next, next = [])) {\n nodes.forEach(function (node) {\n node.depth = x;\n node.sourceLinks.forEach(function (link) {\n if (next.indexOf(link.target) < 0) {\n next.push(link.target);\n }\n });\n });\n }\n for ((nodes = graph.nodes, next = [], x = 0); nodes.length; (++x, nodes = next, next = [])) {\n nodes.forEach(function (node) {\n node.height = x;\n node.targetLinks.forEach(function (link) {\n if (next.indexOf(link.source) < 0) {\n next.push(link.source);\n }\n });\n });\n }\n var kx = (x1 - x0 - dx) / (x - 1);\n graph.nodes.forEach(function (node) {\n node.x1 = (node.x0 = x0 + Math.max(0, Math.min(x - 1, Math.floor(align.call(null, node, x)))) * kx) + dx;\n });\n }", "function computeNodeDepths(graph) {\n var nodes, next, x;\n\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\n nodes.forEach(function(node) {\n node.depth = x;\n node.sourceLinks.forEach(function(link) {\n if (next.indexOf(link.target) < 0) {\n next.push(link.target);\n }\n });\n });\n }\n\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\n nodes.forEach(function(node) {\n node.height = x;\n node.targetLinks.forEach(function(link) {\n if (next.indexOf(link.source) < 0) {\n next.push(link.source);\n }\n });\n });\n }\n\n var kx = (x1 - x0 - dx) / (x - 1);\n graph.nodes.forEach(function(node) {\n node.x1 = (node.x0 = x0 + Math.max(0, Math.min(x - 1, Math.floor(align.call(null, node, x)))) * kx) + dx;\n });\n }", "function computeNodeDepths(graph) {\r\n var nodes, next, x;\r\n\r\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\r\n nodes.forEach(function(node) {\r\n node.depth = x;\r\n node.sourceLinks.forEach(function(link) {\r\n if (next.indexOf(link.target) < 0) {\r\n next.push(link.target);\r\n }\r\n });\r\n });\r\n }\r\n\r\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\r\n nodes.forEach(function(node) {\r\n node.height = x;\r\n node.targetLinks.forEach(function(link) {\r\n if (next.indexOf(link.source) < 0) {\r\n next.push(link.source);\r\n }\r\n });\r\n });\r\n }\r\n\r\n var kx = (x1 - x0 - dx) / (x - 1);\r\n graph.nodes.forEach(function(node) {\r\n node.x1 = (node.x0 = x0 + Math.max(0, Math.min(x - 1, Math.floor(align.call(null, node, x)))) * kx) + dx;\r\n });\r\n }", "function relaxLeftToRight(alpha) {\r\n nodesByBreadth.forEach(function(nodes, breadth) {\r\n nodes.forEach(function(node) {\r\n if (node.targetLinks.length) {\r\n var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);\r\n node.x += (y - center(node)) * alpha;\r\n }\r\n });\r\n });\r\n\r\n function weightedSource(link) {\r\n return center(link.source) * link.value;\r\n }\r\n }", "function computeNodeDepths (graph) {\n var nodes, next, x\n\n for (\n (nodes = graph.nodes), (next = []), (x = 0);\n nodes.length;\n ++x, (nodes = next), (next = [])\n ) {\n nodes.forEach(function (node) {\n node.depth = x\n node.sourceLinks.forEach(function (link) {\n if (next.indexOf(link.target) < 0 && !link.circular) {\n next.push(link.target)\n }\n })\n })\n }\n\n for (\n (nodes = graph.nodes), (next = []), (x = 0);\n nodes.length;\n ++x, (nodes = next), (next = [])\n ) {\n nodes.forEach(function (node) {\n node.height = x\n node.targetLinks.forEach(function (link) {\n if (next.indexOf(link.source) < 0 && !link.circular) {\n next.push(link.source)\n }\n })\n })\n }\n\n var kx = (x1 - x0 - dx) / (x - 1)\n graph.nodes.forEach(function (node) {\n node.x1 =\n (node.x0 =\n x0 +\n Math.max(\n 0,\n Math.min(x - 1, Math.floor(align.call(null, node, x)))\n ) *\n kx) + dx\n })\n }", "function computeNodeDepths(graph) {\n var nodes, next, x;\n\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\n nodes.forEach(function (node) {\n node.depth = x;\n node.sourceLinks.forEach(function (link) {\n if (next.indexOf(link.target) < 0 && !link.circular) {\n next.push(link.target);\n }\n });\n });\n }\n\n for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) {\n nodes.forEach(function (node) {\n node.height = x;\n node.targetLinks.forEach(function (link) {\n if (next.indexOf(link.source) < 0 && !link.circular) {\n next.push(link.source);\n }\n });\n });\n }\n\n // assign column numbers, and get max value\n graph.nodes.forEach(function (node) {\n node.column = Math.floor(align.call(null, node, x));\n });\n }", "function getWeight(node) {\n if (node.weight) {\n return node.weight;\n }\n var order = node.children.map(getWeight).reduce(function(a, b) {\n return a + b;\n }, 0) + 1;\n node.weight = order;\n return order;\n }", "function computeNodeBreadths() {\n\t\t\tvar remainingNodes = nodes, nextNodes, x = 0;\n\t\n\t\t\twhile (remainingNodes.length) {\n\t\t\t\tnextNodes = [];\n\t\t\t\tremainingNodes.forEach(function(node) {\n\t\t\t\t\tnode.x = x;\n\t\t\t\t\tnode.dx = nodeWidth;\n\t\t\t\t\tnode.sourceLinks.forEach(function(link) {\n\t\t\t\t\t\tnextNodes.push(link.target);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tremainingNodes = nextNodes;\n\t\t\t\t++x;\n\t\t\t}\n\t\n\t\t\tif(self.isLikeTree() === false) {\n\t\t\t\tmoveSinksRight(x);\n\t\t\t}\n\t\t\tvar kx = (size[0] - nodeWidth) / (x - 1);\n\t\t\tscaleNodeBreadths(kx);\n\t\t}", "tidy(root) {\n let orderedNodes = [];\n this.postTraverse(root, orderedNodes);\n let modMap = {};\n let centerMap = {};\n let min_dist = 100;\n for (let node of orderedNodes) {\n centerMap[node.id] = 0;\n node.cx = 0;\n if (node.children.length != 0) {\n node.children[0].cx == 0;\n for (let i = 1; i < node.children.length; i++) {\n node.children[i].cx = node.children[i - 1].cx + min_dist;\n }\n centerMap[node.id] = (node.children[0].cx + node.children[node.children.length - 1].cx) / 2;\n }\n }\n // console.log(centerMap);\n for (let node of orderedNodes) {\n // console.log(node.label);\n //Set the top y value\n node.cy = node.depth * 75 + 50;\n let leftSiblings = (node.parents[0] != undefined && node.parents[0].children[0] !== node);\n // console.log(leftSiblings);\n // console.log(centeredValue);\n if (!leftSiblings) {\n node.cx = centerMap[node.id];\n modMap[node.id] = 0;\n }\n else {\n node.cx = node.parents[0].children[node.parents[0].children.indexOf(node) - 1].cx + min_dist;\n modMap[node.id] = node.cx - centerMap[node.id];\n }\n }\n this.shiftChildrenByMod(root, 0, modMap);\n modMap = this.clearModMap(modMap);\n //dealing with conflicts, twice.\n // modMap = this.fixConflicts(root, orderedNodes, modMap);\n modMap = this.fixConflicts(root, orderedNodes, modMap);\n this.fixOffScreen(root, modMap);\n root.cx = (root.children[0].cx + root.children[root.children.length - 1].cx) / 2;\n }", "_determineLevelsDirected() {\n let minLevel = 10000;\n let levelByDirection = (nodeA, nodeB, edge) => {\n let levelA = this.hierarchicalLevels[nodeA.id];\n // set initial level\n if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}\n if (edge.toId == nodeB.id) {\n this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;\n }\n else {\n this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] - 1;\n }\n };\n this._crawlNetwork(levelByDirection);\n this._setMinLevelToZero();\n }", "add(weight, data) {\n let node = new Node(weight, data);\n this.allNodes.push(node);\n let size = this.allNodes.length;\n let current = size - 1;\n let parentIndex = Math.floor((current - 1) / 2);\n this.nodePosition[node.data] = current;\n while (parentIndex >= 0) {\n let parentNode = this.allNodes[parentIndex];\n let currentNode = this.allNodes[current];\n if (parentNode.weight > currentNode.weight) {\n [this.allNodes[parentIndex], this.allNodes[current]] = [this.allNodes[current], this.allNodes[parentIndex]]; // swaps\n this.updatePositionMap(this.allNodes[parentIndex].data, this.allNodes[current].data, parentIndex, current);\n current = parentIndex;\n parentIndex = Math.floor((current - 1) / 2);\n } else {\n break;\n }\n }\n }", "function updateNodePositions() {\n for (var j = 0; j < this.columns.length; j++) {\n for (var i = 0; i < this.columns[j].length; i++) {\n if (j == 0) {\n continue;\n }\n childNodes = this.myTree.nodes[this.columns[j][i]].children;\n var numChildren = 0;\n var totY = 0;\n\n for (var k = 0; k < childNodes.length; k++) {\n totY += $('#tree_' + childNodes[k]).offset().top;\n numChildren += 1;\n }\n var avY = $('#tree_' + this.columns[j][i]).offset().top;\n var avY = totY / numChildren;\n var myY = $('#tree_' + this.columns[j][i]).offset().top;\n var offset = avY - myY;\n $('#tree_' + this.columns[j][i]).css(\"position\", \"relative\");\n $('#tree_' + this.columns[j][i]).css(\"top\", offset + \"px\");\n }\n }\n }", "function repositionNodes() {\n for (var i = 0; i < nodes.length; i++) {\n nodes[i].setX(nodes[i].getXDepth() * (width - 4));\n nodes[i].setY(nodes[i].getYDepth() * (0.72 * height - 4));\n } \n }", "_setNodeOrders(node) {\n if (node.childNodes.length === 0) {\n return;\n }\n\n const pattern = /\\d+$/;\n const sortedKeys = Object.keys(node.childNodes).sort((tag0, tag1) => {\n const num0 = Number(tag0.substring(tag0.match(pattern).index));\n const num1 = Number(tag1.substring(tag1.match(pattern).index));\n return num0 - num1;\n });\n\n for (let i = 0; i < sortedKeys.length; ++i) {\n let key = sortedKeys[i];\n let childNode = node.childNodes[key];\n\n childNode.weight = i;\n this._setNodeOrders(childNode);\n }\n }", "applyAlignment(index) {\n let connectedNodes = this.getConnectedNodes(index);\n\n if (\n connectedNodes.previousNode != undefined && connectedNodes.previousNode instanceof Node &&\n connectedNodes.nextNode != undefined && connectedNodes.nextNode instanceof Node &&\n !this.nodes[index].isFixed\n ) {\n // Find the midpoint between the neighbors of this node\n let midpoint = this.getMidpointNode(connectedNodes.previousNode, connectedNodes.nextNode);\n\n // Move this point towards this midpoint\n this.nodes[index].nextPosition.x = this.p5.lerp(this.nodes[index].nextPosition.x, midpoint.x, this.settings.AlignmentForce);\n this.nodes[index].nextPosition.y = this.p5.lerp(this.nodes[index].nextPosition.y, midpoint.y, this.settings.AlignmentForce);\n }\n }", "function adjustRanks(graph,tree){function dfs(p){var children=tree.successors(p);children.forEach(function(c){var minLen=minimumLength(graph,p,c);graph.node(c).rank=graph.node(p).rank+minLen;dfs(c);});}dfs(tree.graph().root);}", "update(node){ \n let leftHeight=node.left!==null?node.left.height:-1,rightHeight=node.right!==null?node.right.height:-1\n node.height=Math.max(leftHeight,rightHeight)+1\n node.bf=rightHeight-leftHeight\n node.SubTreeNodes=1+(node.left===null?0:node.left.SubTreeNodes )+(node.right===null?0:node.right.SubTreeNodes)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Freeze page content scrolling
function freeze() { if($("html").css("position") != "fixed") { var top = $("html").scrollTop() ? $("html").scrollTop() : $("body").scrollTop(); if(window.innerWidth > $("html").width()) { $("html").css("overflow-y", "scroll"); } //$("html").css({"width": "100%", "height": "100%", "position": "fixed", "top": -top}); $("html").css({"width": "100%", "height": "100%", "position": "fixed", "top": -top}); $('.topbar').css('padding-top',top); } }
[ "function freeze() {\n if($(\"html\").css(\"position\") != \"fixed\") {\n var top = $(\"html\").scrollTop() ? $(\"html\").scrollTop() : $(\"body\").scrollTop();\n if(window.innerWidth > $(\"html\").width()) {\n $(\"html\").css(\"overflow-y\", \"scroll\");\n }\n $(\"html\").css({\"width\": \"100%\", \"height\": \"100%\", \"position\": \"fixed\", \"top\": -top});\n }\n }", "function unfreeze() {\n if($(\"html\").css(\"position\") == \"fixed\") {\n $(\"html\").css(\"position\", \"static\");\n $(\"html, body\").scrollTop(-parseInt($(\"html\").css(\"top\")));\n $(\"html\").css({\"position\": \"\", \"width\": \"\", \"height\": \"\", \"top\": \"\", \"overflow-y\": \"\"});\n }\n }", "function unblockPageScroll() {\n $changeHeaderBackdrop.unbind('mousewheel DOMMouseScroll touchmove');\n $changeHeader.unbind('mousewheel DOMMouseScroll touchmove');\n if (!pointbreak.isCurrentBreakpoint(PointBreak.SMALL_BREAKPOINT)) {\n $('body').css('overflow', 'auto');\n $('#back-to-top').css('visibility', 'visible');\n }\n }", "function _blockScrolling() {\n\t var top = $(window).scrollTop();\n\t var left = $(window).scrollLeft();\n\n\t Utils.addEvent($(window), Constants.SCROLL, function (e) {\n\t e.preventDefault();\n\t $(window).scrollTop(top).scrollLeft(left);\n\t });\n\t // Re-render the components after the scrolling has been locked.\n\t Utils.debounce(__rerenderScroll, 10, true);\n\t}", "function disableScroll() {\n lastScroll = _window.scrollTop();\n $(\".page__content\").css({\n \"margin-top\": \"-\" + lastScroll + \"px\"\n });\n $(\"body\").addClass(\"body-lock\");\n $(\".footer\").addClass(\"is-hidden\"); // if you use revealFooter()\n }", "function enablePageScroll() {\n var scrollTop = parseInt(jQuery('html').css('top'));\n jQuery('html').removeClass('noscroll');\n jQuery('html,body').scrollTop(-scrollTop);\n }", "function lockScrollBody(status) {\r\n\t\tif (status) {\r\n\t\t\t$body.css({\r\n\t\t\t\t'overflow': 'hidden'\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\t$body.css({\r\n\t\t\t\t'overflow': 'auto'\r\n\t\t\t});\r\n\t\t}\r\n\t}", "function freezeBackground(){\n $('body,html').css('overflow-y','hidden');\n $(\"html, body, #page-wrapper\").css({\n height: $(window).height()\n }); \n}", "function enablePageScroll() {\n\n\tvar scrollTop = parseInt(jQuery('html').css('top'));\n\tjQuery('html').removeClass('noscroll');\n\tjQuery('html,body').scrollTop(-scrollTop);\n}", "function enablePageScroll() {\n\tvar scrollTop = parseInt(jQuery('html').css('top'));\n\tjQuery('html').removeClass('noscroll');\n\tjQuery('html,body').scrollTop(-scrollTop);\n}", "unlockWebsiteScroll() {\n if (this.websiteBeforeLockParameters) {\n document.body.style.position = this.websiteBeforeLockParameters.bodyStylePosition;\n document.body.style.overflow = this.websiteBeforeLockParameters.bodyStyleOverflow;\n document.documentElement.style.overflow = this.websiteBeforeLockParameters.htmlStyleOverflow;\n const { windowScrollX } = this.websiteBeforeLockParameters;\n const { windowScrollY } = this.websiteBeforeLockParameters;\n window.scrollTo(windowScrollX, windowScrollY);\n this.websiteBeforeLockParameters = null;\n }\n }", "function disablePageScroll() {\n if (!jQuery('html').hasClass('noscroll')) {\n if (jQuery(document).height() > jQuery(window).height()) {\n var scrollTop = (jQuery('html').scrollTop()) ? jQuery('html').scrollTop() : jQuery('body').scrollTop();\n jQuery('html').addClass('noscroll').css('top',-scrollTop); \n };\n };\n }", "unlockScroll() {\n this.scrollLocked = false;\n }", "lockWebsiteScroll() {\n this.websiteBeforeLockParameters = {\n bodyStylePosition: document.body.style.position ? document.body.style.position : '',\n bodyStyleOverflow: document.body.style.overflow ? document.body.style.overflow : '',\n htmlStyleOverflow: document.documentElement.style.overflow ? document.documentElement.style.overflow : '',\n windowScrollX: window.scrollX,\n windowScrollY: window.scrollY,\n };\n }", "function pageScroll() {\n window.scrollBy(0, scrollStep);\n}", "function _unblockScrolling() {\n\t Utils.removeEvent($(window), Constants.SCROLL);\n\t}", "function refreshScrollForBillers() {\n\tif(mainScroll) {\n\t\tsetTimeout(function() {\n\t\t\tmainScroll.refresh(); \n\t\t}, 1000);\n\t}\n}", "function unFreezeBackground(){\n $('body,html').css('overflow-y','');\n $(\"html, body, #wrapper\").css(\"height\", \"\")\n}", "_updatePageScrollOffset() {\r\n this.setScrollOffset(0, window.pageYOffset);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
en que dia cae el primer dia del mes
function cual_es_el_primerdia_del_mes(){ let primer_dia=new Date(año_actual,mes_actual,1); //me devuelve numeros desde 0 a 7,en caso el dia sea domingo no devolvera 0 return((primer_dia.getDay()-1)=== -1)? 6: primer_dia.getDay()-1; }
[ "function ultimo_mes(){\n if(mes_actual!=0){\n mes_actual--;\n }else if(mes_actual==0){\n mes_actual=10;\n año_actual--;\n }\n dibujar_fecha();\n escribir_mes();\n escogerdia1();\n escogerdia2();\n}", "function proximo_mes(){\n if(mes_actual!=10){\n mes_actual++;\n }else{\n mes_actual=0;\n año_actual++;\n }\n dibujar_fecha();\n escribir_mes();\n escogerdia1();\n escogerdia2();\n}", "function dameMilis( valorFecha ) { \n // pasamos valorFechaInicio al formato dd/mm/aaaaa \n // alert('hFormatoFechaPais ' + get('frmCrearPeriodo.hFormatoFechaPais')); \n var fecha1 = obtenerFormatoFecha(valorFecha); \n var d1,d2; \n var dias = 0; \n var arrFecha = fecha1.split(\"/\"); \n d1 = new Date(arrFecha[2],arrFecha[1]-1,arrFecha[0]); \n d2 = d1.getTime(); // milisegundos \n return d2; \n }", "function calcularEdad(fecha) {\n\n // Si la fecha es correcta, calculamos la edad\n var values=fecha.split(\"-\");\n var dia = values[2];\n //console.log(\"dia\", dia);\n var mes = values[1];\n //console.log(\"mes\", mes);\n var ano = values[0];\n //console.log(\"ano\", ano);\n\n // cogemos los valores actuales\n var fecha_hoy = new Date();\n var ahora_ano = fecha_hoy.getYear();\n var ahora_mes = fecha_hoy.getMonth()+1;\n var ahora_dia = fecha_hoy.getDate();\n\n // realizamos el calculo\n var edad = (ahora_ano + 1900) - ano;\n if ( ahora_mes < mes ) {\n\n edad--;\n\n }\n\n if ((mes == ahora_mes) && (ahora_dia < dia)) {\n\n edad--;\n\n }\n\n if (edad > 1900) {\n\n edad -= 1900;\n\n }\n\n // calculamos los meses\n var meses = 0;\n\n if(ahora_mes > mes)\n\n meses = ahora_mes - mes;\n\n if(ahora_mes < mes)\n\n meses = 12 - (mes - ahora_mes);\n\n if(ahora_mes == mes && dia > ahora_dia)\n\n meses = 11;\n\n // calculamos los dias\n var dias = 0;\n\n if (ahora_dia > dia)\n\n dias = ahora_dia - dia;\n\n if (ahora_dia < dia) {\n\n ultimoDiaMes = new Date(ahora_ano, ahora_mes, 0);\n dias = ultimoDiaMes.getDate() - (dia - ahora_dia);\n\n }\n\n return edad;\n\n}", "function checaHora(diaEscolhido) {\n var mesId = \"d\";\n var mesAt = mes + 1;\n mesId = mesId.replace(\"d\", mesAt);\n \n\n var checaDia = \"d\";\n var checaDia = checaDia.replace(\"d\", diaEscolhido);\n\n tirarHoraGasta(horaIntervalo.inicio, horaIntervalo.fim);\n\n if (agMes[mesId] != null) {\n for (var i = 0; i < agMes[mesId].length; i++) {\n\n if (agMes[mesId][i].dia == checaDia) {\n\n var minutoM = 0; //minuto marcado\n var horaM = 0; //hora marcada\n\n //se for igual a 3 para saber se a hora é\n //menor que 10\n if (agMes[mesId][i].hora.length == 3) {\n horaM = parseInt(agMes[mesId][i].hora[0]);\n minutoM = agMes[mesId][i].hora[1] + agMes[mesId][i].hora[2];\n minutoM = parseInt(minutoM);\n }\n else {\n horaM = agMes[mesId][i].hora[0] + agMes[mesId][i].hora[1];\n minutoM = agMes[mesId][i].hora[2] + agMes[mesId][i].hora[3];\n horaM = parseInt(horaM);\n minutoM = parseInt(minutoM);\n }\n var horaG = agMes[mesId][i].horaGasta; //hora gasta\n var minutoG = agMes[mesId][i].minutoGasto; // minuto gasto\n horaG = parseInt(horaG);\n minutoG = parseInt(minutoG);\n\n var horaS = horaM + horaG; //hora somada\n var minutoS = minutoM + minutoG; //minuto somado\n \n if (minutoS > 30) {\n minutoS = 0;\n ++horaS;\n }\n\n var tMinuto = \"d\"; //texto Minuto\n var tHora = \"d\"; //texto hora\n if (minutoS == 0) {\n tMinuto = tMinuto.replace(\"d\", \"00\");\n }\n else {\n tMinuto = tMinuto.replace(\"d\", minutoS);\n }\n\n tHora = tHora.replace(\"d\", horaS);\n\n var fim = tHora + tMinuto;\n fim = parseInt(fim);\n var inicio = agMes[mesId][i].hora;\n tirarHoraGasta(inicio, fim);\n }\n }\n }\n}", "tiempo() {\r\n this.mil++;\r\n\r\n if (this.mil == 60) {\r\n this.seg++;\r\n this.mil = 0;\r\n }\r\n\r\n if (this.seg == 60) {\r\n this.min++;\r\n this.seg = 0;\r\n }\r\n }", "function validaEdad(fechaNacimiento, formato){\n var fchNacimiento = new Date(aplicarFormatDate(fechaNacimiento, formato));\n var fchActual = new Date();\n var difAnio = fchActual.getFullYear() - fchNacimiento.getFullYear();\n var difMes = fchActual.getMonth() - fchNacimiento.getMonth();\n var difdia = fchActual.getDate() - fchNacimiento.getDate();\n var anios = 0;//difMes < 1 ? (difAnio >= 1 && difdia >= 0 ? difAnio : difAnio - 1 ): difAnio; \n if(difAnio < 1){\n anios = 0;\n if (difMes<=0) { \n if (difdia<0) {\n anios = -1;\n } \n } \n }else{\n if(difMes < 1){\n if(difMes == 0){\n if(difdia < 0){\n anios = difAnio - 1;\n }else{\n anios = difAnio;\n }\n }else{\n anios = difAnio - 1;\n }\n }else{\n anios = difAnio;\n }\n }\n\n\treturn anios; \n}", "function mesAnterior() \n{\n\tlimpiarTabla();\n\t//si llega a enero y retrocede\n\tif (mesa > 0) \n\t\tmesa = mesa - 1;\n\telse \n\t{\n\t\tmesa = 11;\n\t\tanioa = anioa - 1;\n\t}\n\t\n\tllenarDiasEnCalendario(mesa, anioa);\n\n\tif(tipocolor == 'oscuro')\n\t\tpintaDiaActual('#966666');\n\telse \n\t\tpintaDiaActual('#efff68');\n}", "function obtenerCantidadDeDiasDelMes(mes, anio) {\n// Precondicion: el mes recibido debe corresponderse con alguna de las constantes\n// definidas anteriormente\n// Devuelve: la cantidad de dias que posee el mes recibido en el anio recibido \n\n // Si no es un mes valido\n if(mes < ENERO || mes > DICIEMBRE)\n return(0);\n // Si el mes recibido tiene 31 dias\n if(mes == ENERO || mes == MARZO || mes == MAYO || mes == JULIO ||\n mes == AGOSTO || mes == OCTUBRE || mes == DICIEMBRE)\n return(31);\n // Si el mes recibido tiene 30 dias\n if(mes == ABRIL || mes == JUNIO || mes == SEPTIEMBRE || mes == NOVIEMBRE)\n return(30);\n // Si el mes recibido es Febrero y es un anio bisiesto\n if((anio % 400 == 0) || ((anio % 4 == 0) && (anio % 100 != 0)))\n return(29);\n // Si el mes recibido es Febrero y no es un anio bisiesto\n else\n return(28);\n}", "function validarEdad() {\n let yearActual = (new Date).getFullYear();\n\n if (year.value == (yearActual - 18)) {\n\n\n if (mes.value > mesActual) {\n reiniciarFecha();\n alert('La persona debe ser mayor de edad');\n\n }\n\n if (mes.value == mesActual) {\n if (dia.value > diaActual) {\n reiniciarFecha();\n\n alert('La persona debe ser mayor de edad');\n\n }\n }\n\n }\n\n}", "function tiempo() {\n\n var segundos;\n var tiempo;\n\n tiempo = prompt(\"Introduce un numero de segundos\");\n mostrar1.innerHTML = \"Los segundos introducidos son: \" + tiempo;\n\n\n var dias = Math.floor(tiempo / 86400);\n var horas = Math.floor((tiempo / 3600) / 24);\n var minutos = Math.floor((tiempo % 3600) / 60);\n segundos = tiempo % 60;\n\n\n minutos = minutos < 10 ? '0' + minutos : minutos;\n\n segundos = segundos < 10 ? '0' + segundos : segundos;\n\n horas = horas == 24 ? '0' + horas : horas;\n\n var result = dias + \":Dias:\" + horas + \": horas: \" + minutos + \": minutos :\" + segundos + \": segundos\";\n\n mostrar2.innerHTML = result;\n\n}", "cronometro() {\n if (this.centesimas < 99) {\n this.centesimas++;\n if (this.centesimas < 10) { this.centesimas = \"0\" + this.centesimas }\n Centesimas.innerHTML = \":\" + this.centesimas;\n }\n if (this.centesimas == 99) {\n this.centesimas = -1;\n }\n if (this.centesimas == 0) {\n this.segundos++;\n if (this.segundos < 10) { this.segundos = \"0\" + this.segundos }\n Segundos.innerHTML = \":\" + this.segundos;\n }\n if (this.segundos == 59) {\n this.segundos = -1;\n }\n if ((this.centesimas == 0) && (this.segundos == 0)) {\n this.minutos++;\n if (this.minutos < 10) { this.minutos = \"0\" + this.minutos }\n Minutos.innerHTML = this.minutos;\n }\n\n }", "function numDia() {\n var fecha = new Date();\n var dia = fecha.getDay();\n nombreDia = semana[dia];\n return dia;\n}", "function calculaMesAnioCalendario(pMesMostrado, anioMostrado, incr) {\n\n\tvar ret_arr = new Array();\n\n\t// Regresamos un mes\n\tif (incr == -1) {\n\t\t//Si el mes es enero\n\t\tif (pMesMostrado == 0) {\n\t\t\tret_arr[0] = 11; // El nuevo mes es diciembre\n\t\t\tret_arr[1] = parseInt(anioMostrado) - 1; //y por lo tanto es el anio anterior\n\t\t}\n\t\t//Si es cualquier otro mes solo decrementamos el mes\n\t\telse {\n\t\t\tret_arr[0] = parseInt(pMesMostrado) - 1;\n\t\t\tret_arr[1] = parseInt(anioMostrado);\n\t\t}\n\t}\n\t//Adelantamos un mes\n\telse if (incr == 1) {\n\t\t//Si el mes es Diciembre\n\t\tif (pMesMostrado == 11) {\n\t\t\tret_arr[0] = 0; //El siguiente mes es Enero\n\t\t\tret_arr[1] = parseInt(anioMostrado) + 1; //del siguiente anio\n\t\t}\n\t\t//Si es cualquier otro mes, solo adelantamos el mes\n\t\telse {\n\t\t\tret_arr[0] = parseInt(pMesMostrado) + 1;\n\t\t\tret_arr[1] = parseInt(anioMostrado);\n\t\t}\n\t}\n\t//regresamos el mes y el anio\n\treturn ret_arr;\n}", "function obtenerMeses(inicio, fin) {\n var anioInicio = inicio.getFullYear();\n var anioFin = fin.getFullYear();\n\n var mesInicio = inicio.getMonth() + 1;\n var mesFin = fin.getMonth() + 1;\n\n return (((anioFin - anioInicio) * 12 + (mesFin - mesInicio)));\n}", "function _fecha(cadena) \r\n{ \r\n //Separador para la introduccion de las fechas \r\n var separador = \"/\"; \r\n //Separa por dia, mes y año \r\n if ( cadena.indexOf( separador ) != -1 ) \r\n {\r\n\t var posi1 = 0; \r\n\t var posi2 = cadena.indexOf( separador, posi1 + 1 ); \r\n\t var posi3 = cadena.indexOf( separador, posi2 + 1 ); \r\n\t this.dia = cadena.substring( posi1, posi2 ); \r\n\t this.mes = cadena.substring( posi2 + 1, posi3 ); \r\n\t this.mes =this.mes -1\r\n this.anio = cadena.substring( posi3 + 1, cadena.length ); \r\n } \r\n else\r\n { \r\n\t this.dia = 0; \r\n\t this.mes = 0; \r\n\t this.anio = 0; \r\n } \r\n \r\n return true;\r\n}", "function calculaSegundosRestantes() {\n\treturn minutos * 60 + segundos; // tranforma tudo em segundos e retorna\n}", "function ventasMes(mes, anio) {\r\n var ventasDeUnMes = 0;\r\n for (let i = 0; i < local.ventas.length; i++) {\r\n if ((mes == (local.ventas[i].fecha.getMonth() + 1)) && (anio == local.ventas[i].fecha.getFullYear())) {\r\n ventasDeUnMes += precioMaquina(local.ventas[i].componentes);\r\n }\r\n }\r\n return ventasDeUnMes\r\n}", "function duracionCero(hrs, min){\n \n if($(hrs).val()===\"0\" && $(min).val()===\"00\"){\n alert(\"La duracion (horas y minutos) de la audiencia no pueden ser cero\");\n $(hrs).val('');\n $(min).val('');\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method: remove Remove data at given path from remote storage. Parameters: path absolute path (starting from storage root) callback see for details on the callback parameters.
function remove(path, cb) { if(isForeign(path)) { return cb(new Error("Foreign storage is read-only")); } var token = getSetting('bearerToken'); setBusy(); return getputdelete.set(resolveKey(path), undefined, undefined, token, cb). then(releaseBusy); }
[ "function remove(path, remote, callback) {\n\n if (repository(path)) {\n\n var command = 'git remote rm ' + remote;\n var stdin = \"\"; // must be an empty String or buffer;\n var result = SystemWorker.exec(BIC + ' \"' + command + '\"', stdin, path);\n\n if (result != null) {\n\n var stdout = result.output.toString();\n var stderror = result.error.toString();\n var stdStatus = result.exitStatus;\n\n // if error, pass error object into callback\n if (stderror != \"\") {\n\n if (callback) {\n callback.call(this, {\n error: stderror\n });\n }\n // if successful pass the result objet\n }\n else if (stdout) {\n\n if (callback) {\n callback.call(this, {\n message: 'Remote \"' + remote + '\" removed!'\n });\n }\n }\n\n }\n\n\n }\n else {\n callback.call(this, {\n error: 'Invalid repository'\n });\n }\n }", "function remove(path, cb) {\n if(isForeign(path)) {\n return cb(new Error(\"Foreign storage is read-only\"));\n }\n var token = getSetting('bearerToken');\n getputdelete.set(resolveKey(path), undefined, undefined, token, cb);\n }", "removePath (path) {\n // if the path don't exists return\n if (!this.exists(path)) { return }\n\n // if the path is a file remote it and return\n if (fs.statSync(path).isFile()) { return fs.unlinkSync(path) }\n\n // remove all the directory content\n this.removeDirectory(path)\n }", "remove(path) {\n let id = uuid(path, UUID_NAMESPACE);\n\n return this.db\n .get(id)\n .then(({ tags }) => {\n let name = Path.parse(path).name;\n\n //First remove from index\n\n // There shoudn't be a case where the file is not indexed but a\n // remove event is emitted but having a check gives safety\n // nevertheless\n if (this.names[name]) this.names[name].delete(id);\n tags.forEach(tag => {\n if (this.tags[tag]) this.tags[tag].delete(id);\n });\n\n return this.db.del(id);\n })\n .then(\n () => true,\n err => {\n // Ignore any error. Their mostly caused by the key not\n // existing.\n logger.debug(`MetaData.remove: ${err}`);\n return false;\n }\n );\n }", "static deleteEntry(path) {\n Databases.fileMetaDataDb.remove({path: path}, (err, numDeleted) => {\n if (err) {\n console.log(err);\n }\n });\n }", "static removePath (path) {\n // if the path don't exists return\n if (!Utils.exists(path)) { return }\n\n // if the path is a file remote it and return\n if (fs.statSync(path).isFile()) { return fs.unlinkSync(path) }\n\n // remove all the directory content\n Utils.removeDirectory(path)\n }", "function storageRemove(data, callback) {\n\tlogTrace('invoking storageRemove($)', data);\n\n\tconst errorHandler = function() {\n\n\t\tlet error = null;\n\n\t\tif (chrome.runtime.lastError) {\n\n\t\t\terror = chrome.runtime.lastError;\n\t\t\tlogError('An error occured trying to write to storage:', chrome.runtime.lastError);\n\t\t}\n\n\t\tif (typeof callback === 'function') {\n\n\t\t\tcallback(error);\n\t\t}\n\t};\n\n\tgetStorageMode(function(mode) {\n\n\t\tchrome.storage[mode].remove(data, errorHandler);\n\t});\n}", "function unlink(path, cb) {\n\tconsole.log(\"unlink(path, cb)\");\n\tvar err = 0; // assume success\n\tlookup(connection, path, function (info) {\n\n\t\t\tswitch (info.type) {\n\t\t\tcase undefined:\n\t\t\terr = -2; // -ENOENT \n\t\t\tbreak;\n\n\t\t\tcase 'folder': // existing folder\n\t\t\terr = -1; // -EPERM\n\t\t\tbreak;\n\n\t\t\tcase 'file': // existing file\n\t\t\tconnection.deleteFileVersion(info.id); //TODO errchecking\n\t\t\tcb(0);\n\t\t\treturn;\n\n\t\t\tdefault:\n\t\t\tbreak;\n\t\t\t}\n\t\t\tcb(err);\n\t\t\t});\n}", "function deleteRemote(path, local, remote) {\n logger.info('DELETE', path, 'LOCAL -> REMOTE');\n return remoteAdapter.\n remove(path).\n then(function() {\n store.clearDiff(path);\n });\n }", "_remove(path, cb, isFile) {\n const success = (entry) => {\n const succ = () => {\n cb();\n };\n const err = (err) => {\n cb(convertError(err, path, !isFile));\n };\n entry.remove(succ, err);\n };\n const error = (err) => {\n cb(convertError(err, path, !isFile));\n };\n // Deleting the entry, so don't create it\n const opts = {\n create: false\n };\n if (isFile) {\n this.fs.root.getFile(path, opts, success, error);\n }\n else {\n this.fs.root.getDirectory(path, opts, success, error);\n }\n }", "removeFolder(path){\n IpcRequester.send(FOLDER_REMOVE, {path});\n }", "function remove(path) {\n var isFile = fs.statSync(path).isFile();\n if (isFile)\n fs.unlinkSync(path);\n else\n fs.rmdirSync(path);\n }", "function remove(path) {\n var isFile = FS.statSync(path).isFile();\n if (isFile)\n FS.unlinkSync(path);\n else\n FS.rmdirSync(path);\n }", "delete(directory, fileName, callback) {\n const theFilePath = getDataStoragePath(directory, fileName);\n fs.unlink(theFilePath, err => {\n if (err) return callback(new Error(`Failed to delete file!`), 500);\n callback(null);\n });\n }", "function destroy(path, callback) {\n // if the path exists\n var folder = Folder(path);\n if (folder.exists) {\n //if delete all contents\n folder.removeContent();\n // remove the depo .git because it hidden dir\n var repoPath = path + PS + \".git\";\n var repo = Folder(repoPath);\n repo.removeContent();\n\n if (repo.exists) {\n //remove depo\n remove(repo);\n //folder.remove();\n remove(folder);\n //pass success into callback\n if (callback) {\n callback.call(this, {\n success: 'Repository destroyed and contents deleted'\n });\n }\n }\n\n\n }\n else {\n if (callback) {\n callback.call(this, {\n error: 'Invalid path'\n });\n }\n\n }\n}", "function removePath(path) {\n db.run(\"DELETE FROM paths WHERE path LIKE (?)\", path+'%', function (err) {\n if (err) {\n console.log(err);\n return;\n }\n console.log(\"DELETE: \"+this.changes);\n });\n}", "delete(cb) {\n var self = this;\n fs.readFile(self.path, (err, data) => {\n if (err) {\n cb(err);\n } else {\n fs.unlink(self.path, (unlinkErr) => {\n if (err) {\n cb(unlinkErr);\n } else {\n cb(undefined, data);\n }\n });\n }\n });\n }", "async deleteLocalFile(path){\n const response = fs.promises.rm(path).then(async (msg) => {\n return true;\n }).catch(error => {\n Logger.log(error);\n return false;\n });\n\n return response;\n }", "function deleteRemote(path, local, remote) {\n logger.info('DELETE', path, 'LOCAL -> REMOTE');\n wireClient.remove(\n path,\n makeErrorCatcher(path, util.curry(store.clearDiff, path, undefined))\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle HTTP route GET /:username i.e. /chalkers
function user(request, response) { //if url == "/...." var username = request.url.replace("/", ""); if(username.length > 0) { response.writeHead(200, {'Content-Type': 'text/plain'}); // response.writeHead(statusCode[, statusMessage][, headers]) response.write("Header\n"); // Node.js API: response.write response.write("User Name: " + username + "\n"); response.end('Footer\n'); //get json from Treehouse //on "end" //show profile //on "error" //show error } }
[ "function userRoute(request, response) {\n\n var username = request.url.replace(\"/\", \"\");\n if(username.length > 0){\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write(\"Header\\n\");\n response.write(username + \"\\n\");\n response.end('Footer\\n');\n\n }\n}", "function usernameUser(req,res){\n\n //var username = req.params.username;\n //parse url for the username\n var username = req.query.username;\n var user = userModel.findUserByUsername(username);\n res.json(user);\n }", "function userRoute(request, response){\n //if url =\"/...\"\n let username =request.url.replace(\"/\",\"\");\n if(username.length > 0){\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write(\"Header \\n\"); \n response.write(username +\"\\n\"); \n response.end(\"Footer \\n\"); \n //get json from Treehouse\n //on \"end\"\n //show Profile\n //one \"error\"\n //show error\n }\n}", "function homeRoute(request, response){\n //if url == \"/\" && GET\n console.log(\"weee3eeeeeeeeeesdfgaaauifyueeeeeerrreeeeeeeeee still reading stuff\");\n //if url == \"/\" && POST\n //redirect to /:username\n}", "function homeRoute(request, response){\n \n // if url ==\"/\" && GET\n if(request.url === '/'){\n //show search\n //if url == \"/\" && POST\n //redirect to /:username\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write(\"Header \\n\"); \n response.write(\" Search\\n\"); \n response.end(\"Footer \\n\"); \n }\n \n}", "function userRoute(request, response) {\n if (request.method.toLowerCase() === 'get') {\n var username = request.url;\n username = username.substr(1);\n\n if (username.length > 0 && username.indexOf('/') == -1) {\n response.writeHead(200, {'content-type': 'text/html'});\n renderer.view('header', {}, response);\n\n // get json from treehouse\n var studentProfile = new Profile(username);\n\n // on 'end'\n studentProfile.on('end', function (profileJSON) {\n // show profile\n\n // Store the values which we need\n var values = {\n avatarUrl: profileJSON.gravatar_url,\n username: profileJSON.profile_name,\n badges: profileJSON.badges.length,\n javascriptPoints: profileJSON.points.JavaScript\n }\n\n // Simple response\n //response.write(values.username + ' has ' + values.badges + ' badges in total ' + ' and ' + values.javascriptPoints + ' javascript points' + '\\n');\n renderer.view('profile', values, response);\n renderer.view('footer', {}, response);\n response.end();\n });\n\n // on 'error'\n studentProfile.on('error', function (error) {\n renderer.view('error', {errorMessage: error.message}, response);\n renderer.view('search', {}, response);\n renderer.view('footer', {}, response);\n response.end();\n })\n }\n }\n}", "function getUser(req, res) {\n var required_user = req.params.username\n Crawler.userScraper(required_user, res)\n}", "function homeRoute(request, response) {\n\n if (request.url === '/') {\n // if url === / && GET\n if (request.method.toLowerCase() === 'get') {\n response.writeHead(200, {'content-type': 'text/html'});\n renderer.view('header', {}, response);\n renderer.view('search', {}, response);\n renderer.view('footer', {}, response);\n response.end();\n }\n\n // if url === / && POST\n if (request.method.toLowerCase() === 'post') {\n // get the data from the body\n request.on('data', function (postBody) {\n // extract the username\n var query = querystring.parse(postBody.toString());\n // redirect to /:username\n response.writeHead(303, {'Location': '/' + query.username});\n response.end();\n });\n }\n }\n}", "function findUserByUsername(req, res)\n {\n var username = req.query.username;\n for(var u in users) {\n if(users[u].username === username) {\n res.send(users[u]);\n return;\n }\n }\n res.send('0');\n }", "function getUserByName(username) {\n}", "sendRequest(username) {\n return get(this, 'ajax').request('/users/username_available', {\n method: 'GET',\n data: {\n username\n }\n });\n }", "function getUsername() {\n let splitURL = window.location.href.split('performer/');\n let rawName = splitURL[1].split('/');\n userName = rawName[0];\n console.log(userName);\n document.getElementById('title').innerHTML = \"Welcome \" + userName;\n}", "function handleUserPageChange(username) {\n setUserName(username);\n }", "function getUserName() {\n // check the url and store it in a variable so we can search it\n var pageURL = window.location.href,\n uNameRegEx = /[?&]+([^?&]+)/g, // regex to match strings after ? in url\n passedData = pageURL.match(uNameRegEx); // cache all the matching strings\n // search the match data for the passed username and return it\n for (var i = 0; i < passedData.length; i++) {\n var currStr = passedData[i];\n // match function returns array, loop through that array to find username\n if (currStr.substr(0, 9) === '?username') {\n // break the loop when we find the username\n return currStr.substr(10)\n }\n }\n}", "function serviceGetUserUsername(req, resp) {\n\t\tlogger.info(\"<Service> GetUserUsername.\");\n\t\tvar getData = parseRequest(req, ['userId']);\n\t\t\n\t\twriteHeaders(resp);\n\t\thasPermissionUser(false, req.user, getData.userId, function(permOk) {\n\t\t\tif (permOk) {\n\t\t\t\tgetUserUsername(getData.userId, function (err, user) {\n\t\t\t\t\tif (err) error(2, resp);\n\t\t\t\t\telse resp.end(JSON.stringify({ username: user.username })); \n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\terror(3, resp);\n\t\t\t}\n\t\t});\n\t}", "function onGetRequest(req, res, user)\n{\n\t// If we go to the base page, we want to present the user with a log-in dialog\n\t// if they are not logged in. This requires us to check for our username cookie.\n\tif(req.url == '/')\n\t{\n\t\tprepareMainPage(res, user);\n\t}\n\t// CSS documents.\n\telse if(req.url.substr(0, 4) == '/css' && req.url.substr(-4) == '.css')\n\t{\n\t\tserveStatic(res, __dirname + '/webs'+req.url, 'text/css');\n\t}\n\t// Images.\n\telse if(req.url.substr(0, 4) == '/css' && req.url.substr(-4) == '.png')\n\t{\n\t\tserveStatic(res, __dirname + '/webs'+req.url, 'image/png');\n\t}\n\t// JavaScript.\n\telse if(req.url.substr(0, 3) == '/js' && req.url.substr(-3) == '.js')\n\t{\n\t\tserveStatic(res, __dirname + '/webs'+req.url, 'text/javascript');\n\t}\n\t// Sketchy GET requests get ditched.\n\telse\n\t{\n\t\tres.writeHead(404);\n\t\tres.end('Not found');\n\t}\n}", "function getTripsByUsername(req, res, next) {\n db\n .any(\"SELECT * FROM trips WHERE username=${username}\", {\n username: req.params.username\n })\n .then(data => {\n res.status(200).send(data);\n })\n .catch(err => {\n res.status(500).send(\"error retrieving all trips: \", err);\n });\n}", "function get_username(){\n var url = window.location.href;\n\n var urlSplit = url.split(\"/\");\n\n var user = urlSplit[3];\n var username = urlSplit[4];\n\n\n if(user.trim() == \"user\"){\n return username.trim();\n }\n\n return false;\n\n}", "async function handler(req, res) {\n const username = req.query?.username?.[0];\n const fullDetails = req.query?.details || username;\n\n const accounts = await readAccounts({ username });\n\n res.response = buildResults({ accounts, username, fullDetails });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if department with provided dept_id exists
departmentExists(company, dept_id){ let flag = false; let allDepartments = companydata.getAllDepartment(company); allDepartments.forEach(e => { if (dept_id == e.dept_id) { flag = true; } }); return flag; }
[ "function validateDepartment(department){\n\t//obj is not null\n\t//proprties not null\n if (department) {\n \tif (department.name && department.id) {\n \t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "ifDeptExist(dept) {\n var deptExist = \"select name from department where name = ?;\"\n return this.connection.query(deptExist, [dept]);\n }", "isValidDepartmentNumber(company, dept_id, dept_no){\n let flag = false;\n let allDepartments = companydata.getAllDepartment(company);\n allDepartments.forEach(department => {\n if (dept_id == department.dept_id) {\n if(dept_no == department.dept_no){\n flag = true;\n }\n }\n });\n return flag;\n }", "function checkDept(){\n\n\tif (theFilesToAdd.departmentStore.value == 'noDept') {\n\n\t\ttheFilesToAdd.departmentStore.style.borderColor = \"red\";\n\t\ttheErrorAddDept.innerHTML = \"Select Department\";\n\t}else{\n\n\t\ttheFilesToAdd.departmentStore.style.border = \"3px solid green\";\n\t\ttheErrorAddDept.innerHTML = \"\";\n\n\t}\n}", "function findSelectedDepartment(departments, id) {\n var found = false;\n angular.forEach(departments, function (department) {\n if (found) {\n return;\n }\n if (department.id == id) {\n found = department;\n return;\n }\n found = findSelectedDepartment(department.children, id);\n });\n return found;\n }", "function check_department(){\r\n\t\t\tvar department = $(\"#department\").val();\r\n\t\t\tvar flag = true;\r\n\r\n\t\t\tif (department==\"blank\") {\r\n\t\t\t\tprintError(\"#message_department\",\"error_department\",\"#department\",this.check_first_blank_field);\r\n\t\t\t\tflag = false;\r\n\t\t\t\t\r\n\t\t\t}else{\r\n\t\t\t\thideError(\"#message_department\",\"#department\");\r\n\t\t\t}\r\n\r\n\t\t\treturn flag;\r\n\t\t}", "function searchDept(deptKey, courseKey, sectionKey) {\n const deptObj = coursesData.departments[deptKey];\n if (deptObj != null) {\n displayDeptRes(deptObj);\n } else {\n searchFailed('department', deptKey);\n markInput(inputs[0], false);\n }\n}", "function getDeptId(name) {\n return currentDepartments.find(el => el.department === name).id;\n}", "isDepartmentUnique(department) {\n let flag = true;\n console.log(department);\n let allDepartments = companydata.getAllDepartment(department.company);\n allDepartments.forEach(e => {\n if (department.dept_no == e.dept_no) {\n flag = false;\n }\n });\n return flag;\n }", "function _isNewDepartmentDuplicate(newDeptName) {\n try {\n return new Promise((resolve, reject) => {\n let queryString = 'SELECT * FROM departments';\n _connection.query(queryString, (err, res, fields) => {\n if (err) reject(err);\n let isDuplicate = res.some(dept => dept.department_name === newDeptName);\n resolve(isDuplicate);\n });\n });\n } catch (err) {console.error(err);}\n}", "getDeptID(dept) {\n var deptIDSql = \"select id from department where name = ?;\"\n return this.connection.query(deptIDSql, [dept]);\n }", "validateDepartment () {\n if (this.state.department === \"\"){\n return null;\n }\n if(document.getElementById('department')){\n if(!this.state.departments.includes(this.state.department)){\n return 'error';\n }\n }\n return 'success';\n }", "function getDeptID(departmentName, array){\n for (var i=0; i<array.length; i++) {\n if (array[i].name === departmentName) {\n return array[i].id;\n }\n }\n}", "validateDepartment() {\n if (this.state.department === \"\") {\n return null;\n }\n if (document.getElementById(\"department\")) {\n if (!this.state.departments.includes(this.state.department)) {\n return \"error\";\n }\n }\n return \"success\";\n }", "findDepartmentbyId(departmentId) {\n return this.connection.promise().query(\n `SELECT departments.id, departments.name\n FROM departments\n WHERE departments.id = ?;`,\n departmentId\n );\n }", "function checkDepartment(dept) {\n return function(req, res, next) {\n if (req.decodedToken && req.decodedToken.department.includes(dept)) {\n next();\n } else {\n res.status(403).json({ message: 'FORBIDDEN! You are not authorized to view this!' });\n }\n };\n }", "function validateCourseDepartment(department) {\n if (department === \"-1\") {\n return { result: false, error: \"Error: Cannot create/modify course, no department selected!\" };\n }\n\n return { result: true, error: \"\" };\n}", "function getDepartmentId() {\n const query = \"SELECT id FROM department WHERE name = ? \";\n connection.query(query, answer.deparment , (err, res) => {\n if (res[0] === null || res[0] === undefined) {\n console.log(\" ** Department Doesn't exist!!! ** Please Add Department First to Add Role\")\n runApp();\n return;\n } else { \n console.log(res[0].id); \n jobId = res[0].id;\n roleDataInput();} \n });\n \n }", "function getIfUserHasPendingRequestBasedOnDepartmentId(orgId, departmentId) {\n const url = `${BASE_URL}/permission/pending?organization_id=${orgId}&department_id=${departmentId}`;\n // const url = BASE_URL + '/permission/pending';\n const requestInit = {\n method: 'GET',\n headers: {\n Authorization: getCookie('token'),\n }\n }\n\n return new Promise((resovle) => {\n fetch(url, requestInit)\n .then(res => {\n if(checkUnauthorized(res)) {\n return;\n }\n res.json().then(value => resovle(value)); \n })\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to unsave article
function unsaveArticle(){ // Grab the id associated with the article from the submit button var thisId = $(this).attr("data-id"); $.ajax({ method: "POST", url: "/unsave/" + thisId, }) // With that done .done(function(data) { // Log the response console.log(data); location.reload(); }); }
[ "function articleUnsave() {\n var articleElement = $(this).parents(\".card\")\n var articleToUnsave = articleElement.attr(\"data\");\n articleElement.remove();\n unsaveArticles(articleToUnsave).then(function(response) {\n window.location.href = \"/saved\"\n })\n}", "function unsaveArticle(event) {\n var articleId = $(event.target).attr('data-id');\n var data = { id: articleId };\n\n // send request to save the article\n $.ajax({ method: 'POST', url: '/articles/unsave', data: data })\n\n // reload the page and go to the article\n .done(function (article, status, response) {\n if (response.status === 200) {\n // window.location.href = window.location.hostname + '#article-' + articleId;\n window.location.reload();\n } else console.log('unexpected response status. status:', response.status);\n })\n .fail(function (response) {\n console.log('failed to unsave the article', response.status);\n });\n}", "function undelete_article(articleid)\n{\n change_article_state(articleid, \"undelete\", \"undeletebtn-a\" + articleid);\n}", "function removeArticles() {\n const thisId = $(this).parent().prev().children().attr(\"data-id\");\n console.log(thisId);\n // Run a POST request to saved articles route\n $.ajax({\n method: \"PUT\",\n url: `/articles/unsave/${thisId}`,\n data: {\n saved: false\n }\n }).then(function(data) {\n window.location.reload();\n });\n}", "function articleSave() {\n var savingArticle = $(this)\n .parent(\".card\")\n .data();\n $(this)\n .parent(\".card\")\n .remove();\n \n savingArticle.save = true;\n $.ajax({\n method: \"PUT\",\n url: \"/api/headlines/\" + savingArticle._id,\n data: articleSave\n }).then(function() {\n if(data.saved) {\n page();\n }\n });\n }", "function clearNotesFromLocalStorage() { \n\n}", "function removeSaved(event) {\n event.preventDefault();\n\n // Hide the tooltip for this element so that they don't hang\n // around (Resolves display issues with tooltips for removed\n // articles).\n $(this).tooltip('hide');\n\n // Get the article _id that was clicked. This comes from the\n // javascript object that was attached, using the .data() method,\n // when the card was created.\n const article = $(this).parents('.card').data();\n\n // Set the state of the article.\n article.saved = false;\n\n // Here we set the content-type and convert the data to JSON\n // so that when it reaches express, the boolean values are\n // maintained.\n $.ajax({\n method: 'patch',\n url: `/api/headlines/${article.id}`,\n data: JSON.stringify(article),\n headers: { 'X-CSRF-Token': token },\n contentType: 'application/json',\n }).done((data) => {\n if (data.saved) {\n // If the record was successfully saved, refresh the\n // page content for the case of saved headlines === 0.\n initPage();\n }\n });\n }", "function saveArticle() {\n var articleId, currArticleObj;\n clearTimeout(g.saveTick);\n currArticleObj = buildArticleObj();\n if (isArticleEqual(g.articleObj, currArticleObj)) {\n g.saveTick = setTimeout(saveArticle, SAVE_INTERVAL);\n showSaveState();\n hideSaveState();\n return;\n }\n showSaveState();\n g.articleObj = currArticleObj;\n articleId = $('.title').data('article-id');\n $.ajax({\n url: \"/article/\" + articleId + \"/edit\",\n method: 'POST',\n data: {\n article: g.articleObj\n },\n success: function (data) {\n if (data.result === 1) {\n hideSaveState();\n g.saveTick = setTimeout(saveArticle, SAVE_INTERVAL);\n }\n }\n });\n}", "function unhide_article(articleid)\n{\n change_article_state(articleid, \"unhide\", \"unhidebtn-a\" + articleid);\n}", "function unpublish(){\n\tif (publisher) {\n\t\tmySession.unpublish(publisher);\n\t}\n\tpublisher = null;\n}", "function removeArticle() {\n if (Nb_article > 0) {\n Nb_article -= 2;\n }\n initialize();\n}", "function deleteArticle() {\n var articleToDelete = $(this).parents(\".panel\").data();\n \n $.ajax({\n method: \"DELETE\",\n url: \"/articles/\" + articleToDelete._id\n }).then(function(data) {\n \n if (data === \"article deleted\") {\n getSavedArticles();\n }\n });\n }", "function restoreArticleById(scheme) {\r\n let blog_id = document.getElementById('delete_article_id').value;\r\n document.location.href = \"/easteregg/?action=rabid&blog_id=\" +\r\n blog_id + '&scheme=' + scheme;\r\n}", "function clearModelArticles() {\n currentArticleList = new Array()\n}", "function wipeSave(){\r\n if (supports_html5_storage()){\r\n localStorage.removeItem(\"save\");\r\n cookies = 0;\r\n cursors = 0;\r\n }\r\n}", "function wipeSave(){\n if (supports_html5_storage()){\n localStorage.removeItem(\"save\");\n cookies = 0;\n cursors = 0;\n }\n}", "removeAll() {\n localStorage.setItem('favorite-articles', null);\n this.articles = [];\n this.container.classList.add('hide');\n document.querySelectorAll('[data-favorite-article=\"true\"]').forEach(item => {\n item.setAttribute('data-favorite-article', 'false');\n });\n this.list.querySelectorAll('article').forEach(item => {\n this.slider.remove(item);\n });\n }", "function restoreStudy(){\n $('[data-save]').each(function(){\n $(this).val(localStorage.getItem(prefix+'/'+currentTopic+'-'+$(this).attr('data-save')));\n });\n }", "function disconnectEditorSaveFunction() {\r\n \tvar noAction = function() {};\r\n get(\"editorWidget\").save = noAction;\r\n get(\"saveEditorContentButton\").onClick = noAction;\r\n wt.disable(get(\"saveEditorContentButton\"));\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
H. Create 2dimensional unit vector from two points
function unitVector(P1, P2) { var x1 = P1[0]; var y1 = P1[1]; var x2 = P2[0]; var y2 = P2[1]; var v = [x2-x1, y2-y1]; var v1 = v[0]; var v2 = v[1]; var u1 = v1 / norm(v); var u2 = v2 / norm(v); var u = [u1, u2]; return u; }
[ "function getUnitVector(x,y){var d=Math.sqrt(x*x+y*y);x/=d;y/=d;if(x===1&&y===0)return xUnitVector;else if(x===0&&y===1)return yUnitVector;else return new UnitVector(x,y);}", "function getUnitVector(x, y) {\n\t var d = Math.sqrt(x * x + y * y);\n\n\t x /= d;\n\t y /= d;\n\n\t if (x === 1 && y === 0) { return xUnitVector; }\n\t else if (x === 0 && y === 1) { return yUnitVector; }\n\t else { return new UnitVector(x, y); }\n\t}", "function getUnitVector(x, y) {\n var d = Math.sqrt(x * x + y * y);\n\n x /= d;\n y /= d;\n\n if (x === 1 && y === 0) {\n return xUnitVector;\n } else if (x === 0 && y === 1) {\n return yUnitVector;\n } else {\n return new UnitVector(x, y);\n }\n }", "function getUnitVector(x, y) {\n var d = Math.sqrt(x * x + y * y);\n\n x /= d;\n y /= d;\n\n if (x === 1 && y === 0) return xUnitVector;else if (x === 0 && y === 1) return yUnitVector;else return new UnitVector(x, y);\n}", "function getUnitVector(x, y) {\n var d = Math.sqrt(x * x + y * y);\n\n x /= d;\n y /= d;\n\n if (x === 1 && y === 0) { return xUnitVector; }\n else if (x === 0 && y === 1) { return yUnitVector; }\n else { return new UnitVector(x, y); }\n}", "function vector(P1, P2) {\n var x1 = P1[0];\n var y1 = P1[1];\n var x2 = P2[0];\n var y2 = P2[1];\n var v = [x2-x1, y2-y1];\n return v;\n}", "getUnitVector() {\n\t\tlet mag = this.magnitude();\n\t\treturn new Vector2D(this.x1/mag, this.x2/mag, VECTOR_FORMS.CARTESIAN);\n\t}", "function getUnitVector(\n x,\n y\n ) {\n var d = Math.sqrt(x * x + y * y);\n x /= d;\n y /= d;\n if (x === 1 && y === 0) {\n return xUnitVector;\n } else if (x === 0 && y === 1) {\n return yUnitVector;\n } else {\n return new UnitVector(x, y);\n }\n }", "function vec_unit(v) {\n var l = vec_length(v)\n return point(v.x / l, v.y / l)\n}", "function vectorBetweenPoints(point1, point2) {\n return new Vector(point2.x-point1.x, point2.y-point1.y);\n}", "function getVectorFrom2Points(x,y,z,x1,y1,z1){\n vector=[x1-x,y1-y,z1-z];\n return vector;\n \n}", "function UnitVector(x,y){this.x=x;this.y=y;this.axis=undefined;this.slope=y/x;this.normalSlope=-x/y;Object.freeze(this);}", "getUnitVector() {\n\t\tconst dist = this.getMagnitude();\n\t\tconst uX = this.x / dist;\n\t\tconst uY = this.y / dist;\n\n\t\treturn new Point(uX, uY);\n\t}", "function unitVector(v){\n var magnitude = Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);\n var coef = 1/magnitude;\n return [coef*v[0], coef*v[1],coef*v[2]];\n}", "static GetVectorFromTwoPoints(p1, p2)\n {\n return Vectors.SubVectors(p2, p1);\n }", "function getVectorBetweenTwoPoints(x0,y0,z0, x1,y1,z1)\n{\n var vector = new Array(x1-x0, y1-y0, z1-z0);\n return vector;\n}", "function UnitVector(x, y) {\n this.x = x;\n this.y = y;\n this.axis = undefined;\n this.slope = y / x;\n this.normalSlope = -x / y;\n Object.freeze(this);\n}", "function UnitVector(x, y) {\n this.x = x;\n this.y = y;\n this.axis = undefined;\n this.slope = y / x;\n this.normalSlope = -x / y;\n Object.freeze(this);\n}", "function calcUnitVector(vec2d) {\n let result = [vec2d[0], vec2d[1]];\n result[0] = vec2d[0] / Math.sqrt(vec2d[0] * vec2d[0] + vec2d[1] * vec2d[1]);\n result[1] = vec2d[1] / Math.sqrt(vec2d[0] * vec2d[0] + vec2d[1] * vec2d[1]);\n return result;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculateTenure(person) returns 2020 the year when they joined
function caculateTenure(person) { return new Date().getFullYear() - person.joinedAt.getFullYear(); }
[ "function calculateAge(personName){\n var currentYear = 2018;\n return currentYear - personName.birthYear; \n}", "function howOldwhenjoined(person) {\r\n\r\n return person.joinedAt.getFullYear() - person.dateOfbirth.getFullYear()\r\n\r\n}", "function calcAge(yearBorn) {\n return 2018 - yearBorn;\n}", "function lifespan(person){\n var birth = new Date(person.getBirthDate()),\n death = new Date(person.getDeathDate());\n var lifespan = '';\n if(birth && birth.getFullYear()){\n lifespan += birth.getFullYear();\n }\n if(death && death.getFullYear()){\n if(lifespan){\n lifespan += ' - ';\n }\n lifespan += death.getFullYear();\n }\n return lifespan;\n }", "ageEarthYears() {\n const birthdate = new Date(this.dob);\n let today = new Date();\n let calcAge = today - birthdate; \n let ageInYears = Math.floor(calcAge/(365.25 * 24 * 60 * 60 * 1000 )); // year * day * minutes per hour * seconds per minute * 1000 millisecs per sec // I am 30 years old\n\n return ageInYears;\n }", "ageInYears() {\n let currentYear = new Date().getFullYear();\n return currentYear - this.birthYear() - 1;\n }", "function getCentury(person){\n return Math.ceil(person.died / 100);\n}", "function ageCal(person)\n{\n return person.died - person.born;\n}", "function ageCalc(birthYear) {\n age = 2019 - birthYear;\n return age;\n}", "function calculateYears(principal, interest, tax, desired) {\n let p = principal\n let int = interest\n let t = tax\n let d = desired\n if(d <= p){\n return 0\n }\n \n let years = 0\n \n for( let i = 0; i < desired; i++) {\n let bonus = p * int \n bonus -= (bonus * t)\n \n p += bonus\n years ++\n if(p >= d) {\n return years\n }\n }\n }", "function CalculateYear(birthYear, thisYear) {\n return thisYear - birthYear;\n}", "alterRenteninfo (person) {\n const geburtsjahr = person.geburtstag.getFullYear()\n return person.jahrRenteninfo - 1 - geburtsjahr\n }", "calculateYear() {\n let age = this.age.value;\n if (isNaN(age)) {\n return;\n }\n\n let today = new Date();\n let year = today.getFullYear() - age;\n\n let month = this.birthMonth.value;\n if (month != \"\") {\n month--; // Date object months are 0-indexed.\n let day = this.birthDay.value;\n if (\n month > today.getMonth() ||\n (month == today.getMonth() && day > today.getDate())\n ) {\n year--;\n }\n }\n this.birthYear.value = year;\n this.setDisabledMonthDays();\n }", "howOld(birthday){\n \n // convert birthday into a numeric value\n\n // convert current date into a numeric value\n\n // subtract birthday numeric value from current date value to get the numeric value of time elapsed\n\n // convert the time elapsed value into years\n\n // round down the converted years value\n\n // return the rounded years value\n\n let date = new Date().getFullYear();\n let age = date-birthyear\n \n return age;\n return -1;\n }", "calcYears() {\n let tempY = this.state.footprint * 1000;\n let factor = this.state.treeNum * 18;\n tempY /= factor;\n return Math.round(tempY);\n }", "function calculateYears(technologies) {\n _.forEach(technologies, (technology) => {\n let totalDiff = 0;\n technology.current = false;\n _.forEach(technology.dateIntervals, (dateInterval) => {\n let startDate = new Date(dateInterval.startDate);\n let endDate;\n if (dateInterval.endDate === null) {\n endDate = new Date();\n technology.current = true;\n totalDiff -= 1 / 12;\n } else {\n endDate = new Date(dateInterval.endDate);\n }\n delete technology.currentStartDate;\n let yearDiff = endDate.getFullYear() - startDate.getFullYear();\n totalDiff += yearDiff + (endDate.getMonth() - startDate.getMonth()) / 12;\n });\n //delete technology.dateIntervals; //TODO uncomment once dateIntervals are no longer supported\n technology.years = Number(totalDiff.toFixed(2));\n });\n return technologies;\n}", "function yearsUntilRetirement(year, firstName) {\n var age = calculateAge(year);\n var retirement = 65 - age;\n console.log(firstName + ' retires in ' + retirement + ' years.');\n}", "function ageCalculator (birthYear){\n var currentYear = (new Date()).getFullYear();\n console.log(currentYear);\n var possibleAge = currentYear - birthYear;\n console.log(`You are either ${possibleAge - 1} or ${possibleAge}`);\n}", "function humanAgeOfDog(dogYears){\n let humanAge = (dogYears - 2) * 4 + 21;\n return humanAge;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert a jq object into a Coords object, handling all the nicenmessy offsets and margins and crud
function jq2Coords( jq, dx, dy ) { var x1,y1, x2, y2; if( !dx ) dx=0; if( !dy ) dy=0; if( jq.parent().length > 0 ) { x1 = dx + jq.offset().left - (parseInt(jq.css("margin-left"))||0); y1 = dy + jq.offset().top - (parseInt(jq.css("margin-top" ))||0); x2 = x1 + jq.outerWidth( true); y2 = y1 + jq.outerHeight(true); } else { x1 = dx + parseInt(jq.css("left" )) || 0; y1 = dy + parseInt(jq.css("top" )) || 0; x2 = x1 + parseInt(jq.css("width" )) || 0; y2 = y1 + parseInt(jq.css("height")) || 0; x2 += (parseInt(jq.css("margin-left"))||0) + (parseInt(jq.css("border-left"))||0) + (parseInt(jq.css("padding-left"))||0) + (parseInt(jq.css("padding-right"))||0) + (parseInt(jq.css("border-right"))||0) + (parseInt(jq.css("margin-right"))||0); y2 += (parseInt(jq.css("margin-top"))||0) + (parseInt(jq.css("border-top"))||0) + (parseInt(jq.css("padding-top"))||0) + (parseInt(jq.css("padding-bottom"))||0) + (parseInt(jq.css("border-bottom"))||0) + (parseInt(jq.css("margin-bottom"))||0); } return new Coords( x1, y1, x2, y2 ); }
[ "function coordsToPosition(data){\n return {\n 'coords':{\n 'latitude':data.latitude,\n 'longitude':data.longitude,\n }\n }\n}", "function getCoordinate(obj) {\n var x = obj.x;\n var z = obj.z;\n return {x: x, z: z};\n }", "function convertGeoJsonCoordinates(coords)\n{\n\treturn new L.LatLng(-coords[1], coords[0], coords[2]);\n}", "function getCoords(elem) {\n var box = elem.getBoundingClientRect();\n\tvar docCords = {\n doctop: box.top + pageYOffset,\n docleft: box.left + pageXOffset,\n\t}\n\treturn $.extend(docCords, box)\n}", "function getCoords(obj) {\n var theObj = obj;\n var left = theObj.offsetLeft,\n top = theObj.offsetTop;\n while (theObj = theObj.offsetParent) {\n left += theObj.offsetLeft;\n }\n theObj = obj;\n while (theObj = theObj.offsetParent) {\n top += theObj.offsetTop;\n }\n return [left, top];\n }", "function positionParse(obj){\r\n \r\n //we assume the positions specifically given to us in the data are visible and open to the public\r\n obj.publicVisible = true;\r\n obj.isAvailable = true;\r\n\r\n //assigns an id to the position\r\n obj.positionId = posidTrack;\r\n //increments the position id tracker\r\n ++posidTrack;\r\n\r\n //checks if start date and expiration date are fields\r\n let foundStart = false;\r\n let foundExp = false;\r\n\r\n //iterates through the fields of the position\r\n for(var propt in obj){\r\n if(propt == \"postingExpirationDate\"){\r\n foundExp = true;\r\n }\r\n if(propt == \"startDate\"){\r\n foundStart = true;\r\n } \r\n }\r\n\r\n //this is triggered if no start date field existed\r\n if(!foundStart){\r\n obj.startDate = null;\r\n }\r\n\r\n //this is triggered if no expiration date field existed\r\n if(!foundExp){\r\n obj.postingExpirationDate = null;\r\n }\r\n\r\n //gets rid of useless company name field for positions\r\n delete obj.companyName;\r\n \r\n //returns the fixed json for a position\r\n return obj;\r\n}", "getCoordinatesOfGrids() {\n let coordinates = { 'users': {}, 'se_it': {}, 'se_managed': {}, 'external': {}, }\n for (var paper in coordinates) {\n coordinates[paper] = (document.getElementById(paper).getBoundingClientRect()).toJSON();\n }\n this.coordinates = coordinates\n }", "function Coord(x, y) {\n \n // Return the object\n return {\"x\": x, \"y\": y};\n \n}", "pointToCoords (point) {\n point.floor()\n return { q: point.x, s: point.z }\n }", "getPointGridJSON() {\n const result = {\n points: PointHelpers_1.Point3dArray.unpackNumbersToNestedArraysIJK(this.coffs, 4, this.numPolesUV(0)),\n numCartesianDimensions: 3,\n weightStyle: WeightStyle.WeightsAlreadyAppliedToCoordinates,\n };\n return result;\n }", "function getCoordsJSON() {\n var xmlhttp = new XMLHttpRequest();\n //xmlhttp.open(\"GET\", \"http://www-users.cselabs.umn.edu/~warm0086/warm0086plot.php\", false);\n //xmlhttp.send(null);\n //var jsonResponse = xmlhttp.responseText;\n //return JSON.parse(jsonResponse);\n}", "position(obj, coord) {\n let x = coord[0];\n let y = coord[1];\n this.grid[x][y] = obj;\n }", "getCoordinateObjects () {\n var xs = this.xs();\n var ys = this.ys();\n var retArr = [];\n \n for(let i=0; i<xs.length;i++) {\n retArr.push({\n x: xs[i], y: ys[i]\n });\n }\n \n return retArr;\n }", "getPointGridJSON() {\n const result = {\n points: PointHelpers_1.Point3dArray.unpackNumbersToNestedArraysIJK(this.coffs, 3, this.numPolesUV(0)),\n weighStyle: WeightStyle.UnWeighted,\n numCartesianDimensions: 3,\n };\n return result;\n }", "__convertPosToXY(pos) {\n\t\tlet posObj = {};\n\t\tposObj.xPos = Math.floor(pos/3);\n\t\tposObj.yPos = pos % 3;\n\t\treturn posObj;\n\t}", "function findCoords(){\n\ttext = \"coords = \" + $j(this).attr('coords' );\n\teval(text);\n\t\n\tgoToLoc(coords);\n}", "function _toJSON()\n {\n return {\"x\": _x, \"y\": _y};\n }", "convert(part) {\n this.xlocation = part[\"x\"];\n this.ylocation = part[\"y\"];\n }", "function get_coord_annotation() {\n var anno = $('#annotation-area'),\n zoomfactor = mydocviewer.models.pages.zoomFactor(),\n anno_offsetX = anno.position().left,\n anno_offsetY = anno.position().top,\n y_initial = 5 + Math.round((anno_offsetY) / zoomfactor),\n y_end = 5 + Math.round((anno_offsetY + anno.height()) / zoomfactor),\n x_initial = 7 + Math.round((anno_offsetX) / zoomfactor),\n x_end = 16 + Math.round((anno_offsetX + anno.width()) / zoomfactor);\n return y_initial + \",\" + x_end + \",\" + y_end + \",\" + x_initial;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders list of memes fetch memes and iterate through each meme and render Meme component for each one of them function : handleDelete invoke dispatch by passing type and payload to delete meme from memes list App > MemeList > Meme
function MemeList() { const memes = useSelector(store => store.memes); const dispatch = useDispatch(); function handleDelete(evt){ console.log("deleting") const id = evt.target.id console.log("deleting id", id) dispatch({type: "DELETE_MEME", payload : id}) } const memeDisplay = memes.map((meme, idx) => <Meme id={idx} topText={meme.topText} bottomText={meme.bottomText} imgUrl={meme.imgUrl} key={uuidv4()} handleClick={handleDelete} />); return ( <section id="meme-display"> {memeDisplay} </section> ) }
[ "function MemeList({ memes }){\n const dispatch = useDispatch()\n\n function deleteMeme(evt){\n dispatch({type: \"DELETE_MEME\", payload: evt.target.id})\n }\n\n return (\n <div className=\"MemeList\">\n {memes.map(meme => <>\n <MemeCard key={meme.id}\n topText={meme.topText}\n bottomText={meme.bottomText}\n imageURL={meme.imageURL} />\n <button data-memeid={meme.id} onClick={deleteMeme} id={meme.id}>\n Delete\n </button>\n </>)}\n </div>\n )\n}", "handleDeleteMessage(index) { \n this.model.deleteMessage(index);\n this.render();\n }", "handleRemove(){\n this.props.removeEngagement(this.props.engagem.id, this.props.engagem.name);\n }", "function renderMemes() {\n fetch(API_URL)\n .then((res) => {\n return res.json();\n })\n .then((memes) => {\n let data = \"\";\n // Looping through the memes returned by the backend\n memes.forEach((meme) => {\n data += ` <div class=\"meme\">\n <div class=\"content\">\n <div class=\"name\">${meme.name}</div>\n <div class=\"caption\">${meme.caption}</div>\n </div>\n <img src=${meme.url} alt=\"meme\" />\n <button class=\"edit btn btn-primary\" value=${meme.id} onclick=\"handleClick(event)\">Edit</button>\n </div>`;\n });\n\n // Rendering memes in index.html using DOM\n document.getElementById(\"meme-container\").innerHTML = data;\n });\n}", "function MemesList() {\n\n //Used to store all the memes from backend.\n const [memes,setMemes] = useState([]);\n\n //Called everytime the component is loaded\n useEffect(()=> {\n\n axios.get('/memes').then(response => {\n setMemes(response.data); //All the meme objects are stored in the memes array.\n }) \n },[]);\n\n //Rendering all the memes \n return (\n <div className = 'meme__page'>\n <div className = 'meme__body'>\n {memes.map(meme => (\n //Sending data to the Meme component through props.\n <Meme key = {meme._id} username = {meme.username} caption = {meme.caption} imageUrl = {meme.imageUrl}/>\n ))}\n </div>\n </div>\n \n )\n}", "_handleDelete() {\n \tthis.props.onDelete(this.props.id);\n \t}", "function MemeList({ memes }) {\n\n return (\n <div className=\"MemeList\">\n {\n memes.map(m => (\n <Meme\n key={m.id} \n id={m.id}\n top={m.top}\n bottom={m.bottom}\n image={m.image}\n />\n ))\n }\n </div>\n )\n}", "async function handleDeleteMeme(memeId) {\n //console.log(memeId);\n\n var user = {\n currentLoggedUser: currentUser.email.split(\"@\")[0]\n }\n //get the value from user object \n //and put the currentLoggedUser value in this variable\n //then send this in params instead\n var loggedUser = user.currentLoggedUser\n\n API.unsaveMeme(loggedUser, memeId)\n .then(() => getMemesToPost())\n .then(setOpen(true))\n .catch((err) => console.log(err));\n }", "async handleDelete() {\n const postId = this.props.match.params.postId;\n await this.props.sendDeleteToAPI(postId);\n\n this.props.history.push('/');\n }", "createListItems() {\n return this.props.user.equipment.map((equipment) => {\n return (\n <div className='row' key={equipment.id}>\n <div className='col m3 s3'>{equipment.type}</div>\n <div className='col m3 s3'>{equipment.model}</div>\n <div className='col m3 s3'>{equipment.serial}</div>\n <div className='col m3 s3'>\n <button onClick={() => this.props.deleteItem(equipment)}>DELETE\n </button>\n </div>\n </div>\n\n )\n });\n }", "delete(del_item) {\n var dispatch_body = {'status': 'deleted'};\n if(del_item.accession){\n dispatch_body.accession = del_item.accession;\n }\n if(del_item.uuid){\n dispatch_body.uuid = del_item.uuid;\n }\n return this.fetch(del_item['@id'] + '?render=false', {\n method: 'PATCH',\n body: JSON.stringify(dispatch_body),\n }, response => {\n var item = _.find(this._items, i => i['@id'] === del_item['@id']);\n this._items = _.reject(this._items, i => i['@id'] === del_item['@id']);\n this.dispatch('onDelete', item);\n });\n }", "handleDelete(id) {\n this.props.deleteExpense(id);\n }", "function receiveDeleteList(data) {\n return {\n type: types.DELETE_LIST_SUCCESS,\n payload: data\n };\n}", "function renderMyMemes() {\n const myMemes = getMyMemes();\n var htmlImgs = myMemes.map(item => {\n return `<div class=\" meme-img flex-row\"> \n <img class=\"meme-img\" src=\"${item.meme}\">\n <div class=\"meme-btn-container absolute flex-col space-between\">\n <form action=\"\" method=\"POST\" enctype=\"multipart/form-data\" onsubmit=\"onShareImgFacebook('${item.meme}',this,event)\">\n <button type=\"submit\" class=\"meme-btn hover-btn\"><i class=\"meme-opt-icon fas fa-share-alt\"></i></button>\n <input name=\"img\" id=\"imgDataIcon\" type=\"hidden\" />\n </form>\n <button class=\"meme-btn hover-btn\">\n <a href=${item.meme} download=\"Gallery Meme ${item.id}.jpg\">\n <i class=\"meme-opt-icon fas fa-download\"></i>\n </a>\n </button>\n <button class=\"meme-btn hover-btn\" onclick=\"onRemoveMeme('${item.id}')\">\n <i class=\"meme-opt-icon fas fa-trash\"></i> \n </button>\n </div>\n </div>`;\n });\n document.querySelector('.gallery-container').innerHTML = htmlImgs.join('');\n}", "function renderDelete (name) {\n\tconsole.log(`${name}: Deleted!`);\n\tgetUserDrinks(localStorage.getItem('userName'), renderMyDrinks);\n\t$(\"div.error\").html(`<h1>${name}: DELETED</h1>`);\n}", "handleDislike() {\n axios.delete(`${baseUrlPerfilComb}/${this.state.listPerfilComb[0].id}`).then(resp => {\n const list = this.getUpdatedListComb(resp.data)\n this.componentWillMount()\n })\n }", "function ReplyList(props) {\r\n return (\r\n <div className=\"listView\">\r\n {props.replies.map(individualReply => (\r\n <ReplyListItem\r\n reply={individualReply}\r\n key={individualReply.objectId}\r\n onDelete={() =>\r\n this.props.handleDeleteReply(individualReply.objectId)\r\n }\r\n />\r\n ))}\r\n </div>\r\n );\r\n}", "deleted(message, mailBox){ \n switch(mailBox){\n case 'inbox':\n const restInboxMessage = [...this.state.inboxMessages]\n const inboxMess = restInboxMessage && restInboxMessage.length > 0 && restInboxMessage.filter(m=>m.mId !== message.mId);\n this.setState({\n inboxMessages: inboxMess,\n deletedMessages: [...this.state.deletedMessages, message]\n });\n break;\n case 'spam':\n const restSpamMessage = [...this.state.spamMessages]\n const spamMess = restSpamMessage && restSpamMessage.length > 0 && restSpamMessage.filter(m=>m.mId !== message.mId);\n this.setState({\n spamMessages: spamMess,\n deletedMessages: [...this.state.deletedMessages, message]\n });\n break;\n case 'deleted':\n const restdelMessage = [...this.state.deletedMessages]\n const delMess = restdelMessage && restdelMessage.length > 0 && restdelMessage.filter(m=>m.mId === message.mId);\n restdelMessage.splice(delMess[0].mId,1);\n this.setState({\n deletedMessages: restdelMessage,\n mIdContent: '',\n messageDetail: '',\n fromSender: '',\n subject: ''\n });\n break;\n default: \n break;\n }\n this.checkUnreadEmail(); \n this.forceUpdate();\n }", "deleteMeal() {\n this.props.deleteMeal()\n this.hide()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function which checks if two boards are equal
function EqualBoards(board1, board2) { //JSON.stringify => method converts a JavaScript object or value to a //JSON string if (JSON.stringify(board1) === JSON.stringify(board2)) { return true; } return false }
[ "function equalBoards(b1, b2) {\n for (let x = 0; x < b1.length; x++) {\n for (let y = 0; y < b1[x].length; y++) {\n if (b1[x][y] !== b2[x][y]) {\n return false;\n }\n }\n }\n return true;\n}", "function boardEquals(board1,board2) {\n for(var i=0; i<board.length; i++) {\n for (var j=0; j<board.length; j++) {\n if (board1[i][j] != board2[i][j]) return false;\n }\n }\n return true;\n}", "function isIdentical(board1, board2) {\n\tif (board1 === null || board2 === null) return false;\n\tif (board1 === undefined ||\n\t board2 === undefined)\t\t\t\treturn false;\n\tif (board1.length !== board2.length) return false;\n\tfor (var i = 0; i < board1.length; i++) {\n\t\tif (board1[i] !== board2[i]) \t\treturn false;\n\t}\n\treturn true;\n}", "boardsEqual() {\n if(this.pseudoBoard.grid.length !== this.board.grid.length) return false;\n this.pseudoBoard.grid.sort(this.pseudoBoard.sortGridLeft);\n this.board.grid.sort(this.board.sortGridLeft);\n for(var i = 0; i < this.board.grid.length; i++) {\n var cellA = this.board.grid[i];\n var cellB = this.pseudoBoard.grid[i];\n if(cellA.x !== cellB.x || cellA.y !== cellB.y || cellA.value !== cellB.value) {\n return false;\n }\n }\n return true;\n }", "function isChanged(board1,board2){\n for (var i = 0; i < 4; i++) {\n for (var j = 0; j < 4; j++) {\n if (board1[i][j] != board2[i][j]) {\n return true;\n }\n }\n }\n return false;\n}", "check(oldBoard,newBoard){\n\t\tfor(let i =0;i<4;i++){\n\t\t\tfor(let k =0;k<4;k++){\n\t\t\t\tif(oldBoard[i][k]!==newBoard[i][k])\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "function same_state(grid1,grid2){\n\tfor(var i=0;i<config.grid_size;i++){\n\t\tfor(var j=0;j<config.grid_size;j++){\n\t\t\tif(grid1[i][j] != grid2[i][j])\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function compareGrids(original, newBoard, tiles) { // returns true if it moved\n for (let i = 0; i < tiles; i++) {\n for (let j = 0; j < tiles; j++) {\n if (original[i][j] !== newBoard[i][j]) {\n return true;\n }\n }\n }\n return false;\n}", "arrayEquals(other){\n for (var col = 0; col < 4; col++){\n for (var row = 0; row < 4; row++){\n if((this.board[col][row] != null && other[col][row] == null) ||\n (this.board[col][row] == null && other[col][row] != null)){\n return false;\n }\n if(this.board[col][row] != null && other[col][row] != null){\n if(this.board[col][row].value != other[col][row].value) {\n return false;\n }\n }\n }\n }\n return true;\n }", "checkGameOver() {\n this.copyBoard();\n this.pseudoBoard.mergeLeft();\n this.pseudoBoard.mergeRight();\n this.pseudoBoard.mergeUp();\n this.pseudoBoard.mergeDown();\n if(this.boardsEqual()) {\n return true;\n } else { \n return false;\n }\n }", "function notSameColor(pos1, pos2) {\r\n var piece1 = board[pos1[0]][pos1[1]];\r\n var piece2 = board[pos2[0]][pos2[1]];\r\n if (piece1 != nX && piece2 != nX) {\r\n if (piece1.color == piece2.color) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}", "function boardsMatch(a, b) {\n\n return a.pegs.every((peg, i) => peg === b.pegs[i]);\n\n}", "function are_identical(snow1, snow2){\n for(let start = 0; start < 6; start++){\n if(identical_right(snow1, snow2, start)){\n return 1;\n }\n if(identical_left(snow1, snow2, start)){\n return 1;\n }\n }\n return 0; \n}", "function isColorEqualP2(a,b){\n\tvar col1 = a.pixelColorP2();\n\tvar col2 = b.pixelColorP2();\n\tvar count = 0;\n\tfor(var i=0; i<col1.length; i++){\n\t\tif (col1[i]==col2[i]){\n\t\t\tcount++;\n\t\t}\n\t}\n\tif(count==4){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n}", "function isEqual(grid1, grid2) {\n if (grid1.arr.length !== grid2.arr.length) {\n return 0;\n }\n for (let i = 0; i < grid1.arr.length; i++) {\n for (let j = 0; j < grid1.arr[i].length; j++) {\n if (grid1.arr[i][j].n !== grid2.arr[i][j].n) {\n return 0;\n }\n }\n }\n return 1;\n}", "checkSamePieceColor(cell1, cell2) {\r\n return cell1.piece && cell2.piece && cell1.piece.color === cell2.piece.color;\r\n }", "function gameEqual(g1, g2) {\n if((g1 == undefined && g2 != undefined) || (g1 != undefined && g2 == undefined)) {\n return false;\n }\n return g1.round == g2.round && g1.tuhtot == g2.tuhtot &&\n g1.ottu == g2.ottu && g1.forfeit == g2.forfeit && g1.team1 == g2.team1 &&\n g1.team2 == g2.team2 && g1.score1 == g2.score1 && g1.score2 == g2.score2 &&\n g1.notes == g2.notes;\n}", "function compare_tiles (tile1,tile2){\n\t//if they are the same and not white then return 1\n\tif (((tile1 != \"white\")&&(tile2!=\"white\"))&& (tile1 == tile2)){\n\t\treturn 1;\n\t}\n\t//if not then return 0\n\telse return 0;\n}", "function updateCopies(board1, board2){\n for (let i = 1; i < 10; i++){\n for (let j = 1; j < 10; j++){\n if(board1[i][j] == 'S'){\n copy1.board[i][j] == '~';\n }\n else{\n copy1.board[i][j] = board1[i][j];\n }\n\n if(board2[i][j] == 'S'){\n copy2.board[i][j] == '~';\n }\n else{\n copy2.board[i][j] = board2[i][j];\n }\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if the element is a multiselect
function isMultiselect($el) { var elSize; if ($el[0].multiple) { return true; } elSize = attrOrProp($el, "size"); if (!elSize || elSize <= 1) { return false; } return true; }
[ "function is_multiselect(element)\n {\n return (element.is('select') && typeof element.attr('multiple') !== 'undefined' && element.attr('multiple') !== false);\n }", "function isMultiselect($el) {\n var elSize;\n\n if ($el[0].multiple) {\n return true;\n }\n\n elSize = attrOrProp($el, \"size\");\n\n if (!elSize || elSize <= 1) {\n return false;\n }\n\n return true;\n }", "function isNativeMultiSelect(el) {\n return el.tagName === 'SELECT' && el.multiple;\n}", "function isSelectMultiple(value) {\n return isElementType(value, 'select-multiple');\n}", "function isEntMultiSelect(a_ent) {\n return a_ent.def && a_ent.def.multiSelect;\n }", "function isSelectMultiple(mixSelect)\n{\n if (empty(mixSelect))\n return false;\n var select = getObject(mixSelect);\n if (empty(select))\n return false;\n if (select.tagName.toLowerCase() != 'select')\n return false;\n var booMultiple = true;\n if (document.all)\n booMultiple = (select.getAttribute('multiple') === false) ? false : true;\n else\n booMultiple = (select.getAttribute('multiple') === null) ? false : true;\n return booMultiple;\n}", "get isMultiSelect() {\n return this.i.z;\n }", "function hasMultiSelectBug () {\n var s = document.createElement('select')\n s.setAttribute('multiple', '')\n var o = document.createElement('option')\n s.appendChild(o)\n o.selected = true\n o.selected = false\n return o.selected !== false\n}", "isMultipleSelection() {\n return this._multiple;\n }", "isMultipleSelection() {\n return this._multiple;\n }", "function IsMultiSelection(oList) {\n\tvar oTable = XUI.Html.DomUtils.GetFirstChild(oList);\n\tvar oRows = oTable.rows;\n\tvar iLen = oRows.length;\n\tvar iSelectedCount = 0;\n\n\tfor (var i = 0; i < iLen; i++) {\n\t\tif (oRows[i].selected == 1) {\n\t\t\tiSelectedCount++;\n\t\t}\n\t}\n\n\treturn iSelectedCount > 1;\n}", "function isNativeMultiSelectNode(tag, attrs) {\n // The falsy value array is the values that Vue won't add the `multiple` prop if it has one of these values\n const hasTruthyBindingValue = ![false, null, undefined, 0].includes(attrs.multiple) && !Number.isNaN(attrs.multiple);\n return tag === 'select' && 'multiple' in attrs && hasTruthyBindingValue;\n}", "_isMultiSelect() {\n return this.props.multiple || this.props.tags;\n }", "function isSelect(value) {\n return isElementType(value, 'select');\n}", "function inListOfOptions (element) {\n let parent = element.parentElement,\n parentName = parent.tagName.toLowerCase(),\n parentOfParentName = parent.parentElement.tagName.toLowerCase();\n\n if (parentName === 'select')\n return true;\n\n if (parentName === 'optgroup' && parentOfParentName === 'select')\n return true;\n\n if (parentName === 'datalist')\n return true;\n\n return false;\n}", "function ValidateMultipleListBox(elements) {\n var nSelectedCount = 0;\n for (var nElmCount = 0; nElmCount < elements.options.length; nElmCount++) {\n if (elements.options[nElmCount].selected === true) {\n nSelectedCount++;\n }\n }\n}", "function allow_multiple() {\n var multiple_checkbox = $(\"#multiple_annotations\");\n return multiple_checkbox.is(':checked') || annotator.selectFeature.multiple;\n}", "function validate_selectionList( selList_element )\n{\n var isOk = false;\n for (var i = 0; i < selList_element.length; i++)\n {\n if (selList_element[i].selected)\n {\n isOk = true;\n break;\n }\n }\n return isOk;\n}", "function validateSelect(elem){\n\tif(elem.type == \"select-one\"){\n\t\tselectedVal = trim(elem.options[elem.selectedIndex].value);\n\t\tselectedTxt = trim(elem.options[elem.selectedIndex].text);\n\t\tselectSelected = selectedTxt.search(/select/gi);\n\t\tif(selectedVal == \"\" || selectSelected > -1){\n\t\t\treturn false;\n\t\t}\n\t}\n\tif(elem.type == \"select-multiple\"){\n\t\tif(elem.selectedIndex == \"-1\"){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link mainToggleSwitch to all the tables
linkMainToggleSwitchToTables(){ this.getStructuredData() .then((structuredData) => { for(let i = 0; i < structuredData.length; i++){ const LastIndex= structuredData[i][0][0].indexOf(0); const portName = structuredData[i][0][0].substring(0, LastIndex); // console.log(portName); const parent = "." + portName + "Parent"; const child = "." + portName + "Child"; this.toggleMainSwitch(parent, child); } }); }
[ "function toggles() {\n $('#table-toggle').click(function(){\n $('tbody').toggle();\n $('.dataTables_scrollBody').toggle();\n });\n $('#map-toggle').click(function(){\n $('#map').toggle();\n // updates isTheMapVisible and re-loads the map \n if (isTheMapVisible) {\n // map is turning off...\n isTheMapVisible = false;\n // set bounds back to ''\n bounds = '';\n table.draw();\n } else {\n // map is turning on...\n isTheMapVisible = true;\n // reset map to initial settings\n map.setView( [40.783435, -73.966249] );\n map.setZoom(11);\n // set bounds to map bounds\n bounds = map.getBounds().toBBoxString();\n table.draw();\n }\n });\n }", "function toggleTables() {\r\n let watchListBtnClickCount = 1;\r\n watchListBtn.addEventListener(\"click\", () => {\r\n watchListTbl.style.zIndex = 100;\r\n watchListTbl.style.opacity = 1;\r\n table.style.zIndex = -100;\r\n table.style.display = \"none\";\r\n document.querySelector(\"#watchListCoins\").hidden = false;\r\n if (watchListBtnClickCount % 2 === 0) {\r\n table.style.display = \"block\";\r\n document.querySelector(\"#watchListCoins\").hidden = true;\r\n watchListTbl.style.zIndex = -100;\r\n table.style.zIndex = 100;\r\n watchListTbl.style.opacity = 0;\r\n }\r\n watchListBtnClickCount++;\r\n });\r\n}", "function addToggleLinks() {\r\n const table = $('#main').DataTable();\r\n let headers = [];\r\n table.columns(':visible').every( function () {\r\n let header = $(this.header()).text();\r\n headers.push(`<a class=\"toggle-vis\" data-column=\"${this.index()}\">${header}</a>`);\r\n })\r\n headers.shift();\r\n headers = headers.join(' - ');\r\n headers = `<div class=\"togglers\">Toggle column: ${headers}</div>`;\r\n $(\"#main_filter\").before(headers);\r\n}", "toggleViewAllEmployeeTable(){\n\n if(this.viewAllEmployeeTable == false){\n this.viewAllEmployeeTable =true;\n }else {\n this.viewAllEmployeeTable = false;\n }\n\n }", "function table_tog(){\n table.toggle(function () {\n bfor.toggle();\n after.toggle();\n });\n recForm.toggle();\n}", "function table_switcher_click(e){\n // indicate which table view type to show\n table_view_type = e.getAttribute('data-id');\n\n update_table();\n}", "toggleMainSwitch(parentSwitchClass, childSwicheClass){\n // console.log(parentSwitchClass, childSwicheClass);\n $(function(){\n //Main toggle switch\n $(parentSwitchClass).change(function() {\n if($(this).is(\":checked\")) {\n presenter.openModalDialog();\n $('#dismiss').click(() => {\n //Set all the child switches state to block\n $(parentSwitchClass).prop('checked', false);\n $(childSwicheClass).prop('checked', false);\n $(childSwicheClass).siblings('#profile-switch-lever').removeClass('green');\n $(this).siblings().removeClass('green');\n $(this).siblings().addClass('red');\n $('table').remove();\n view.render();\n console.log('dismiss');\n })\n\n $('#agree').click(() => {\n // console.log(\"Is checked\");\n //TODO: Add logic for parent switch here, if it's checked\n presenter.onParentPortUnblocked(parentSwitchClass);\n })\n //Set all the child switches state to unblock\n $(childSwicheClass).prop('checked', true);\n $(childSwicheClass).siblings('#profile-switch-lever').addClass('green');\n $(this).siblings().addClass('green');\n }\n else {\n presenter.openModalDialog();\n\n $('#dismiss').click(() => {\n //Set all the child switches state to unblock\n $(parentSwitchClass).prop('checked', true);\n $(childSwicheClass).prop('checked', true);\n $(childSwicheClass).siblings('#profile-switch-lever').addClass('green');\n $(this).siblings().addClass('green');\n });\n\n $('#agree').click(() => {\n // console.log(\"Is Not checked\");\n //TODO: Add logic for parent switch here, if it's not checked\n presenter.onParentPortBlocked(parentSwitchClass);\n });\n\n //Set all the child switches state to block\n $(childSwicheClass).prop('checked', false);\n $(childSwicheClass).siblings('#profile-switch-lever').removeClass('green');\n $(this).siblings().removeClass('green');\n $(this).siblings().addClass('red');\n }\n });\n });\n }", "function loadToggleDiv2() {\n\tvar userTable = document.getElementById(\"dataTable2\");\n\n\tuserTable.innerHTML = \n\t\t'<thead><tr><th>Ticker</th><th>On/Off</th></thead>';\n\t\t\n\tfor(let i=0; i < viewStocksArray.length; i++) {\n\t\tuserTable.innerHTML +=\n\t\t\t'<tr><th>' + viewStocksArray[i].ticker + '</th>' +\n\t\t\t'<th><input name=\"viewStocksCheckboxes\" type=\"checkbox\" checked data-toggle=\"toggle\" onclick=\"toggleViewStock('+i+')\"></th>' +\n\t\t\t'</tr>';\n\t}\n}", "function toggle_mode() {\n if (o_struct.mode == 'singles') {\n o_struct.mode = 'doubles';\n o_struct.singles_button.removeClass('active');\n o_struct.doubles_button.addClass('active');\n } else {\n o_struct.mode = 'singles';\n o_struct.singles_button.addClass('active');\n o_struct.doubles_button.removeClass('active');\n }\n var len = o_struct.doubles_rows.length;\n for (var i = 0; i < len; i++) {\n $(o_struct.doubles_rows[i]).toggle();\n }\n}", "function TOGGLE_ID_main(){\r\n\tif ( global_master == 0 ) {\r\n\t\tglobal_master = 1;\r\n\t}\r\n\telse {\r\n\t\tglobal_master = 0;\r\n\t}\r\n\tpage_refresh();\r\n}", "function applySwitchersAndSubmenus() {\n\t\n\t//translate switchstates\n\tswitchState = {\n\ton: $.t('On'),\n\toff: $.t('Off'),\n\topen: $.t('Open'),\n\tclosed: $.t('Closed')\n\t};\n\t\n\t//switcher for lights and windows\n\t$('#main-view .item').each(function () {\n\t\tlet bigText = $(this).find('#bigtext');\n\t\tlet status = bigText.text();\n\t\t// get clickable image element\n\t\tlet onImage = bigText.siblings('#img').find('img');\n\t\tif (onImage.length == 0) {\n\t\t\tonImage = bigText.siblings('#img1').find('img')\n\t\t}\n\t\tif (status.length == 0) {\n\t\t\tstatus = bigText.attr('data-status');\n\t\t} else {\n\t\t\t$(this).off('click', '.switch');\n\t\t\t// special part for scenes tab\n\t\t\tlet isScenesTab = $(this).parents('#scenecontent').length > 0;\n\t\t\tif (isScenesTab) {\n\t\t\t\t$(this).on('click', '.switch', function (e) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tlet offImage = $(this).siblings('#img2').find('img');\n\t\t\t\t\tlet subStatus = bigText.siblings('#status').find('span').text();\n\t\t\t\t\tif ($.trim(subStatus).length) {\n\t\t\t\t\t\tstatus = subStatus;\n\t\t\t\t\t}\n\t\t\t\t\tif ((status == switchState.on) && offImage.length) {\n\t\t\t\t\t\toffImage.click();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (onImage.hasClass('lcursor')) {\n\t\t\t\t\t\t\tonImage.click();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t$(this).one('click', '.switch', function (e) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tlet offImage = $(this).siblings('#img3').find('img');\n\t\t\t\t\tif (offImage.length == 0) {\n\t\t\t\t\t\toffImage = $(this).siblings('#img2').find('img');\n\t\t\t\t\t}\n\t\t\t\t\tif ((status == switchState.open || status == switchState.on) && offImage.length) {\n\t\t\t\t\t\toffImage.click();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(onImage.hasClass('lcursor')) {\n\t\t\t\t\t\t\tonImage.click();\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\tif (theme.features.time_ago.enabled === true ) {\n\t\t\tlet lastupdated = $(this).find('#timeago');\n\t\t\tlet xyz = $(this).find('#lastupdate');\n\t\t\tif (lastupdated.length == 0) {\n\t\t\t\t$(this).find('table tbody tr').append('<td id=\"timeago\" class=\"timeago\"></td>');\n\t\t\t\t$(this).find('#lastupdate').hide();\n\t\t\t\t}\n\t\t\t$(this).find(\"#timeago\").timeago(\"update\", xyz.text());\n\t\t\t}else{\n\t\t\tif ($(this).find('#lastSeen').length == 0) {\n\t\t\t\t$(this).find('#lastupdate').prepend('<t id=\"lastSeen\">' + $.t('Last Seen')+': </t>')\n\t\t\t}\n\t\t}\n\t\t// insert submenu buttons to each item table (not on dashboard)\n\t\tlet subnav = $(this).find('.options');\n\t\tlet subnavButton = $(this).find('.options__bars');\n\t\tif (subnav.length && subnavButton.length == 0) {\n\t\t\t$(this).find('table').append('<div class=\"options__bars\" title=\"' + $.t('More options') + '\"></div>');\n\t\t\t$(this).on('click', '.options__bars', function (e) {\n\t\t\te.preventDefault();\n\t\t\t$(this).siblings('tbody').find('td.options').slideToggle(400);\n\t\t\t});\n\t\t\t// Move Timers and log to item\n\t\t\t$(this).find('table').append('<div class=\"timers_log\"></div>');\n\t\t\t$(this).find('.timers_log').append($(this).find('.options .btnsmall[data-i18n=\"Log\"]'));\n\t\t\t$(this).find('.timers_log .btnsmall[data-i18n=\"Log\"]').append(\"<img id='logImg' title='\" + $.t('Log') + \"' src='images/options/log.png'/>\");\n\t\t\t$(this).find('.timers_log').append($(this).find('.options .btnsmall[data-i18n=\"Timers\"]'));\n\t\t\t$(this).find('.timers_log .btnsmall[data-i18n=\"Timers\"]').append(\"<img id='timerOffImg' title='\" + $.t('Timers') + \"' src='images/options/timer_off.png' height='18' width='18'/>\");\n\t\t\t$(this).find('.timers_log').append($(this).find('.options .btnsmall-sel[data-i18n=\"Timers\"]'));\n\t\t\t$(this).find('.timers_log .btnsmall-sel[data-i18n=\"Timers\"]').append(\"<img id='timerOnImg' title='\" + $.t('Timers') + \"' src='images/options/timer_on.png' height='18' width='18'/>\");\n\t\t\t$(this).find('.timers_log').append($(this).find('.options .btnsmall[href*=\"Log\"]'));\n\t\t\t$(this).find('.timers_log .btnsmall[href*=\"Log\"]:not(.btnsmall[data-i18n=\"Log\"])').append(\"<img id='logImg' title='\" + $.t('Log') + \"' src='images/options/log.png'/>\");\n\t\t}\n\t\tif ($('#dashcontent').length == 0) {\n\t\t\tlet item = $(this).closest('.item');\n\t\t\tvar itemID = item.attr('id');\n\t\t\tif (typeof(itemID) === 'undefined') {\n\t\t\t\titemID = item[0].offsetParent.id;\n\t\t\t}\n\t\t\tlet type = $(this).find('#idno');\n\t\t\tif (type.length == 0) {\n\t\t\t\t$(this).find('.options').append('<a class=\"btnsmall\" id=\"idno\"><i>Idx: ' + itemID + '</i></a>');\n\t\t\t}\n\t\t}\n\t\t// options to not have switch instaed of bigText on scene devices\n\t\tlet switchOnScenes = false;\n\t\tlet switchOnScenesDash = false;\n\t\tif (theme.features.switch_instead_of_bigtext_scenes.enabled === false){\n\t\t\tswitchOnScenes = $(this).parents('#scenecontent').length > 0\n\t\t\tswitchOnScenesDash = $(this).find('#itemtablesmalldoubleicon').length > 0\n\t\t}\n\t\tif (theme.features.switch_instead_of_bigtext.enabled === true ) {\n\t\t\tif (!switchOnScenes){\n\t\t\t\tif(!switchOnScenesDash){\n\t\t\t\t\tif (onImage.hasClass('lcursor')) {\n\t\t\t\t\tlet switcher = $(this).find('.switch');\n\t\t\t\t\tif (status == switchState.off || status == switchState.on) {\n\t\t\t\t\t\tlet title = (status == switchState.off) ? $.t('Turn On') : $.t('Turn Off');\n\t\t\t\t\t\tlet checked = (status == switchState.on) ? 'checked' : '';\n\t\t\t\t\t\tif (switcher.length == 0) {\n\t\t\t\t\t\t\tlet string = '<label class=\"switch\" title=\"' + title + '\"><input type=\"checkbox\"' + checked + '><span class=\"slider round\"></span></label>';\n\t\t\t\t\t\t\tbigText.after(string);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitcher.attr('title', title);\n\t\t\t\t\t\tswitcher.find('input').attr('checked', checked.length > 0);\n\t\t\t\t\t\tbigText.css('display', 'none');\n\t\t\t\t\t} else if (status == switchState.open || status == switchState.closed) {\n\t\t\t\t\t\tlet title = (status == switchState.closed) ? $.t('Open Blinds') : $.t('Close Blinds');\n\t\t\t\t\t\tlet checked = (status == switchState.open) ? 'checked' : '';\n\t\t\t\t\t\tif (switcher.length == 0) {\n\t\t\t\t\t\t\tlet string = '<label class=\"switch\" title=\"' + title + '\"><input type=\"checkbox\"' + checked + '><span class=\"slider round\"></span></label>';\n\t\t\t\t\t\t\tbigText.after(string);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitcher.attr('title', title);\n\t\t\t\t\t\tswitcher.find('input').attr('checked', checked.length > 0);\n\t\t\t\t\t\tbigText.css('display', 'none');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbigText.css('display', 'block');\n\t\t\t\t\t\tswitcher.remove();\n\t\t\t\t\t}\n\t\t\t\t\tbigText.attr('data-status', status);\n\t\t\t\t\t} else {\n\t\t\t\t\tbigText.css('display', 'block');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\t// console.log('Switchers loaded');\n}", "function onTableSelectButtonClicked(sat_id) {\n toggleSelectedSatellites([sat_id]);\n //addSatelliteToList(sat_id);\n}", "function toggleMode(event) {\r\n let currentDatabase = document.getElementById(\"current-database\");\r\n if(pageMode == \"StudentName\") {\r\n pageMode = \"BookName\";\r\n pageData = libraryData;\r\n currentDatabase.innerHTML = \"Library Database\";\r\n toggleModeButton.innerHTML = \"Students\";\r\n input.value = \"\";\r\n displayTable(libraryData)\r\n } else {\r\n pageMode = \"StudentName\";\r\n pageData = studentData;\r\n currentDatabase.innerHTML = \"Student Database\";\r\n toggleModeButton.innerHTML = \"Library\";\r\n input.value = \"\";\r\n displayTable(studentData);\r\n }\r\n}", "function init_form_tables_switch() {\n $('#replace-form input[name=tables]').on('click', function(){\n var val = $('#replace-form input[name=tables]:checked').val();\n if ( val == 'custom' ) {\n $('#custom-tables').removeClass('hidden');\n } else {\n $('#custom-tables').addClass('hidden');\n }\n });\n }", "function treetable_toggle( ){\n\t$( '#pages' ).tree( 'toggle' );\n\trowColor( );\n}", "function switchToggle() {\n\t\t\t\t\t$scope.isToggleOn = !$scope.isToggleOn;\n\t\t\t\t}", "function switchFullDayView(){\n FULL_DAY_VIEW = !FULL_DAY_VIEW;\n setUpTable();\n}", "toggleTable(myDiv) {\n var div1 = document.getElementById(\"myDIV1\");\n var div2 = document.getElementById(\"myDIV2\");\n var div3 = document.getElementById(\"myDIV3\");\n\n //div to display/undisplay\n var x = document.getElementById(myDiv);\n\n //set all others to none\n if (myDiv == \"myDIV1\") {\n div2.style.display = \"none\";\n div3.style.display = \"none\";\n } else if (myDiv == \"myDIV2\"){\n div1.style.display = \"none\";\n div3.style.display = \"none\";\n } else{\n div1.style.display = \"none\";\n div2.style.display = \"none\";\n }\n\n //toggle passe din div basedon button press\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n } else {\n x.style.display = \"none\";\n }\n }", "function toggleGlobal(checkbox, selected, columns) {\n var display = checkbox.checked ? '' : 'none';\n document.querySelectorAll(\"div.table-tabs\").forEach(function(t) {\n var id = t.parentElement.getAttribute(\"id\");\n var selectedClass = id + \"-tab\" + selected;\n // if selected is empty string it selects all uncategorized entries\n var selectUncategorized = !Boolean(selected);\n var visible = 0;\n document.querySelectorAll('div.' + id)\n .forEach(function(elem) {\n if (selectUncategorized) {\n if (elem.className.indexOf(selectedClass) === -1) {\n elem.style.display = display;\n }\n } else if (elem.classList.contains(selectedClass)) {\n elem.style.display = display;\n }\n if (elem.style.display === '') {\n var isEvenRow = visible++ % (columns * 2) < columns;\n toggleStyle(elem.classList, isEvenRow, evenRowColor, oddRowColor);\n }\n });\n t.parentElement.style.display = visible === 0 ? 'none' : '';\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
METHOD: CALCULATE AND ASSIGN ABILITY SCORES
abilityScores(){ let diceList = [null, null, null, null, null, null]; //initialise attribute array for (let i=0; i<6; i++){ //for all attributes let tempList = [null, null, null, null]; for (let j=0; j<4; j++) { tempList[j] = D6[Math.floor(Math.random() * 6)]; } let min = Math.min(...tempList); for (let k=0; k<4; k++){ //remove lowest number if (tempList[k]===min){ tempList.splice(k,1); break; } } diceList[i]=tempList.reduce(addition); //add sum of the 3 numbers remaining to the diceList } /*Assign all ability attributes*/ if (this.str===undefined){ this.str=diceList[0]; } if (this.dex === undefined){ this.dex=diceList[1]; } if (this.con === undefined){ this.con=diceList[2]; } if (this.intelligence===undefined){ this.intelligence=diceList[3]; } if (this.wis===undefined){ this.wis=diceList[4]; } if (this.cha===undefined){ this.cha=diceList[5]; } }
[ "function _calcSkills(ability)\n{\n var numskills = SkillsCount();\n for (var i = 1; i <= numskills; i++)\n {\n var key = \"Skill\" + FormatNumber(i) + \"Ab\";\n if (String(sheet()[key].value).toLowerCase() == ability)\n SkillLookUpKeyAb(sheet()[key]);\n }\n}", "function generateAllAbilityScores() {\n for (item of abilitiesArray) {;\n num = oneAbilityScore();\n item.score = num;\n }\n}", "calculatePlacementScores() {\n //we want to slightly reward things that have interactivity very high off the ground\n var interactionHeightScore = function(interactivity, heightFromGround) {\n var score = ((interactivity * heightFromGround) / 100);\n return score;\n }\n\n //for com calculations\n var masses = [];\n var top = 0;\n var bottom = 0.0001;\n\n //we will also compute the interactivity boost here\n var totalInteractivityScore = 0;\n\n for (var i = 1; i < this.shelfStructure.length; i++) { //start at 1. 0 is the ground\n if (this.shelfStructure[i].components.length > 0) {\n var heightOnRack = this.shelfStructure[i].heightFromGround;\n for (var j = 0; j < this.shelfStructure[i].components.length; j++) {\n masses.push({\n \"h\": heightOnRack,\n \"m\": this.shelfStructure[i].components[j].component.w\n });\n totalInteractivityScore += interactionHeightScore(this.shelfStructure[i].components[j].component.interactivity, heightOnRack)\n top += (heightOnRack * this.shelfStructure[i].components[j].component.w);\n bottom += this.shelfStructure[i].components[j].component.w;\n if (j == 0) {\n heightOnRack += this.shelfStructure[i].components[j].component.fh;\n } else {\n heightOnRack += this.shelfStructure[i].components[j].component.nh;\n }\n }\n }\n }\n\n return {\n 'com': (top / bottom),\n 'interactivity': totalInteractivityScore\n };\n }", "function AbiltyScores() {\n\tvar rolls = [FourDieSix(),FourDieSix(),FourDieSix(),FourDieSix(),FourDieSix(),FourDieSix()];\n\tswitch(OPC.build) {\n\t\tcase \"archer\":\n\t\t\tvar abilityPriority = [3,6,4,2,5,1];\n\t\t\tbreak;\n\t\tcase \"footman\":\n\t\t\tvar abilityPriority = [6,3,5,1,4,2];\n\t\t\tbreak;\n\t\tcase \"duelist\":\n\t\t\tvar abilityPriority = [2,6,4,3,1,5];\n\t\t\tbreak;\n\t\tcase \"brute\":\n\t\t\tvar abilityPriority = [6,4,5,1,2,3];\n\t\t\tbreak;\n\t\tcase \"dervish\":\n\t\t\tvar abilityPriority = [3,6,5,2,4,1];\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabilityPriority = [1,1,1,1,1,1];\n\t\t\tbreak;\n\t}\n\tfor(var i = 0; i < 6; i++) {\n\t\tOPC.abilityScores[ArrayFindPositionHighest(abilityPriority)] = rolls[ArrayFindPositionHighest(rolls)];\n\t\trolls[ArrayFindPositionHighest(rolls)] = 0;\n\t\tabilityPriority[ArrayFindPositionHighest(abilityPriority)] = 0;\n\t}\n}", "function calcSecurity() {\n\n // percent = balanceScore + supplyScore [%]\n var percent, balanceScore, supplyScore;\n \n balanceScore = 0.0;\n supplyScore = 0.0;\n \n // WEIGHTS SHOULD ADD UP TO 1.0\n var BALANCE_WEIGHT = 0.5;\n var SUPPLY_WEIGHT = 0.5;\n\n // Magnitude of allowed value difference before score reaches 0% (1.0 for 100% deviance; 2.0 for 200% deviance, etc)\n var TOLERANCE = 2.0;\n // Ideal %Capacity Available in Network\n var IDEAL_NETWORK_BUFFER = 0.2;\n \n var siteCapacity;\n var totalCapacity, numBackup, bufferSupply;\n var scoreCount;\n var current;\n \n // If Demand Exists; NCE's Score Counts toward Total\n scoreCount = 0;\n \n // Cycles through Each NCE\n for (var i=0; i<agileModel.activeProfiles.length; i++) {\n\n numBackup = 0.0;\n \n // Calculates NCE Capacity at each site;\n siteCapacity = new Array(agileModel.SITES.length);\n for (var s=0; s<agileModel.SITES.length; s++) {\n siteCapacity[s] = 0.0;\n for (var b=0; b<agileModel.SITES[s].siteBuild.length; b++) {\n current = agileModel.SITES[s].siteBuild[b];\n if (current.PROFILE_INDEX == agileModel.activeProfiles[i].ABSOLUTE_INDEX) {\n siteCapacity[s] += current.capacity;\n }\n }\n \n }\n \n // Calculates Total NCE Capacity\n totalCapacity = 0.0;\n for (var s=0; s<agileModel.SITES.length; s++) {\n totalCapacity += siteCapacity[s];\n }\n \n var demand = float(agileModel.activeProfiles[i].demandProfile.getString(2, min(session.current.TURN, NUM_INTERVALS-1) ));\n demand /= 1000.0; // units of kiloTons\n \n // Calaculates normalized balance and supply scores and adds them to total\n if ( demand > 0) { // Only scores if demand exists\n // If Demand Exists; NCE's Score Counts toward Total\n scoreCount ++;\n \n // Determines how many \"backup\" sites there are\n if (agileModel.SITES.length == 1) {\n // Scores Perfect if only one site\n numBackup = 1.0;\n } else {\n // assigns \"1\" if capacity exists at site\n for (var s=0; s<agileModel.SITES.length; s++) {\n if (siteCapacity[s] > 0.0) {\n numBackup += 1.0;\n }\n }\n }\n \n // normalizes balance/backup to a score 0.0 - 1.0;\n if (agileModel.SITES.length > 1) {\n numBackup -= 1.0; // Eliminates effect of first site\n numBackup /= (agileModel.SITES.length - 1);\n if (numBackup < 0.0) numBackup = 0.0;\n }\n \n // Adds the current NCE's balance score to the overall\n balanceScore += agileModel.activeProfiles[i].weightBalance * numBackup;\n \n\n // Calculate Normalized supply score and add it to total\n var sup = 0;\n bufferSupply = (1.0 + IDEAL_NETWORK_BUFFER) * demand / totalCapacity;\n if (totalCapacity == 0) {\n sup = 0.0;\n } else if (bufferSupply > 0 && bufferSupply <= 1.0) {\n sup = 1.0;\n } else if (bufferSupply > 1.0) {\n sup = TOLERANCE - bufferSupply;\n if (sup < 0.0) sup = 0;\n }\n supplyScore += agileModel.activeProfiles[i].weightSupply * sup;\n \n }\n \n }\n \n // Aggregate scores\n balanceScore /= scoreCount;\n supplyScore /= scoreCount;\n percent = BALANCE_WEIGHT * balanceScore + SUPPLY_WEIGHT * supplyScore;\n \n return percent;\n}", "function assignRarity() {\n console.log(\"Assigning Rarity Scores... Please Wait\");\n attributesCombinations.forEach(combo => {\n let set = new Set(combo);\n let diff = combo.length - set.size;\n let index = attributesCombinations.indexOf(combo);\n combo.push({\"trait_type\": \"rarity\", \"value\": diff/*rarity[diff]*/}); });\n console.log(\"Rarity Scores Assigned\");\n}", "calcRating() {\n let allyRating = this.allyRating;\n let totalXP = this.totalXP;\n let combatDifficulty = \"Trivial\";\n\n Object.keys(allyRating).forEach(function (key) {\n let threshold = allyRating[key]\n if (totalXP > threshold) {\n combatDifficulty = key;\n }\n });\n\n this.combatDifficulty = combatDifficulty;\n }", "function calculateSystemKnowledge(systemList, teammembers) {\n\tsystemList.forEach(system => {\n\t\tsystem.members = [];\n\t\tlet totalvalue = 0;\n\t\tlet valuecount = 0;\n\t\tlet indepths = 0;\n\t\tfor (var id in teammembers) {\n\t\t\tlet level = teammembers[id].systemlevels[system.id] || unknownLevel;\n\t\t\t\n\t\t\tif (level.value !== null) {\n\t\t\t\ttotalvalue += level.value;\n\t\t\t\tvaluecount++;\n\t\t\t}\n\t\t\tif (level.relationship == \"knowsAbout\") indepths++;\n\t\t\tsystem.members.push({\n\t\t\t\tid: id,\n\t\t\t\tlevel: level.relationship,\n\t\t\t\tlevellabel: level.label,\n\t\t\t});\n\t\t}\n\n\t\t/** Data for aveage score column **/\n\t\tif (valuecount) {\n\t\t\tsystem.avglevel = (totalvalue / valuecount).toFixed(2);\n\t\t\tif (system.avglevel >= 1.5) {\n\t\t\t\tsystem.avgclass = \"good\";\n\t\t\t} else if (system.avglevel >= 0.75) {\n\t\t\t\tsystem.avgclass = \"medium\";\n\t\t\t} else {\n\t\t\t\tsystem.avgclass = \"poor\";\n\t\t\t}\n\t\t} else {\n\t\t\tsystem.avglevel = \"unknown\";\n\t\t\tsystem.avgclass = \"unknown\";\n\t\t}\n\n\t\t/** Data regarding column for number of members with In Depth relationship **/\n\t\tsystem.indepths = indepths;\n\t\tlet indepthspercent = (indepths / Object.keys(teammembers).length) * 100;\n\t\tif (system.indepths >= 4) {\n\t\t\tsystem.indepthclass = \"good\";\n\t\t} else if (system.indepths >= 2) {\n\t\t\tsystem.indepthclass = \"medium\";\n\t\t} else {\n\t\t\tsystem.indepthclass = \"poor\";\n\t\t}\n\t\tsystem.indepthspercent = indepthspercent.toFixed();\n\t});\n}", "assess( positive = new Map (), negative = new Map() ){\n if(positive instanceof Array){\n positive = new Map(positive);\n }\n if(negative instanceof Array){\n negative = new Map(negative);\n }\n\n let emergingIssues = [];\n // update each condition\n this.conditionsMap.forEach((condition,key) => {\n let type = condition.type;\n let {rate, weight} = condition.progression;\n // impact of progression\n let updates = [];\n // calc\n updates.push( Costs.weight(rate, weight, this.age, this.conditionsMap) );\n // impact of Outcomes\n updates.push( this._effects(type, positive, 'positive') );\n updates.push( this._effects(type, negative, 'negative') );\n // update events emerging from the update\n emergingIssues = emergingIssues.concat( this._update(key,updates) );\n });\n\n // consolidate emerging issues in one object\n // [{type,weight}]\n let issues = emergingIssues.reduce((partial,issue)=>{\n return mergeObjects(partial,issue);\n },{});\n // returns issues {key:weight}\n return issues;\n }", "function assignScore() {\n\t\t // Assigns the score based on the maximum health the zombie had reached\n\t\t\tvar maxHealthScore = 100;\n\t\t\t//maxHealth = parseInt(Math.sqrt(maxHealth));\n\t\t\tif(zeroUsed == 1) {\n\t\t\t\tscore += 5;\n\t\t\t} else {\n\t\t\t if (maxHealth <= maxHealthScore) {\n\t\t\t\t score += maxHealth + (varietyBonus * 5);\n\t\t\t } else {\n\t\t\t\t score += maxHealthScore + (varietyBonus * 5);\n\t\t\t }\n\t\t\t}\n\t\t zeroUsed = 0;\n\t\t}", "function alivenessStats(){\n\n\t//Avg. aliveness\n\n\t\n\n\t//Highest aliveness reported\n\n\t//Lowest aliveness\n\n}", "_computeAllScores() {\n const self = this;\n self.patientWs.forEach((pw) => {\n pw.scores = RecommendationService._computeScore(pw);\n });\n }", "accessibilityCost(objs) {\n /**\n * i is the parent object\n * j is the child object\n */\n\n let cost = 0;\n \n objs.forEach(function(i) {\n objs.forEach(function(j) {\n\n if(i.id === j.id)\n return;\n\n for(let area of j.accessibilityAreas) {\n let dem = i.b + area.ad;\n\n if (dem == 0 || isNaN(dem))\n throw new Error('Error: Division by 0 at accessibility');\n\n cost += Math.max(0, 1 - (VectorMath.magnitude(VectorMath.subtract(i.p, VectorMath.add(j.p, area.a))) / dem));\n }\n\n });\n });\n\n return cost;\n }", "function calculategradatedskill(statname,charclass,level){\n\t\t\tif (['Fort','Ref','Will'].indexOf(statname) !== -1) {savename =statname; statname = \"Saves\";} else {savename = statname;\t}\n\t\t\tconsole.log(statname); console.log(baseattributeclasslevellookup[statname][classqualities[charclass][savename]])\n\t\t\treturn baseattributeclasslevellookup[statname][classqualities[charclass][savename]](level);\n\t\t}", "function _calcSkills(ability)\n{\n var numskills = document.getElementById(\"skills\").rows.length - 3;\n for (var i = 1; i <= numskills; i++)\n {\n var num = FormatNumber(i);\n if (String(sheet()[\"Skill\" + num + \"Ab\"].value).toLowerCase() == ability)\n SkillLookUpKeyAb(sheet()[\"Skill\" + num + \"Ab\"]);\n }\n}", "function setupScoreMatricies() {\n\t\t// Set up domain score matrix\n\t\tif(( domain_score = new Array(num_domain /* double */\n\t\t)) == null) {\n\t\t\tconsole.error(\"Insufficient memory for declaring domain score matrix!\\n\");\n\t\t\tthrow 'Error';\n\t\t}\n\n\t\tif(( domain_intrinsic = new Array(num_domain /* double */\n\t\t)) == null) {\n\t\t\tconsole.error(\"Insufficient memory for declaring domain score matrix!\\n\");\n\t\t\tthrow 'Error';\n\t\t}\n\n\t\t// Set up crosstalk and interaction matrices\n\t\tif(( crosstalk = new Array(num_domain /* double* */\n\t\t)) == null) {\n\t\t\tconsole.error(\"Insufficient memory for declaring crosstalk matrices!\\n\");\n\t\t\tthrow 'Error';\n\t\t}\n\n\t\tfor( i = 0; i < num_domain; i++) {\n\t\t\tif((crosstalk[i] = new Array(num_domain /* double */\n\t\t\t)) == null) {\n\t\t\t\tconsole.error(\"Insufficient memory for declaring crosstalk matrices!\\n\");\n\t\t\t\tthrow 'Error';\n\t\t\t}\n\t\t}\n\n\t\tif(( interaction = new Array(num_domain /* double* */\n\t\t)) == null) {\n\t\t\tconsole.error(\"Insufficient memory for declaring interaction matrices!\\n\");\n\t\t\tthrow 'Error';\n\t\t}\n\n\t\tfor( i = 0; i < num_domain; i++) {\n\t\t\tif((interaction[i] = new Array(num_domain /* double */\n\t\t\t)) == null) {\n\t\t\t\tconsole.error(\"Insufficient memory for declaring interaction matrices!\\n\");\n\t\t\t\tthrow 'Error';\n\t\t\t}\n\t\t}\n\t\t//debugger;\n\t}", "function calculateResourceRarity() {\n for (i = 0; i < positions.length; i++) {\n var sum = 0;\n for (x = 0; x < positions[i].tiles.length; x++) {\n sum += positions[i].tiles[x].dotRarity\n }\n positions[i].resourceRarityScore = sum\n }\n}", "UPDATE_OPP_ATHLETE_STATISTICS(state) {//TODO-----------------------------------------------------------------------\n let result = [];\n\n for (let athlete in state.oppRoster) {\n result.push(\n {\n name: state.oppRoster[athlete].name,\n number: state.oppRoster[athlete].number,\n hit: 0,\n strike: 0,\n ball: 0,\n out: 0,\n atBat: 0,\n run: 0,\n homerun: 0,\n runBattedIn: 0,\n strikeOut: 0,\n baseOnBall: 0,\n leftOnBase: 0\n }\n );\n }\n\n // For each game action, update athlete statistics accordingly.\n for (let index in state.gameActions) {\n let currentAction = state.gameActions[index];\n if (currentAction.team !== \"opponent\") {\n continue;\n }\n let athlete_index = -1;\n for (let athlete in state.oppRoster) {\n if (state.oppRoster[athlete].key == \"athlete-\" + currentAction.athlete_id) {\n athlete_index = athlete;\n break;\n }\n }\n\n // Continue when an athlete has been removed.\n if (athlete_index === -1) {\n continue;\n }\n\n switch (currentAction.action_type) {\n case \"Hit\":\n result[athlete_index].hit++;\n break;\n\n case \"Strike\":\n result[athlete_index].strike++;\n break;\n\n case \"Homerun\":\n result[athlete_index].homerun++;\n result[athlete_index].run++;\n result[athlete_index].hit++;\n break;\n\n case \"Run\":\n result[athlete_index].run++;\n break;\n\n case \"AtBat\":\n result[athlete_index].atBat++;\n break;\n\n case \"RunBattedIn\":\n result[athlete_index].runBattedIn++;\n \n break;\n\n case \"LeftOnBase\":\n result[athlete_index].leftOnBase++;\n break;\n\n case \"Ball\":\n result[athlete_index].ball++;\n break;\n\n case \"BaseOnBall\":\n result[athlete_index].baseOnBall++;\n break;\n\n case \"StrikeOut\":\n result[athlete_index].strikeOut++;\n result[athlete_index].out++;\n break;\n\n case \"Out\":\n result[athlete_index].out++;\n break;\n\n default:\n break;\n }\n }\n\n state.oppAthleteStatistics = result;\n }", "function markScore(income) {\r\n\t\t\t\tincome.score = [\"fuel\",\"ammo\",\"steel\",\"bauxite\"]\r\n\t\t\t\t\t.map( resourceName => income[resourceName] * resourceWeight[resourceName] )\r\n\t\t\t\t\t.reduce( (a,b) => (a+b), 0);\r\n\t\t\t\treturn;\r\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go the the previous task
function previousTask() { if(tasks.length == 1) return; hideCurrentTask(); changeCurrentIndex(-1); var id = tasks[current_task]; if(id) $("task-"+id).className = "active"; }
[ "runOneStepBackwards() {\n this.stateHistory.previousState()\n }", "goBack() {\n if(this.canGoBack()) {\n // get the current event\n let curr = this._stack[this._pointer];\n // get the most recent \"related\" event\n let prev = this.getPrevRelated(curr, this._pointer);\n this.decrementPointer();\n \n // Execute \"prev\" event\n this.execute(prev);\n }\n }", "function goToPreviousState()\n{\n\t//2->1\n\tif(STATE == STATE_STEP_2)\n\t\ttransitionToState(STATE_STEP_2, STATE_STEP_1);\n\t//3->2\n\tif(STATE == STATE_STEP_3)\n\t\ttransitionToState(STATE_STEP_3, STATE_STEP_2);\n\n\t//Don't need to transition otherwise\n}", "function gotoPreviousStep()\n {\n var stepNumber = vm.currentStepNumber - 1;\n\n // Test the previous steps and make sure we\n // will land to the one that is not hidden\n for ( var s = stepNumber; s >= 1; s-- )\n {\n if ( !isStepHidden(s) )\n {\n stepNumber = s;\n break;\n }\n }\n\n vm.setCurrentStep(stepNumber);\n }", "function previousStep()\n {\n if ( isFirstStep() )\n {\n return;\n }\n\n vm.selectedIndex--;\n }", "function previousWithPause() {\n previous();\n pause();\n }", "function previousWithPause() {\n \tprevious();\n \tpause();\n }", "function goPrevious() {\n goto(currentIndex - 1, \"\", true);\n}", "function prev() {\n\t\tvar prevStep = steps.prev();\n\t\tsetSteps(steps);\n\t\tsetCurrent(prevStep);\n\t}", "function markTaskDoneAndGoBack() {\n\t\tlet category = 'Done';\n\t\tlet isDone = true;\n\t\tsetIsTaskDone(true);\n\t\tupdateTask({ taskId, isDone, category });\n\t\tnavigation.navigate('TaskHome');\n\t}", "function gotoPrev() {\n showStep(vm.currentStep - 1);\n }", "function backStep () {\n vm.currentStep --;\n }", "function previousStep() {\r\n switch (stage) {\r\n case \"Present Proposal\":\r\n break;\r\n case \"Q&A\":\r\n stage = \"Present Proposal\";\r\n break;\r\n case \"Conclusion\":\r\n stage = \"Q&A\";\r\n break;\r\n case \"Judge Questions\":\r\n stage = \"Conclusion\";\r\n break;\r\n case \"Custom\":\r\n stage = oldStage;\r\n break;\r\n default:\r\n stage = \"default\";\r\n break;\r\n }\r\n stopTimer();\r\n reset(\"Reset\");\r\n }", "back() {\n var steps = this.get('steps');\n var step = this.get('step');\n var i = steps.findIndex((e) => e === step);\n\n if (i > 0) {\n this.set('step', steps[i-1]);\n }\n }", "function gotoPrevious() {\n\tif(typeof previousInventory !== 'undefined') {\n\t\tnextInventory = currentInventory;\n\t\tcurrentInventory = previousInventory;\n\t\tpreviousInventory = undefined;\n\t}\n}", "prev() {\r\n return this._to(this._taskData.index - 1);\r\n }", "function _seekToPreviousRun() {\n if (!currentRunRep.value) {\n return;\n }\n const prevRun = scheduleRep.value.slice(0).reverse().find((item) => {\n if (item.type !== 'run') {\n return false;\n }\n return item.order < currentRunRep.value.order; // tslint:disable-line:no-non-null-assertion\n });\n nextRunRep.value = clone(currentRunRep.value);\n currentRunRep.value = (prevRun && prevRun.type === 'run') ? clone(prevRun) : null;\n checklist.reset();\n timer.reset();\n}", "function goToPrevious() {\n goTo(_currentContext.previous);\n }", "async function prev() {\r\n await navigation.setParams({ userId: prevUserId });\r\n const prevStoryData = await data.find(\r\n (storyData) => storyData.user.id === prevUserId\r\n );\r\n await setActiveStoryIndex(0);\r\n await setActiveStoryIndex(prevStoryData.stories.length - 1);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The directory entry callback
function gotDir(d){ console.log("got dir"); alert("d-"+JSON.stringify(d)); DATADIR = d; var reader = DATADIR.createReader(); reader.readEntries(function(d){ // gotFiles(d); appReady(d); },onError); }
[ "function gotDirEntry(dirEntry) {\n var directoryReader = dirEntry.createReader();\n directoryReader.readEntries(win,fail);\n }", "function gotDirEntry(dirEntry) {\n var directoryReader = dirEntry.createReader();\n directoryReader.readEntries(success,fail);\n }", "ondir() {}", "function getDirectoryHandler(onDone){\n return function(lines){\n var results = processListResponce(lines, /^file$|^directory$/);\n onDone(results.map(function(file){\n if(typeof file.file !== 'undefined'){\n return MPD.FileSong(self,file);\n }\n else{\n return MPD.Directory(self,file);\n }\n }));\n };\n }", "onFolderAdded() {}", "get entry() {\n return this.dirEntry_;\n }", "function loadDirEntry(_chosenEntry) {\n chosenEntry = _chosenEntry;\n if (chosenEntry.isDirectory) {\n var dirReader = chosenEntry.createReader();\n var entries = [];\n\n // Call the reader.readEntries() until no more results are returned.\n var readEntries = function() {\n dirReader.readEntries (function(results) {\n if (!results.length) {\n textarea.value = entries.join(\"\\n\");\n saveFileButton.disabled = true; // don't allow saving of the list\n displayEntryData(chosenEntry);\n } \n else {\n results.forEach(function(item) { \n entries = entries.concat(item.fullPath);\n });\n readEntries();\n }\n }, errorHandler);\n };\n\n readEntries(); // Start reading dirs. \n }\n}", "function addContentsDirectoryToReaddirResultAndCallOriginalCallback(err, entryNames) {\n if (!err && Array.isArray(entryNames)) {\n entryNames = ['gitFakeFs'].concat(entryNames);\n }\n cb.call(this, err, entryNames);\n }", "function findEXEFileMarkerSuccess(fileEntry) {\n var fileFullPath = fileEntry.fullPath;\n debugLog(\"Found \" + fileFullPath + \" is an EXE directory - adding...\");\n var folderName = fileEntry.getParent();\n fileEntry.getParent(function(parentEntry) {\n debugLog(\"Got a parent Book directory name\");\n debugLog(\"The full path = \" + parentEntry.fullPath);\n folderName = parentEntry.name; \n booksFound[booksFound.length] = folderName;\n $(\"#UMBookList\").append(\"<a onclick='openBLPage(\\\"\" + fileFullPath + \"\\\")' href=\\\"#\\\" data-role=\\\"button\\\" data-icon=\\\"star\\\" data-ajax=\\\"false\\\">\" + folderName + \"</a>\").trigger(\"create\");\n }, function(error){\n debugLog(\"failed to get parent directory folderName: \" + folderName + \" with an error: \" + error);\n }\n ); \n debugLog(\"Before we scan the directory, the number of Books Found is: \" + booksFound.length);\n scanNextDirectoryIndex();\n}", "function successDirectoryReader(entries) {\n var i;\n debugLog(\"In successDirectoryReader path\");\t\n currentEntriesToScan = new Array();\n currentEntriesIndex = 0;\n\n for (i=0; i<entries.length; i++) {\n if (entries[i].isDirectory) {\n currentEntriesToScan[currentEntriesToScan.length] = entries[i];\n }\n }\n\n scanNextDirectoryIndex();\n\n}", "function dirReader(dirEntry){\n var directoryReader = dirEntry.createReader();\n debugLog(\"dirReader Directory: \" + dirEntry.fullPath);\n directoryReader.readEntries(successDirectoryReader,failDirectoryReader);\n}", "enterDirectory_path(ctx) {\n\t}", "function DirectoryEntry () {\n this.children = {};\n this.buffer = new Buffer(0);\n this.sha = \"\";\n}", "function traverseEntryTree (entry, callback) {\n // This entry is a file, so we are done here\n if (entry.isFile) {\n entry.file(function (file) { callback([file]) })\n }\n\n // This entry is a directory, we have to go deeper\n if (entry.isDirectory) {\n var dirReader = entry.createReader()\n dirReader.readEntries(function (entries) { getFilesFromEntries(entries, callback) })\n }\n}", "function readEntries(){\n\t\t\t\tdirReader.readEntries(function(results){\n\t\t\t\t\tif (!results.length) callback(null, entries);\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (var i = 0; i < results.length; i++) entries.push(results[i].name);\n\t\t\t\t\t\treadEntries();\n\t\t\t\t\t}\n\t\t\t\t}, fsErrorHandler(callback));\n\t\t\t}", "function addEntry(filepath,filename,physicalpath){\n if(physicalpath==undefined)\n physicalpath=filepath+\"/\"+filename;\n\n var path=filepath.split(\"/\").filter(a=>a!='');\n var file=filename+\".ann\";\n var child=createDir(filesys,path,0);\n var fileNode = document.createElement(\"li\");\n fileNode.innerHTML = file;\n fileNode.dataset.path=physicalpath;\n fileNode.classList.add(\"clickable\");\n fileNode.addEventListener(\"click\", function(){\n initAnn(this.dataset.path);\n });\n child.appendChild(fileNode);\n}", "enterFileControlEntry(ctx) {\n\t}", "onFolderLoading(aIsFolderLoading) {}", "function _onOneHierarchyEntryFound(the_entry) {\n\n\t\t\t\t//Entry found, prepare entry for upload\n\t\t\t\tself.current_entry = the_entry;\n\n\t\t\t\t//keep track this is a hierarchy entry\n\t\t\t\tself.is_branch_entry = false;\n\n\t\t\t\t//enable upload data button\n\t\t\t\tself.upload_data_btn.removeClass(\"ui-disabled\");\n\n\t\t\t\t//hide all synced message\n\t\t\t\tself.all_synced_message.addClass('hidden');\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
script validasi formlogin jika ada kolom yang tidak diisi atau kosong
function validateFormlogin() { if (document.forms["formlogin"]["email"].value == "") { alert("Email Tidak Boleh Kosong"); document.forms["formlogin"]["email"].focus(); return false; } if (document.forms["formlogin"]["password"].value == "") { alert("Password Tidak Boleh Kosong"); document.forms["formlogin"]["password"].focus(); return false; } }
[ "function walgreensValidateLoginForm(formObj){\n\t if(CUtils.isEmpty(formObj.username.value) == true){\n\t formObj.username.focus() ;\n\t alert(\"Username cannot be empty.\") ;\n\t return false ;\n\t }\n\t if(CUtils.isEmpty(formObj.password.value) == true){\n\t formObj.password.focus() ;\n\t alert(\"Password cannot be empty.\") ;\n\t return false ;\n\t }\n\t if(CUtils.isEmpty(formObj.password.value) == false &&\n\t formObj.password.value.length < 6)\n\t {\n\t formObj.password.focus() ;\n\t formObj.password.select() ;\n\t alert(\"Password cannot be less than 6 characters.\") ;\n\t return false ;\n\t }\n\n\t return true ;\n }", "function validaFormLogin(){\n\tvar User = document.getElementById(\"Username\").value;\n\tvar Pwd = document.getElementById(\"Password\").value;\n\tvar check = true;\n\n//Svuoto gli errori dell'username\n\t\tvar Form = document.getElementById('user').innerHTML;\n\t\tvar Form = Form.replace(/<span class=\"error\" id=\"errore1\">.*<\\/span>/ , \"<!-- errore_username -->\");\n\t\tdocument.getElementById('user').innerHTML = Form;\n//Svuoto gli errori della password\n\t\tvar Form = document.getElementById('pwd').innerHTML;\n\t\tvar Form = Form.replace(/<span class=\"error\" id=\"errore2\">.*<\\/span>/, \"<!-- errore_password -->\");\n\t\tdocument.getElementById('pwd').innerHTML = Form;\n\n//Controllo se il campo username è definito e lo segnalo\n\tif(User == \"\" || User == \"undefined\"){\n\t\tvar Form = document.getElementById('user').innerHTML;\n\t\tvar Form = Form.replace(\"<!-- errore_username -->\",'<span class=\"error\" id=\"errore1\"><span lang=\"en\">Username<\\/span> non inserito <\\/span>');\n\t\tdocument.getElementById('user').innerHTML = Form;\n\t\tcheck = false;\n\t}\n//Controllo se il campo password è definito e lo segnalo\n\tif(Pwd == \"\" || Pwd == \"undefined\"){\n\t\tvar Form = document.getElementById('pwd').innerHTML;\n\t\tvar Form = Form.replace(\"<!-- errore_password -->\",'<span class=\"error\" id=\"errore2\"><span lang=\"en\">Password<\\/span> non inserita <\\/span>');\n\t\tdocument.getElementById('pwd').innerHTML = Form;\n\t\tcheck = false;\n\t}\n\treturn check;\n}", "function validate_login_form(form, data) {\n if (data.user_username == \"\") {\n // if username variable is empty\n addFormError(form[\"user_username\"], 'The username is invalid');\n return false; // stop the script if validation is triggered\n }\n\n if (data.user_password == \"\") {\n // if password variable is empty\n addFormError(form[\"user_password\"], 'The password is invalid');\n return false; // stop the script if validation is triggered\n }\n\n $('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');\n $('#dialog').addClass('dialog-effect-out');\n\n $('#successful_login').addClass('active');\n //return true;\n }", "function validarFormLogin() {\n f = document.getElementById(\"formlogin\");\n if (f.peoEmail.value == \"\") {\n f.peoEmail.style.backgroundColor = \"red\";\n f.peoEmail.style.color = \"#ffffff\";\n f.peoEmail.focus();\n return false;\n }\n //validar email(verificao de endereco eletrônico)\n parte1 = f.peoEmail.value.indexOf(\"@\");\n parte3 = f.peoEmail.value.length;\n if (!(parte1 >= 3 && parte3 >= 9)) {\n f.peoEmail.style.backgroundColor = \"#F5A9A9\";\n f.peoEmail.style.color = \"#ffffff\";\n f.peoEmail.focus();\n return false;\n }\n if (f.peoPass.value == \"\" || f.peoPass.value.length < 6) {\n f.peoPass.style.backgroundColor = \"#F5A9A9\";\n f.peoPass.style.color = \"#ffffff\";\n return false;\n f.peoPass.focus();\n }\n f.submit();\n}", "function validateLoginForm() {\n var correcto = false, msg = \"\";\n if ($('#user-login').val() === \"\") {\n msg = \"Coloque el Usuario\";\n $('#user-login').focus();\n } else if ($('#password-login').val() === \"\") {\n msg = \"Coloque la Contraseña\";\n $('#password-login').focus();\n } else {\n correcto = true;\n loginJSON.Usuario = $('#user-login').val();\n loginJSON.Password = $('#password-login').val();\n }\n if (!correcto) {\n msgPop(\"Atención\", msg, 2500, \"warning\");\n }\n return correcto;\n}", "function validarLogin()\n{\n\tvar estado=true;\n\tvar nombre = document.getElementById('lnombre').value;\n\tif ((nombre.length == 0) || (nombre.length >30) || (/^\\s+$/.test(nombre)) || (!isNaN(nombre)))\n\t{\t\n\t\tdocument.getElementById('mostrarError').innerHTML=\"Nombre obligatorio.\";\n\t\tdocument.getElementById('mostrarError').style.color=\"red\";\n\t\testado=false;\n\t}\n\telse\n\t{\n\t\tdocument.getElementById('mostrarError').innerHTML=\"\";\n\t}\n\n\tvar contrasena = document.getElementById('lcontrasena').value;\n\tif ((contrasena.length > 8) || (contrasena.length < 4)) \n\t{\n\t\terrorTexto(datos,error,literal);\t\n\t\tdocument.getElementById('mostrarError').innerHTML=\"Contraseña obligatoria.\";\n\t\tdocument.getElementById('mostrarError').style.color=\"red\";\n\t\testado=false;\n\t}\n\telse\n\t{\n\t\tdocument.getElementById('mostrarError').innerHTML=\"\";\n\t}\t\n\treturn estado;\n}", "function validazioneFormAccesso() {\n var username = document.getElementById(\"nomeUtente\");\n\tvar password = document.getElementById(\"passwordAcc\");\n\t\n\tvar risUsername = checkAlfanumerico(username);\n\tvar risPassword = checkMinLen(password);\n\t\n\tif(risUsername)\n\t{\n\t\ttogliErrore(username);\n\t}\n\telse\n\t{\n\t\tmostraErrore(username, \"L'username deve contenere solo caratteri alfanumerici e avere almeno 2 caratteri\");\n\t}\n\tif(risPassword)\n\t{\n\t\ttogliErrore(password);\n\t}\n\telse\n\t{\n\t\tmostraErrore(password, \"La password deve essere lunga almeno due caratteri\");\n\t}\n\t\n\treturn risUsername && risPassword;\n}", "function validarLogin(){\n var defaultUser = \"root\";\n var defaultPassword = \"root\"; \n var userInp = username.value;\n var passInp = password.value;\n if(userInp == defaultUser && passInp == defaultPassword){\n loginMsg.innerHTML = \"Login OK: \"+\"user=\"+userInp+\" i password=\"+passInp;\n } else {\n loginMsg.innerHTML = \"Error Login No Correcte: user=\"+userInp+\" i password=\"+passInp;\n }\n \n}", "function validateLogin() {\n var gv = true;\n\n /* Vlaidation content */\n if (!magicValidate(\"E-mail\", document.getElementById('login-email'), 0, true)) gv = false;\n if (!magicValidate(\"Password\", document.getElementById('login-pass'), 8)) gv = false;\n\n if (!gv) event.preventDefault();\n}", "function comprobarLogin(form)\r\n{\r\n document.getElementById(\"invalidform\").style.display = 'none';\r\n //extrae los inputs para el login y su password\r\n var log = form['email'];\r\n var pass = form['password'];\r\n\r\n //compruba los vacíos\r\n if (comprobarVacio(log) === false || comprobarVacio(pass) === false){\r\n\r\n //Párrafo que muestra el error\r\n document.getElementById(\"invalidform\").style.display = 'block';\r\n return false;\r\n }\r\n //comprueba los formatos\r\n if (comprobarCorreo(log, 60) === false || comprobarAlfanum(pass,20) === false){\r\n return false;\r\n }\r\n \r\n}", "function ConvalidaLogin() {\r\n\t\t// definisce la variabile booleana blnControllo e la setta a false\r\n\t\tvar blnControllo = false;\r\n \r\n\t\t// controllo del nome utente inserito \r\n if (document.getElementById(\"txtNomeUtente\").value.length ==0) {\r\n\t\t\t//alert (\"Non hai inserito il nome utente!\");\r\n\t\t\tsetTimeout(\"document.getElementById(\\\"txtNomeUtente\\\").focus();\", 1);\t\t\t// la setTimeout serve a farlo funzionare con FF\r\n\t\t\treturn;\r\n } \r\n\t\telse {\r\n\t\t\tblnControllo = true;\r\n }\r\n \r\n\t\t// controllo della password inserita\r\n if (document.getElementById(\"txtPassword\").value.length ==0) {\r\n\t\t\t//alert (\"Non hai inserito la password!\");\r\n\t\t\tsetTimeout(\"document.getElementById(\\\"txtPassword\\\").focus();\", 1);\t\t\t// la setTimeout serve a farlo funzionare con FF\r\n\t\t\treturn;\r\n } \r\n\t\telse {\r\n blnControllo = true;\r\n }\r\n \r\n return;\r\n } // chiusura della function ConvalidaLogin\t", "function validateFormLogIn(username , password){\n\t // cheking name and password for not empty\n\t if(!username || !password){\n\t\t \t//alert error \n\t\t alert('Please fill in the form');\n\t\t //if error, return false\n\t\t return false;\n\t \t}\n\t //if OK, return true\n\t return true;\n }", "function validate_login() {\n var form = get_form_data('#login_form');\n\n if (check_field_empty(form.nick, 'nick'))\n return false;\n if (check_field_empty(form.password, 'password'))\n return false;\n\n var dataObj = {\n \"content\" : [ {\n \"nick\" : form.nick\n }, {\n \"password\" : form.password\n } ]\n };\n call_server('login', dataObj);\n}", "function login_val() {\n \n\n //validate username exists\n if (typeof users_reg_data[request.body.uname] != 'undefined') {\n console.log('uname success');\n var username = request.body.uname; //links variable to username after validation\n //if username exists then moves on to validate password\n if (request.body.psw == users_reg_data[request.body.uname].password) {\n console.log('psw success');\n return true;\n } else {\n console.log('psw fail');\n return false;\n }\n } else {\n console.log('uname fail');\n return false;\n }\n }", "function login_validate() {\n\tvar username = document.getElementById(\"username\");\n\tvar password = document.getElementById(\"password\");\n\n\tif (username.value == \"\" || username.value == \"用户名\" || password.value == \"\" || password.value == \"password\")\n\t\talert(\"输入不能为空!\");\n\telse\n\t\tlogin_valid = true;\n}", "function adminloginValidate(){\n \t var email=document.adminloginform.aname.value; \n \t var pass=document.adminloginform.apassword.value;\n \t var atposition=email.indexOf(\"@\"); \n \t var dotposition=email.lastIndexOf(\".\"); \n \t if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email.length ){ \n\t /* alert(\"Name can't be blank\"); */\n\t document.getElementById(\"adminemail\").innerHTML=\" Please Enter Valid Email\";\n\t event.preventDefault();\n\t console.log(\" for email\");\n\t return false; \n\t }\n\t else if (pass==null || pass==\"\"){ \n\t document.getElementById(\"adminpassword\").innerHTML=\" Please Enter Valid Password\";\n\t event.preventDefault();\n console.log(\" for password\");\n return false; \n\t } \n\t\n}", "function validatelogin(part){\t\n\n\t if($('#username').val() == '')\n\t {\n\t\t inlineMsg('username','<strong>Username required.</strong>',2);\n\t\t return false;\n\t }\n\tif(hasWhiteSpace($('#username').val()) == true){\n\t\t\t\t inlineMsg('username','<strong>Only alpha numeric character allowed.</strong>',2);\n\t\t\t\t return false; \n\t\t\t}\n\t if(tagValidate($('#username').val()) == true){\n\t\t inlineMsg('username','<strong>Please dont use script tags.</strong>',2);\n\t\t return false; \n\t } \n\tif($('#password').val() == '')\n\t {\n\t\t inlineMsg('password','<strong>Password required.</strong>',2);\n\t\t return false;\n\t }\n\t if(tagValidate($('#password').val()) == true){\n\t\t inlineMsg('password','<strong>Please dont use script tags.</strong>',2);\n\t\t return false; \n\t } \n\n \t\n return true; \n}", "function validar_login(formu){\n\n\tvar correcto=false,usuario_correcto,pass_correcto;\n\n\t//Comprobamos usu y pass\n\tusuario_correcto=comprobar_usu_pass_login(formu.login_usu);\n\tpass_correcto=comprobar_usu_pass_login(formu.login_pass);\n\n\tif(usuario_correcto && pass_correcto)\n\t\tcorrecto=true;\n\n\treturn correcto;\n}", "function loginValidation() {\n if (state_name === false) {\n $name.alertMsg(\"Please type in your name or an alias.\");\n }\n if (state_email === false) {\n $email.alertMsg(\"Please type in your email.<br>No email? Use \\\"none@none.com\\\".\");\n }\n if (state_password === false) {\n $password.alertMsg(\"Please adjust your password so it meets the requirements below.\")\n }\n if (state_name && state_email && state_password) {\n return true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We've got some basic info about Karen's home Debug the type of data provided Return the types concatenated in a single variable We've got some basic information about Karen's home. Find out the type of each data. Create a function `moreAboutHome()` which takes `address, distanceFromTown, hasNeighbours` as arguments and _returns all datatypes concatenated in a single variable_.
function moreAboutHome(address, distanceFromTown, hasNeighbours){ // var address, distanceFromTown, hasNeighbours; return typeof(address)+typeof(distanceFromTown)+typeof(hasNeighbours); }
[ "function displayHometownData () {\n let homeTown = instructorData.additionalData.moreDetails.hometown;\n for(let key in homeTown) {\n console.log(homeTown[key]);\n }\n}", "function displayHometownData() {\n let hometown = instructorData.additionalData.moreDetails.hometown;\n for(let key in hometown) {\n console.log(hometown[key]);\n }\n}", "function displayHometownData() {\n var homeTownList = instructorData.additionalData.moreDetails.hometown;\n for (key in homeTownList) {\n console.log(homeTownList[key]);\n }\n}", "function displayHomeData() {\r\n Object.keys(instructorData.additionalData.moreDetails.hometown).forEach(x => {\r\n console.log(instructorData.additionalData.moreDetails.hometown[x]);\r\n });\r\n}", "function displayHometownData(collection) {\n // VARIABLES\n var hometownObject;\n\n // PROCESS\n // drill down to the hometown object and set the location equal to a variable\n hometownObject = instructorData.additionalData.moreDetails.hometown;\n // loop thru the objects keys and console.log their values\n for(var n in hometownObject) {\n \tconsole.log(hometownObject[n]);\n }\n}", "function displayHometownData() {\n var hometownObj = instructorData.additionalData.moreDetails.hometown;\n for (key in hometownObj) {\n console.log(hometownObj[key]);\n }\n}", "_extractPlaceInfo(pl, searchTerm) {\n const p = {\n place_id: pl.place_id,\n formatted_address: pl.formatted_address,\n search: searchTerm || pl.formatted_address,\n latLng: {\n lat: pl.geometry.location.lat(),\n lng: pl.geometry.location.lng(),\n },\n basic: {\n name: pl.name || '',\n address: '',\n city: '',\n state: '',\n stateCode: '',\n postalCode: '',\n country: '',\n countryCode: '',\n phone: pl.formatted_phone_number || '',\n },\n placeDetails: {\n address_components: [],\n icon: pl.icon,\n international_phone_number: pl.international_phone_number || '',\n permanently_closed: pl.permanently_closed || false,\n types: pl.types ? JSON.parse(JSON.stringify(pl.types)) : [],\n website: pl.website || '',\n url: pl.url || '',\n utc_offset_minutes: pl.utc_offset_minutes,\n },\n };\n // extract address components\n const address = {\n street_number: '',\n route: '',\n };\n // eslint-disable-next-line\n for (let i = 0; i < pl.address_components.length; i++) {\n // @ts-ignore\n p.placeDetails.address_components.push(JSON.parse(JSON.stringify(pl.address_components[i])));\n switch (pl.address_components[i].types[0]) {\n case 'locality':\n p.basic.city = pl.address_components[i].long_name;\n break;\n case 'administrative_area_level_1':\n p.basic.stateCode = pl.address_components[i].short_name;\n p.basic.state = pl.address_components[i].long_name;\n break;\n case 'country':\n p.basic.country = pl.address_components[i].long_name;\n p.basic.countryCode = pl.address_components[i].short_name;\n break;\n case 'postal_code':\n p.basic.postalCode = pl.address_components[i].long_name;\n break;\n case 'street_number':\n address.street_number = pl.address_components[i].short_name;\n p.basic.address = `${address.street_number} ${address.route}`;\n // @ts-ignore\n p.basic.streetNumber = address.street_number;\n break;\n case 'route':\n address.route = pl.address_components[i].long_name;\n p.basic.address = `${address.street_number} ${address.route}`;\n // @ts-ignore\n p.basic.route = address.route;\n break;\n default:\n // @ts-ignore\n address[pl.address_components[i].types[0]] = pl.address_components[i].long_name;\n }\n }\n return p;\n }", "function restaurantDescript(address){\n var info;\n // if (address == \"700 E Grand Ave, Chicago, IL 60611, USA\") {\n // info = \"<div class = 'red'><h1> Giordano's</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>\";\n // return info;\n // }else if (address == \"9102 TX-1604 Loop, San Antonio, TX 78254, USA\") {\n // info = \"<div class = 'red'><h1>Popeyes</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>\"\n // return info;\n // }else if (address == \"5706 W Loop 1604 N, San Antonio, TX 78251, USA\") {\n // info = \"<div class = 'red'><h1>Longhorn's</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>\"\n // return info;\n // }\n info = \"<div> <object type='text/html' data = 'http://codeup.dev/calculator.html' width = '800px' height ='600px'></object></div> \"\n return info;\n }", "_extractPlaceInfo(pl, searchTerm) {\n\n var p = {\n place_id: pl.place_id,\n formatted_address: pl.formatted_address,\n search: searchTerm ? searchTerm : pl.formatted_address,\n latLng: {\n lat: pl.geometry.location.lat(),\n lng: pl.geometry.location.lng()\n },\n basic: {\n name: pl.name || \"\",\n address: \"\",\n city: \"\",\n state: \"\",\n stateCode: \"\",\n postalCode: \"\",\n country: \"\",\n countryCode: \"\",\n phone: pl.formatted_phone_number || \"\"\n },\n placeDetails: {\n address_components: [],\n icon: pl.icon,\n international_phone_number: pl.international_phone_number || \"\",\n permanently_closed: pl.permanently_closed || false,\n types: pl.types ? JSON.parse(JSON.stringify(pl.types)) : [],\n website: pl.website || \"\",\n url: pl.url || \"\",\n utc_offset: pl.utc_offset\n }\n };\n // extract address components\n var address = {\n street_number: \"\",\n route: \"\"\n };\n for (var i = 0; i < pl.address_components.length; i++) {\n p.placeDetails.address_components.push(JSON.parse(JSON.stringify(pl.address_components[i])));\n switch (pl.address_components[i].types[0]) {\n case \"locality\":\n p.basic[\"city\"] = pl.address_components[i].long_name;\n break;\n case \"administrative_area_level_1\":\n p.basic[\"stateCode\"] = pl.address_components[i].short_name;\n p.basic[\"state\"] = pl.address_components[i].long_name;\n break;\n case \"country\":\n p.basic[\"country\"] = pl.address_components[i].long_name;\n p.basic[\"countryCode\"] = pl.address_components[i].short_name;\n break;\n case \"postal_code\":\n p.basic[\"postalCode\"] = pl.address_components[i].long_name;\n break;\n case \"street_number\":\n address.street_number = pl.address_components[i].short_name;\n p.basic.address = address.street_number + \" \" + address.route;\n p.basic.streetNumber = address.street_number;\n break;\n case \"route\":\n address.route = pl.address_components[i].long_name;\n p.basic.address = address.street_number + \" \" + address.route;\n p.basic.route = address.route;\n break;\n default:\n address[pl.address_components[i].types[0]] = pl.address_components[i].long_name;\n }\n }\n\n return p;\n\n }", "function isHometown(town) {\n return town;\n}", "function extractFacts(hotel) {\n $('#hotel').text(hotel['name']);\n $('#rating').text(hotel['rating']);\n\n var hotelLat = hotel['geometry']['location']['lat'];\n var hotelLong = hotel['geometry']['location']['lng'];\n var placeID = hotel['place_id'];\n\n placeHotelMarker(hotelLat, hotelLong);\n getLocation(placeID);\n getRestaurant(hotelLat, hotelLong);\n getMuseums(hotelLat, hotelLong);\n getArt(hotelLat, hotelLong);\n}", "function isHomeTown(town){\n if(town === 'San Francisco'){\n return 'True'; \n }\n\n else{\n return 'False'; \n }\n}", "function visitorsInfo (town) {\n return _.map(town, function(neighborhood){\n return {\n name: neighborhood.name,\n isSafe: !neighborhood.hasRats\n };\n });\n}", "function HomeAddress(xmlHomeAddressBody) {\n if (!xmlHomeAddressBody) {\n return null;\n }\n this.addressTypeCode = xmlHomeAddressBody.AddressTypeCode;\n this.locationCode = xmlHomeAddressBody.LocationCode;\n this.emiratesCode = xmlHomeAddressBody.EmiratesCode;\n this.emiratesDescArabic = xmlHomeAddressBody.EmiratesDescArabic;\n this.emiratesDescEnglish = xmlHomeAddressBody.EmiratesDescEnglish;\n this.cityCode = xmlHomeAddressBody.CityCode;\n this.cityDescArabic = xmlHomeAddressBody.CityDescArabic;\n this.cityDescEnglish = xmlHomeAddressBody.CityDescEnglish;\n this.streetArabic = xmlHomeAddressBody.StreetArabic;\n this.streetEnglish = xmlHomeAddressBody.StreetEnglish;\n this.pOBOX = xmlHomeAddressBody.POBOX;\n this.areaCode = xmlHomeAddressBody.AreaCode;\n this.areaDescArabic = xmlHomeAddressBody.AreaDescArabic;\n this.areaDescEnglish = xmlHomeAddressBody.AreaDescEnglish;\n this.buildingNameArabic = xmlHomeAddressBody.BuildingNameArabic;\n this.buildingNameEnglish = xmlHomeAddressBody.BuildingNameEnglish;\n this.flatNo = xmlHomeAddressBody.FlatNo;\n this.residentPhoneNumber = xmlHomeAddressBody.ResidentPhoneNumber;\n this.mobilePhoneNumber = xmlHomeAddressBody.MobilePhoneNumber;\n this.email = xmlHomeAddressBody.Email;\n}", "function overTheRoad(address, n){\n\n\n\n\n}", "function displayShowingForAddress(data) {\n const a = data.address;\n const address = `Showing results${\n a.house_number == undefined ? '' : ' near ' + a.house_number\n } ${a.road == undefined ? '' : a.road}${\n a.city == undefined ? '' : ' in ' + a.city\n }, ${a.state == undefined ? '' : a.state}`;\n yourLocation.innerText = address;\n}", "function isHometown(town){\n return town === 'San Francisco';\n}", "function displayInformation(data, route) {\n console.log('Christofides Algorithm');\n route.path.forEach((city) => console.log(data[city].city));\n console.log(route.distance / 1000 + ' km');\n}", "function getAlternativePlaceInfo(e, callback) {\r\n var result;\r\n var count = e.query.count;\r\n \r\n if(count > 1) {\r\n for(var i in e.query.results.place) {\r\n if(checkAlternativePlaceIsTown(e.query.results.place[i])) {\r\n result = e.query.results.place[i];\r\n break;\r\n }\r\n }\r\n } else if(count == 1) {\r\n if(checkAlternativePlaceIsTown(e.query.results.place))\r\n result = e.query.results.place;\r\n }\r\n\r\n if(!result)\r\n getPlaceLocationDataError(callback);\r\n\r\n return result;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the Cocktail Recipe Data
function formatDrinkData(data) { cockTailData = data; removeSearchDropdowns(); cocktailSearchResultsBody.classList.remove("hide"); for (i = 0; i < 3; i++) { cocktailName = cockTailData.drinks[i].strDrink; cocktailImage = cockTailData.drinks[i].strDrinkThumb; cocktailID = cockTailData.drinks[i].idDrink; getCocktailRecipeData(cocktailID); } }
[ "function formatCocktailRecipeData(data, drinkID) {\n cocktailRecipe = data;\n //=================================================================\n cocktailName = cocktailRecipe.drinks[0].strDrink;\n cocktailImage = cocktailRecipe.drinks[0].strDrinkThumb;\n meas1 = cocktailRecipe.drinks[0].strMeasure1;\n meas2 = cocktailRecipe.drinks[0].strMeasure2;\n meas3 = cocktailRecipe.drinks[0].strMeasure3;\n meas4 = cocktailRecipe.drinks[0].strMeasure4;\n meas5 = cocktailRecipe.drinks[0].strMeasure5;\n meas6 = cocktailRecipe.drinks[0].strMeasure6;\n meas7 = cocktailRecipe.drinks[0].strMeasure7;\n meas8 = cocktailRecipe.drinks[0].strMeasure8;\n meas9 = cocktailRecipe.drinks[0].strMeasure9;\n meas10 = cocktailRecipe.drinks[0].strMeasure10;\n instructions = data.drinks[0].strInstructions;\n\n ingredients = [];\n measurements = [];\n\n ingr1 = cocktailRecipe.drinks[0].strIngredient1;\n if (ingr1 != null) {ingredients.push(ingr1)};\n if (meas1 != null) {measurements.push(meas1)};\n ingr2 = cocktailRecipe.drinks[0].strIngredient2;\n if (ingr2 != null) {ingredients.push(ingr2)};\n if (meas2 != null) {measurements.push(meas2)};\n ingr3 = cocktailRecipe.drinks[0].strIngredient3;\n if (ingr3 != null) {ingredients.push(ingr3)};\n if (meas3 != null) {measurements.push(meas3)};\n ingr4 = cocktailRecipe.drinks[0].strIngredient4;\n if (ingr4 != null) {ingredients.push(ingr4)};\n if (meas4 != null) {measurements.push(meas4)};\n ingr5 = cocktailRecipe.drinks[0].strIngredient5;\n if (ingr5 != null) {ingredients.push(ingr5)};\n if (meas5 != null) {measurements.push(meas5)};\n ingr6 = cocktailRecipe.drinks[0].strIngredient6;\n if (ingr6 != null) {ingredients.push(ingr6)};\n if (meas6 != null) {measurements.push(meas6)};\n ingr7 = cocktailRecipe.drinks[0].strIngredient7;\n if (ingr7 != null) {ingredients.push(ingr7)};\n if (meas7 != null) {measurements.push(meas7)};\n ingr8 = cocktailRecipe.drinks[0].strIngredient8;\n if (ingr8 != null) {ingredients.push(ingr8)};\n if (meas8 != null) {measurements.push(meas8)};\n ingr9 = cocktailRecipe.drinks[0].strIngredient9;\n if (ingr9 != null) {ingredients.push(ingr9)};\n if (meas9 != null) {measurements.push(meas9)};\n ingr10 = cocktailRecipe.drinks[0].strIngredient10;\n if (ingr10 != null) {ingredients.push(ingr10)};\n if (meas10 != null) {measurements.push(meas10)};\n\n cocktailRecipesResults.innerHTML += `\n <div class=\"card\" style=\"width: 18rem\">\n <div class=\"card-body drink-result\">\n <img src=\"${cocktailImage}\" class=\"card-img-top\" alt=\"Responsive image of cocktail\"/>\n <h2 class=\"card-title text-center\">${cocktailName}</h2>\n <h4>Ingredients:</h4>\n <ul id=\"${drinkID}\">\n </ul>\n <h4>Instructions:</h4>\n <p id=\"instructionsSection1\">${instructions}</p>\n <button type=\"button\" class=\"btn btn-primary saveBtn\">Save</button>\n </div>\n </div>\n`\n\n// this appends only measurements and ingredients that are not null\n for (step = 0; step < ingredients.length; step++) {\n if (measurements[step] != undefined) {\n $(\"#\" + drinkID).append(`<li>${measurements[step]} ${ingredients[step]}</li>`);\n } else {\n $(\"#\" + drinkID).append(`<li>${ingredients[step]}</li>`);\n }\n }\n\n // save drink card to localstorage\n $(saveBtnEl).click(function (event) {\n event.preventDefault();\n event.stopPropagation();\n var drinkName = $(this).siblings(\"h2\").text();\n var drinkCard = $(this).parent(\"div\").parent(\"div\").html();\n localStorage.setItem(drinkName, drinkCard);\n });\n}", "printRecipeInfo(data) {\n\t\tlet recipes = [];\n \n\t\tfor (let i = 0; i < data.hits.length; i++) {\n\t\t\tconst ptr = data.hits[i].recipe;\n\t\t\tlet recipe = {\n\t\t\t\tname: ptr.label,\n\t\t\t\tdescription: ptr.uri,\n\t\t\t\timage: null,\n\t\t\t\timageURL: ptr.image,\n\t\t\t\tgluten_free: (Math.random() > 0.5),\n\t\t\t\tdairy_free: (Math.random() > 0.5),\n\t\t\t\tvegetarian: (Math.random() > 0.5),\n\t\t\t\tvegan: (Math.random() > 0.5),\n\t\t\t\tprep_time: Math.floor(Math.random() * 60),\n\t\t\t\tcook_time: Math.floor(Math.random() * 180),\n\t\t\t\tinstructions: ptr.url, \n\t\t\t\trating: Math.floor(Math.random() * 10) + 1 \n\t\t\t};\n\t\t\trecipes.push(recipe);\n\t\t}\n \n\t\tconst jRecipes = JSON.stringify(recipes);\n\t\tconsole.log(jRecipes);\n\t}", "function formatRecipe(recipe) {\n let recipeHTML = \"\"\n\n for (let i = 0; i < recipe.length; i++) {\n recipeHTML += `<li>${recipe[i][0]}: ${recipe[i][1]}</li>\\n`\n }\n\n return `<ul>\\n${recipeHTML}</ul>`\n}", "function formatMealData(data) {\n mealData = data;\n recipeNumber = mealData.hits.length;\n removeSearchDropdowns();\n\n for (i = 0; i < recipeNumber; i++) {\n recipeLabel = mealData.hits[i].recipe.label; \n recipeSourceName = mealData.hits[i].recipe.source; \n recipeImage = mealData.hits[i].recipe.image; \n recipeInstructionsLink = mealData.hits[i].recipe.url;\n foodSearchResultsBody.classList.remove('hide');\n showFoodCards(recipeImage, recipeLabel, recipeSourceName, recipeInstructionsLink);\n }\n}", "combineData(){\n var len = 0;\n var i;\n var str = \"\";\n\n //titleID\n str = this.state.titleID;\n\n //messageID\n str += \"\\0\" + this.state.messageID;\n\n //title\n str += \"\\0\" + this.state.title;\n\n //description\n str += \"\\0\" + this.state.description;\n\n //ingredients\n len = this.state.ingredients[0].length;\n str += \"\\0\" + len;\n for(i = 0; i < len; i++){//ingredientIDs\n str += \"\\0\" + this.ingredientIDs[i];\n }\n for(i = 0; i < len; i++){//ingredients\n str += \"\\0\" + this.state.ingredients[0][i];\n }\n for(i = 0; i < len; i++){//Amount\n str += \"\\0\" + this.state.ingredients[1][i];\n }\n for(i = 0; i < len; i++){//Units\n str += \"\\0\" + this.state.ingredients[2][i];\n }\n\n //recipe\n len = this.state.recipe[0].length;\n str += \"\\0\" + len;\n for(i = 0; i < len; i++){\n str += \"\\0\" + this.state.recipe[0][i];\n }\n for(i = 0; i < len; i++){\n str += \"\\0\" + this.state.recipe[1][i];\n }\n\n this.content = str;\n }", "function makeFullRecipe(recipe) {\n const {\n id,\n title,\n readyInMinutes,\n aggregateLikes,\n vegetarian,\n vegan,\n glutenFree,\n image,\n servings,\n } = recipe;\n\n let arrInstruction = [];\n //check if instarction are empty\n if (\n recipe.instructions == \"\" ||\n !recipe.instructions ||\n !recipe.analyzedInstructions ||\n recipe.analyzedInstructions.length == 0\n ) {\n console.log(\"recipe instructions is empty !!!! \");\n } else {\n // add instractions\n let analyzedInstructions = recipe.analyzedInstructions[0].steps;\n\n analyzedInstructions.map((crrStep) => arrInstruction.push(crrStep.step));\n }\n\n let arrIngredients = [];\n if (!recipe.extendedIngredients) {\n console.log(\"recipe extendedIngredients is empty !!!! \");\n } else {\n // add ingredients\n let extendedIngredients = recipe.extendedIngredients;\n\n extendedIngredients.map((ingredient) =>\n arrIngredients.push(ingredient.original)\n );\n }\n\n return {\n // return object\n id: id,\n title: title,\n readyInMinutes: readyInMinutes,\n aggregateLikes: aggregateLikes,\n vegetarian: vegetarian,\n vegan: vegan,\n glutenFree: glutenFree,\n image: image,\n servings: servings,\n instructions: arrInstruction,\n ingredients: arrIngredients,\n };\n}", "function setRecipe(data) {\n // API data arrays:\n const tags = splitString(data.strTags, \",\");\n\n let ingredients = [\n data.strIngredient1,\n data.strIngredient2,\n data.strIngredient3,\n data.strIngredient4,\n data.strIngredient5,\n data.strIngredient6,\n data.strIngredient7,\n data.strIngredient8,\n data.strIngredient9,\n data.strIngredient10,\n data.strIngredient11,\n data.strIngredient12,\n data.strIngredient13,\n data.strIngredient14,\n data.strIngredient15,\n data.strIngredient16,\n data.strIngredient17,\n data.strIngredient18,\n data.strIngredient19,\n data.strIngredient20,\n ];\n\n let measures = [\n data.strMeasure1,\n data.strMeasure2,\n data.strMeasure3,\n data.strMeasure4,\n data.strMeasure5,\n data.strMeasure6,\n data.strMeasure7,\n data.strMeasure8,\n data.strMeasure9,\n data.strMeasure10,\n data.strMeasure11,\n data.strMeasure12,\n data.strMeasure13,\n data.strMeasure14,\n data.strMeasure15,\n data.strMeasure16,\n data.strMeasure17,\n data.strMeasure18,\n data.strMeasure19,\n data.strMeasure20,\n ];\n\n // Remove empty strings from arrays:\n ingredients = ingredients.filter((str) => checkValue(str));\n measures = measures.filter((str) => checkValue(str));\n\n // DOM manipulation:\n for (i = 0; i < ingredients.length; i++) {\n const row = document.createElement(\"div\");\n const ing = document.createElement(\"p\");\n const mes = document.createElement(\"p\");\n const ingText = document.createTextNode(ingredients[i] + \":\");\n const mesText = document.createTextNode(measures[i]);\n\n ing.appendChild(ingText);\n mes.appendChild(mesText);\n mes.classList.add(\"align-right\");\n row.appendChild(ing);\n row.appendChild(mes);\n ingredientList.appendChild(row);\n }\n\n if (tags) {\n for (i = 0; i < tags.length; i++) {\n const tag = document.createElement(\"span\");\n const tagText = document.createTextNode(tags[i]);\n\n tag.appendChild(tagText);\n tagRow.appendChild(tag);\n }\n }\n\n recipeImg.src = data.strMealThumb;\n recipeTitle.innerHTML = data.strMeal;\n recipeCat.innerHTML = data.strCategory;\n instructions.innerHTML = data.strInstructions;\n recipeOriginBg.style.backgroundImage = \"url(\" + data.strMealThumb + \")\";\n originalRecipeBtn.href = data.strSource;\n readMore.onclick = function () {\n instructionsContainer.classList.add(\"extended\");\n };\n}", "function generateRecipeText(recipe) {\n let title = document.querySelector(\"#title\");\n let ingredients = document.querySelector(\"#ingredients\");\n let payload = document.querySelector(\"#payload\");\n let steps = document.querySelector(\"#steps\");\n\n title.innerText = `Recipe: ${recipe.title}`;\n\n let ingredient_text = '';\n for (let ingredient of recipe.ingredients) {\n ingredient_text += `- ${ingredient}\\n`;\n }\n ingredients.innerText = ingredient_text;\n\n payload.innerText = `Payload: ${recipe.payload}`;\n\n let steps_text = '';\n for (let step of recipe.steps) {\n steps_text += `- ${step}\\n`;\n }\n steps.innerText = steps_text;\n}", "function formatCitationData(citationData) {\r\n const getField = field => (citationData[field] || '').trim() // safe access which wont return undefined\r\n const dateInfo = new Date().toDateString().split(' ')\r\n switch (getField('format') || 'MLA') {\r\n default:\r\n return `${getField('Authors')}.` +\r\n ` \"${getField('Title')}.\"` +\r\n ` _${getField('Container')}_,` +\r\n ` ${getField('Publish Date')},` +\r\n ` ${getField('Reference')}. Accessed ${+dateInfo[2]} ${dateInfo[1]} ${dateInfo[3]}.`\r\n }\r\n}", "function prettifyRecipes(){\n let raw_recipes = require('../data/recipes_raw.json')\n let stringifiedRecipes = JSON.stringify(raw_recipes, null, 2);\n fs.writeFile('../data/recipes.json', stringifiedRecipes, 'utf8');\n console.log('done')\n}", "function generateRecipe(){\n let rolls = dice();\n\n let steps = [\"Temperature\",\"Steep Time / Grind\",\"Water / Coffee\",\"Stirring\",\"Position / Bloom\"]\n\n let recipe = {\n temperature: `${steps[0]}: ${temperatureOptions[rolls[0]]}`,\n steepTimeGrind: `${steps[1]}: ${steepTimeGrindOptions[rolls[1]]}`,\n waterToCoffee: `${steps[2]}: ${waterToCoffeeOptions[rolls[2]]}`,\n stirring: `${steps[3]}: ${stirringOptions[rolls[3]]}`,\n positionBloom:`${steps[4]}: ${positionBloomOptions[rolls[4]]}`\n } \n \n return recipe;\n}", "function createEncodingRubric() {\n // The CSV format is \"entryID,variable,value,x,y,radius\\n\";\n let csvContent = '';\n Object.entries(canvas.entries).forEach(([entryID, entry]) => {\n Object.values(entry.answerSpaces).forEach((answerSpace) => {\n csvContent += `${entryID},${answerSpace.variable},${answerSpace.value},${answerSpace.left + canvas.markSize},${answerSpace.top + canvas.markSize},${answerSpace.radius}\\n`;\n });\n });\n return csvContent.slice(0, -1);\n }", "function createRecipeItem(recipe) { \r\n var p = document.createElement(\"p\");\r\n var span = document.createElement(\"span\");\r\n var text = document.createTextNode(recipe.name);\r\n //var recipe = recipe;\r\n span.appendChild(text);\r\n p.appendChild(span); \r\n \r\n text = document.createTextNode(\" in \" + recipe.book + \", page: \" + recipe.page);\r\n p.appendChild(text);\r\n var br = document.createElement(\"br\");\r\n p.appendChild(br);\r\n \r\n var ingredients = recipe.ingredients.join(\", \");\r\n \r\n if (recipe.ingredients.length === 0) { \r\n ingredients = \"not specified\";\r\n } \r\n var type = recipe.types.join(\", \");\r\n \r\n if (recipe.types.length === 0) { \r\n type = \"not specified\";\r\n } \r\n\r\n text = document.createTextNode(\"ingredient(s): \" + ingredients); \r\n p.appendChild(text);\r\n br = document.createElement(\"br\");\r\n p.appendChild(br);\r\n text = document.createTextNode(\"type: \" + type); \r\n p.appendChild(text);\r\n br = document.createElement(\"br\");\r\n p.appendChild(br);\r\n text = document.createTextNode(\"remarks: \" + recipe.remark);\r\n p.appendChild(text); \r\n return p;\r\n}", "function recipeInfo(recipe) {\n console.log('*********************************')\n console.log('Recipe Selected: ' + recipe)\n var url = 'http://www.allrecipes.com/Recipe/' + recipe.replace(' ','-');\n\n request(url, function(err, resp, body) {\n // create a DOM of the provided response body, call other scrapers\n $ = cheerio.load(body);\n var json = {\n rating: getRating($),\n time: getCookTime($),\n ingredients: getIngredients($),\n instructions: getInstructions($),\n review: getReviews($),\n nutrition: getNutrition($)\n }\n\n var stringed = JSON.stringify(json, null, 4)\n console.log(JSON.parse(stringed))\n fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){})\n })\n}", "function displayRecipe(recipe) {\n const displayElem = document.getElementById(\"recipeDisplay\");\n displayElem.innerHTML = formatRecipe(recipe);\n}", "function buildRecipeList(json) {\n var html = \"\";\n var count = 0;\n\n html += \"<thead>\";\n html += tableGen.headerRow([\"Title\", \"Description\", \"Author\", \"Tags\"]);\n html += \"</thead><tbody>\";\n for (var key in json) {\n value = json[key];\n\n var output = [];\n output.push(tableGen.dataCell(\"<a href='#view/ID=\" + value['ID'] + \"'>\" + value['Title'] + \"</a>\"));\n output.push(tableGen.dataCell(value['Description']));\n output.push(tableGen.dataCell(value['Author'] != undefined ? value['Author']['Name'] : ''));\n var tagList = [];\n var tags = value['Tags']\n for (var tagKey in tags) {\n tagList.push(tags[tagKey]['Tag']);\n }\n output.push(tableGen.dataCell(tagList));\n var attrs = \"data-cmd='view' data-id='\" + value['ID'] + \"'\";\n var sClass = (count++ % 2 == 1 ? ' alt' : '');\n html += tableGen.dataRow(attrs, sClass, output);\n }\n html += \"</tbody>\";\n\n return html;\n}", "function formatWardYieldData(rawData) {\n\n /*\n - following format:\n data = {first_row: first row of data,\n first_column: first column of data,\n data:[{id: row's id, name: row's name, \n data: [{id: column's id, percentage: %, number: #}\n ...]\n }\n ....\n ]\n }\n */\n\n // get data\n var resData = rawData.response;\n\n // check data\n if (!resData || typeof resData === 'undefined' || resData.length == 0) {\n return { first_row: null, first_column: null, data: [{ id: 1, name: \"Không có dữ liệu\" }] };\n }\n\n var brands = $rootScope.brands;\n var first_row = [];\n var first_column = [];\n var data = [];\n var temp;\n\n // get the total of the data\n var total;\n for (var i = 0; i < resData.length; i++) {\n if (resData[i].companyname) {\n total = resData[i].yield;\n break;\n }\n }\n\n // format the data\n temp = { id: 0, name: \"Sản lượng\", data: [] };\n angular.forEach(resData, function (val, key) {\n var percent = !total ? 0 : (val.yield / total) * 100;\n percent = percent.toFixed(2) + '%';\n\n if (val.companyname) {\n first_row.unshift(brands[val.companyname]);\n temp.data.unshift({ id: val.companyname, percentage: percent, number: $rootScope.numberWithCommas(val.yield) });\n }\n else {\n first_row.push(brands[val.company]);\n temp.data.push({ id: val.company, percentage: percent, number: $rootScope.numberWithCommas(val.yield) });\n }\n });\n data.push(temp);\n return { first_row: first_row, first_column: null, data: data };\n }", "function cookbook (batches) {\n var ingredients = {\n flour: 4,\n sugar: 3,\n cocoa: 2\n };\n var recipe = \n`Combine ${batches * ingredients.flour} cups of flour with ${batches * ingredients.sugar} tablespoons of sugar.\nAdd ${batches * ingredients.cocoa} grams of coco and whisk.\nBake for 1 hour at 200C.`\n return recipe;\n}", "function printRecipeToScreen(recipeRead) {\n var seen = [];\n\n var tempOutput = JSON.stringify(recipeRead, function (key, val) {\n if (val != null && typeof val == \"object\") {\n if (seen.indexOf(val) >= 0) {\n return;\n }\n seen.push(val);\n }\n return val;\n })\n\n // This is an array of the FDA API queries for each ingredient\n var ingredients = JSON.parse(tempOutput)._docs;\n\n // Run through each FDA API query and compile information\n ingredients.forEach(sumNutrition);\n\n // Set the text element to display the recipe\n setRecipeOutput(ingredientList + '\\nTotal calories: ' + totalCalories);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simplifies and returns Poke details
getPokeDetails(){ let pokeData = this.props; return { name: pokeData.name, imgData: this.getPokeImgs(pokeData.sprites), type: this.getPokeType(pokeData.types), hp: pokeData.base_experience } }
[ "function pokeInfo (pkm) {\n P.getPokemonByName(pkm) // with Promise\n .then(function (response) {\n // console.log(response)\n msg.channel.send('name: ' + response.name + '\\nid: ' + response.id + '\\nheight: ' + response.height / 10 + ' m \\nweight: ' + response.weight / 10 + 'kg')\n var pokeType1 = response.types[0].type.name\n if (response.types.length === 2) {\n var pokeType2 = response.types[1].type.name\n } else pokeType2 = null\n msg.channel.send('type1 : ' + pokeType1 + '\\ntype2: ' + pokeType2)\n msg.channel.send('sprite: ' + response.sprites.front_default)\n })\n .catch(function (error) {\n console.log(error)\n })\n }", "function pokeCodeToPokemon(pokeCode) {\r\n return {\r\n \"poke\": sys.pokemon(toNumber(pokeCode.substr(0, 2)) + 65536 * toNumber(pokeCode.substr(2, 1))),\r\n \"pokeId\": toNumber(pokeCode.substr(0, 2)) + 65536 * toNumber(pokeCode.substr(2, 1)),\r\n \"speciesNum\": toNumber(pokeCode.substr(0, 2)),\r\n \"formNum\": toNumber(pokeCode.substr(2, 1)),\r\n \"species\": sys.pokemon(toNumber(pokeCode.substr(0, 2))),\r\n \"nature\": sys.nature(toNumber(pokeCode.substr(3, 1))),\r\n \"natureId\": toNumber(pokeCode.substr(3, 1)),\r\n \"natureInfo\": getNature(sys.nature(toNumber(pokeCode.substr(3, 1)))),\r\n \"ability\": sys.ability(toNumber(pokeCode.substr(4, 2))),\r\n \"abilityId\": toNumber(pokeCode.substr(4, 2)),\r\n \"item\": sys.item(toNumber(pokeCode.substr(6, 3))),\r\n \"itemId\": toNumber(pokeCode.substr(6, 3)),\r\n \"level\": toNumber(pokeCode.substr(9, 2)),\r\n \"moves\": [\r\n sys.move(toNumber(pokeCode.substr(11, 2))),\r\n sys.move(toNumber(pokeCode.substr(13, 2))),\r\n sys.move(toNumber(pokeCode.substr(15, 2))),\r\n sys.move(toNumber(pokeCode.substr(17, 2)))\r\n ],\r\n \"moveIds\": [\r\n toNumber(pokeCode.substr(11, 2)),\r\n toNumber(pokeCode.substr(13, 2)),\r\n toNumber(pokeCode.substr(15, 2)),\r\n toNumber(pokeCode.substr(17, 2))\r\n ],\r\n \"evs\": [\r\n toNumber(pokeCode.substr(19, 2)),\r\n toNumber(pokeCode.substr(21, 2)),\r\n toNumber(pokeCode.substr(23, 2)),\r\n toNumber(pokeCode.substr(25, 2)),\r\n toNumber(pokeCode.substr(27, 2)),\r\n toNumber(pokeCode.substr(29, 2))\r\n ],\r\n \"dvs\": [\r\n toNumber(pokeCode.substr(31, 1)),\r\n toNumber(pokeCode.substr(32, 1)),\r\n toNumber(pokeCode.substr(33, 1)),\r\n toNumber(pokeCode.substr(34, 1)),\r\n toNumber(pokeCode.substr(35, 1)),\r\n toNumber(pokeCode.substr(36, 1))\r\n ],\r\n \"gen\": sys.generation(toNumber(pokeCode.substr(37, 1)),\r\n toNumber(pokeCode.substr(38, 1))),\r\n \"genNum\": toNumber(pokeCode.substr(37, 1)),\r\n \"subgenNum\": toNumber(pokeCode.substr(38, 1))\r\n };\r\n}", "function addPokeInfo() {\n let pokeId = parseInt(this.innerText);\n let pokeInfo = allPokemon[pokeId - 1];\n changeSprite(pokeInfo);\n changeStats(pokeInfo);\n }", "function formatPokedexEntry(entry) {\n let output = `\n ${chalk.blue('species')}: ${entry.Name}\n ${chalk.yellow('type')}: ${entry.Type1} ${chalk.yellow('type 2')}: ${entry.Type2}\n\n ${chalk.grey('base stats')}:\n -----------\n ${chalk.blue('health')} : ${entry.HP}\n ${chalk.blue('attack')} : ${entry.Attack}\n ${chalk.blue('defense')} : ${entry.Defense}\n ${chalk.blue('sp attack')} : ${entry['Special Attack']}\n ${chalk.blue('sp defense')} : ${entry['Special Defense']}\n ${chalk.blue('speed')} : ${entry.Speed}\n `\n return output;\n}", "function updatePokedex(pokeEntry) {\n pokeID = pokeEntry.id;\n\n sprites.src = pokeEntry.sprites.front_default;\n number.innerHTML = \"n°\" + pokeID;\n name.innerHTML = pokeEntry.species.name;\n input.value = pokeEntry.species.name;\n\n type.innerHTML = \" \";\n pokeEntry.types.forEach(name => {\n type.innerHTML += name.type.name + \" \";\n });\n\n moves.innerHTML =\n pokeEntry.moves[0].move.name + \"<br>\" + pokeEntry.moves[1].move.name + \"<br>\" + pokeEntry.moves[2].move.name + \"<br>\" + pokeEntry.moves[3].move.name;\n}", "function parsePokeName(name){\r\n var splitName = name.split(':')[1].trim();\r\n return splitName;\r\n}", "function stripPokemonResponse(pokemonResponse) {\n const strippedPokemonResponse = {\n id: pokemonResponse.id,\n name: pokemonResponse.name,\n hp: pokemonResponse.stats.find(stat => stat.stat.name === 'hp').base_stat,\n attacks: pokemonResponse.moves.map(move => ({\n id: getIdFromUrl(move.move.url),\n name: move.move.name\n }))\n };\n return strippedPokemonResponse;\n}", "ChangeName (name) {\n this.pokemon.forEach(item => {\n if (item.name === name.selected.name) {\n item.name = name.name\n const caughtPoke = this.pokemon.splice(this.pokemon.indexOf(item), 1)\n console.log(caughtPoke[0], 'Caught poke')\n this.caughtPokemon.push(caughtPoke[0])\n return this.pokemon\n }\n })\n }", "function createPokeInfo(pokemon, element) {\n //Grab pokemon ID and pad it with leading 0s\n var displayID = JSON.stringify(pokemon.id).padStart(3, '0');\n //Grab pokemon name and capitalize\n var pokeName = pokemon.name[0].toUpperCase() + pokemon.name.slice(1);\n //Grab pokemon type\n var typeArray = [];\n if (Object.keys(pokemon.types).length === 1) {\n typeArray.push(pokemon.types[0].type.name);\n } else {\n pokemon.types.forEach(function(res) {\n typeArray.push(res.type.name);\n })\n }\n var pokeTypes = typeArray.join(\", \");\n //Grab pokemon picture\n var pokePic = pokemon.sprites.front_default;\n //Grab pokemon height\n var pokeHeight = pokemon.height * 10;\n //Grab pokemon weight\n var pokeWeight = pokemon.weight / 10;\n //Put API info into DOM\n var pokeElement = `<div class='infoTile' id='${pokemon.name}Info' data-id='tile-${pokemon.id}'>\n <p class='back'>Go Back</p>\n <h3 class='pokemonTitle'>#${displayID} ${pokeName}</h3>\n <div class=\"pokemonInfo\" data-id='info-${pokemon.id}'>\n <img class='pokemonPic' data-id='picture-${pokemon.id}' src='${pokePic}'>\n <div class=\"pokemonInner\" data-id='inner-${pokemon.id}'>\n <span class='pokemonType' data-id='type-${pokemon.id}'><b>Type:</b> ${pokeTypes}</span></br>\n <span class='pokemonHeight' data-id='height-${pokemon.id}'><b>Height:</b> ${pokeHeight}cm</span></br>\n <span class='pokemonWeight' data-id='weight-${pokemon.id}'><b>Weight:</b> ${pokeWeight}kg</span>\n </div>\n </div>\n <div class=\"poke-btn-container\">\n <button class=\"choose-btn\" value=\"${pokeName}\" >I choose you!</button>\n </div>\n</div>`;\n element.insertAdjacentHTML('afterend',pokeElement);\n pendo.track(\"Poke Info Viewed\", {\n PokemonName: `${pokeName}`\n });\n }", "static getPokeForCartItem(cartItem, pokemon) {\n const pokeItem = pokemon.find(poke => poke.id === cartItem.itemId);\n return pokeItem;\n }", "renderByPoem() {\n var data = GetData();\n\n var information = [];\n var pushedPoems = {};\n for(var i = 0; i < data.length; i++) {\n for(var j = 0; j < data[i][\"details\"].length; j++){\n // If there's not an instance of the poem in the pushed poems then it needs to be pushed\n if (!pushedPoems.hasOwnProperty(data[i][\"details\"][j][detailLeftKey])){\n pushedPoems[data[i][\"details\"][j][detailLeftKey]] = information.length;\n\n information.push({\n titleLeft : data[i][\"details\"][j][detailLeftKey],\n titleRight : \" \",\n \"details\" : []\n })\n }\n // This happens no matter what\n information[pushedPoems[data[i][\"details\"][j][detailLeftKey]]][\"details\"].push({\n detailLeft : data[i][titleLeftKey],\n detailRight : data[i][\"details\"][j][detailRightKey]\n });\n }\n }\n\n return information;\n }", "ChangeCaughtPokeName (name) {\n this.caughtPokemon.forEach(item => {\n if (item.name === name.selected.name) {\n item.name = name.name\n }\n })\n }", "get pokemonList() {\n // Filtering out Trainers\n return this.enemyList.filter((enemy) => {\n return !enemy.hasOwnProperty('name');\n }).map((enemy) => {\n // Collapsing DetailedPokemon\n if (typeof enemy === 'string') {\n return enemy;\n }\n else if (enemy.hasOwnProperty('pokemon')) {\n return enemy.pokemon;\n }\n });\n }", "function getStats(src, team, poke) {\r\n var movelist = [];\r\n for (var m=0; m<4; m++) {\r\n var move = sys.teamPokeMove(src, team, poke, m);\r\n movelist.push(sys.move(move));\r\n }\r\n var evlist = [];\r\n for (var e=0; e<6; e++) {\r\n var ev = sys.teamPokeEV(src, team, poke, e);\r\n evlist.push(ev);\r\n }\r\n var dvlist = [];\r\n for (var d=0; d<6; d++) {\r\n var dv = sys.teamPokeDV(src, team, poke, d);\r\n dvlist.push(dv);\r\n }\r\n var genders = [\"\", \"(M) \", \"(F) \"];\r\n var info = {\r\n 'poke': sys.pokemon(sys.teamPoke(src,team,poke)),\r\n 'species': sys.pokemon(sys.teamPoke(src,team,poke)%65536),\r\n 'nature': sys.nature(sys.teamPokeNature(src,team,poke)),\r\n 'ability': sys.ability(sys.teamPokeAbility(src,team,poke)),\r\n 'item': sys.item(sys.teamPokeItem(src,team,poke)),\r\n 'level': sys.teamPokeLevel(src,team,poke),\r\n 'moves': movelist,\r\n 'evs': evlist,\r\n 'dvs': dvlist,\r\n 'gender': genders[sys.teamPokeGender(src,team,poke)]\r\n };\r\n var stats = [\"HP\", \"Attack\", \"Defense\", \"Sp.Atk\", \"Sp.Def\", \"Speed\"];\r\n var statlist = [];\r\n var pokeinfo = [];\r\n if (pokedb.hasOwnProperty(info.poke)) {\r\n pokeinfo = pokedb[info.poke];\r\n }\r\n else if (pokedb.hasOwnProperty(info.species)) {\r\n pokeinfo = pokedb[info.species];\r\n }\r\n else {\r\n throw \"UNHANDLED EXCEPTION: Pokeinfo not found\";\r\n }\r\n for (var s=0; s<6; s++) {\r\n var natureboost = getNature(info.nature);\r\n if (s === 0) { // HP Stat\r\n if (pokeinfo[s] == 1) { // Shedinja\r\n statlist.push(\"1 HP\");\r\n }\r\n else {\r\n var hstat = 10 + Math.floor(Math.floor(info.dvs[s]+2*pokeinfo[s]+info.evs[s]/4+100)*info.level/100);\r\n statlist.push(hstat+\" HP\");\r\n }\r\n }\r\n else {\r\n var bstat = 5 + Math.floor(Math.floor(info.dvs[s]+2*pokeinfo[s]+info.evs[s]/4)*info.level/100);\r\n var newstat = 0;\r\n if (natureboost[0] === s) {\r\n newstat = Math.floor(bstat*1.1);\r\n }\r\n else if (natureboost[1] === s) {\r\n newstat = Math.floor(bstat*0.9);\r\n }\r\n else {\r\n newstat = bstat;\r\n }\r\n statlist.push(newstat+\" \"+stats[s]);\r\n }\r\n }\r\n var msg = [];\r\n msg.push(info.poke+\" \"+info.gender+\"@ \"+info.item+\"; Ability: \"+info.ability+\"; \"+info.nature+\" Nature; Level \"+info.level)\r\n msg.push(info.moves.join(\" / \"),\"Stats: \"+statlist.join(\" / \"));\r\n return msg;\r\n}", "function formatJoke(joke) {\n return [\n 'Knock, knock.',\n 'Who’s there?',\n joke.name + '.',\n joke.name + ' who?',\n joke.name + ' ' + joke.answer\n ].join('\\n')\n}", "getAllPokeDtls(){\n return this.state.allPokeData.map((result)=>{\n return (\n <div key={result.data.name} className=\"srch-poke-card\">\n <PokeCard {...result.data} />\n </div>\n );\n });\n }", "getPokeList() {\n return Axios.get('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=964');\n }", "function exportPokemon(pokemon) {\n var text = '';\n // PokemonName (F) @ Item\n text += POKEMON_DATA[pokemon.name].name;\n if (pokemon.gender !== GENDER_GENDERLESS) {\n text += ' (';\n if (pokemon.gender === GENDER_MALE) {\n text += 'M';\n } else {\n text += 'F';\n };\n text += ')';\n };\n if (pokemon.item) {\n text += ' @ ' + ITEMS[pokemon.item].name;\n };\n text += '\\n';\n // Ability: (ability)\n if (pokemon.ability) {\n text += 'Ability: ' + ABILITIES[pokemon.ability].name + '\\n';\n };\n // Level: 100\n if (pokemon.level !== 100) {\n text += 'Level: ' + pokemon.level + '\\n';\n };\n // EVs: \n if (! isDefaultEVs(pokemon.ev)) {\n // export EVs\n text += 'EVs: ';\n text += getEVSpread(pokemon);\n text += '\\n';\n };\n // Bold Nature\n if (pokemon.nature) {\n text += NATURES[pokemon.nature].name + ' Nature\\n';\n };\n // IVs:\n if (! isDefaultIVs(pokemon.iv)) {\n // export IVs\n var ivs = [];\n for (var stat = 0; stat < 6; stat++) {\n if (pokemon.iv[stat] !== 31) {\n ivs.push(pokemon.iv[stat] + ' ' + getShowdownStat(stat));\n };\n };\n text += 'IVs: ';\n text += ivs.join(' / ');\n text += '\\n';\n };\n // Moves:\n for (var moveNum = 0; moveNum < 4; moveNum++) {\n if (pokemon.moves[moveNum]) {\n // we have a move\n text += '- ' + MOVE_DATA[pokemon.moves[moveNum]].name + '\\n';\n };\n };\n text += '\\n';\n return text;\n}", "function getName(hikes, entry){\n let hikeId;\n let title;\n hikes.forEach(hike => {\n hikeId= hike.id;\n if(hikeId== entry.hikeId){\n //console.log(`hikeId ${hikeId} hike.id: ${hike.id}`)\n title= hike.title;\n }\n })\n return title;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
showing the amount of money
function updateMoney() { moneyText.text = money.toString(); }
[ "showBalance(){\n this.balance = Number(this.budgetObj - this.totalExpenses).toFixed(2);\n this.uiBalance.innerText = this.balance;\n }", "function show_money() {\r\n\t$(\"#money\").html(\"Balance: \" + money + \" €\");\r\n}", "showTotal(){\n let total = 0;\n for(let i = 0; i < this.expenseObj.length; i++) {\n let row = this.expenseObj[i];\n total = total+Number(row.amount);\n }\n this.uiExpenses.innerText = Number(total).toFixed(2);\n this.totalExpenses = total;\n }", "function amount() {}", "static displayBudget() {\n const calced = Store.getBudget();\n document.getElementById(\"budgetDisplay\").innerHTML = \"$\" + calced;\n }", "function renderMoney() {\n document.querySelector('.wage').innerHTML = \"Wage Total: $\" + wager;\n document.querySelector('.bankTotal').innerHTML = \"Bank Total: $\" + bank;\n}", "function redisplayTotalMoney(){\n document.querySelector(\"#total-money\").textContent = \"Total Money: \" + money.toFixed(2);\n}", "function updateMoneyDisplay(){\n moneyDisplay.html('$' + userMoney);\n}", "function displayTotalAmount() {\n\tvar totalAmount = getTotalAmount();\n\t$('#total').html(totalAmount);\n\t$('#currentCurrency').html(defaultCurrency);\n\t$('#basketTotal').removeClass('d-none');\n\tdisplayCurrencyConverter();\n}", "showBudget(amount) {\n totalBudget.innerHTML = html.separate(amount);\n availableBudget.innerHTML = html.separate(amount);\n }", "function renderBidTotalEarnings(){\n\tlet bid_total_earnings_display = parseFloat(statistics.bid_total_earnings).toFixed(2);\n\t$('#total_earnings_description').text(\"Total bid earnings: \");\n\t$('#total_earnings_val').text(\"$\"+bid_total_earnings_display);\n}", "function showAmount() {\n if (location === 'inventory') {\n return amount + 'X';\n }\n }", "showBudget(){\n this.uiBudget.innerText = Number(this.budgetObj).toFixed(2);\n this.budget.value = this.budgetObj;\n }", "function setMoney(amt) {\n display.setMoneyDisplay(amt);\n}", "function renderBuyoutTotalEarnings(){\n\tlet buyout_total_earnings_display = parseFloat(statistics.buyout_total_earnings).toFixed(2);\n\t$('#total_earnings_description').text(\"Total buyout earnings: \");\n\t$('#total_earnings_val').text(\"$\"+buyout_total_earnings_display);\n}", "function MoneyDisplay({money}) {\n return(<div className=\"moneyDisplay\">credit: {Number(money).toFixed(2)}$</div>)\n}", "function depositMoney(){\n var monies = 0;\n $(\"#player-cards .card-title-money\").each(function(){\n var card = discoverCard($(this).html());\n monies += card.money;\n });\n setMoney(monies);\n}", "function updateMoney() {\n id('player-money').textContent = GAME.playerMoney;\n id('pot').textContent = GAME.pot;\n }", "function updateTotal() {\n totalAmountPerson = (billAmount/peopleNum)+tipAmountPerson;\n console.log(totalAmountPerson);\n document.querySelector('#totalAmount').innerHTML = '<span>$' + totalAmountPerson.toFixed(2) + '</span>';\n if (totalAmountPerson > 0){\n document.querySelector('#totalAmount').style.color = \"#38AC9E\";\n } else{\n document.querySelector('#totalAmount').style.color = \"hsl(185, 41%, 84%)\";\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the event (digg, comment) date related with this user.
set eventDate(aValue) { this._logger.debug("eventDate[set]"); this._eventDate = aValue; }
[ "set eventDate(aValue) {\n this._logService.debug(\"gsDiggUserDTO.eventDate[set]\");\n this._eventDate = aValue;\n }", "function setUserEvDate(value) {\n user_evt_date = value;\n}", "set date(aValue) {\n this._logger.debug(\"date[set]\");\n this._date = aValue;\n }", "get eventDate() {\n this._logService.debug(\"gsDiggUserDTO.eventDate[get]\");\n return this._eventDate;\n }", "set promoteDate(aValue) {\n this._logger.debug(\"promoteDate[set]\");\n this._promoteDate = aValue;\n }", "set promoteDate(aValue) {\n this._logService.debug(\"gsDiggStoryDTO.promoteDate[set]\");\n this._promoteDate = aValue;\n }", "function assignDatesToEvent(start, end, allDay, event) {\n\n\t\t// normalize the date based on allDay\n\t\tif (allDay) {\n\t\t\t// neither date should have a time\n\t\t\tif (start.hasTime()) {\n\t\t\t\tstart.stripTime();\n\t\t\t}\n\t\t\tif (end && end.hasTime()) {\n\t\t\t\tend.stripTime();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// force a time/zone up the dates\n\t\t\tif (!start.hasTime()) {\n\t\t\t\tstart = t.rezoneDate(start);\n\t\t\t}\n\t\t\tif (end && !end.hasTime()) {\n\t\t\t\tend = t.rezoneDate(end);\n\t\t\t}\n\t\t}\n\n\t\tevent.allDay = allDay;\n\t\tevent.start = start;\n\t\tevent.end = end || null; // ensure null if falsy\n\n\t\tif (options.forceEventDuration && !event.end) {\n\t\t\tevent.end = getEventEnd(event);\n\t\t}\n\n\t\tbackupEventDates(event);\n\t}", "function assignDatesToEvent(start, end, allDay, event) {\n\n\t\t// normalize the date based on allDay\n\t\tif (allDay) {\n\t\t\t// neither date should have a time\n\t\t\tif (start.hasTime()) {\n\t\t\t\tstart.stripTime();\n\t\t\t}\n\t\t\tif (end && end.hasTime()) {\n\t\t\t\tend.stripTime();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// force a time/zone up the dates\n\t\t\tif (!start.hasTime()) {\n\t\t\t\tstart = t.rezoneDate(start);\n\t\t\t}\n\t\t\tif (end && !end.hasTime()) {\n\t\t\t\tend = t.rezoneDate(end);\n\t\t\t}\n\t\t}\n\n\t\tif (end && end <= start) { // end is exclusive. must be after start\n\t\t\tend = null; // let defaults take over\n\t\t}\n\n\t\tevent.allDay = allDay;\n\t\tevent.start = start;\n\t\tevent.end = end || null; // ensure null if falsy\n\n\t\tif (options.forceEventDuration && !event.end) {\n\t\t\tevent.end = getEventEnd(event);\n\t\t}\n\n\t\tbackupEventDates(event);\n\t}", "function setDate(date) {\n if (!date) {\n var d = new Date();\n var dateFormat = d.getUTCFullYear() + \"-\" + (d.getUTCMonth() + 1) + \"-\" + d.getUTCDate();\n recolt.date = dateFormat;\n }\n dom.date.text(\"Date : \" + recolt.date);\n}", "function setEvent(event) {\n console.info(\"Setting the Current Event: \", event);\n $('#edit_event').val(event);\n }", "set submitDate(aValue) {\n this._logService.debug(\"gsDiggStoryDTO.submitDate[set]\");\n this._submitDate = aValue;\n }", "function setEvent() {\n $('.day-event').each(function(i) {\n var eventMonth = $(this).attr('date-month');\n if (eventMonth < 10) {\n eventMonth = eventMonth[1];\n }\n var eventDay = $(this).attr('date-day');\n if (eventDay < 10) {\n eventDay = eventDay[1];\n }\n var eventYear = $(this).attr('date-year');\n var eventClass = $(this).attr('event-class');\n if (eventClass === undefined) eventClass = 'event';\n else eventClass = 'event ' + eventClass;\n\n if (parseInt(eventYear) === yearNumber) {\n $('.event-calendar div[date-month=\"' + eventMonth + '\"][date-day=\"' + eventDay + '\"]').addClass(eventClass);\n }\n });\n }", "set submitDate(aValue) {\n this._logger.debug(\"submitDate[set]\");\n this._submitDate = aValue;\n }", "function setDate( date ) {\n\n switch ( scope.current.view ) {\n case 'minutes':\n if ( canPickMinute(date) ) {\n selectedDate.minutes = date.getMinutes();\n setCurrentDate(date.getMinutes(), scope.current.view);\n openNextView();\n }\n break;\n case 'hours':\n if ( canPickHour(date) ) {\n selectedDate.hours = date.getHours();\n setCurrentDate(date.getHours(), scope.current.view);\n openNextView();\n }\n break;\n case 'date':\n if ( canPickDay(date) ) {\n selectedDate.date = date.getDate();\n setCurrentDate(date.getDate(), scope.current.view);\n openNextView();\n }\n break;\n case 'month':\n if ( canPickMonth(date) ) {\n selectedDate.month = date.getMonth();\n setCurrentDate(date.getMonth(), scope.current.view);\n openNextView();\n }\n break;\n case 'year':\n if ( canPickYear(date) ) {\n selectedDate.year = date.getFullYear();\n setCurrentDate(date.getFullYear(), scope.current.view);\n openNextView();\n }\n break;\n }\n }", "function setEvent() {\n $('.day-event').each(function (i) {\n var eventMonth = $(this).attr('date-month');\n var eventDay = $(this).attr('date-day');\n var eventType = $(this).attr('date-type');\n $('tbody.event-calendar tr td[date-month=\"' + eventMonth + '\"][date-day=\"' + eventDay + '\"]').addClass('event');\n $('tbody.event-calendar tr td[date-month=\"' + eventMonth + '\"][date-day=\"' + eventDay + '\"]').addClass(eventType);\n });\n }", "function setDate( d ) {\n\n if ( d ) {\n if ( d instanceof Date ) {\n date = d;\n } else if ( isNaN(d) === false ) {\n date = new Date( d );\n } else {\n return;\n }\n } else {\n date = new Date();\n }\n }", "set viewDate(value) {\n if (Array.isArray(value)) {\n return;\n }\n const validDate = this.validateDate(value);\n if (this._viewDate) {\n this.selectedDatesWithoutFocus = validDate;\n }\n const date = this.getDateOnly(validDate).setDate(1);\n this._viewDate = new Date(date);\n }", "onDateSelectedListen(event) {\n const detail = event.detail;\n this.selectedDate = this.getFormattedDate(detail.month, detail.date, detail.year);\n }", "get eventDate() {\n return new Date(this._data.event_timestamp);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of specific spot requests
async listSpotRequests(conditions = {}, client = undefined) { assert(typeof conditions === 'object'); return this._listTable('spotrequests', conditions, client); }
[ "function requestSpots()\n{\n // Show the loading indicator\n $('#map-loader').css('visibility', 'visible');\n // console.log(\"MAP LOADER VISIBLE\");\n // Record the download request\n downloadingSpots = true;\n\n // console.log(\"REQUESTING SPOT DATA\");\n // console.log('ENDPOINT SPOTS: ' + refs['endpoint_spot_query_active']);\n var timestamp_begin = 0;\n\n var xhrHT = new XMLHttpRequest();\n xhrHT.open('POST', refs['endpoint_spot_query_active'], true);\n xhrHT.setRequestHeader(\"Content-Type\", \"application/json\");\n xhrHT.send(JSON.stringify({\n 'app_version': appVersion\n , 'timestamp_begin': timestamp_begin\n }));\n xhrHT.onerror = function()\n {\n console.log(\"XHR ERROR\")\n\n // DEV CHECK BEFORE PROD\n // // The error might be a CORS error (www) - redirect?\n // window.location = domain;\n }\n xhrHT.onreadystatechange = function()\n {\n if (xhrHT.readyState == XMLHttpRequest.DONE)\n {\n // Indicate the download is complete\n downloadingSpots = false;\n\n // console.log(xhrHT.responseText.toString());\n var jsonResponse = JSON.parse(xhrHT.responseText);\n allSpots = jsonResponse.spots;\n addSpots();\n\n allSpotRequests = jsonResponse.spot_requests;\n addSpotRequests();\n\n // If nothing is being downloaded currently, hide the loader\n if (!downloadingStructures && !downloadingSpots && !downloadingHazards)\n {\n $('#map-loader').css('visibility', 'hidden');\n // console.log(\"MAP LOADER HIDDEN\");\n }\n }\n }\n}", "async spotRequestsToPoll({region}, client) {\n let states = ['open'];\n let statuses = [\n 'pending-evaluation',\n 'pending-fulfillment',\n ];\n let result = await this.listSpotRequests({region, state: states, status: statuses}, client);\n // This is slightly inefficient because we're selecting * from the table\n // instead of just the id. I think that's really not a huge deal\n // considering we're not even using a cursor or anything... Let's optimize\n // that when we can show it's actuall important enough to make the query\n // generator complex enough to understand it\n return result.map(x => x.id);\n }", "function getTopSpots() {\n return $http({\n method: 'GET',\n url: '../topspots.json'\n }).then(function(response){\n\n return response.data;\n\n });\n\n }", "function getTopSpots() {\n\n var defer = $q.defer();\n\n $http({\n method: 'GET',\n url: url\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n } else {\n defer.reject(\"No data found!\");\n }\n },\n function(error) {\n defer.reject(error);\n });\n\n return defer.promise;\n\n }", "knownSpotInstanceRequestIds() {\n // We need to know all the SpotInstanceRequestIds which are known\n // to aws state. This is mostly just the id from the requests\n let allKnownSrIds = this.__apiState.requests.map(r => r.SpotInstanceRequestId);\n\n // We also want to make sure that the Spot Request isn't in any\n // instance's object\n for (let instance of this.__apiState.instances) {\n let sird = instance.SpotInstanceRequestId;\n if (sird && !_.includes(allKnownSrIds, sird)) {\n allKnownSrIds.push(sird);\n }\n }\n\n return allKnownSrIds;\n }", "function getTopSpots () {\n\n \t\tsanDiegoTopSpotsFactory.getSanDiegoTopSpots().then( \n \t\tfunction(response) { \n markers = response.data;\n \t\t\tvm.topspots = response.data; //grabs topspots API JSON data response from sanDiegoTopSpotsFactory\n\n angular.forEach(markers, function(marker){ //grabs lat/lon data from json file and uses it to create the google maps markers.\n marker.coords = { \n latitude: marker.location[0],\n longitude: marker.location[1]\n };\n });\n \n $scope.markers = markers; \t\t\t\t\t\n \t\t\t},\n \t\t\tfunction(error){ //handles errors given by the sanDiegoTopSpotsFactory\n \n toastr.error('There was an error');\n \t\t\t}\n \t);\n }", "getPastLists() {\n\n return new TotoAPI().fetch('/supermarket/pastLists?maxResults=20').then((response) => response.json());\n }", "async function getItemsFromSpotify(url) {\n\tvar json = await requestSpotify(url);\n\tvar data = json[\"items\"];\n\twhile(json[\"next\"] !== null && json[\"next\"] !== undefined) {\n\t\tjson = await requestSpotify(json[\"next\"]);\n\t\tdata.push(...json[\"items\"]);\n\t}\n\treturn data;\n}", "async function requestSpotify(url) {\n\tconst response = await fetch(url, {method: 'GET', headers: {'Authorization': 'Bearer ' + bearer}})\n\t\t.catch((error) => {console.log(\"error: \" + error + \", url: \" + url);});\n\treturn response.json();\n}", "function RequestSpotInstancesRequest() {\n _classCallCheck(this, RequestSpotInstancesRequest);\n\n RequestSpotInstancesRequest.initialize(this);\n }", "function addSpotRequests()\n{\n // Remove the current SpotRequests from the map and clear the arrays\n spotRequestsMapNull();\n spotRequestMarkers = [];\n filteredSpotRequests = [];\n\n // Create a common infowindow for all markers\n var infowindow = new google.maps.InfoWindow(\n {\n content: 'Photo Requested<br><br>APP ONLY: Take photos by location in the iPhone app.'\n });\n\n for (i = 0; i < allSpotRequests.length; i++)\n {(function (spotRequest)\n {\n // Only add the entity if the timestamp is newer than the current filter setting\n var secondsOld = Math.floor(Date.now() / 1000) - allSpotRequests[i].timestamp;\n if (secondsOld <= menuFilterSeconds)\n {\n var icon = {\n url: 'img/markers/marker_icon_camera_yellow@3x.png',\n scaledSize: new google.maps.Size(50, 50), // scaled size\n origin: new google.maps.Point(0,0), // origin\n anchor: new google.maps.Point(25,50) // anchor\n };\n // console.log(allSpotRequests[i].lat)\n var spotRequestMarker = new google.maps.Marker({\n position: {lat: allSpotRequests[i].lat, lng: allSpotRequests[i].lng},\n map: map,\n icon: icon,\n optimized: false,\n zIndex: 4\n });\n\n spotRequestMarker.addListener('click', function()\n {\n infowindow.open(map, this);\n });\n\n spotRequestMarkers.push(spotRequestMarker);\n filteredSpotRequests.push(allSpotRequests[i]);\n }\n })(allSpotRequests[i])\n }\n}", "function spotifyAPI(userFavorites){\r\n const spotifyID = {\r\n id: \"520a7273452546879b3b85f62e8b9939\",\r\n secret: \"2d59e1d6dd5a40b3a291fe29a18aaa3c\"\r\n };\r\n\r\n let spotify = new spotify(spotifyID);\r\n\r\n spotify.search( {type: \"artist\", query: userFavorites,} ).then(function(response){\r\n console.log(response);\r\n });\r\n}", "function getNearbyShops() {\n const requestOptions = {\n method: 'GET',\n headers: Header()\n };\n\n return fetch(`${API_URL}shops`, requestOptions)\n .then(handleResponse)\n}", "async function getListOfServedTickets() {\n try {\n const response = await fetch(`${baseURL}/ticket?served`);\n const listServedTickets = await response.json();\n if (response.ok) {\n return listServedTickets[0];\n } else {\n return [];\n }\n } catch (error) {\n console.log(\"Error\", error);\n throw error;\n }\n }", "function spotifyRequest(response) {\n var spotifyRequest = [\n `Artist: ${response.artists[0].name}`,\n `Song's Name: ${response.name}`,\n `Preview Url: ${response.preview_url}`,\n `Album Name: ${response.album.name}`,\n divider\n ].join( \"\\n\");\n console.log(spotifyRequest);\n\n logTxt(spotifyRequest);\n}", "function getOmnifySearch(req, res) {\n var getOmnifySearchResponse = res;\n var searchTerm = req.swagger.params.q.value;\n var spotifySearchUri = 'search?type=track&limit=10&q=' + searchTerm;\n\n\n request.post({\n url: spotifyAuthUrl,\n headers: {\n 'content-type': 'application/json',\n 'Authorization': 'Basic ' + spotifyAppId\n },\n form: {\n grant_type: 'client_credentials'\n }\n }, function (err, res, body) {\n\n var body = JSON.parse(body);\n\n spotifyAccessToken = body['access_token'];\n\n request({\n url: spotifyEndpoint + spotifySearchUri,\n headers: {\n 'Authorization': 'Bearer ' + spotifyAccessToken\n }\n }, function(err, res, body) {\n\n var body = JSON.parse(body);\n\n var echoNestUrls = body.tracks.items.map(function (track) {\n return spotifyEndpoint + 'audio-features/' + track.id;\n });\n\n var omniUrls = body.tracks.items.map(function (track) {\n\n var result = {\n id: track.id,\n trackName: track.name,\n trackArtist: track.artists[0].name,\n trackImageUrl: track.album.images[2].url,\n trackLength: track.duration_ms,\n trackPreviewUrl: track.preview_url\n };\n\n results.push(result);\n\n var matchTerm = (track.artists[0].name + ' ' + track.name).replace(/[^A-Za-z0-9 ]/g, '');\n return encodeURI(Config.omniEndPoint + omniSearchUri + '&query=' + matchTerm + '&apiKey=' + Config.omniAppKey);\n });\n\n async.forEachOf(omniUrls, getOmnifoneContentUrl, function (err, res){\n\n if (err) {\n return console.log(err);\n }\n\n async.forEachOf(echoNestUrls, getAudioFeatures, function (err, res) {\n\n if (err) {\n return console.log(err);\n }\n\n getOmnifySearchResponse.json({\n results: results\n });\n results = [];\n spotifyAccessToken = '';\n });\n\n });\n\n });\n\n });\n}", "function getSanDiegoTopSpots() {\n\n \tvar defer = $q.defer(); \n\n \t$http({\n \t\tmethod: 'GET',\n \t\turl: 'http://localhost:55471/api/topspots'\n \n \t})\n .then(function(response){ \n \n \t\t\tif(typeof response.data === 'object'){ \n \t\t\t\tdefer.resolve(response); \n \t\t\t} else {\n \t\t\t\tdefer.reject(response); \n \t\t\t}\n\t\t\t},\n\t\t\tfunction(error){ \n \t\tdefer.reject(error);\n \t\t\n\t\t\t});\n\n\t\t\treturn defer.promise; \n \t \n }", "function getPlaces(){\n // Get places : this function is useful to get the ID of a PLACE\n // Ajust filters, launch search and view results in the log\n // https://developers.jivesoftware.com/api/v3/cloud/rest/PlaceService.html#getPlaces(List<String>, String, int, int, String)\n\n // Filters\n // ?filter=search(test,report)\n // recentlyviewed\n // ?filter=type() = space, blog, group ...\n \n var result = fetch( BASEURL + \"/places/?filter=type(group)&filter=search(test collaboration)&count=100\" , options(\"get\")).list; \n for(var i in result){\n Logger.log(i + \" \" + result[i].name + \" \" + result[i].placeID); \n }\n}", "function getCommentsFromSpot(req, res){\n\n let spotId;\n\n //Make sure that the id supplied is valid\n if(ObjectId.isValid(req.params.spotId))\n spotId = new ObjectId(req.params.spotId);\n else\n return res.status(400).send({error:\"ID for spot is not valid\"});\n\n Spots.findOne(spotId)\n .then(function(spot){\n //Make sure the Spot does exist\n if(!spot)\n return res.status(422).send({error:\"No spot found for the spotId sent\"});\n\n //Query all the comments from spotId\n Comments.find({commentFor: spotId})\n .then(function(comments){\n res.send(comments);\n })\n .catch(function(err){\n console.log(err);\n res.status(422).send({error: err.message});\n });\n\n }).catch(function(err){\n console.log(err);\n res.status(422).send({error: err.message});\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
html_entity_decode from (MIT Licensed)
function html_entity_decode(string, quote_style) { // http://kevin.vanzonneveld.net // + original by: john (http://www.jd-tech.net) // + input by: ger // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: marc andreu // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Ratheous // + bugfixed by: Brett Zamir (http://brett-zamir.me) // + input by: Nick Kolosov (http://sammy.ru) // + bugfixed by: Fox // - depends on: get_html_translation_table // * example 1: html_entity_decode('Kevin &amp; van Zonneveld'); // * returns 1: 'Kevin & van Zonneveld' // * example 2: html_entity_decode('&amp;lt;'); // * returns 2: '&lt;' var hash_map = {}, symbol = '', tmp_str = '', entity = ''; tmp_str = string.toString(); if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) { return false; } // fix &amp; problem // http://phpjs.org/functions/get_html_translation_table:416#comment_97660 delete(hash_map['&']); hash_map['&'] = '&amp;'; for (symbol in hash_map) { entity = hash_map[symbol]; tmp_str = tmp_str.split(entity).join(symbol); } tmp_str = tmp_str.split('&#039;').join("'"); return tmp_str; }
[ "function html_entity_decode(str) {\n\treturn String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function decodeHtmlEntity(str) {\n return str.replace(/&#(\\d+)/g, function(match, dec) {\n return String.fromCharCode(dec);\n });\n}", "function decodeHtmlEntity(str) {\n return str.replace(/&#(\\d+);/g, function(match, dec) {\n return String.fromCharCode(dec);\n });\n }", "function html_entity_decode(str)\n {\n var tmp = document.createElement('textarea');\n tmp.innerHTML = str.replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\");\n toReturn = tmp.value;\n tmp = null;\n return toReturn;\n }", "function htmlEntityDecode(str)\n {\n return $( '<div />').html( str ).text();\n }", "decodeHTML( str ) { return he.decode(str); }", "function nativeDecode(text){var elm;elm=document.createElement(\"div\");elm.innerHTML=text;return elm.textContent||elm.innerText||text;}// Build a two way lookup table for the entities", "function decode_entities(str) {\n\tstr = str.replace(/&lt;/g, '<');\n\tstr = str.replace(/&gt;/g, '>');\n\treturn(str.replace(/&quot;/g, '\"'));\n}", "function tryDecodeEntities(text){var decoded=decodeEntities(text);return decoded===text?undefined:decoded;}", "function decodeEntitiesToSymbols() {\n var element = document.createElement('div');\n\n function decodeHTMLEntities(str) {\n if (str && typeof str === 'string') {\n str = str.replace(/<script[^>]*>([\\S\\s]*?)<\\/script>/gmi, '');\n str = str.replace(/<\\/?\\w(?:[^\"'>]|\"[^\"]*\"|'[^']*')*>/gmi, '');\n element.innerHTML = str;\n str = element.textContent;\n element.textContent = '';\n }\n\n return str;\n }\n\n return decodeHTMLEntities;\n }", "function html_unescape(text) {\n return jQuery('<div/>').html(text.split('<').join('&lt;').split('>').join('&gt;')).text();\n}", "function tryDecodeEntities(text) {\n var decoded = decodeEntities(text);\n return decoded === text ? undefined : decoded;\n }", "function tryDecodeEntities(text) {\n var decoded = decodeEntities(text);\n return decoded === text ? undefined : decoded;\n }", "function unescape(text) {\n const matchHtmlEntity =\n /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g\n const htmlEntities = {\n '&amp;': '&',\n '&#38;': '&',\n '&lt;': '<',\n '&#60;': '<',\n '&gt;': '>',\n '&#62;': '>',\n '&apos;': \"'\",\n '&#39;': \"'\",\n '&quot;': '\"',\n '&#34;': '\"',\n '&nbsp;': ' ',\n '&#160;': ' ',\n '&copy;': '©',\n '&#169;': '©',\n '&reg;': '®',\n '&#174;': '®',\n '&hellip;': '…',\n '&#8230;': '…',\n '&#x2F;': '/',\n '&#47;': '/',\n }\n\n const unescapeHtmlEntity = (m) => htmlEntities[m]\n\n return text.replace(matchHtmlEntity, unescapeHtmlEntity)\n}", "htmlDecode(input) {\n var doc = new DOMParser().parseFromString(input, \"text/html\");\n return doc.documentElement.textContent;\n }", "function htmlDecode( html ) {\n var a = document.createElement('wj_abc'); a.innerHTML = html;\n return a.textContent;\n}", "function htmlEntities(str) {\r\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\r\n}", "function unescapeHTML() {\n // Warning: In 1.7 String#unescapeHTML will no longer call String#stripTags.\n return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');\n }", "function decodeHTML(str) {\n return htmlDecoder(str, false);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eql a b If the value of a and b are equal, then store the value 1 in variable a. Otherwise, store the value 0 in variable a.
eql(a, b) { this.registers[a] = this.get(a) === this.get(b) ? 1 : 0; }
[ "function _eq (a, b) {\n return a === b\n}", "function sameValue(a, b) {\n return a == b\n}", "function isEqual(a,b){\n return a === b\n}", "function sameValueBoth(a, b) {\n var result = sameValue(a, b);\n assertTrue(result === sameValueZero(a, b));\n return result;\n}", "function isEqual(a,b){\n if (a === b) {\n return true;\n } else {\n return false;\n }\n}", "function isEqual(a, b) {\n return a == b;\n\n}", "function SameValue(a, b) {\n\n if (typeof a !== typeof b) {\n return false;\n }\n if (isType(a) === 'undefined') {\n return true;\n }\n if (isType(a) === 'number') {\n if (a !== a && b !== b) {\n return true;\n }\n // 0 === -0, but they are not identical.\n if (a === 0) {\n return 1 / a === 1 / b;\n }\n }\n return a === b;\n }", "function isEqual(a1, a2) {\n return a1 === a2\n}", "function sameValueBoth(a, b) {\n var result = sameValue(a, b);\n result === sameValueZero(a, b);\n return result;\n} // Calls SameValue and SameValueZero and checks that their results don't match.", "function compare2Values(a,b) {\n if(a == b){\n return true;\n }else{\n return false;\n }\n \n}", "function looseEqualityReplication(a, b) {\n let result;\n if (a === null || a === undefined) {\n result = b === null || b === undefined;\n } else if (typeof a === typeof b) {\n result = a === b;\n } else {\n const castA = Number(a);\n const castB = Number(b);\n result = castA === castB;\n };\n return result;\n}", "function caml_equal (x, y) { return +(caml_compare_val(x,y,false) == 0); }", "function caml_js_equals (x, y) { return +(x == y); }", "function aequal(a, b) {\n return getAlias(a).indexOf(b) >= 0;\n}", "function equal (lhs, rhs) {\n return lhs === rhs;\n }", "function equals(a, b) {\n // Initialize a variable with 'UNEQUAL'.\n // Use 'if' to set the variable to 'EQUAL' if necessary.\n // Return the variable.\n\n const unequal = \"UNEQUAL\";\n\n if (a === b) {\n return \"EQUAL\";\n } else {\n return unequal;\n }\n}", "function checkEquality(a, b) {\n return a === b\n}", "function equal(lhs, rhs) {\n return lhs === rhs;\n }", "function equal(lhs, rhs) {\n return lhs === rhs;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current line. May become public.
get currentline() { return this._currentline; }
[ "get currentLine() {\n return this.lines[this.lineIndex];\n }", "get line() {\n return this.getLine();\n }", "get line() {\n return this._line;\n }", "getCurrentBufferLine() {\n return this.editor.lineTextForBufferRow(this.getBufferRow());\n }", "function getCurrLine() {\n return gMeme.lines[gMeme.selectedLineIdx]\n}", "function getSelectedLine() {\n return gMeme.lines[gMeme.selectedLineIdx]\n}", "getLine() {\n return this.args[4];\n }", "get line() {\n return this._colorTable.line;\n }", "peekLine(){\n const cur = this.#cursor;\n const oldPos = cur.pos;\n const oldPB = cur.putbackPos;\n const oldPBL = cur.putbackLineNo;\n const oldLine = cur.lineNo;\n try {\n return this.getLine();\n }finally{\n cur.peekedPos = cur.pos;\n cur.peekedLineNo = cur.lineNo;\n cur.pos = oldPos;\n cur.lineNo = oldLine;\n cur.putbackPos = oldPB;\n cur.putbackLineNo = oldPBL;\n }\n }", "function getCurrentLine() {\n return displayNextWriteLine;\n}", "function nextLine() {\n\t\t_this._compConst('LINE', _this.currentLine+1);\n\t\treturn lines[_this.currentLine++];\n\t}", "getRealCurrentLineNb() {\n return this.currentLineNb + this.offset;\n }", "function getCurrLineIdx() {\n return gMeme.selectedLineIdx\n}", "getRealCurrentLineNb() {\n return this.currentLineNb + this.offset;\n }", "get line() {\n return this._lineStyle;\n }", "function currentLine(line) {\n \n if(line.length < 1){\n return \"The line is currently empty.\";\n }\n \n const lineList = [];\n \n for(let n=0; n<line.length; n++){\n lineList.push((n+1) + \". \" + line[n]);\n }\n \n return 'The line is currently: ' + lineList.join(', ');\n}", "function getCurrentLine() {\n return termText.length - 1;\n }", "function currentLine(line){\n if (line.length === 0){\n return 'The line is currently empty.'\n } else {\n let output = 'The line is currently: '\n for(var i = 0; i < line.length; i++){\n output += `${i+1}. ${line[i]}, `\n }\n return output.slice(0, -2)\n }\n}", "function getLine(row) {\n return editor.session.getLine(row);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
obtain a map from URL to Set of saved windows, for use on initial attach. returns: Map>
getUrlBookmarkIdMap () { const bmEnts = this.bookmarkIdMap.entrySeq() // bmEnts :: Iterator<[BookmarkId,TabWindow]> const getSavedUrls = (tw) => tw.tabItems.map((ti) => ti.url) const bmUrls = bmEnts.map(([bmid, tw]) => getSavedUrls(tw).map(url => [url, bmid])).flatten(true) const groupedIds = bmUrls.groupBy(([url, bmid]) => url).map(vs => Immutable.Set(vs.map(([url, bmid]) => bmid))) // groupedIds :: Seq.Keyed<URL,Set<BookmarkId>> return Immutable.Map(groupedIds) }
[ "function saveWindow(){\n var folder = document.getElementById(\"curr-folder-name\").innerHTML\n\n chrome.windows.getCurrent({populate:true},function(window){\n //collect all of the urls here\n window.tabs.forEach(function(tab){\n\n var myURL = {\n url: tab.url,\n title: tab.title\n };\n\n // make sure you're not adding repeats\n if (!myTabDict[folder].urlSet.includes(myURL.url)){\n addTabToFolder(myURL, folder)\n saveData();\n updateURLS(folder); // here so that I can see all the tabs without needing exit\n }\n });\n });\n // why can't i see the urls appear? seems more efficient to have it here, but...\n // updateURLS(folder);\n}", "function mapChromeWindows(windows){\n\t\twindows.forEach(function(window){\n\t\t\tvar groupId = findGroupId(window);\n\t\t\tif(groupId != null){\n\t\t\t\tmapWin[window.id] = groupId;\n\t\t\t\tGROUPS[groupId].chromeId = window.id;\n\n\t\t\t\tvar index = INDEXES(groupId);\n\t\t\t\tvar tabs = window.tabs;\n\t\t\t\tfor(var i = 0; i < tabs.length; i++){\n\t\t\t\t\tmapPage[tabs[i].id] = index[i].pageId;\n\t\t\t\t\tindex[i].chromeId = tabs[i].id;\n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsaveNewGroup(window);\n\t\t\t}\n\t\t});\n\t\t\n\t\t//Refresh database\n\t\tvar data = {};\n\t\tGROUPS.forEach(function(group, groupId){\n\t\t\tdata[KEY.group(groupId)] = group.getInfo();\n\t\t\tdata[KEY.index(groupId)] = getIndex(groupId);\n\t\t});\n\t\tPAGES.forEach(function(page){\n\t\t\tdata[KEY.page(page.pageId)] = page.getInfo();\n\t\t});\n\t\tsync.set(data);\n\t\t\n\t\t\n\t\texecQueue.shift()();\t\n\t}", "function fetch() {\n const storage = JSON.parse(localStorage.getItem(key));\n return new Map(storage.profiles);\n}", "get innerWindowIDsByBrowser() {\n delete this.innerWindowIDsByBrowser;\n return this.innerWindowIDsByBrowser = new WeakMap();\n }", "function LocationCache(window)\n{\n this.tabs = window.getBrowser().tabContainer;\n this.cache = new Map();\n}", "findURL (url: string) {\n // TODO: && !url.startsWith('chrome-extension://')\n if (url !== 'chrome://newtab/') {\n const urlRE = new RegExp('^' + escapeStringRegexp(url) + '$')\n const openWindows = this.getOpen().toArray()\n const filteredWindows = searchOps.filterTabWindows(openWindows,\n urlRE, { matchUrl: true, matchTitle: false, openOnly: true })\n // expand to a simple array of [TabWindow,TabItem] pairs:\n const matchPairs = _.flatten(filteredWindows.map(ftw => {\n const { tabWindow: targetTabWindow, itemMatches } = ftw\n return itemMatches.map(match => [targetTabWindow, match.tabItem]).toArray()\n }))\n return matchPairs\n } else {\n return []\n }\n }", "function saveUrls() {\n var spans = listView.children;\n\n var urlMap = new Map();\n\n for (var i = 0; i < spans.length; i++) {\n var span = spans[i].children[0];\n var name = span.children[0].value;\n var url = span.children[1].value;\n if (!isEmpty(name) && !isEmpty(url)) {\n urlMap.set(name, url);\n }\n }\n storeMap(urlMap);\n}", "function make_map ()\n {\n return (wait_for_map ().then (wait_for_map_loaded).then (domap));\n }", "function getWindows(uri) {\n\tComponents.utils.import(\"resource://gre/modules/Services.jsm\");\n\tvar enumerator = Services.wm.getEnumerator(null);\n\tvar wins = [];\n\twhile(enumerator.hasMoreElements()) {\n\t\tvar win = enumerator.getNext();\n\t\tif(win.location == uri) {\n\t\t\twins.push(win);\n\t\t}\n\t}\n\treturn wins;\n}", "function getMaps() { return _maps; }", "function loadMapFromURL(url, redirectedFromHTML)\n{\n if (!url || url.length == 0){\n return false;\n }\n \n // reformat the url\n url = url.replace(/^(feed:\\/\\/)/, \"http://\");\n if (url.indexOf(\"://\") < 0) {\n url = \"http://\" + url;\n }\n \n // save the last loaded url\n attributes.lastMapURL = url;\n \n // show the Loading indicator\n setLoadingVisibility(true);\n\n // get the source file for the map and parse it\n var httpRequest = new XMLHttpRequest();\n httpRequest.onload = function (e) {\n // first check that the response is valid\n if (httpRequest.status != 200) {\n displayErrorMessage(dashcode.getLocalizedString(\"Fehler beim Abfragen der Karteninformationen.\"));\n setLoadingVisibility(false);\n return false;\n }\n\n var contentType = httpRequest.getResponseHeader(\"Content-Type\") || \"\";\n var parsedDoc = null;\n // if it is an XML document\n if (contentType.indexOf(\"xml\") > -1 || httpRequest.responseXML) {\n var docElement = httpRequest.responseXML.documentElement;\n if (docElement) {\n // if it is a KML document\n if (contentType.indexOf(\"kml\") > -1 || findChild(docElement, \"kml\")) {\n parsedDoc = parseKMLFeed(docElement, url);\n }\n // if it is an Atom document\n else if (docElement.tagName.toLowerCase() == \"feed\") {\n parsedDoc = parseAtomFeed(docElement);\n }\n // if it is an RSS document\n else if (contentType.indexOf(\"rss\") > -1 || findChild(docElement, \"channel\")) {\n parsedDoc = parseRSSFeed(docElement);\n }\n // else, parse as a generic XML document\n else {\n parsedDoc = parseXMLFeed(docElement, url);\n } \n }\n else {\n displayErrorMessage(dashcode.getLocalizedString(\"Fehler beim Abfragen der Karteninformationen.\"));\n }\n }\n // if it is HTML\n else if (!redirectedFromHTML && contentType.indexOf(\"html\") > -1) {\n // try to get the xml version (google maps \"link to this page\")\n url += \"&output=nl\"; // parameter that indicates google maps to send the kml version\n loadMapFromURL(url, true);\n parsedDoc = \"redirected\";\n }\n \n // if the document was successfully parsed, render it\n if (parsedDoc) {\n if (parsedDoc != \"redirected\") {\n renderMapOverlay(parsedDoc);\n displayErrorMessage(\"\");\n }\n }\n else {\n displayErrorMessage(dashcode.getLocalizedString(\"Das Quelldokument konnte nicht verarbeitet werden.\"));\n }\n\n // if the map is loaded, hide the Loading indicator\n setLoadingVisibility(false);\n }\n // Send the request asynchronously\n httpRequest.open(\"GET\", url);\n httpRequest.setRequestHeader(\"Cache-Control\", \"no-cache\");\n httpRequest.send(null);\n}", "function load () {\n return svl.storage.get(\"map\");\n }", "function getOverviewMaps() {\n var map_container = document.getElementById('overviewMaps');\n\n if(oPageProperties.showmaps !== 1 || g_map_names.length == 0) {\n if (map_container)\n map_container.parentNode.style.display = 'none';\n hideStatusMessage();\n return false;\n }\n\n eventlog(\"worker\", \"debug\", \"getOverviewMaps: Start requesting maps...\");\n\n for (var i = 0, len = g_map_names.length; i < len; i++) {\n var mapdiv = document.createElement('div');\n mapdiv.setAttribute('id', g_map_names[i])\n map_container.appendChild(mapdiv);\n mapdiv = null;\n getAsyncRequest(oGeneralProperties.path_server+'?mod=Overview&act=getObjectStates'\n + '&i[]=map-' + escapeUrlValues(g_map_names[i]) + getViewParams(),\n false, addOverviewMap, g_map_names[i]);\n }\n}", "function findWindowByUrl (url) {\r\n\t\tvar win;\r\n\t\tvar list = global.__nwWindowsStore;\r\n\t\tfor(var i in list) {\r\n\t\t\tvar v = list[i];\r\n\t\t\tif(v.window.location.href == url){\r\n\t\t\t\twin = v;\r\n\t\t\t}\r\n\t\t};\r\n\t\treturn win;\r\n\t}", "function getSavedWebsites() {\n\n urls = [];\n urls.push(localStorage.getItem(\"saved_url\"));\n return urls;\n // Fetch the websites\n // For all websites, do addItemToList?\n}", "dumpMaps () {\n console.log('dumpMaps')\n let mapId = this.state.mapId;\n /* Infer map id if it's not set */\n if (undefined === mapId) mapId = Object.keys(this.state.maps).find(key => this.state.maps[key] === this.map);\n const mapsCopy = JSON.parse(JSON.stringify(this.state.maps));\n const map = mapsCopy[mapId];\n if (map && this.state.isFirstLoadDone) { /* Map may have been deleted */\n this.notify('Building data urls...', undefined, 'dumpMaps');\n [map.fogUrl, map.$fogDumpedAt] = this.dumpCanvas('fog');\n [map.drawUrl, map.$drawDumpedAt] = this.dumpCanvas('draw');\n this.notify('Data urls readied', undefined, 'dumpMaps');\n }\n return mapsCopy;\n }", "function save() {\n var data = map.toDataURL({\n 'mimeType' : 'image/jpeg', // or 'image/png'\n 'save' : true, // to pop a save dialog\n 'fileName' : 'map' // file name\n });\n}", "function openDefaultMap() {\r\n\t\t\r\n\t\tvar mapWin = GptUtils.popUp(mapViewerUrl, \r\n GptMapViewer.TITLE, \r\n GptMapViewer.dimensions.WIDTH, \r\n GptMapViewer.dimensions.HEIGHT);\r\n \r\n\t\treturn mapWin;\r\n\t}", "function getMap() {\r\n return map;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper to the validatePhone() function
function helperValidatePhone() { //sends the error state to change the background sendState(on, "phone"); //adds the error to the array addDataAllErrors(allErrorMess[3]); }
[ "function simplePhoneValidation(phoneNumber) {\n\n}", "processPhone() {\n let input = this.phone\n resetError(input)\n\n if (isEmpty(input)) {\n this.valid = false\n } else if (isNumber(input)) {\n this.valid = false\n } else if (exact(input, 11)) {\n this.valid = false\n } else\n input.success = true\n }", "function validatePhone() {\r\n var content = $(\"#number\").val();\r\n if (content != \"\" && (content.length < 11 || content.length > 11 || content[0] != 0 || content[1] != 1)){\r\n pcond = 0;\r\n return false;}\r\n else return true;\r\n }", "function valid_phone()\n\t{\n\t\t// Retrieves the customer value from the text field\n\t\tvar mobile=cust_form.mobile_number.value;\n\t\t// Check for the character validation\n\t\tvar exp=/\\d{10}/;\n\t\tvar reg_name=new RegExp(exp);\n\t\tif(!(reg_name.test(mobile)))\n\t\t{\n\t\t\talert(\"Mobile Number must contain 10 digits\");\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\t// returns true to indicate validation success\n\t\t\treturn true;\n\t\t\n\t}", "function validatePhoneNumber(phone){\n var regex = '^(\\\\+\\\\d{1,2})?\\\\d{10}$';\n return validateField(phone, regex);\n}", "function validatePhone(el, typestr) {\n var phonenodash = el.value.split(\"-\").join(\"\"); // If phone number like ###-###-#### remove the dashes\n if (phonenodash.length != 10 || // phone number must be 10 characters\n isNaN(phonenodash)) { // phone number must be all digits\n doError(el, typestr + \" Information: 10 digit phone number (###-###-####) required\");\n return false;\n }\n\n return true;\n}", "function testPhoneNumberSearch(){\n validatePhoneNumber(\"3832720339\"); // invalid entry\n\t validatePhoneNumber(\"2125551235\"); // valid entry\n\t validatePhoneNumber(null); // invalid entry\n\t validatePhoneNumber(1312); // invalid entry\n }", "function validatePhone(inputtxt) {\n\t\n\t//+XX-XXXX-XXXX\n\t//+XX.XXXX.XXXX\n\t//+XX XXXX XXXX\n\t\t\t\n\tvar phoneno = /^\\+?([0-9]{2})\\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;\n\tif(inputtxt.match(phoneno)) \n\t{\n\t\treturn true;\n\t} \n\telse \n\t{ \n\t\treturn false;\n\t}\n}", "validatePhone() {\n var phoneregex = /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;\n var match = this.state.phone.match(phoneregex);\n if (!match){\n //notification that pops up\n this.dropdown.alertWithType(\n 'error',\n '\\nError',\n 'Invalid Phone input. \\nFormat should be: XXX-XXX-XXXX\\n');\n return false;\n }\n return true;\n }", "function phoneValidate(phone) {\n if (!phone) {\n return false;\n } else {\n var res = phone.match(/\\d{3}\\-\\d{7}/g);\n if (res && phone.length === 11) {\n return true;\n } else {\n return false;\n }\n }\n }", "function checkPhone() {\n\n // create an empty array called 'errors'\n var errors = [],\n\n // convert the arguments object to an array and assign it to the variable 'args'\n args = Array.prototype.slice.call(arguments),\n\n // convert the args array to a string and assign it to the variable 'input'\n input = args.toString();\n\n\n // Perform the first check\n var check1 = input;\n\n // regular expression to check the first character of the input and verify that it is a number\n check1 = check1.match(/^[^0-9]/);\n\n if(check1 !== null) {\n errors += 'Invalid phone number';\n }\n\n\n // Perform the second check\n var check2 = input;\n\n // regular expression to check for any character other than a number or hyphen\n check2 = check2.match(/[^-0-9]/);\n\n if (check2 !== null && check2 !== ' ' && errors === '') {\n errors += 'Invalid phone number';\n }\n\n\n // Perform the third check\n var check3 = input;\n\n // regular expression to check for a hyphen followed by a space\n check3 = check3.match(/[-]\\s/);\n\n if (check3 !== null && errors === '') {\n errors += 'Invalid phone number';\n }\n\n\n // Perform the fourth check\n var check4 = input;\n\n // regular expression to check for a space followed by a hyphen\n check4 = check4.match(/\\s[-]/);\n\n if (check4 !== null && errors === '') {\n errors += 'Invalid phone number';\n }\n\n\n // regular expression to remove spaces and hyphens\n input = input.replace(/\\D/g, '');\n\n\n // Perform the final check\n if (errors === '' && input.length < 7 || errors === '' && input.length > 12) {\n errors += 'Invalid phone number';\n }\n\n\n // check for errors and return them if they exist - else return the valid phone number\n if (errors === '') {\n return input;\n } else {\n return errors;\n }\n\n }", "static validatePhoneNumber(value){\n if(!/(03|05|07|08|09|01[2|6|8|9])+([0-9]{8})\\b/.test(value)){\n return Resources.ValidateError.PhoneNumber;\n }\n }", "function checkUSPhone(field, error)\r\n{\r\n\t\r\n\t//make sure that field value exists\r\n\tcheckText(field,error + ' can not be empty');\r\n\t\r\n\tif (field.value.length > 0)\r\n\t{\r\n\t\tvar badformat = 0;\r\n\t\t\r\n\t\t//checking for non-allowable characters\r\n\t\tvar str = stripNotAllowable(field.value, \"1234567890.()- \");\r\n\t\tbadformat = (str.length < field.value.length)?1:0;\r\n\t\t\r\n\t\t//checking for 10 digits\r\n\t\tUSPhone = stripNotAllowable(field.value, \"1234567890\");\r\n\t\tbadformat = (USPhone.length != 10 || badformat )?1:0;\r\n\t\t\r\n\t\tif (badformat) \r\n\t\t{\r\n\t\t\tturnRed(field);\r\n\t\t\terror_message += error +\": wrong format\\n\";\t\r\n\t\t\tif(firstfield == \"\")\r\n\t\t\t\tfirstfield = field;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tturnBlack(field);\r\n\t\t}\r\n\t}\r\n}", "function validate_phonenumber(inputtxt) \n\t{ \n\t \tvar phoneno = /^\\d{10}$/; \n\t \tif( inputtxt.match(phoneno) ) \n\t\t{ \n\t \treturn true; \n\t } \n\t else \n\t { \n\t return false; \n\t } \n\t}", "function phoneDetailsValidator(inputtxt) {\n //regex to metch phone number\n var phoneno = /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;\n console.log(\"Phone valid \" + phoneno.test(inputtxt));\n if (phoneno.test(inputtxt)) {\n return true;\n } else {\n return false;\n }\n}", "function validatePhoneNumber(el){\n\t\n /* in order for a phone number to be valid, it must have at least 10 digits. \n\tAlso, only digits and spaces are allowed. This means that the sum of the number of digits and the number of spaces\n\tshould be equal to the total number of characters*/\n\t\n\t//get the length of the phone number\n\tvar phoneNumberLength = el.value.length;\n\t//get the number of digits\n\tvar digitsNumber = getNoOfDigits(el);\n\t//get the number of spaces\n\tvar spacesNumber = getNoOfSpaces(el);\n\t\n\t\n\t// if the user has typed a phone number and it is invalid\n if ( (phoneNumberLength>0) && ((phoneNumberLength < 10) || (phoneNumberLength != digitsNumber+spacesNumber)) )\n\t{\n\t\t// set the message, for the invalid phone number\n\t\tel.setCustomValidity('Ο τηλεφωνικός αριθμός δεν είναι έγκυρος. Χρησιμοποιείστε μόνο ψηφία (τουλάχιστον 10) και κενά. ');\n\t\t\n }\n else // the user hasn't typed a phone number or the phone number typed is valid. Reset the validity\n {\n\t\tel.setCustomValidity('');\n }\n}", "function validatePhone(phone, countryCode) {\r\n var stripped;\r\n var formated =\"\";\r\n if((countryCode.toUpperCase() == \"US\") || (countryCode.toUpperCase() == \"CA\")) {\r\n stripped = phone.value.replace(/[\\(\\)\\.\\-\\x\\_\\ ]/g, '');\r\n \r\n if(stripped.length == 10) {\r\n formated = \"(\"+ stripped.substring(0,3) +\")\"+ stripped.substring(3,6) +\"-\"+ stripped.substring(6,10);\r\n }else if((stripped.length > 10) && (stripped.length < 15)){\r\n formated = \"(\"+ stripped.substring(0,3) +\")\"+ stripped.substring(3,6) +\"-\"+ stripped.substring(6,10) +\"x\"+ stripped.substring(10, stripped.length); \r\n }else if(stripped.length > 14){\r\n formated = \"(\"+ stripped.substring(0,3) +\")\"+ stripped.substring(3,6) +\"-\"+ stripped.substring(6,10) +\"x\"+ stripped.substring(10, 14); \r\n }\r\n else {\r\n phone.value = \"(___) ___-____ x____\";\r\n phone.focus();\r\n phone.select();\r\n }\r\n if(formated !=\"\") {\r\n phone.value = formated;\r\n } \r\n }\r\n else { // Freeformat International phone number\r\n if(phone.value.indexOf(\"+___\") != -1) {\r\n formated = \"\";\r\n }else {\r\n stripped = phone.value.replace(/[\\+\\ ]/g, '');\r\n if(stripped.length < 25) {\r\n formated = \"+\"+ stripped;\r\n }else {\r\n formated = \"+\"+ stripped.substring(0,24);\r\n }\r\n }\r\n } \r\n return formated;\r\n}", "function PhoneFormatValid(obj) {\r\n\tif (obj.value.search(new RegExp(\"^[\\\\d\\+)(-]{1,20}$\", \"i\")) != 0)\r\n\t\treturn -1;\r\n\treturn 0; \t\r\n}", "function isPhone(phone) {\r\n return /^[0-9\\+]{11,14}$/.test(phone);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks this injector as ready. This means all dependencies are registered and resolvable.
ready() { if (!this._ready) { this._listeners.forEach(listener => listener()); this._ready = true; } else { console.warn('Injector already marked as ready!'); } }
[ "markAsReady() {\n\t\tthis._ready = true;\n\t\tthis._emitter.emit('ready');\n\t}", "function ready() {\n this._isAttached = true;\n this._isReady = true;\n this._callHook('ready');\n }", "ready() {\n this.isReady = true;\n if (this.onLoad) {\n this.onLoad.call();\n }\n }", "async ready() {\n await this._readyPromise;\n }", "_onReady() {\n this.ready = true;\n if (this._whenReady) {\n this._whenReady.forEach(fn => fn.call(this, this));\n this._whenReady = null;\n }\n }", "ready() {\n // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n this.startSafetyTimer(12000, 'ready()');\n\n // Clear the safety timer\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n });\n\n // Set listeners on the Plyr instance\n this.listeners();\n\n // Setup the IMA SDK\n this.setupIMA();\n }", "function dependencyLoaded() {\n dependenciesLoaded += 1;\n if (dependenciesLoaded >= dependencies) {\n odyssey.dispatchEvent(new Odyssey.Events.InitializedEvent());\n }\n }", "function onReady() {\r\n forEachCoordinateButton(setUpCoordinateButton);\r\n setUpRotate90Button();\r\n setUpRequestMakeRealButton();\r\n\r\n realityBuilderIsReady = true;\r\n\r\n unhideViewIfAllReady();\r\n }", "function _ready() {\n _isReady = true;\n _flushNextTickCallbacks();\n}", "function ready() {\n\tif (onJatosLoad && !onJatosLoadCalled && initialized) {\n\t\tonJatosLoadCalled = true;\n\t\tonJatosLoad();\n\t}\n}", "Init() {\n this.Ready = true;\n if (this.ReadyEvent) {\n this.ReadyEvent();\n }\n }", "function domReady () {\n if (!_initCalled) {\n _doReadyOnInit = true;\n return;\n }\n site.isReady = true;\n\n // do this first, just in case.\n configureVendorLibs();\n\n // call all other domready site.events\n site.events.emit('global:ready');\n site.events.domReadyDone = true;\n }", "triggerReady() {\n this.isReady_ = true;\n\n // Ensure ready is triggered asynchronously\n this.setTimeout(function() {\n const readyQueue = this.readyQueue_;\n\n // Reset Ready Queue\n this.readyQueue_ = [];\n\n if (readyQueue && readyQueue.length > 0) {\n readyQueue.forEach(function(fn) {\n fn.call(this);\n }, this);\n }\n\n // Allow for using event listeners also\n /**\n * Triggered when a `Component` is ready.\n *\n * @event Component#ready\n * @type {Event}\n */\n this.trigger('ready');\n }, 1);\n }", "ensureReady () {\n return new Promise((resolve) => {\n if (this.ready) {\n resolve()\n } else {\n this.$once('is-ready', resolve)\n }\n })\n }", "triggerReady() {\n this.isReady_ = true;\n\n // Ensure ready is triggered asynchronously\n this.setTimeout(function () {\n const readyQueue = this.readyQueue_;\n\n // Reset Ready Queue\n this.readyQueue_ = [];\n if (readyQueue && readyQueue.length > 0) {\n readyQueue.forEach(function (fn) {\n fn.call(this);\n }, this);\n }\n\n // Allow for using event listeners also\n /**\n * Triggered when a `Component` is ready.\n *\n * @event Component#ready\n * @type {EventTarget~Event}\n */\n this.trigger('ready');\n }, 1);\n }", "ready() {\n this._root = this._createRoot();\n super.ready();\n this._firstRendered();\n }", "async executeReadyHooks() {\n if (this.logger) {\n this.logger.trace('executing ready hooks');\n }\n await Promise.all(this.providersWithReadyHook.map((provider) => provider.ready()));\n this.providersWithReadyHook = [];\n }", "ready() {\n this.__dataReady = true;\n // Run normal flush\n this._flushProperties();\n }", "ready() {\n this.__dataReady = true;\n // Run normal flush\n this._flushProperties();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to enable or disable the ability to swipe open the menu.
swipeGesture(shouldEnable, menuId) { return _ionic_core__WEBPACK_IMPORTED_MODULE_5__["menuController"].swipeGesture(shouldEnable, menuId); }
[ "function enableSwipe() {\n allowSwipe = true;\n }", "enableTouchSwipes() {\n\t\tvar boundToggleMenu = this.toggleMenu.bind(this);\n\t\tthis.swipe1 = new Swipe(this.nav, null, boundToggleMenu, null, boundToggleMenu);\n\t\tthis.swipe2 = new Swipe(this.pullOutOverlay, null, boundToggleMenu, null, boundToggleMenu);\t\t\n\t}", "swipeGesture(enable, menu) {\r\n return menuController.swipeGesture(enable, menu);\r\n }", "swipeEnable(shouldEnable, menuId) {\n return apiUtils.proxyMethod(this.tag, 'swipeEnable', shouldEnable, menuId)\n }", "enable() {\n\t\tMenu.enableItem(this.handle);\n\t}", "function SwipeOpenMenu() {\n //create swipe-selector\n if ($('.multilevelMenu').length > 0) {\n $('body').append('<span class=\"js-swipe\"></span>');\n var touchstartX = 0,\n touchendX = 0;\n // open menu on tap swipe\n $('.js-swipe, .multilevelMenu').on('touchstart', function(e) {\n touchstartX = e.originalEvent.changedTouches[0].pageX;\n });\n\n $('.js-swipe').on('touchend', function (e) {\n touchendX = e.originalEvent.changedTouches[0].pageX;\n if (touchendX > touchstartX) {\n //call animate-menu function\n openMenu();\n element.find('ul').attr('style', '');\n }\n });\n\n //close menu left-swipe\n $('.multilevelMenu').on('touchend', function (e) {\n touchendX = e.originalEvent.changedTouches[0].pageX;\n if (touchendX < (touchstartX - 30)) {\n $('body').removeClass('bodyFixed');\n setTimeout(function () {\n $('.multilevelMenu ul').attr('class', '');\n }, 200);\n }\n });\n } else {\n return false;\n }\n }", "enableMenuButtons() {\n var elements = this.__menuElements;\n for (var i = 0; i < elements.length; i++) {\n elements[i].setEnabled(true);\n }\n }", "enable() {\n this.navigation.open(this);\n }", "function enableMenu(menu) {\n if (menu === \"Sides\") {\n disableAll();\n setToggleSides({ display: \"inline-block\" });\n console.log({ toggleSides })\n } else \n if (menu === \"Appetizers\") {\n disableAll();\n setToggleAppetizers({ display: \"inline-block\" });\n console.log({ toggleAppetizers })\n\n }\n else if (menu === \"Main\") {\n disableAll();\n setToggleMain({ display: \"inline-block\" });\n console.log({ toggleMain })\n } else if (menu === \"Drinks\") {\n disableAll();\n setToggleDrinks({ display: \"inline-block\" });\n console.log({ toggleDrinks })\n }\n }", "function enableTabsSwipe() {\r\n $('.tabs-custom').swipe(\"enable\");\r\n }", "isEnabled(menu) {\r\n return menuController.isEnabled(menu);\r\n }", "function enableMenu() {\n\n\t$(\"#menuIconImg\").show();\n\t$(\"#menuLink\").show();\n\tchangeMenuVisibility();\n}", "function onSwipe(e){\n if (e.direction==\"right\"){\n closeMenu();\n }\n}", "enable() {\n this.enabled_ = true;\n this.removeClass('vjs-disabled');\n\n this.menuButton_.enable();\n }", "function _enable_keyboard_navigation() {\r\n $(document).keydown(_keyboard_action);\r\n }", "disable() {\n\t\tMenu.disableItem(this.handle);\n\t}", "function mi_enable() {\n\tif(this.status == MI_STATUS_DISABLED) {\n\t\tif(this.HTMLElement != null) {\n\t\t\tif(typeof this.menu.component.cssMenuItem == 'string') {\n\t\t\t\tthis.HTMLElement.className = this.menu.component.cssMenuItem;\n\t\t\t}\n\t\t}\n\n\t\tthis.status = MI_STATUS_NORMAL;\n\t}\n}", "enable(enable, menu) {\r\n return menuController.enable(enable, menu);\r\n }", "function _enable_keyboard_navigation() {\n\t\t\t$(document).keydown(function(objEvent) {\n\t\t\t\t_keyboard_action(objEvent);\n\t\t\t});\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get single odds info
function getSingleOddsInfo(mutexObject, betslip, betslipMap, betslipStake, isBoosting, boostBets) { const oddsInfoMap = []; const bonus = []; const qualifyingOddsLimit = betslipStake.qualifyingOddsLimit; const bonusRatios = betslipStake.bonusRatios; const betslips = betslip.betslips || []; const outcomeMap = getOutcomeMap(mutexObject, betslips, betslipMap); const keys = Object.keys(outcomeMap); let singleCount = 0; let boostCount = 0; for (const key of keys) { const eventObj = outcomeMap[key]; eventObj && Object.keys(eventObj).forEach(marketId => {// eslint-disable-line const outcomes = eventObj[marketId]; if (outcomes && outcomes.length > 0) { const tempOddsInfoMap = getMaxOdds(outcomes, qualifyingOddsLimit, bonusRatios, isBoosting, boostBets); singleCount += tempOddsInfoMap.count; boostCount += tempOddsInfoMap.boostCount; oddsInfoMap.push(tempOddsInfoMap.oddsMap); bonus.push(tempOddsInfoMap.bonus); } }); } return { count: singleCount, oddsInfoMap, bonus, boostCount }; }
[ "function returnFirstOddNumber() {\n\tfor (var i = 0; i < numbers.legnth; i++) {\n\t\tif (numbers[i] % 2 != 0) {\n\t\t\treturn numbers[i];\n\t\t}\n\t}\n}", "function returnFirstOddNumber(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 1) {\n\t\t\t\treturn array[i];\n\t\t\t}\n\t\t}\n\t}", "function printOneReturnAnother(arr) {\n for(var j = 0; j < arr.length; j++) {\n if(arr[j] % 2 !== 0) {\n var first_odd = arr[j];\n }\n }\n console.log(`This is the second to last number in the array: ${arr[arr.length -2]}`);\n return first_odd;\n}", "function returnFirstEvenNumber() {\n\tfor (var i = 0; i < numbers.legnth; i++) {\n\t\tif (numbers[i] % 2 === 0) {\n\t\t\treturn numbers[i];\n\t\t}\n\t}\n}", "function firstOddNum() {\n for (let i = 0; i < numbers.length; i++) {\n if(numbers[i] % 2 !== 0) {\n return(numbers[i]); \n }\n }\n}", "function printOneReturnAnother(array) {\n console.log(array[array.length - 2]); //-2 prints the second to last item -1 prints the last item\n for(var i = 0; i < array.length; i++) {\n if(array[i] % 2 != 0) {\n console.log(array[i]); // printing the first item in the array that is an odd value\n return array[i];\n }\n }\n }", "function evenAppearance() {\n let obj = {};\n arr.forEach((e) => {\n obj[e] = obj[e] + 1 || 1;\n });\n for (let i = 0; i < arr.length; i++) {\n if (obj[arr[i]] % 2 === 0) {\n return arr[i];\n }\n }\n return null;\n}", "function returnFirstEvenNumber(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 0) {\n\t\t\t\treturn array[i];\n\t\t\t}\n\t\t}\n\t}", "function displayOddNumbers(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 1) {\n\t\t\t\tconsole.log(array[i]);\n\t\t\t}\n\t\t}\n\t}", "function odd(data) {\n return integer(data) && data % 2 !== 0;\n }", "function neighbourhoodInfo2(cases) {\n cases.forEach(cases => {\n console.log(cases.neighbourhoodInfo2 + ' ' + '(' + cases.Outcome + ')');\n });\n}", "isOdd() {\n return (this.low & 1) === 1;\n }", "function printOneReturnAnother(arr) {\n var secondToLast = arr[arr.length - 2];\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 != 0) {\n firstOdd = arr[i];\n break;\n }\n }\n console.log(secondToLast);\n return firstOdd;\n}", "function getOddEl(arr) {\n return arr.filter((val, idx) => idx % 2 !== 0);\n}", "function odd (data) {\n return integer(data) && data % 2 !== 0;\n }", "function displayOddNumber() {\n\tfor (var i = 0; i < numbers.length; i++) {\n\t\tif (numbers[i] % 2 != 0) {\n\t\t\tconsole.log(numbers[i]);\n\t\t}\n\t}\n}", "function oddOne (arr) {\n return arr.findIndex(function (x) { return Math.abs(x) % 2 === 1 })\n}", "function returnOdds(array) {\n //CODE HERE\n const odds = [];\n for (let i = 0; i < array.length; i++) {\n if (array[i] % 2 === 1) {\n odds.push(array[i]);\n }\n }\n return odds;\n}", "_getOpent2tInfo(HueDevice) {\n if (HueDevice.modelid.startsWith('L')) {\n return { \n \"schema\": 'org.opent2t.sample.lamp.superpopular',\n \"translator\": \"opent2t-translator-com-hue-bulb\"\n };\n }\n \n return undefined;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the value of the first vector, rotated towards the second by multiplicative percent
static RotateTowardsMult(vec1, vec2, percent) { let A = new Vec2(vec1); let B = new Vec2(vec2); return A.RotateTowardsMult(percent, B); }
[ "RotateTowardsMult(percent, x, y) {\n let Mag = this.Magnitude();\n let B = new Vec2(x, y).Normalize();\n this.Normalize();\n let VecLine = Vec2.Subtract(B, this).Multiply(percent);\n this.Add(VecLine);\n this.Normalize().Multiply(Mag);\n return this;\n }", "rotationTo(a, b) {\n const dot = a.dot(b);\n if (dot < -0.999999) {\n const tmpvec3 = vec3_1.Vec3.right().cross(a);\n if (tmpvec3.length < common_1.EPSILON) {\n const axis = vec3_1.Vec3.up()\n .cross(a)\n .normalize();\n this.setFromAxisAngle(axis, Math.PI);\n return this;\n }\n }\n else if (dot > 0.999999) {\n this.set([0, 0, 0, 1]);\n return this;\n }\n const tmp = a.clone().cross(b);\n this[0] = tmp[0];\n this[1] = tmp[1];\n this[2] = tmp[2];\n this[3] = 1 + dot;\n return this.normalize();\n }", "r(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (this.m(u) * this.m(v)); }", "function directionTo(vector, vector1) {\n\tvar modulus = distanceTo (vector, vector1);\n\tif (modulus) {\n\t\treturn [ (vector1[0] - vector[0]) / modulus, (vector1[1] - vector[1]) / modulus];\n\t}\n\telse {\n\t\treturn [0,0];\n\t}\n}", "function map(v, a, b){\n\treturn (v - a[0])/(a[1] - a[0])*(b[1] - b[0]) + b[0];\n}", "function boost(vector, direction1, direction2, angle)\n{\n\tvar component1 = inner(vector, direction1);\n\tvar component2 = -inner(vector, direction2);\n\tvar vector1 = scale(direction1, component1);\n\tvar vector2 = scale(direction2, component2);\n\tvar vector_fixed = subtract(vector, add(vector1, vector2));\n\tvar component1_rotated = component1 * Math.cosh(angle) + component2 * Math.sinh(angle);\n\tvar component2_rotated = component1 * Math.sinh(angle) + component2 * Math.cosh(angle);\n\tvar vector1_rotated = scale(direction1, component1_rotated);\n\tvar vector2_rotated = scale(direction2, component2_rotated);\n\tvar vector_rotated = add(vector1_rotated, vector2_rotated);\n\treturn add(vector_rotated, vector_fixed);\n}", "static createPartialRotationVectorToVector(vectorA, fraction, vectorB, result) {\n let upVector = vectorA.unitCrossProduct(vectorB);\n if (upVector) { // the usual case --\n return Matrix3d.createRotationAroundVector(upVector, Angle_1.Angle.createRadians(fraction * vectorA.planarAngleTo(vectorB, upVector).radians));\n }\n // fail if either vector is zero ...\n if (Geometry_1.Geometry.isSmallMetricDistance(vectorA.magnitude())\n || Geometry_1.Geometry.isSmallMetricDistance(vectorB.magnitude()))\n return undefined;\n // nonzero but aligned vectors ...\n if (vectorA.dotProduct(vectorB) > 0.0)\n return Matrix3d.createIdentity(result);\n // nonzero opposing vectors ..\n upVector = Matrix3d.createPerpendicularVectorFavorPlaneContainingZ(vectorA, upVector);\n return Matrix3d.createRotationAroundVector(upVector, Angle_1.Angle.createRadians(fraction * Math.PI));\n }", "function outP (vec1, vec2, vecr) {\n vecr[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1]\n vecr[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2]\n vecr[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0]\n}", "setRotationAToB(a, b) {\n // see http://graphics.cs.brown.edu/~jfh/papers/Moller-EBA-1999/paper.pdf for information on this implementation\n const start = a;\n const end = b;\n const epsilon = 0.0001;\n let v = start.cross(end);\n const e = start.dot(end);\n const f = e < 0 ? -e : e;\n\n // if \"from\" and \"to\" vectors are nearly parallel\n if (f > 1.0 - epsilon) {\n let x = new Vector3(start.x > 0.0 ? start.x : -start.x, start.y > 0.0 ? start.y : -start.y, start.z > 0.0 ? start.z : -start.z);\n if (x.x < x.y) {\n if (x.x < x.z) {\n x = Vector3.X_UNIT;\n } else {\n x = Vector3.Z_UNIT;\n }\n } else {\n if (x.y < x.z) {\n x = Vector3.Y_UNIT;\n } else {\n x = Vector3.Z_UNIT;\n }\n }\n const u = x.minus(start);\n v = x.minus(end);\n const c1 = 2.0 / u.dot(u);\n const c2 = 2.0 / v.dot(v);\n const c3 = c1 * c2 * u.dot(v);\n return this.rowMajor(-c1 * u.x * u.x - c2 * v.x * v.x + c3 * v.x * u.x + 1, -c1 * u.x * u.y - c2 * v.x * v.y + c3 * v.x * u.y, -c1 * u.x * u.z - c2 * v.x * v.z + c3 * v.x * u.z, -c1 * u.y * u.x - c2 * v.y * v.x + c3 * v.y * u.x, -c1 * u.y * u.y - c2 * v.y * v.y + c3 * v.y * u.y + 1, -c1 * u.y * u.z - c2 * v.y * v.z + c3 * v.y * u.z, -c1 * u.z * u.x - c2 * v.z * v.x + c3 * v.z * u.x, -c1 * u.z * u.y - c2 * v.z * v.y + c3 * v.z * u.y, -c1 * u.z * u.z - c2 * v.z * v.z + c3 * v.z * u.z + 1);\n } else {\n // the most common case, unless \"start\"=\"end\", or \"start\"=-\"end\"\n const h = 1.0 / (1.0 + e);\n const hvx = h * v.x;\n const hvz = h * v.z;\n const hvxy = hvx * v.y;\n const hvxz = hvx * v.z;\n const hvyz = hvz * v.y;\n return this.rowMajor(e + hvx * v.x, hvxy - v.z, hvxz + v.y, hvxy + v.z, e + h * v.y * v.y, hvyz - v.x, hvxz - v.y, hvyz + v.x, e + hvz * v.z);\n }\n }", "function directionTo(vector, vector1) {\n\tvar modulus = distanceTo (vector, vector1);\n\treturn [ (vector1[0] - vector[0]) / modulus, (vector1[1] - vector[1]) / modulus];\n}", "interpolate(percent, vec) {\n this[0] += (vec[0] - this[0]) * percent;\n this[1] += (vec[1] - this[1]) * percent;\n\n return this;\n }", "function vecRot(v1, v2) {\n // calculate l1, l2\n var l1 = Math.sqrt(Math.pow(v1.x, 2) + Math.pow(v1.y, 2));\n var l2 = Math.sqrt(Math.pow(v2.x, 2) + Math.pow(v2.y, 2));\n\n // calculate cos, sin\n var cosPhi1 = v1.x / l1;\n var sinPhi1 = v1.y / l1;\n var cosPhi2 = v2.x / l2;\n var sinPhi2 = v2.y / l2;\n var cosTheta = cosPhi1 * cosPhi2 + sinPhi1 * sinPhi2;\n var sinTheta = sinPhi1 * cosPhi2 - cosPhi1 * sinPhi2;\n\n // calculate theta\n var theta = (sinTheta >= 0.0) ? Math.acos(cosTheta) : - Math.acos(cosTheta);\n\n return theta;\n}", "function vector2Angle(v)\r\n{\r\n\tvar results = vector2AngleBetween(v, {x:1, y:0});\r\n\tif (v.y > 0)\r\n\t{\r\n\t\tresults *= -1;\r\n\t\tresults += 2 * Math.PI;\r\n\t}\r\n\treturn results;\r\n}", "function project(vec1, vec2) {\n return vecMult(vec2, dot(vec1, vec2) / Math.pow(magnitude(vec2), 2));\n}", "function vector2AngleBetween(v1, v2) { return Math.acos(vector2Dot(v1,v2) / vector2Length(v1) / vector2Length(v2)); }", "function lerp(x, x1, x2, v1, v2) {\n return ((x2 - x) / (x2 - x1)) * v1 + ((x - x1) / (x2 - x1)) * v2;\n}", "function rotate(vector, direction1, direction2, angle)\n{\n\tvar component1 = -inner(vector, direction1);\n\tvar component2 = -inner(vector, direction2);\n\tvar vector1 = scale(direction1, component1);\n\tvar vector2 = scale(direction2, component2);\n\tvar vector_fixed = subtract(vector, add(vector1, vector2));\n\tvar component1_rotated = component1 * Math.cos(angle) - component2 * Math.sin(angle);\n\tvar component2_rotated = component1 * Math.sin(angle) + component2 * Math.cos(angle);\n\tvar vector1_rotated = scale(direction1, component1_rotated);\n\tvar vector2_rotated = scale(direction2, component2_rotated);\n\tvar vector_rotated = add(vector1_rotated, vector2_rotated);\n\treturn add(vector_rotated, vector_fixed);\n}", "function vector_rotate() {\n var args = Array.prototype.slice.call(arguments);\n var angle = args.shift();\n var result = [];\n var sin=Math.sin(angle);\n var cos=Math.cos(angle);\n var vector;\n\n while (vector = args.shift()) {\n result.push([vector[0] * cos - vector[1] * sin,\n vector[0] * sin + vector[1] * cos]);\n }\n\n return result.length == 1 ? result[0] : result;\n}", "function v_angle(v1,v2){\n return Math.acos(dot_product(v1,v2) / (l2(v1) * l2(v2)));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implementation of localStorage API to save filters to local storage. This should get called everytime an onChange() happens in either of filter dropdowns
function saveFiltersToLocalStorage(filters) { // TODO: MODULE_FILTERS // 1. Store the filters to localStorage using JSON.stringify() let filtersData = JSON.stringify(filters); localStorage.setItem("filters", filtersData) return true; }
[ "function setFilters(filterData) {\n localStorage.setItem(\"filters\", JSON.stringify(filterData));\n setFilterState(filterData);\n }", "function saveFiltersToLocalStorage(filters) {\n // TODO: MODULE_FILTERS\n // 1. Store the filters to localStorage using JSON.stringify()\n localStorage.setItem('filters', JSON.stringify({ duration: \"\", category: [] }))\n\n\n return true;\n}", "function locallyStoreFilters() {\n var filterInstances = Filter.instances;\n // Store string representation of filterInstances list in local storage.\n localStorage.setItem('filterInstances', JSON.stringify(filterInstances));\n}", "function saveFiltersToLocalStorage(filters) {\n // TODO: MODULE_FILTERS\n // 1. Store the filters to localStorage using JSON.stringify()te\n localStorage.setItem(\"filters\",JSON.stringify(filters))\n return true;\n}", "function saveFiltersToLocalStorage(filters) {\n // TODO: MODULE_FILTERS\n // 1. Store the filters to localStorage using JSON.stringify()\n localStorage.setItem(\"filters\", JSON.stringify(filters));\n return true;\n}", "function saveFiltersToLocalStorage(filters) {\n // TODO: MODULE_FILTERS\n // 1. Store the filters to localStorage using JSON.stringify()\n window.localStorage.setItem('filters', JSON.stringify(filters))\n return true;\n}", "function saveFiltersToLocalStorage(filters) {\n // TODO: MODULE_FILTERS\n // 1. Store the filters to localStorage using JSON.stringify()\n window.localStorage.setItem('filters', JSON.stringify(filters));\n return true;\n}", "function setLocalstorageFilter( filterName, filterObj ){\n let currentFilterObj = getLocalstorageFilter( filterName );\n let mergedFilter = Object.assign( currentFilterObj, filterObj );\n localStorage.setItem( `${filterName}` , JSON.stringify(mergedFilter) )\n}", "function saveFilterData() {\n let filterData = {\n \"currentPicker\": currentPicker,\n \"startDate\": startDate,\n \"endDate\": endDate,\n \"savedDate\": savedDate,\n \"savedEmpIds\": JSON.stringify([...savedEmpIds]), // Stringify set converted to array.\n \"pieFilter\": pieFilter,\n \"savedCategory\": savedCategory,\n \"savedJobNum\": savedJobNum,\n \"savedNotes\": savedNotes,\n \"savedRd\": savedRd\n };\n\n localStorage[\"filterData\"] = JSON.stringify(filterData);\n}", "function saveSearchFilter() {\n var searchOptions = {};\n searchOptions[HOTEL_SEARCH_FILTER] = filterParams;\n searchOptions[HOTEL_SEARCH_BODY] = filterBody;\n searchOptions[HOTEL_SEARCH_ADVANCE] = filterAdvance;\n $localStorage[HOTEL_SEARCH_OPTIONS] = searchOptions;\n }", "function setFilters() {\n loadFaultCount = 0;\n var filters = JSON.parse(localStorage.getItem('filters'));\n for (var filter in filters) {\n var value = $('#' + filter + 'Filter').val();\n console.log(value);\n if (value == 'none' || value == \"\") {\n filters[filter] = null;\n }\n else {\n filters[filter] = value;\n }\n\n }\n console.log(filters);\n localStorage.setItem('filters', JSON.stringify(filters));\n filterFaults(filters);\n}", "function loadFilters(){\n let param =localStorage.getItem('savedFilters');\n if(param){\n param = param.split('&');\n param.shift();\n param.forEach(parameter=>{\n let filters = parameter.split('=');\n let filterType = filters[0];\n filters = filters[1].split(',');\n switch(filterType)\n {\n case \"location\":\n document.getElementById(\"zipcode\").value = filters[0];\n break;\n case \"distance\":\n document.getElementById(\"distance\").value = filters[0];\n break;\n case \"type\":\n document.getElementById(\"type\").value = filters[0];\n break;\n case \"gender\":\n document.getElementById(\"gender\").value = filters[0];\n break;\n case \"size\":\n document.getElementById(\"size\").value = filters[0];\n break;\n case \"age\":\n document.getElementById(\"age\").value = filters[0];\n break;\n case \"breed\":\n filters.forEach(filter=>{\n filter = decodeURIComponent(filter);\n var newOption = new Option(filter, filter, true, true);\n $(\"#breed\").append(newOption).trigger('change');\n })\n break;\n case \"color\":\n filters.forEach(filter=>{\n filter = decodeURIComponent(filter);\n var newOption = new Option(filter, filter, true, true);\n $(\"#color\").append(newOption).trigger('change');\n })\n break;\n case \"coat\":\n filters.forEach(filter=>{\n filter = decodeURIComponent(filter);\n var newOption = new Option(filter, filter, true, true);\n $(\"#coat\").append(newOption).trigger('change');\n })\n break;\n case \"good_with_cats\":\n document.getElementById(\"good_with_cats\").checked = true;\n break;\n case \"good_with_dogs\":\n document.getElementById(\"good_with_dogs\").checked = true;\n break;\n case \"good_with_children\":\n document.getElementById(\"good_with_children\").checked = true;\n break;\n\n }\n })\n }\n}", "function restoreFilters() {\n const retrievedFilterString = localStorage.getItem('filterInstances');\n console.log(\" Filter string=\" + retrievedFilterString);\n // Add default filters to the instances list.\n FilterUIDefault.initialize();\n\n if (!retrievedFilterString) {\n return;\n }\n\n var retrievedFilterInstances = JSON.parse(retrievedFilterString);\n // Remove any default filter duplicates from restored filters.\n for (const defaultFilter of defaultFilters) {\n retrievedFilterInstances = retrievedFilterInstances.filter\n (instance => !isDuplicate(instance, defaultFilter));\n }\n // Re-create non-default filter chips from local storage.\n // Pre-existing filters are appended behind the default ones.\n retrievedFilterInstances.forEach((instance) =>\n createFilterComplete(instance.enabled_,\n instance.selector_, instance.action_));\n}", "function resetFilters() {\n var filters = JSON.parse(localStorage.getItem('filters'));\n for (var filter in filters) {\n var value = $('#' + filter + 'Refilter').val();\n console.log(value);\n if (value == 'none' || value == \"\") {\n filters[filter] = null;\n }\n else {\n filters[filter] = value;\n }\n\n }\n console.log(filters);\n localStorage.setItem('filters', JSON.stringify(filters));\n filterFaults(filters);\n filtNav();\n}", "function getFiltersFromLocalStorage() {\n // TODO: MODULE_FILTERS\n // 1. Get the filters from localStorage and return in JSON format\n\n\n // Place holder for functionality to work in the Stubs\n return null;\n}", "function clearFilters(){\n localStorage.removeItem('parameters');\n localStorage.removeItem('savedFilters');\n}", "function getFiltersFromLocalStorage() {\n // TODO: MODULE_FILTERS\n // 1. Get the filters from localStorage and return in JSON format\n let filter = JSON.parse(window.localStorage.getItem('filters'));\n // Place holder for functionality to work in the Stubs\n return filter;\n}", "function getFiltersFromLocalStorage() {\n // TODO: MODULE_FILTERS\n // 1. Get the filters from localStorage and return in JSON format\n return JSON.parse(window.localStorage.getItem('filters'));\n\n // Place holder for functionality to work in the Stubs\n return null;\n}", "function getFiltersFromLocalStorage() {\n // TODO: MODULE_FILTERS\n // 1. Get the filters from localStorage and return in JSON format\n let filters = JSON.parse(window.localStorage.getItem('filters'))\n // Place holder for functionality to work in the Stubs\n return filters;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all input tags in current page
function GetAllInputTags(rootId) { let inputTags = []; let document = GetCurrentDocument(); let rootElement = document.getElementById(rootId); let elements = GetAllElements(rootElement); // loop through and get input tags elements.forEach((element) => { if (element.tagName === "INPUT") { inputTags.push(element); } }); return inputTags; }
[ "static getEnabledInputTags () {\r\n return document.querySelectorAll('.tag--enabled > input');\r\n }", "function getInputs() {\n var inputs = document.querySelectorAll('input, textarea');\n return inputs;\n}", "static getDisabledInputTags () {\r\n return document.querySelectorAll('.tag--disabled > input');\r\n }", "allTokenFields() {\n return document.querySelectorAll('input[name=token]');\n }", "function getInputs(id){\n var form = document.getElementById(id);\n return form.getElementsByTagName(\"input\");\n}", "function getInputs () {\n inputsArray = [];\n $(\"input\").each(function () {\n inputsArray.push($(this).val());\n });\n return inputsArray;\n}", "function getAvailableInputs(parent) {\n return Array.from(parent.querySelectorAll(\"input,textarea,select\"));\n}", "function returnInputs(object) {\n\tvar _self = this;\n\tvar _inputCollection = new Array();\n\t\n\t//convert the dom collection to array so that it may use concatenation\n\t_self.getInputArray = function(inputType) {\n\t\tvar collection = object.getElementsByTagName(inputType);\n\t\t\n\t\tvar tmpArray = new Array();\n\t\tfor( var i = 0; i < collection.length; i++) {\n\t\t\ttmpArray.push(collection[i]);\n\t\t}\n\t\treturn tmpArray;\n\t}\n\t\n\t//assemble all inputs into one array\n\t_inputCollection = _inputCollection.concat(\n\t\t_self.getInputArray('INPUT'),\n\t\t_self.getInputArray('SELECT'),\n\t\t_self.getInputArray('TEXTAREA')\n\t);\n\treturn _inputCollection;\n}", "function get_searched_tags(){\n\t\tvar tags = [];\n\t\t\n\t\t$.each($(\"#search_box\").tokenInput(\"get\"), function(index, val){\n\t\t\tvar split = val[\"name\"].split(/[=<>:]/);\n\t\t\tif (split[0] != null && split[0] != \"\"){\n\t\t\t\ttags.push(split[0]);\n\t\t\t}\t\t\n\t\t});\n\t\treturn tags;\n\t}", "function getInputElements(parent) {\r\n\t//CQ28461 - make the for-loop more efficient by not selecting types we don't want (ie. hidden, submit, image, etc...)\r\n\tvar p = $(parent);\r\n\tvar elems = p.find('input:enabled[type=text]');\r\n\telems = $.merge(elems, p.find('input:enabled[type=checkbox]'));\r\n\telems = $.merge(elems, p.find('input:enabled[type=radio]'));\r\n\telems = $.merge(elems, p.find('input:enabled[type=file]'));\r\n\telems = $.merge(elems, p.find('input:enabled[type=password]'));\r\n\telems = $.merge(elems, p.find('select:enabled'));\r\n\telems = $.merge(elems, p.find('textarea:enabled'));\r\n\treturn $(elems);\r\n}", "async function getTextInputs(page, elementList){\n let textInputs = await page.$$('input');\n let input;\n for (let i = 0; i < textInputs.length ; i++ ){\n input = {\n 'type' : 'input',\n 'element': textInputs[i],\n 'url': page.url()\n }\n elementList.push(input);\n }\n}", "function getAllTagName() {\n const tags = [...window.document.querySelectorAll('*')].map((item) => {\n return item.tagName\n })\n return Array.from(new Set(tags))\n // return [...new Set(tags)]\n}", "function find_elems(){\n\tinp = $(document.activeElement)\n\tinp_store = inp.clone().wrap('<p>').parent().html();\n\n\tinp.parents().each(function(){\n\t\tvar cur = $(this);\n\t\t//console.log(cur.prop('tagName'))\n\t\tif(cur.prop('tagName')==\"FORM\"){\n\t\t\tform = cur;\n\t\t\tform_store = form.clone().wrap('<p>').parent().html();\n\t\t}\n\t});\n\n}", "function getSiteMinderTags(response, tags) {\n\n var inputs = new Array();\n inputs = response.getElementsByTagName(\"input\");\n\n // get the 'input' tags\n for (var i = 0; i < inputs.length; i++) {\n var element = inputs.item(i).outerHTML;\n var value = \"\";\n\n // filter out inputs with type=button\n var stridex = element.indexOf(\"type=\");\n if (stridex != -1) {\n var typ = element.substring(stridex + 5);\n stridex = typ.indexOf(' ');\n typ = typ.substring(0, stridex);\n\n if (typ.toLowerCase() === \"button\") {\n continue;\n }\n }\n\n stridex = element.indexOf(\"value=\")\n if (stridex != -1) {\n value = element.substring(stridex + 6);\n stridex = value.indexOf(' ');\n value = value.substring(0, stridex);\n }\n\n tags[inputs.item(i).name] = value;\n }\n}", "function printTags(){\n var pkInput = document.querySelector('#pk-list');\n var pkList = [];\n tags.forEach (function(tag) {\n pkList.push(emotions.pk[tag]);\n })\n if (pkList.length > 0){\n pkInput.value = JSON.stringify(pkList);\n }\n}", "function get_all_fields() {\n return $('.ibm-id-fields :input,#email :input,#confirmationCode :input');\n}", "function eachFormElement() {\n var cb = this\n , e, i, j\n , serializeSubtags = function(e, tags) {\n for (var i = 0; i < tags.length; i++) {\n var fa = e[byTag](tags[i])\n for (j = 0; j < fa.length; j++) serial(fa[j], cb)\n }\n }\n \n for (i = 0; i < arguments.length; i++) {\n e = arguments[i]\n if (/input|select|textarea/i.test(e.tagName)) serial(e, cb)\n serializeSubtags(e, [ 'input', 'select', 'textarea' ])\n }\n }", "function getAllInputValues()\n {\n var inputFields = document.getElementsByTagName(\"input\");\n var backupDictionary = [];\n for (var i = 0; i < inputFields.length; i++)\n {\n if(inputFields[i].type == \"text\")\n {\n backupDictionary[inputFields[i].id] = inputFields[i].value;\n }\n }\n return backupDictionary;\n }", "function eachFormElement() {\n var cb = this\n , e, i, j\n , serializeSubtags = function(e, tags) {\n for (var i = 0; i < tags.length; i++) {\n var fa = e[byTag](tags[i])\n for (j = 0; j < fa.length; j++) serial(fa[j], cb)\n }\n }\n\n for (i = 0; i < arguments.length; i++) {\n e = arguments[i]\n if (/input|select|textarea/i.test(e.tagName)) serial(e, cb)\n serializeSubtags(e, [ 'input', 'select', 'textarea' ])\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this from a test suite (i.e. inside a describe() clause) to start the given server. If the same server is used by multiple tests, the server is reused.
function useServer(server) { before(async function () { if (!_servers.has(server)) { _servers.set(server, server.start(this)); } await _servers.get(server); }); // Stopping of the started-up servers happens in cleanup(). }
[ "function start() {\n // Run the server tests\n printHeader('SERVER');\n\n // We need to set the reporter when the tests actually run to ensure no conflicts with\n // other test driver packages that may be added to the app but are not actually being\n // used on this run.\n if (reporter == 'junit') {\n console.log('Mocha: Using JUnit reporter');\n mochaInstance.reporter(MochaJUnitReporter, { toConsole: !!process.env.MOCHA_FILE_TOCONSOLE });\n } else {\n mochaInstance.reporter(reporter);\n }\n\n mochaInstance.run((failureCount) => {\n exitIfDone('server', failureCount);\n });\n\n // Simultaneously start phantom to run the client tests\n startPhantom({\n stdout(data) {\n clientLogBuffer(data.toString());\n },\n stderr(data) {\n clientLogBuffer(data.toString());\n },\n done(failureCount) {\n exitIfDone('client', failureCount);\n },\n });\n}", "function startTestDebuggerServer(title, server = DebuggerServer) {\n initTestDebuggerServer(server);\n addTestGlobal(title);\n DebuggerServer.addTabActors();\n\n let transport = DebuggerServer.connectPipe();\n let client = new DebuggerClient(transport);\n\n return connect(client).then(() => client);\n}", "function setupTestServer() {\n before((done) => {\n const middleware = maybeMiddleware();\n if (middleware !== null) {\n this.server = middleware.listen(0, () => {\n this.baseURL = `http://127.0.0.1:${server.address().port}`;\n done();\n });\n } else { // Inside a browser\n this.baseURL = ''; // default to relative path, for browser-based tests\n done();\n }\n });\n\n after(() => {\n if (this.server) this.server.close();\n });\n\n return { // these use global references as we are leaving 'this'\n url(path) {\n return `${global.baseURL}${path}?index=10&count=300`;\n }\n };\n}", "function startServer() {\n\tserver = require(__dirname + '/NetworkServer');\n\tserver.startServer();\n}", "function setupTestServer() {\n before((done) => {\n const middleware = maybeMiddleware();\n if (middleware !== null) {\n this.server = middleware.listen(0, () => {\n this.baseURL = `http://127.0.0.1:${this.server.address().port}`;\n done();\n });\n } else { // Inside a browser\n this.baseURL = ''; // default to relative path, for browser-based tests\n done();\n }\n });\n\n after(() => {\n if (this.server) this.server.close();\n });\n\n return { // these use global references as we are leaving 'this'\n url(path) {\n return `${global.baseURL}${path}?index=10&count=300`;\n }\n };\n}", "function run_server_tests() {\n setTimeout(function() {\n single_server_test(test_l[index].options, test_l[index].expected)\n }, 1000);\n}", "function testStart(callback)\n{\n\tvar options = {\n\t\tport: 11234,\n\t};\n\tvar server = exports.start(options, function(error)\n\t{\n\t\ttesting.check(error, 'Could not start server');\n\t\texports.stop(server, callback);\n\t});\n}", "function start() {\r\n test();\r\n var httpService = http.createServer(serve);\r\n httpService.listen(ports[0], 'localhost');\r\n var options = { key: key, cert: cert };\r\n var httpsService = https.createServer(options, serve);\r\n httpsService.listen(ports[1], 'localhost');\r\n}", "start() {\n return new Promise((resolve, reject) => {\n this.server = mockingbirdServer.listen(this.port, (err) => {\n if (err) return reject(err);\n return resolve(this.server);\n });\n });\n }", "function startServer() {\n\tapp.serverInstance = server.listen(config.PORT, config.HOST, function() {\n\t\tlogger.info('Express server listening on %d, in %s mode...', config.PORT, config.ENV);\n\t});\n}", "function startServer(options) {\n if (options.master) {\n remote(options, function() {\n server(options);\n });\n } else {\n console.log('lack of option master');\n }\n}", "function setupFakeServer() {\n beforeEach(function() {\n this.server = sinon.fakeServer.create();\n this.server.answeredIndex = 0;\n });\n afterEach(function() {\n this.server.restore();\n });\n}", "function startTestServer(port) {\n\t\tconst testServer = spawn('npx', ['svelte-kit', 'dev', `--port=${port}`]);\n\n\t\ttestServer.stderr.on('data', (data) => {\n\t\t\tconsole.error(data.toString());\n\t\t});\n\n\t\ttestServer.stdout.on('data', (data) => {\n\t\t\tconsole.log(data.toString());\n\t\t});\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\ttestServer.stdout.on('data', (data) => {\n\t\t\t\tif (/http:\\/\\/localhost:\\d+/.test(data)) {\n\t\t\t\t\tresolve(testServer);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\ttestServer.on('close', reject);\n\t\t});\n\t}", "startServer() {\n this._server = http.createServer(this._app);\n this._server.listen(this._listeningPort, '0.0.0.0');\n this._server.on('error', this._onServerError);\n this._server.on('listening', this._onServerListening);\n }", "function startServer() {\n\tportscanner.findAPortNotInUse(portStart, portEnd, '127.0.0.1', function(error, port) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t} else {\n\t\t\tconsole.log('Port available at: ' + port);\n\t\t\thttp.createServer(ecstatic).listen(port);\n\n\t\t\tcmd.get('open http://localhost:' + port, function(err) {\n\t\t\t\tif (err) {\n\t\t\t\t\tconsole.log('error', err)\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log('Listening on : ' + port);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "function startServer(){\n var ps = spawn('forever', [ 'start', base + 'lib/www.js' ]);\n var err = '';\n ps.stderr.on('data', function (data) { \n err += data;\n });\n ps.on('exit', function (code) {\n if(code !== null){\n success('Nserv started on port 8080.');\n }\n else {\n error(err, \"Could not start main nserv server.\");\n }\n });\n}", "function startServer() {\n return new Promise((resolve, reject) => {\n serverPromise = app.run('node', 'server.js', {\n onOutput(output, child) {\n // detect start of fastboot app server\n if (output.includes('HTTP server started')) {\n serverProcess = child;\n resolve();\n }\n },\n }).catch(reject);\n });\n }", "start() {\n return new Promise((resolve, reject) => {\n compose((composeErr, server) => {\n if (composeErr) {\n return reject(composeErr);\n }\n\n return hooks.beforeStart(server, (beforeStartErr) => {\n if (beforeStartErr) {\n return reject(beforeStartErr);\n }\n\n return server.start(() => {\n hooks.afterStart(server, (afterStartErr) => {\n if (afterStartErr) {\n return reject(afterStartErr);\n }\n return resolve(server);\n });\n });\n });\n });\n });\n }", "serverCheck(server) {\n if(!this.serverExists(server)) {\n console.log(`Initializing ${server.name}`);\n this.newServer(server);\n } \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
myDate function This function is called on every HTML page in the body tag
function myDate() { var d = new Date(); //The current date is saved to the date string document.getElementById("date").innerHTML = d.toDateString(); }
[ "function dateRendered() {\r\n \"use strict\";\r\n //define all variables\r\n var todaysDate;\r\n\r\n //get date and make pretty\r\n todaysDate = new Date();\r\n todaysDate = todaysDate.toDateString();\r\n\r\n //display date\r\n document.write(\"Rendered: \" + todaysDate);\r\n}", "function set_date(){\n var query = getQueryParams(document.location.search),\n date_num = query.date,\n today,\n year, day, month, divided, divided_2;\n\n if(date_num == '' || date_num == undefined){\n var today = new Date().toDateString();\n }else{\n divided = date_num.match(/.{1,4}/g);\n year = divided[1];\n divided_2 = divided[0].match(/.{1,2}/g);\n month = divided_2[0];\n day = divided_2[1];\n today = new Date(year, month, day).toDateString();\n }\n $('#date').html(today);\n }", "function dateFinder () {\r\n\tvar modifiedDate = new Date(document.lastModified);\r\n\tvar today = new Date();\r\n\t//Check for dynamically created page\r\n\tif (String(modifiedDate) !== String(today)) {\r\n\t\tvar splitDate = String(modifiedDate).split(' ');\r\n\t\tvar returnDate = splitDate[0]+' '+splitDate[1]+' '+splitDate[2]+' '+splitDate[3];\r\n\t\treturn returnDate;\r\n\t}\r\n\t//If modifiedDate doesn't work, search page for updated, posted, revised, modified + date\r\n\telse {\r\n\t\tvar bodyTag = document.getElementsByTagName(\"body\");\r\n\t\tvar bodyDates = bodyTag[0].innerText.match(/((((U|u)pdated)|((P|p)osted)|((R|r)evised)|((M|m)odified))( |: | on )(\\d{1,2})(-|\\/)(\\d{1,2})(-|\\/)(\\d{4}))|(\\d{1,2})(-|\\/)(\\d{1,2})(-|\\/)(\\d{4})/);\r\n\t\t//Check that we found anything\r\n\t\tif (bodyDates) {\r\n\t\treturn bodyDates.toString();\r\n\t\t}\r\n\t\telse {\r\n\t\treturn 'No dates found. Enter if you find one.';\r\n\t\t};\r\n\t};\r\n}", "function footerDate() {\n const date = new Date();\n const year = date.getFullYear();\n document.querySelector(\"#footer-date\").innerHTML = year;\n }", "function addDatesToPage() {\n// checkForReferrer(startMondayList); // sets startMonday\n createRelativeDateDict(startMonday, numberOfWeeks);\n var pageText = document.body.innerHTML;\n var processedPage = processMarkers(pageText);\n document.body.innerHTML = processedPage;\n replaceRelativeDates();\n}", "function date() {\n\t// storing the variable for the current Date() function\n\tvar current = new Date()\n\t// storing the variables for the month, day, and year\n\tvar currentMonth = current.getMonth() + 1\n\tvar currentDay = current.getDate()\n\tvar currentYear = current.getYear() - 100\n\t// addig a zero to keep the dates in two digit format\n\tmonth = addZero(currentMonth)\n\tday = addZero(currentDay)\n\tyear = addZero(currentYear)\n\tdocument.getElementById(\"date\").textContent =\"Date: \" + month + \"/\" + day + \"/\" + year\n\t// setting a a timout fuction so the date is refreshed every hour\n\tsetTimeout(function(){\n\t\tdate()\n\t\t// 3600000 milliseconds = 1 hour\n\t}, 3600000)\n}", "function dateInfo() {\n alert(\"Date search results may be inaccurate for this site\");\n}", "function dateTime() {\r\n let currentDate = new Date();\r\n return document.write(currentDate);\r\n}", "function DateUpdater() { }", "function afficherdate(){ // permet d'avoir la date)\n let numeroJour = new Date().getDay();\n let nomJour = jourStr(numeroJour);\n let numeroMois = new Date().getMonth();\n let nomMois = moisStr(numeroMois);\n let annee =new Date().getFullYear();\n document.getElementById(\"date\").innerText = nomJour + \" \" + new Date().getDate() + \" \" + nomMois + \" \" + annee;\n}", "function DateHelper() {}", "function displayDate() {\n currentDay\n}", "function setCopyrightDate(){\r\n (function($){\r\n\r\n // Create Instance of the Date Object\r\n var date = new Date();\r\n\r\n // Extract Four Digit Year and Add to Footer\r\n $(\"#year\").text(date.getFullYear());\r\n\r\n })(jQuery);\r\n}", "function myDate(){\n return Date(); \n}", "function LoadDate()\n{\n var dateCurrentDate = new Date();\n var dateMonth = GetMonthString(dateCurrentDate.getMonth());\n var dateDay = dateCurrentDate.getDate();\n var dateString = dateMonth + \" \" + dateDay;\n $greetingDate.text(dateString);\n return;\n}", "function DateUtil() {\r\n\t\r\n\t}", "function mcds_setDateDisplay()\n{\n var titleStr = mcds_getMonthString();\n titleStr += \" \" + mcds_getYearString();\n titleStr += \" \" + mcds_getEpochString();\n $(document).find('div#DateDisplay').text(titleStr);\n}", "static date_bill(){\r\n \t\treturn new Date();\r\n \t}", "function setTheDate() {\r\n 'use strict';\r\n $(\"today\").value = month + \"/\" + day + \"/\" + year;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if image is on last row
function lastRowImage(image) { return image.row == lastRowIndex; }
[ "isLastImageReached(){\n if(this.imageIndex < this.images.length-1){\n return false;\n }\n else{\n return true;\n }\n }", "function imageIsLast() {\n let current_image_index = parseInt($('.fs-image')[0].id);\n if (current_image_index == 1) {\n left_btn.classList.add('opacity')\n left_btn.classList.add('unclickable')\n } else if (current_image_index == total - 1) {\n right_btn.classList.add('opacity')\n right_btn.classList.add('unclickable')\n } else {\n left_btn.classList.remove('opacity')\n right_btn.classList.remove('opacity')\n left_btn.classList.remove('unclickable')\n right_btn.classList.remove('unclickable')\n }\n }", "onLastRow () {\n const { row, column } = this.editor.getCursorBufferPosition()\n return row === this.editor.getBuffer().getLastRow()\n }", "function isLastSlide() {\n return SlideShowState.currentSlideID == SlideImageUrls.length - 1;\n}", "hasImageToDisplay() {\n return this.currentIndex < this.size();\n }", "function checkBottom(){\n //initiallise 0\n total = 0\n //loop through each element in the bottom row of the array\n for (var i = 0; i < current.shape.length; i++) {\n //if there is anything then increase total to not equal 0\n total += current.shape[current.shape.length - 1][i]\n }\n //id nothing in bottom row return value 1\n if (total == 0){\n return 1\n }\n //otherwise return value 0, meaning bottom row is full\n else{\n return 0\n }\n\n}", "function styleLastImg() {\r\n\t$('.sml-img').each(function() {\r\n\t\t$(this).css('border-right', '3px solid transparent');\r\n\t});\r\n\t$('.sml-img').not('.no-display').last().css('border-right', 'none');\r\n}", "function is_last_slide(){\n\t\treturn !mygallery.options.loop && mygallery.getCurrentIndex() === mygallery.options.getNumItemsFn() - 1;\n\t}", "function isBottom(){\n\t\tvar domLast = $(\".img-box\").last().get(0)\n\t\tvar lastHeight = domLast.offsetTop + Math.floor(domLast.offsetHeight/2)\n\t\tconsole.log(window.scrollY, window.innerHeight , lastHeight)\n\t\tif (window.scrollY +window.innerHeight > lastHeight){\n\t\t\treturn true\n\t\t} else{\n\t\t\treturn false\n\t\t}\n\t}", "get isLast() {\n return this.index === this.length - 1;\n }", "isLastCellHidden(element, container)\n\t\t{\n\t\t\tif (! element[0]) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tlet rect = element[0].getBoundingClientRect();\n\t\t\tlet threshold = container[0].getBoundingClientRect().left + container[0].getBoundingClientRect().width;\n \t\n \tif (rect.left == 0 && threshold == 0) {\n \t\t// this means the stat table is currently hidden (user looking at different tab)\n \t\t// best we can do is just guess until it is actually scrolled on\n \t\treturn this.guesstimate();\n \t}\n \t\n \treturn rect.left >= threshold;\n }", "function isLastStep() {\n return activeStep === totalSteps() - 1;\n }", "Last() {\n if (this.CanLast()) {\n this.Position = this.fRows.length - 1;\n }\n }", "function isLastStep () {\n return vm.currentStep === (vm.cntSteps - 1);\n }", "isRowSpanEnd(row, viewer) {\n let rowIndex = row.index;\n let rowSpan = 1;\n for (let i = 0; i < viewer.splittedCellWidgets.length; i++) {\n let splittedCell = viewer.splittedCellWidgets[i];\n // tslint:disable-next-line:max-line-length\n rowSpan = (isNullOrUndefined(splittedCell) || isNullOrUndefined(splittedCell.cellFormat)) ? rowSpan : splittedCell.cellFormat.rowSpan;\n if (rowIndex - splittedCell.rowIndex === rowSpan - 1) {\n return true;\n }\n }\n return false;\n }", "function isLastItem() {\n var curListItem = $(this).closest(\".listItem\");\n var totalItems = $(this).closest(\".list\").find(\".listItem\").length;\n var itemInd = $(curListItem).index(); // this starts at 1\n return totalItems === itemInd;\n}", "function lastImageSelector()\n{\n return $('img:last')\n}", "function lastImageSelector() {\n return $('img:last');\n}", "function isLast(idx) {\n const parent = inArr[idx][1];\n for (let i = idx + 1; i < inArr.length; i++) {\n if (inArr[i][1] === parent) {\n return false;\n }\n }\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the gamma values for the rotational matrix.
function GetGammaValue() { var _DETECTOR_ORIENTATION = $('#' + DOM_FieldID_DetectorOrientation).val (); var gamma = (((+_DETECTOR_ORIENTATION) - 45) * (Math.PI / 180)); return gamma; }
[ "function gamma(z) {\r\n if (z < 0.5) {\r\n return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));\r\n }\r\n else {\r\n z -= 1;\r\n var x = gamma_C[0];\r\n for (var i = 1; i < gamma_g + 2; i++) {\r\n x += gamma_C[i] / (z + i);\r\n }\r\n var t = z + gamma_g + 0.5;\r\n return Math.sqrt(2 * Math.PI) * Math.pow(t, (z + 0.5)) * Math.exp(-t) * x;\r\n }\r\n}", "function gammaFunct(a3,b3,R){\n gamma[0]=b3 - R * (b3 - a3)//c\n gamma[1]=a3 + b3 - gamma[0]//d\n return gamma\n}", "gamma(z) {\n var g = 7;\n var C = [\n 0.99999999999980993,\n 676.5203681218851,\n -1259.1392167224028,\n 771.32342877765313,\n -176.61502916214059,\n 12.507343278686905,\n -0.13857109526572012,\n 9.9843695780195716e-6,\n 1.5056327351493116e-7\n ];\n\n if (z < 0.5) {\n return Math.PI / (Math.sin(Math.PI * z) * this.gamma(1 - z));\n } else {\n z -= 1;\n\n var x = C[0];\n for (var i = 1; i < g + 2; i++)\n x += C[i] / (z + i);\n\n var t = z + g + 0.5;\n return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;\n }\n }", "function normaliseGammaClockwiseRotation(gamma) {\n if (gamma < 0) { gamma = 180 - Math.abs(gamma); }\n return gamma;\n }", "function gamma(x) {\n\n // Use Lanczos' approximation\n // https://en.wikipedia.org/wiki/Lanczos_approximation\n // http://www.rskey.org/CMS/index.php/the-library/11\n\n const coefficients = [\n 676.5203681218851,\n -1259.1392167224028,\n 771.32342877765313,\n -176.61502916214059,\n 12.507343278686905,\n -0.13857109526572012,\n 9.9843695780195716e-6,\n 1.5056327351493116e-7\n ];\n\n if (x < 0.5) {\n return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x)); // reflection formula\n }\n\n --x;\n\n const n = coefficients.reduce((sum, p, i) => sum + p / (x + i + 1), 0.99999999999980993);\n const t = x + coefficients.length - 0.5;\n\n return Math.sqrt(2 * Math.PI) * t ** (x + 0.5) * Math.exp(-t) * n;\n}", "get gamma() {}", "function gamma(x) {\n\n\t\tvar p = [\n\t\t\t\t\t\t4.212760487471622013093E-5,\n\t\t\t\t\t\t4.542931960608009155600E-4,\n\t\t\t\t\t\t4.092666828394035500949E-3,\n\t\t\t\t\t\t2.385363243461108252554E-2,\n\t\t\t\t\t\t1.113062816019361559013E-1,\n\t\t\t\t\t\t3.629515436640239168939E-1,\n\t\t\t\t\t\t8.378004301573126728826E-1,\n\t\t\t\t\t\t1.000000000000000000009E0,\n\t\t\t\t\t\t0.0, 0.0 ];\n\n\t\tvar q = [\n\t\t\t\t\t\t-1.397148517476170440917E-5,\n\t\t\t\t\t\t2.346584059160635244282E-4,\n\t\t\t\t\t\t-1.237799246653152231188E-3,\n\t\t\t\t\t\t-7.955933682494738320586E-4,\n\t\t\t\t\t\t2.773706565840072979165E-2,\n\t\t\t\t\t\t-4.633887671244534213831E-2,\n\t\t\t\t\t\t-2.243510905670329164562E-1,\n\t\t\t\t\t\t4.150160950588455434583E-1,\n\t\t\t\t\t\t9.999999999999999999908E-1,\n\t\t\t\t\t\t0.0 ];\n\n\t\tvar sgnGam, n;\n\t\tvar a, x1, z;\n\n\t\tsgnGam = sgnGamma(x);\n\n\t\tif((x == 0.0) || ((x < 0.0) && (frac(x) == 0.0))) {\n\t\t\t\treturn NaN;\n\t\t}\n\n\t\tif(x > MAXGAM) {\n\t\t\t\treturn Infinity;\n\t\t}\n\n\t\ta = Math.abs(x);\n\t\tif(a > 13.0) {\n\t\t\t\tif(x < 0.0) {\n\t\t\t\t\t\tn = Math.trunc(a);\n\t\t\t\t\t\tz = a - n;\n\t\t\t\t\t\tif(z > 0.5) {\n\t\t\t\t\t\t\t\tn = n + 1;\n\t\t\t\t\t\t\t\tz = a - n;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tz = Math.abs(a * Math.sin(Math.PI * z)) * stirf(a);\n\t\t\t\t\t\t\t\tif(z <= PI / MAXDOUBLE) {\n\t\t\t\t\t\t\t\t\t\treturn Infinity;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tz = PI / z;\n\t\t\t\t} else {\n\t\t\t\t\t\tz = stirf(x);\n\t\t\t\t}\n\t\t\t\treturn sgnGam * z;\n\t\t} else {\n\t\t\t\tz = 1.0;\n\t\t\t\tx1 = x;\n\t\t\t\twhile(x1 >= 3.0) {\n\t\t\t\t\t\tx1 = x1 - 1.0;\n\t\t\t\t\t\tz = z * x1;\n\t\t\t\t}\n\t\t\t\twhile(x1 < -0.03125) {\n\t\t\t\t\t\tz = z / x1;\n\t\t\t\t\t\tx1 = x1 + 1.0;\n\t\t\t\t}\n\t\t\t\tif(x1 <= 0.03125) {\n\t\t\t\t\t\treturn gamSmall(x1, z);\n\t\t\t\t} else {\n\t\t\t\t\t\twhile(x1 < 2.0) {\n\t\t\t\t\t\t\t\tz = z / x1;\n\t\t\t\t\t\t\t\tx1 = x1 + 1.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif((x1 == 2.0) || (x1 == 3.0)) {\n\t\t\t\t\t\t\t\treturn z;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tx1 = x1 - 2.0;\n\t\t\t\t\t\t\t\treturn z * PolEvl(x1, p, 7) / PolEvl(x1, q, 8);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n}", "gamma(previous)\n {\n //calculating gamma from the previous state\n return (this.ni-previous.ni) / previous.i;\n }", "function log_gamma(xx)\n{\n var cof = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5]; \n\n var x = xx - 1.0;\n var tmp = x + 5.5; tmp -= (x + 0.5)*Math.log(tmp);\n var ser=1.000000000190015;\n for (j=0;j<=5;j++){ x++; ser += cof[j]/x; }\n return -tmp+Math.log(2.5066282746310005*ser);\n}", "function sgammaforsurf(hangle, gamma) {\n let saz = hangle - gamma;\n saz = (saz > 180) ? saz - 360 : saz;\n saz = (saz < -180) ? saz + 360 : saz;\n return saz;\n}", "function gamma(x) {\n\n\tvar P = [1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, 9.99999999999999996796E-1];\n\tvar Q = [-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0];\n\n\tvar p = void 0,\n\t z = void 0,\n\t i = void 0;\n\tvar q = Math.abs(x);\n\n\tif (q > 33.0) {\n\t\tif (x < 0.0) {\n\t\t\tp = Math.floor(q);\n\t\t\tif (p == q) throw new Error(\"gamma: overflow\");\n\t\t\ti = Math.round(p);\n\t\t\tz = q - p;\n\t\t\tif (z > 0.5) {\n\t\t\t\tp += 1.0;\n\t\t\t\tz = q - p;\n\t\t\t}\n\t\t\tz = q * Math.sin(Math.PI * z);\n\t\t\tif (z == 0.0) throw new Error(\"gamma: overflow\");\n\t\t\tz = Math.abs(z);\n\t\t\tz = Math.PI / (z * stirlingFormula(q));\n\n\t\t\treturn -z;\n\t\t} else {\n\t\t\treturn stirlingFormula(x);\n\t\t}\n\t}\n\n\tz = 1.0;\n\twhile (x >= 3.0) {\n\t\tx -= 1.0;\n\t\tz *= x;\n\t}\n\n\twhile (x < 0.0) {\n\t\tif (x == 0.0) {\n\t\t\tthrow new Error(\"gamma: singular\");\n\t\t} else if (x > -1.E-9) {\n\t\t\treturn z / ((1.0 + 0.5772156649015329 * x) * x);\n\t\t}\n\t\tz /= x;\n\t\tx += 1.0;\n\t}\n\n\twhile (x < 2.0) {\n\t\tif (x == 0.0) {\n\t\t\tthrow new Error(\"gamma: singular\");\n\t\t} else if (x < 1.e-9) {\n\t\t\treturn z / ((1.0 + 0.5772156649015329 * x) * x);\n\t\t}\n\t\tz /= x;\n\t\tx += 1.0;\n\t}\n\n\tif (x == 2.0 || x == 3.0) return z;\n\n\tx -= 2.0;\n\tp = Polynomial.polevl(x, P, 6);\n\tq = Polynomial.polevl(x, Q, 7);\n\n\treturn z * p / q;\n}", "function gamma(chi, aoi, scl){\n var mode = chi.reduceRegion({\n reducer: ee.Reducer.mode(),\n geometry: aoi,\n scale: scl,\n maxPixels: 1e13\n }).toImage();\n var sd = chi.reduceRegion({\n reducer: ee.Reducer.sampleStdDev(),\n geometry: aoi,\n scale: scl,\n maxPixels: 1e13\n }).toImage();\n var rate = (((((sd.pow(2)).multiply(4)).add(mode.pow(2))).sqrt()).add(mode)).divide(sd.pow(2).multiply(2));\n //shape calculated from observed mode\n var shape = mode.multiply(rate).add(1);\n //shape calculated assuming mode = 0 (i.e. no change)\n //var shape = ee.Image.constant(1);\n var p = //ee.Image.constant(1).subtract(\n shape.gammainc(chi.multiply(rate)).rename(['p']);\n return p;\n}", "function gamma(n) { // accurate to about 15 decimal places\r\n //some magic constants \r\n var g = 7, // g represents the precision desired, p is the values of p[i] to plug into Lanczos' formula\r\n p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];\r\n if (n < 0.5) {\r\n return Math.PI / Math.sin(n * Math.PI) / gamma(1 - n);\r\n }\r\n else {\r\n n--;\r\n var x = p[0];\r\n for (var i = 1; i < g + 2; i++) {\r\n x += p[i] / (n + i);\r\n }\r\n var t = n + g + 0.5;\r\n return Math.sqrt(2 * Math.PI) * Math.pow(t, (n + 0.5)) * Math.exp(-t) * x;\r\n }\r\n}", "function createGammaCorrectionArray(gamma = 1) {\n let gammaArray = []\n\n for (let i = 0; i < 256; i++) {\n gammaArray.push(Math.floor(Math.pow(i/255, gamma) * 255 + 0.5))\n }\n\n return gammaArray\n\n}", "function gamma_(kappa, theta) {\n const C = 1 + kappa / Math.E;\n while ( true ) {\n\tvar p = C * random.uniform01();\n\tvar y;\n\tif ( p > 1 ) {\n\t y = - Math.log( (C - p ) / kappa );\n\t if ( random.uniform01() <= Math.pow(y, kappa-1) ) {\n\t\treturn 0;\n\t }\n\t} else {\n\t y = Math.pow(p, 1/kappa);\n\t if ( random.uniform01() <= Math.exp(-y) ) {\n\t\treturn theta * y;\n\t }\n\t}\n }\n}", "function getGammaData() {\n var calibration = [];\n for (var i = 0; i < 65; i++) {\n var lookup = [];\n\n // Calculate gamma curve for all three channels\n var r = g = b = Math.round(3865 * Math.pow(i / 64, 2.2));\n \n for (var j = 0; j < DisplayConfig.pixelsPerUnit; j++) {\n lookup.push(r);\n lookup.push(g);\n lookup.push(b);\n }\n calibration.push(lookup);\n }\n\n return calibration;\n}", "function gammafn(x) {\n var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563,\n 629.3311553128184, 866.9662027904133, -31451.272968848367,\n -36144.413418691176, 66456.14382024054\n ];\n var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192,\n -3107.771671572311, 22538.118420980151, 4755.8462775278811,\n -134659.9598649693, -115132.2596755535];\n var fact;\n var n = 0;\n var xden = 0;\n var xnum = 0;\n var y = x;\n var i, z, yi, res;\n if (y <= 0) {\n res = y % 1 + 3.6e-16;\n if (res) {\n fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res);\n y = 1 - y;\n }\n else {\n return Infinity;\n }\n }\n yi = y;\n if (y < 1) {\n z = y++;\n }\n else {\n z = (y -= n = (y | 0) - 1) - 1;\n }\n for (i = 0; i < 8; ++i) {\n xnum = (xnum + p[i]) * z;\n xden = xden * z + q[i];\n }\n res = xnum / xden + 1;\n if (yi < y) {\n res /= yi;\n }\n else if (yi > y) {\n for (i = 0; i < n; ++i) {\n res *= y;\n y++;\n }\n }\n if (fact) {\n res = fact / res;\n }\n return res;\n}", "function gammaCF(x, a){\r\n\tvar maxit = 100, eps = 0.0000003;\r\n\tvar gln = logGamma(a), g = 0, gOld = 0, a0 = 1, a1 = x, b0 = 0, b1 = 1, fac = 1;\r\n\tvar an, ana, anf;\r\n\tfor (var n = 1; n <= maxit; n++){\r\n\t\tan = 1.0 * n;\r\n\t\tana = an - a;\r\n\t\ta0 = (a1 + a0 * ana) * fac;\r\n\t\tb0 = (b1 + b0 * ana) * fac;\r\n\t\tanf = an * fac;\r\n\t\ta1 = x * a0 + anf * a1;\r\n\t\tb1 = x * b0 + anf * b1;\r\n\t\tif (a1 !== 0){\r\n\t\t\tfac = 1.0/a1;\r\n\t\t\tg = b1 * fac;\r\n\t\t\tif (Math.abs((g - gOld)/g) < eps) break;\r\n\t\t\tgOld = g;\r\n\t\t}\r\n\t}\r\n\treturn Math.exp(-x + a * Math.log(x) - gln) * g;\r\n}", "function gamma(i) {\n return (\"0\".repeat(Math.floor(Math.log2(i + 1)))).concat((i + 1).toString(2));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
keydown handler booleans for button presses for moving player
function keydownEventHandler(e) { // key movement for player up, down, left, right if (e.keyCode == 87) { // W key playerUp = true; } if (e.keyCode == 83) { // S key playerDown = true; } if (e.keyCode == 65) { // A key playerLeft = true; } if (e.keyCode == 68) { // D key playerRight = true; } }
[ "function keydownEventHandler(e) {\n // key movement for player up, down, left, right\n if (e.keyCode == 87) { // W key\n keyUp = true;\n }\n if (e.keyCode == 83) { // S key\n keyDown = true;\n }\n if (e.keyCode == 65) { // A key\n keyLeft = true;\n }\n if (e.keyCode == 68) { // D key\n keyRight = true;\n }\n}", "function keyPressed(){\n if (key === \"w\"){\n movingUp = true;\n }\n if (key === \"a\"){\n movingLeft = true;\n }\n if (key === \"d\"){\n movingRight = true;\n }\n }", "function keyReleased(){\n if (key === \"w\"){\n movingUp = false;\n }\n if (key === \"a\"){\n movingLeft = false;\n }\n if (key === \"d\"){\n movingRight = false;\n }\n }", "function keyupEventHandler(e) {\n if (e.keyCode == 87) { // W key\n playerUp = false;\n }\n if (e.keyCode == 83) { // S key\n playerDown = false;\n }\n if (e.keyCode == 65) { // A key\n playerLeft = false;\n }\n if (e.keyCode == 68) { // D key\n playerRight = false;\n }\n}", "function playerOneKeyDownHandler(e) {\n if(e.keyCode == 87) {\n playerOneUpPressed = true;\n }\n else if(e.keyCode == 83) {\n playerOneDownPressed = true;\n }\n}", "function keyPressed() {\n // Player 1\n if(keyCode == LEFT_ARROW) {\n player1.changeDirection(-1);\n } else if (keyCode == RIGHT_ARROW) {\n player1.changeDirection(1);\n }\n // Player 2\n if(keyCode == 65) {\n player2.changeDirection(-1);\n } else if(keyCode == 83) {\n player2.changeDirection(1);\n }\n\n // Space\n if(keyCode == 32) {\n player2.enableBoost();\n }\n\n if(keyCode == 13) {\n player1.enableBoost();\n }\n return 0;\n}", "function keyPressed(){\n\n switch(key){\n case \" \": playerIsFullThreshold +=1; break;\n case \"z\": toggleObsMode(); break;\n // player stuck key\n case \"x\": findGoodPosition(player); break;\n }\n}", "function keyPressed() {\n\n // If up arrow is pressed (player two)\n if (keyCode === UP_ARROW) {\n playerTwo.direction(0, -5);\n\n // if down arrow is pressed (player two)\n } else if (keyCode === DOWN_ARROW) {\n playerTwo.direction(0, 5);\n\n // if \"W\" is pressed (player one)\n } else if (keyCode === 87) {\n\n playerOne.direction(0, -5);\n\n // if \"S\" is pressed (player two)\n } else if (keyCode === 83) {\n\n playerOne.direction(0, 5);\n }\n}", "function keyUp(e) {\n if (e.keyCode == Keyboard.letter('a') || e.keyCode == Keyboard.LEFT) {\n stopTimer(playerMoveLeft);\n movingLeft = false;\n\n }\n if (e.keyCode == Keyboard.letter('d') || e.keyCode == Keyboard.RIGHT) {\n stopTimer(playerMoveRight);\n movingRight = false;\n\n }\n if (e.keyCode == Keyboard.letter('w') || e.keyCode == Keyboard.UP) {\n spaceDown = false;\n }\n }", "function listenForKeyboard()\n{\n // A or <-, move left\n if(Key.isDown(Key.A) || Key.isDown(Key.LEFT_ARROW))\n {\n player_paddle.changeX(Paddle.SPEED * -1);\n }\n // D or ->, move right\n else if(Key.isDown(Key.D) || Key.isDown(Key.RIGHT_ARROW))\n {\n player_paddle.changeX(Paddle.SPEED);\n }\n}", "function keyReleased() {\n if (key === \"w\") {\n movingUp = false;\n }\n\n if (key === \"a\") {\n movingLeft = false;\n }\n\n if (key === \"s\") {\n movingDown = false;\n }\n\n if (key === \"d\") {\n movingRight = false;\n }\n}", "function keyPressed() {}", "function listenForPlayerMovement() {\n // Listen for when a key is pressed\n // If it's a specified key, mark the direction as true since moving\n var onKeyDown = function(event) {\n\n switch (event.keyCode) {\n\n case 38: // up\n case 87: // w\n moveForward = true;\n break;\n\n case 37: // left\n case 65: // a\n moveLeft = true;\n break;\n\n case 40: // down\n case 83: // s\n moveBackward = true;\n break;\n\n case 39: // right\n case 68: // d\n moveRight = true;\n break;\n\n }\n\n };\n\n // Listen for when a key is released\n // If it's a specified key, mark the direction as false since no longer moving\n var onKeyUp = function(event) {\n\n switch (event.keyCode) {\n\n case 38: // up\n case 87: // w\n moveForward = false;\n break;\n\n case 37: // left\n case 65: // a\n moveLeft = false;\n break;\n\n case 40: // down\n case 83: // s\n moveBackward = false;\n break;\n\n case 39: // right\n case 68: // d\n moveRight = false;\n break;\n }\n };\n\n // Add event listeners for when movement keys are pressed and released\n document.addEventListener('keydown', onKeyDown, false);\n document.addEventListener('keyup', onKeyUp, false);\n}", "handleInput(keycode) {\n if (keycode !== undefined && player.moves === true) {\n key = keycode;\n }\n }", "checkKeysDown() {\r\n if (keys.W.isDown || keys.S.isDown || keys.D.isDown || keys.A.isDown) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "function keyboard_input(event){\n\t// TODO: Modify code so the paddle goes up and down but not outside the area of play.\n var key = event.keyCode;\n\t switch(key)\n\t {\n\t\tcase 38: // Calling for the up arrow key\n\t\tplayer_2.move_up(); // calling the Paddle move up function for player 2\n\t\tbreak;\n\t \n\t\tcase 40: // Calling for the down arrow key\n\t\tplayer_2.move_down(); // Calling for the Paddle move down function for player 2\n\t\tbreak;\n\n\t\tcase 87: // Calling for the W key\n\t\tplayer_1.move_up(); // Calling for the Paddle move up function for player 1\n\t break;\n\t \n\t\n\t\tcase 83: // Calling for the S key\n\t\tplayer_1.move_down(); // Calling for the Paddle move down function for player 1\n\t\tbreak;\n\t }\n\t \n\tconsole.log(event.keyCode); // use this to view key codes\n}", "startListening() {\n document.addEventListener('keydown', (event) => {\n if (event.keyCode == 37) {\n //left\n if(document.getElementById(\"player1\")){\n this.tryMove(-1, 0);\n event.preventDefault();\n event.stopPropagation();}\n }\n });\n document.addEventListener('keydown', (event) => {\n if (event.keyCode == 39) {\n if(document.getElementById(\"player1\")){\n //right\n this.tryMove(1, 0);\n event.preventDefault();\n event.stopPropagation();}\n }\n });\n document.addEventListener('keydown', (event) => {\n if (event.keyCode == 40) {\n //down\n if(document.getElementById(\"player1\")){\n\n this.tryMove(0, -1);\n event.preventDefault();\n event.stopPropagation();}\n }\n })\n document.addEventListener('keydown', (event) => {\n if (event.keyCode == 38) {\n //up\n if(document.getElementById(\"player1\")){\n\n this.tryMove(0, 1);\n event.preventDefault();\n event.stopPropagation();}\n }\n })\n }", "function keyPressed() {\n if (key === \"p\" || key === \"P\") pong.pauseRound();\n if (key === \" \" && !pong.isStarted) pong.newRound();\n}", "function keyHandler(e) {\n var allowedKeys = {\n 37: 'left',\n 38: 'up',\n 39: 'right',\n 40: 'down'\n };\n\n player.handleInput(allowedKeys[e.keyCode]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET CITES FROM WOK
function getWokCites(title, year){ // Go to WOK web page iimPlay('CODE: URL GOTO=http://apps.webofknowledge.com'); //Prepare search fields and click search button if (year && year > 0){ iimPlay('CODE: TAG POS=1 TYPE=SELECT FORM=NAME:UA_GeneralSearch_input_form ATTR=ID:select1 CONTENT=%TI\n' + 'TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:UA_GeneralSearch_input_form ATTR=ID:value(input1) CONTENT=' + title.replace(/ /g, '<SP>') + '\n' + 'TAG POS=1 TYPE=INPUT:RADIO FORM=ID:UA_GeneralSearch_input_form ATTR=ID:periodRange\n' + 'TAG POS=1 TYPE=SELECT FORM=NAME:UA_GeneralSearch_input_form ATTR=NAME:startYear CONTENT=%' + year + '\n' + 'TAG POS=1 TYPE=SELECT FORM=NAME:UA_GeneralSearch_input_form ATTR=NAME:endYear CONTENT=%' + year + '\n' + 'TAG POS=1 TYPE=INPUT:IMAGE FORM=ID:UA_GeneralSearch_input_form ATTR=SRC:http://images.webofknowledge.com/WOKRS512B4.1/images/search.gif'); } else { iimPlay('CODE: TAG POS=1 TYPE=SELECT FORM=NAME:UA_GeneralSearch_input_form ATTR=ID:select1 CONTENT=%TI\n' + 'TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:UA_GeneralSearch_input_form ATTR=ID:value(input1) CONTENT=' + title.replace(/ /g, '<SP>') + '\n' + 'TAG POS=1 TYPE=INPUT:IMAGE FORM=ID:UA_GeneralSearch_input_form ATTR=SRC:http://images.webofknowledge.com/WOKRS512B4.1/images/search.gif'); } //Position at "Times Cited" span to know if it has been found and save value in EXTRACT iimPlay('CODE: TAG POS=1 TYPE=SPAN ATTR=TXT:Times<SP>Cited: EXTRACT=TXT'); var citesTextExists = iimGetLastExtract().trim(); if (citesTextExists == '#EANF#'){ return -1 } else { //Try to position at Cites counter <a> to get the number, if it has no cite it wont have an <a> iimPlay('CODE: TAG POS=1 TYPE=A ATTR=TITLE:View<SP>all<SP>of<SP>the<SP>articles<SP>that<SP>cite<SP>this<SP>one EXTRACT=TXT'); var citesText = iimGetLastExtract().trim(); if (citesText == '#EANF#' || citesText == '' || citesText == '0'){ return 0 } else { return parseInt(citesText) } } }
[ "function getClips() {\n const game = 'League of Legends';\n const limit = 10;\n const period = 'day';\n const language = 'en';\n const id = nconf.get('twitchclient');\n const options = {\n method: 'get',\n url: `https://api.twitch.tv/kraken/clips/top?game=${game}&limit=${limit}&period=${period}&language=${language}`,\n json: true,\n headers: {\n 'Client-ID': id,\n Accept: 'application/vnd.twitchtv.v5+json',\n },\n };\n return new bluebird.Promise((resolve) => {\n req(options, (error, response, body) => {\n resolve(body);\n });\n });\n}", "async getDrinksByCat(cat){\r\n const look = await fetch('https://www.thecocktaildb.com/api/json/v1/1/filter.php?c='+cat);\r\n const cocktail = await look.json();\r\n return{\r\n cocktail\r\n } \r\n }", "function getWinePhotos() {\n\n getPhotos('wine', winePhotoUrls, getFoodPhotos);\n}", "getChannelCategories (cb) {\n instance().get('/api/devices/channel-categories')\n .then(res => cb(res.data))\n .catch(err => console.log(err))\n }", "async function getComicData(url){ return getWebData(url,\"comic\") }", "getComics() {\r\n return api.get('/comics')\r\n }", "async function getClips(channelID, clipCount, pageToken) {\n // channelID, gameID, or clipID\n\n // Call Clip endpoint\n let channelClipsURL = \"https://api.twitch.tv/helix/clips?broadcaster_id=\" + channelID;\n return fetch(channelClipsURL, {\n method: 'GET',\n headers: {\n 'Authorization': OAUTH_TOKEN,\n 'Client-Id': CLIENT_ID\n }\n })\n .then(response => {\n return response.json();\n })\n .then(clipData => {\n\n // Get first n clips, trim the rest\n if (clipCount !== null && clipCount === parseInt(clipCount)) {\n clipData.data = clipData.data.slice(0, clipCount);\n }\n return clipData;\n })\n .catch(error => {\n console.warn(error);\n });\n}", "function retrieveChampions () {\n var parameters = {\n api_key: apikey.getApiKey(),\n champData: \"image\"\n };\n var options = {\n host: 'na.api.pvp.net',\n path: '/api/lol/static-data/na/v1.2/champion?' + querystring.stringify(parameters),\n method: 'GET'\n };\n\n https.request(options, function (res) {\n var fullBody = \"\";\n res.on(\"data\", function (chunk) {\n fullBody += chunk;\n }).on(\"end\", function () {\n cachedChampions = extractChampionData(JSON.parse(fullBody).data);\n });\n }).on(\"error\", function (error) {\n console.log(\"An error has occurred getting the champions\");\n console.log(error);\n }).end();\n\n}", "function getScopusCites(title, year){\n \n // Goto to url\n iimPlay('CODE: URL GOTO=http://www.scopus.com/search/form.url');\n \n //Prepare search fields and click search button\n if (year && year > 0) {\n iimPlay('CODE: TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:BasicValidatedSearchForm ATTR=ID:searchterm1 CONTENT=' + title.replace(/ /g, '<SP>') + '\\n' +\n 'TAG POS=1 TYPE=SELECT FORM=NAME:BasicValidatedSearchForm ATTR=ID:yearFrom CONTENT=%' + year + '\\n' +\n 'TAG POS=1 TYPE=SELECT FORM=NAME:BasicValidatedSearchForm ATTR=ID:yearTo CONTENT=%' + year + '\\n' +\n 'TAG POS=1 TYPE=INPUT:CHECKBOX FORM=NAME:BasicValidatedSearchForm ATTR=ID:subArea-2 CONTENT=NO\\n' +\n 'TAG POS=1 TYPE=INPUT:CHECKBOX FORM=NAME:BasicValidatedSearchForm ATTR=ID:subArea-4 CONTENT=NO\\n' +\n 'TAG POS=2 TYPE=INPUT:SUBMIT FORM=NAME:BasicValidatedSearchForm ATTR=VALUE:Search');\n } else {\n iimPlay('CODE: TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:BasicValidatedSearchForm ATTR=ID:searchterm1 CONTENT=' + title.replace(/ /g, '<SP>') + '\\n' +\n 'TAG POS=1 TYPE=INPUT:CHECKBOX FORM=NAME:BasicValidatedSearchForm ATTR=ID:subArea-2 CONTENT=NO\\n' +\n 'TAG POS=1 TYPE=INPUT:CHECKBOX FORM=NAME:BasicValidatedSearchForm ATTR=ID:subArea-4 CONTENT=NO\\n' +\n 'TAG POS=2 TYPE=INPUT:SUBMIT FORM=NAME:BasicValidatedSearchForm ATTR=VALUE:Search');\n }\n \n //Position at \"Cited by\" result col \"dataCol6\" and save value in EXTRACT\n iimPlay('CODE: TAG POS=1 TYPE=LI ATTR=CLASS:dataCol6 EXTRACT=TXT');\n var citesText = iimGetLastExtract().trim();\n \n // Extract cites number\n if (citesText == '#EANF#' || citesText == ''){\n return undefined;\n } else {\n return parseInt(citesText);\n }\n}", "function getChampions() {\n return fetch(BASE_URL + 'champion.json')\n .then(res => res.json());\n}", "function getGenres() {\n fetch('http://movie-api.cederdorff.com/wp-json/wp/v2/categories')\n .then(function(response) {\n return response.json();\n })\n .then(function(categories) {\n console.log(categories);\n appendGenres(categories);\n });\n}", "function fetchFaveChannels() {\n var list = document.getElementById('channels').getElementsByTagName('ul')[0];\n list.innerHTML = '';\n for (var i = 0; i < channelsList.length; i++) {\n var channel = '&id=' + channelsList[i];\n var url = 'https://www.googleapis.com/youtube/v3/channels?part=snippet,brandingSettings' + channel + apik;\n loadChannelsList(url);\n }\n}", "function getGenres() {\n // TODO: get categories from wp headless\n // https://movie-api.cederdorff.com/wp-json/wp/v2/categories\n}", "function getcues()\n{\n\toutlet(1, \"clear\");\n\tif(cueindex.length==0){\n\t\tpost(\"no defined cues\")\n\t}\n\telse {\n\t\tfor(i=0; i<cueindex.length; i++){\n\t\t\t\t\n\t\t\t\tcuenameI=\"\";\n\t\t\t\tfor(y in alllines[cueindex[i]]){\n\t\t\t\t\tif(y==0){}\n\t\t\t\t\telse cuenameI=cuenameI.concat(alllines[cueindex[i]][y], \" \");\n\t\t\t\t}\n\t\t\t\t\n\t\t\toutlet(1, \"append\" , cuenameI );\n\t\t}\t\n\t}\n\toutlet(0, \"cuecount\", cueindex.length);\n\toutlet(0, \"cuelist_ready\");\n}", "function getCheeps() {\n return $.get('/cheeps');\n }", "async function callCocktailIngredients(ingredient){\n let ingredientFilter = `https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${ingredient}`\n let fetchedCocktails = await fetch(ingredientFilter);\n let cocktailsList = await fetchedCocktails.json();\n console.dir(cocktailsList);\n}", "function ct_getcat() {\n let ctgc_headers = new Headers({\n 'x-api-key': '2b032810-c828-48e7-8c8c-c7a83907e312',\n });\n let ctgc_request = new Request('https://api.thecatapi.com/v1/images/search', {\n method: 'GET',\n headers: ctgc_headers,\n mode: 'cors',\n cache: 'default',\n });\n fetch(ctgc_request)\n .then(function (response) {return response.json()})\n .then(json => {\n ct_getcat_return = json[0];\n })\n}", "async function getKijkwijzers() {\n const KijkwijzerResponse = await chromelyRequest('/kijkwijzer');\n return KijkwijzerResponse.getData();\n}", "function ct_getcat() {\n let ctgc_headers = new Headers({\n 'x-api-key': '2b032810-c828-48e7-8c8c-c7a83907e312',\n });\n let ctgc_request = new Request('https://api.thecatapi.com/v1/images/search', {\n method: 'GET',\n headers: ctgc_headers,\n mode: 'cors',\n cache: 'default',\n });\n fetch(ctgc_request)\n .then(function(response) { return response.json() })\n .then(json => {\n ct_getcat_return = json[0];\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
const input = "3,26,1001,26,4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,1,28,1005,28,6,99,0,0,5";
function parseInput(input){     return input.split(",").map(x => Number(x)); }
[ "function parseNumbers(s) {\n var result = [];\n s.split(',').forEach(x => {\n let m = x.match(/(\\d+)\\s*\\-\\s*(\\d+)/);\n if (m) {\n for (let i = parseInt(m[1]); i <= m[2]; i++) {\n result.push(i);\n }\n } else {\n result.push(parseInt(x));\n }\n });\n // return without duplicates\n return result.filter(indexAt);\n}", "function extractNumber(str) {\r\n let arr = str.split('').filter(a => a * 0 == 0)\r\n return arr.join('')\r\n}//End function numbers from string", "function main2() {\n\tlet input = getIn().split(\"-\").map(Number)\n\tlet total = []\n\tfor (let i = input[0]; i <= input[1]; i++) {\n\t\tif (!/(\\d)\\1/.test(i) || !/^0*1*2*3*4*5*6*7*8*9*$/.test(i)) continue\n// All this looks familiar\n\t\tlet str = String(i).replace(/(\\d)(?!\\1)/g, (m,p1)=>p1+\" \").split(\" \")\n// Look for every digit that's doesn't have its repeat after it.\n// I tried matching the transition boundary and putting a space in between, but then you couldn't match the second digit if it was all by itself.\n// so, ...replace(/(\\d)(?!\\1)(\\d)/g, (m,p1,p2)=>p1+\" \"+p2)... wouldn't let me capture p2 again, so 123456 would look like \"1 23 45 6\" instead of \"1 2 3 4 5 6 \"\n\t\tif (str.some(x=>x.length==2)) total.push(i)\n// is one of those blocks 2 digits long? great, I want that number\n\t}\n\tdisplayOut(2, total.length)\n}", "function completeNumbers(list) {\n if (list === '') return [];\n let elements = list.split(', ');\n let listOfCompletedNumbers = [];\n listOfCompletedNumbers.push(completeNumber(elements[0]));\n\n for (let idx = 1; idx < elements.length; idx += 1) {\n let previousCompletedNumber = String(listOfCompletedNumbers[idx - 1]);\n let element = elements[idx];\n if (!element.match(/:|-|\\.\\./)) {\n let shortHandNumber = element;\n listOfCompletedNumbers.push(completeNumber(shortHandNumber, previousCompletedNumber));\n }\n }\n return listOfCompletedNumbers;\n}", "function stringToArrayOfNumbers(input) {\n var grades=input.split(\",\");\n return grades;\n}", "function getArrayOfResults(string, num) {\n let result = [];\n\n if (num === 1) {\n for (let index = 1; index < string.length; index += 1) {\n result.push(string.slice(0, index) + ',' + string.slice(index, string.length));\n }\n } else if (num === 2) {\n let i = 0;\n\n while (i < string.length - 1) {\n let n = i + 1;\n while (n < string.length - 1) {\n let temp = string.split('');\n temp[i] = temp[i] + ',';\n temp[n] = temp[n] + ',';\n n++;\n result.push(temp.join(''));\n }\n\n i++;\n }\n } else if (num === 3) {\n let i = 0;\n\n while (i < string.length - 1) {\n let n = i + 1;\n while (n < string.length - 1) {\n let m = n + 1;\n while (m < string.length - 1) {\n let temp = string.split('');\n temp[i] = temp[i] + ',';\n temp[n] = temp[n] + ',';\n temp[m] = temp[m] + ',';\n m++;\n result.push(temp.join(''));\n }\n\n n++;\n }\n\n i++;\n }\n } else if (num === 4) {\n let i = 0;\n\n while (i < string.length - 1) {\n let n = i + 1;\n while (n < string.length - 1) {\n let m = n + 1;\n while (m < string.length - 1) {\n let j = m + 1;\n while (j < string.length - 1) {\n let temp = string.split('');\n temp[i] = temp[i] + ',';\n temp[n] = temp[n] + ',';\n temp[m] = temp[m] + ',';\n temp[j] = temp[j] + ',';\n result.push(temp.join(''));\n j++;\n }\n\n m++;\n }\n\n n++;\n }\n\n i++;\n }\n }\n\n return result;\n}", "function baseFinder(seq) {\n let result = seq\n .map((x) => {\n return parseInt(x) % 10;\n })\n .filter((v, i, a) => a.indexOf(v) === i).length;\n\n return result;\n}", "function extractUniqueNumbersFromString(str) {\n var numericChars = \"1234567890.\";\n var result = [];\n var buffer = \"\";\n var nextMaybeNegative = false;\n \n for (var index = 0; index < str.length; index++) {\n // For why charAt vs. [], see:\n // http://stackoverflow.com/a/5943760\n\n var ch = str.charAt(index);\n\n // We don't want to interpret 10-20 as 10 and -20 because that\n // looks very much like a range notation. (So does 10 - 20) We\n // only accept it to make things negative if the building buffer is\n // empty AND the next number is a digit.\n\n if ((ch == '-') && !buffer) {\n nextMaybeNegative = true;\n continue;\n }\n\n var isNumericChar = (numericChars.indexOf(ch) != -1);\n if (isNumericChar) {\n if (nextMaybeNegative)\n buffer += '-';\n\n buffer += ch;\n }\n\n nextMaybeNegative = false;\n\n if (!isNumericChar || (index == str.length - 1)) {\n var value = null;\n if (buffer.length) {\n value = parseFloat(buffer);\n if (!isNaN(value) && result.indexOf(value) == -1)\n result.push(value);\n }\n buffer = \"\";\n }\n }\n return result;\n }", "getNumbers(string) {\n\t\tlet result = \"\";\n\t\tlet regex = /\\d+/g\n\t\tlet m;\n\t\twhile ((m = regex.exec(string)) != null) {\n\t\t result += m;\n\t\t}\n\n\t\treturn result;\n\t}", "function calc(arr){\n \n let sum = 0;\n \n return arr.split(',').map(Number).filter(num => num <= 9).reduce((sum, digit) => {\n return sum += digit\n }, 0);\n \n}", "function parseInt(string) {\n const DICT = {\n 'zero': 0,\n 'one': 1,\n 'two': 2,\n 'three': 3,\n 'four': 4,\n 'five': 5,\n 'six': 6,\n 'seven': 7,\n 'eight': 8,\n 'nine': 9,\n 'ten': 10,\n 'eleven': 11,\n 'twelve': 12,\n 'thirteen': 13,\n 'fourteen': 14,\n 'fifteen': 15,\n 'sixteen': 16,\n 'seventeen': 17,\n 'eighteen': 18,\n 'nineteen': 19,\n 'twenty': 20,\n 'thirty': 30,\n 'forty': 40,\n 'fifty': 50,\n 'sixty': 60,\n 'seventy': 70,\n 'eighty': 80,\n 'ninety': 90,\n 'hundred': 100,\n 'thousand': 1000,\n 'million': 1000000\n }\n\n // split up the input by spaces\n let nums = string.split(' ');\n\n // go over each element and find the number pair for the text\n let parts = nums.map(element => {\n // check if element contains hyphen -\n if (element.indexOf('-') !== -1) {\n // split up by hyphen \n let subNums = element.split('-')\n return subNums.reduce((sum, num) => {\n return sum += DICT[num];\n }, 0)\n } else {\n return DICT[element] || 0;\n }\n });\n\n let sum = 0;\n let highest_tens = 1;\n let tens = 1;\n\n let result = [];\n\n if (parts.length === 1) {\n return parts[0];\n } else {\n i = 0;\n while (i < parts.length) {\n //get next two values\n let next = parts[i];\n let multiplier = parts[i + 1];\n\n // if multiplier is really a factor\n if (multiplier === 100 || multiplier === 1000 || multiplier === 1000000) {\n tens = Math.log10(multiplier);\n\n // use multiplier if it is bigger then previous biggest\n if (tens > highest_tens) {\n highest_tens = tens;\n\n sum += next;\n sum *= multiplier;\n } else {\n // if it is not bigger then store the got number\n result.push(sum);\n sum = next;\n sum *= multiplier;\n }\n i += 2;\n } else {\n sum += next;\n i += 1;\n }\n }\n\n result.push(sum);\n }\n\n return result.reduce((sum, val) => sum += val);\n}", "function handleInputInt(inputStr) {\n if (!inputStr.length) {\n \t\tthrow new Error(\"Data Set is empty\");\n }\n const inputArr = inputStr.split(',').map( item => inputNumberValid(item, \"for each array element separated by comma\"));\n const numbersArr = inputArr.map( (item => parseFloat(item)))\n return numbersArr.filter ( number => number % 1 === 0);\n}", "function ancientVsMemory(input) {\n let data = input.join(\" \").split(\" \");\n let result = [];\n\n for (let index = 0; index < data.length; index++) {\n \n if( data[index] === \"32656\" && data[index + 1] === \"19759\" && data[index + 2] === \"32763\" && data[index + 3] === \"0\" && data[index + 5] === \"0\") {\n let count = +data[index + 4];\n let word = \"\";\n for (let charIndex = index + 6 ; charIndex < index + 6 + count; charIndex++) {\n word += String.fromCharCode(+data[charIndex]);\n }\n result.push(word);\n }\n }\n\n result.forEach(r => console.log(r));\n}", "function numDecodings2(s) {\n if (s == null || s.length === 0) {\n return 0;\n }\n if (s[0] === \"0\") {\n return 0;\n }\n\n // dp = Dynamics Programming Array\n // dp[i] = # of ways of decoding a substring\n const dp = new Array(s.length + 1).fill(0);\n\n // initialize baton to be passed\n dp[0] = 1;\n // first character of string is not zero\n dp[1] = 1;\n\n // iterate through string\n for (let i = 2; i <= s.length; i++) {\n // The index i of dp is the i-th character of the string s, that is character at index i-1 of s.\n const a = Number(s.slice(i - 1, i)); // last one digit\n // check if valid single digit decode is possible (non zero)\n if (a >= 1 && a <= 9) {\n // if possible, add dp[i-1] to dp[i], currently 0\n dp[i] += dp[i - 1];\n }\n\n const b = Number(s.slice(i - 2, i)); // last two digits\n // check if valid two digit decode is possible\n // This means the substring s[i-2]s[i-1] is between 10 to 26.\n // If the valid two digit decoding is possible then we add dp[i-2] to dp[i].\n if (b >= 10 && b <= 26) {\n dp[i] += dp[i - 2];\n }\n }\n\n return dp[s.length];\n}", "function extractNums(str) {\n var matches = str.match(/\\d+/g);\n if (matches == null)\n return [];\n return matches.map(function (s) { return parseInt(s, 10); });\n}", "static intSplit(string) {\r\n\t\tlet array = string.split(\",\");\r\n\t\treturn array.map(x => parseInt(x));\r\n\t}", "function lottery(str) {\n if (/\\d/.test(str)) {\n let number = str.replace(/[^0-9]/g, '').toString().split('')\n return [...new Set(number)].join('')\n } else {\n return 'One more run!'\n }\n}", "function separateComma(int) {\n var intArray = int.toString().split('');\n var results = []; \n \n var i = intArray.length - 1\n while (i >= 0) {\n if (intArray[i - 2]) {\n results.unshift(\",\" + intArray[i-2] + intArray[i-1] + intArray[i])\n i -= 3\n }\n else {\n results.unshift(intArray[i])\n i -= 1\n }\n }\n return results.join('')\n}", "function getCount(n)\n{\n n=n.toString();\n var len=n.length;\n var i=0;\n var count=0;\n var j=1;\n while(j<len)\n {\n i=0;\n while(i<len)\n {\n if((i+j)<=len)\n {\n //console.log(n.substring(i,i+j));\n if(parseInt(n)%parseInt(n.substring(i,i+j))===0 && n.substring(i,i+j)!==n && n.substring(i,i+j)!=='0')\n {\n \n count++;\n }\n }\n i++;\n }\n j++;\n }\n return count;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Safely compare two MACs. This function will compare two MACs in a way that protects against timing attacks. TODO: Expose elsewhere as a utility API. See:
function compareMacs(key, mac1, mac2) { var hmac = forge.hmac.create(); hmac.start('SHA1', key); hmac.update(mac1); mac1 = hmac.digest().getBytes(); hmac.start(null, null); hmac.update(mac2); mac2 = hmac.digest().getBytes(); return mac1 === mac2; }
[ "compare(a, b) {\n return __awaiter(this, void 0, void 0, function* () {\n const macKey = yield this.randomBytes(32);\n const signingAlgorithm = {\n name: 'HMAC',\n hash: { name: 'SHA-256' },\n };\n const impKey = yield this.subtle.importKey('raw', macKey, signingAlgorithm, false, ['sign']);\n const mac1 = yield this.subtle.sign(signingAlgorithm, impKey, a);\n const mac2 = yield this.subtle.sign(signingAlgorithm, impKey, b);\n if (mac1.byteLength !== mac2.byteLength) {\n return false;\n }\n const arr1 = new Uint8Array(mac1);\n const arr2 = new Uint8Array(mac2);\n for (let i = 0; i < arr2.length; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n });\n }", "function compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n return mac1 === mac2;\n}", "function compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}", "function compareHMACcode(code1, code2) {\n 'use strict';\n\n if (code1.length !== code2.length) {\n return false;\n }\n\n if ((util.isString(code1)) && (util.isString(code2))) {\n // just do a string compare\n return code1 === code2;\n } else {\n assert(false, 'compareHMACcode can only compare two strings at the moment');\n return false;\n }\n}", "function fnValidateMacAddress(macaddr)\r\n{\r\n var reg1 = /^[A-Fa-f0-9]{1,2}\\-[A-Fa-f0-9]{1,2}\\-[A-Fa-f0-9]{1,2}\\-[A-Fa-f0-9]{1,2}\\-[A-Fa-f0-9]{1,2}\\-[A-Fa-f0-9]{1,2}$/;\r\n var reg2 = /^[A-Fa-f0-9]{1,2}\\:[A-Fa-f0-9]{1,2}\\:[A-Fa-f0-9]{1,2}\\:[A-Fa-f0-9]{1,2}\\:[A-Fa-f0-9]{1,2}\\:[A-Fa-f0-9]{1,2}$/;\r\n\r\n if (reg1.test(macaddr)) {\r\n return true;\r\n } else if (reg2.test(macaddr)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "function isValidMac(mac) {\r\n var temp = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;\r\n if (!temp.test(mac)){\r\n return false;\r\n }\r\n return true;\r\n}", "function compare(a, b) {\n var first = a;\n var second = b;\n var shadow = false;\n if (b.length < a.length) {\n first = b;\n second = a;\n shadow = true;\n }\n for (var i = 0; i < first.length; i++) {\n if (first[i].equals(second[i]) === false) {\n return KeySequence.CompareResult.NONE;\n }\n }\n if (first.length < second.length) {\n if (shadow === false) {\n return KeySequence.CompareResult.PARTIAL;\n }\n else {\n return KeySequence.CompareResult.SHADOW;\n }\n }\n return KeySequence.CompareResult.FULL;\n }", "function caml_bytes_equal(s1, s2) {\n if(s1 === s2) return 1;\n (s1.t & 6) && caml_convert_string_to_bytes(s1);\n (s2.t & 6) && caml_convert_string_to_bytes(s2);\n return (s1.c == s2.c)?1:0;\n}", "function checkNullMac(mac) {\n if (!checkMAC(mac)) {\n return false;\n } else {\n var hwaddr = mac.value.split(\":\");\n if ((parseInt(hwaddr[0], 16) | parseInt(hwaddr[1], 16) | parseInt(hwaddr[2], 16) | parseInt(hwaddr[3], 16) | parseInt(hwaddr[4], 16) | parseInt(hwaddr[5], 16)) == 0x00) {\n return true;\n } else {\n return false;\n }\n }\n}", "function equalsBytes(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}", "function validateMAC(mac) \n{ \n\tvar exp=/^([A-Fa-f\\d]{2})(:[0-9A-Fa-f]{2}){5}$/; //00:24:21:19:BD:E4\n\tif(!exp.test(mac))/*不符合*/\n\t{\n\t\treturn false;\n\t}\n\telse/*符合*/\n\t{\n\t\t/*排除全0*/\n\t\tvar exp_zero=/^(00)(:00){5}$/; \n\t\tif(exp_zero.test(mac))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/*排除组播;首字节末位是1,16进制表示首字节,合法情况;第二个数字只能是0 2 4 6 8 A C E*/\n\t\tvar exp_muticast=/^([A-Fa-f\\d][0 2 4 6 8 A C E])(:[0-9A-Fa-f]{2}){5}$/i;\n\t\tif(!exp_muticast.test(mac))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\t\n\treturn true;\n}", "async comparePasswords(saved, supplied) {\n const [hashed, salt] = saved.split(\".\");\n const hashedSuppliedBuf = await scrypt(supplied, salt, 64);\n return hashed === hashedSuppliedBuf.toString(\"hex\");\n }", "function caml_bytes_greaterequal(s1, s2) {\n return caml_bytes_lessequal(s2,s1);\n}", "function caml_bytes_compare(s1, s2) {\n (s1.t & 6) && caml_convert_string_to_bytes(s1);\n (s2.t & 6) && caml_convert_string_to_bytes(s2);\n return (s1.c < s2.c)?-1:(s1.c > s2.c)?1:0;\n}", "function caml_bytes_notequal(s1, s2) { return 1-caml_string_equal(s1, s2); }", "function checkMulticastMac(mac) {\n if (!checkMAC(mac)) {\n return false;\n } else {\n var hwaddr = mac.value.split(\":\");\n if ((parseInt(hwaddr[0], 16) & 1) != 0) {\n return true;\n } else {\n return false;\n }\n }\n}", "function checkBroadcastMac(mac) {\n if (!checkMAC(mac)) {\n return false;\n } else {\n var hwaddr = mac.value.split(\":\");\n if ((parseInt(hwaddr[0], 16) & parseInt(hwaddr[1], 16) & parseInt(hwaddr[2], 16) & parseInt(hwaddr[3], 16) & parseInt(hwaddr[4], 16) & parseInt(hwaddr[5], 16)) == 0xff) {\n return true;\n } else {\n return false;\n }\n }\n}", "function caml_bytes_lessthan(s1, s2) {\n (s1.t & 6) && caml_convert_string_to_bytes(s1);\n (s2.t & 6) && caml_convert_string_to_bytes(s2);\n return (s1.c < s2.c)?1:0;\n}", "function compPasswords(pass1, pass2) {\n\treturn (pass1 == pass2);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a string in the form of type[length] we want to split this into an object that extracts that information. We want to note that we could possibly have nested arrays so this should only check the furthest one. It may also be the case that we have no [] pieces, in which case we just return the current type.
function ctParseType(str) { var begInd, endInd; var type, len; if (typeof (str) != 'string') throw (new Error('type must be a Javascript string')); endInd = str.lastIndexOf(']'); if (endInd == -1) { if (str.lastIndexOf('[') != -1) throw (new Error('found invalid type with \'[\' but ' + 'no corresponding \']\'')); return ({ type: str }); } begInd = str.lastIndexOf('['); if (begInd == -1) throw (new Error('found invalid type with \']\' but ' + 'no corresponding \'[\'')); if (begInd >= endInd) throw (new Error('malformed type, \']\' appears before \'[\'')); type = str.substring(0, begInd); len = str.substring(begInd + 1, endInd); return ({ type: type, len: len }); }
[ "function ctParseType(str)\n {\n \tvar begInd, endInd;\n \tvar type, len;\n \tif (typeof (str) != 'string')\n \t\tthrow (new Error('type must be a Javascript string'));\n \n \tendInd = str.lastIndexOf(']');\n \tif (endInd == -1) {\n \t\tif (str.lastIndexOf('[') != -1)\n \t\t\tthrow (new Error('found invalid type with \\'[\\' but ' +\n \t\t\t 'no corresponding \\']\\''));\n \n \t\treturn ({ type: str });\n \t}\n \n \tbegInd = str.lastIndexOf('[');\n \tif (begInd == -1)\n \t\tthrow (new Error('found invalid type with \\']\\' but ' +\n \t\t 'no corresponding \\'[\\''));\n \n \tif (begInd >= endInd)\n \t\tthrow (new Error('malformed type, \\']\\' appears before \\'[\\''));\n \n \ttype = str.substring(0, begInd);\n \tlen = str.substring(begInd + 1, endInd);\n \n \treturn ({ type: type, len: len });\n }", "function ctParseType(str)\n\t{\n\t\tvar begInd, endInd;\n\t\tvar type, len;\n\t\tif (typeof (str) != 'string')\n\t\t\tthrow (new Error('type must be a Javascript string'));\n\n\t\tendInd = str.lastIndexOf(']');\n\t\tif (endInd == -1) {\n\t\t\tif (str.lastIndexOf('[') != -1)\n\t\t\t\tthrow (new Error('found invalid type with \\'[\\' but ' +\n\t\t\t\t 'no corresponding \\']\\''));\n\n\t\t\treturn ({ type: str });\n\t\t}\n\n\t\tbegInd = str.lastIndexOf('[');\n\t\tif (begInd == -1)\n\t\t\tthrow (new Error('found invalid type with \\']\\' but ' +\n\t\t\t 'no corresponding \\'[\\''));\n\n\t\tif (begInd >= endInd)\n\t\t\tthrow (new Error('malformed type, \\']\\' appears before \\'[\\''));\n\n\t\ttype = str.substring(0, begInd);\n\t\tlen = str.substring(begInd + 1, endInd);\n\n\t\treturn ({ type: type, len: len });\n\t}", "function getTypeSlice(x){\n if(x.match(\"STRING\")){\n\t\treturn \"\\\"\" + x.slice(8,x.length) + \"\\\"\";\n\t}\n\telse if(x.match(\"NUM\")){\n\t\treturn parseInt(x.slice(5,x.length));\n\t}\n\telse if(x.match(\"EXPR\")){\n\t\treturn x.slice(6,x.length);\n\t}\n \n}", "function parseTypeArray (type) {\n var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n if (tmp) {\n return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n }\n return null\n}", "function parse(str) {\n var types = [];\n var toks = tokens(str);\n\n for (var i = 0, tok; tok = toks[i]; i++) {\n if (regex.block.test(tok)) types.push('block');\n else if (regex.cell.test(tok)) types.push('cell');\n else if (regex.rows.test(tok)) types.push('rows');\n else if (regex.cols.test(tok)) types.push('cols');\n else if (regex.row.test(tok)) types.push('row');\n else if (regex.col.test(tok)) types.push('col');\n }\n\n switch(unique(types).length) {\n case 0: return null;\n case 1: return types[0];\n }\n\n // pluralize and test again\n for (var i = 0, type; type = types[i]; i++) {\n if ('col' == type) types[i] = 'cols';\n if ('row' == type) types[i] = 'rows';\n }\n\n switch(unique(types).length) {\n case 1: return types[0];\n default: return 'mixed';\n }\n}", "function getInnerType(str){\n var index = str.indexOf('(');\n return index > 0 ? str.substring(index + 1, str.length - 1) : str;\n}", "function parseType (str) {\n // Use regex to split into more useful array\n const parsed = str.split(/\\b/)\n\n // Filter only whole words\n const [primaryType, secondaryType] = _.filter(parsed, token => token.match(/^\\w+$/))\n\n return {primaryType, 'secondaryType': secondaryType || 'None'}\n}", "function parse_array_type(str){\n var String = \"\";\n for(var i in str){\n if(isObject(str[i])){\n return parse_struct_type(str);\n }\n String += jschema_parser(str[i]);\n String += \"_\" + i + \";\\n\";\n }\n return String;\n}", "function splitType(str,types){\r\n\t\tvar regexpStr='(['+types+']?)([^'+types+']+)',\r\n\t\t\tregexp=new RegExp(regexpStr,'g'),\r\n\t\t\t\r\n\t\t\tresult=getMatchResult(str,regexp,function(eachMatch,type,selector){\r\n\t\t\t\treturn {\r\n\t\t\t\t\ttype:type,\r\n\t\t\t\t\tselector:selector\r\n\t\t\t\t};\r\n\t\t\t});\r\n\t\t\t\r\n\t\treturn result;\r\n\t}", "function stringToObjectKeys(str) {\n var dot;\n var braket;\n\n if (str.includes(\".\"))\n dot = true;\n\n if (str.includes(\"[\") && str.includes(\"]\"))\n braket = true;\n\n console.log(\"str\", str, \"dot\", dot, \"braket\", braket)\n\n if (!dot && !braket)\n return [str]\n\n if (dot)\n return str.split(\".\")\n\n return false;\n\n //TODO add braket\n //if (!dot && braket)\n // return false;\n //if (dot && braket)\n // return false;\n}", "function getPopType(str) {\n let arr = str.split(/[ ,]+/);\n return arr[0];\n }", "function Splitter(item) {\n var index = 0; // string scanning index\n var from = 0; // start index for parts\n var parts = []; // parts array\n var completed = false; // parsing finished flag\n\n this.item = item;\n // extracting key\n var key = (typeof (extractor) === 'function') ?\n extractor(item) :\n item;\n if (typeof(key) === 'string') {\n key = trim(key);\n } else {\n throw new TypeError('Key should be String');\n }\n this.key = key;\n // amount of parts found\n this.count = function () {\n return parts.length;\n };\n // checking key emptiness\n this.isEmpty = function () {\n return (key === '');\n }\n // getting part by index, parts[] array as preferable source\n this.part = function (i) {\n while (parts.length <= i && !completed) {\n next(); \t// going on with string processing\n }\n return (i < parts.length) ? parts[i] : null;\n };\n // parsing string till next part\n function next() {\n // string is not yet over\n if (index < key.length) {\n // working until non-digits/digits border\n while (++index) {\n var currentIsDigit = isDigit(key.charAt(index - 1));\n var nextChar = key.charAt(index);\n var currentIsLast = (index === key.length);\n // we reached the border if we're at the last char,\n // or if current and next chars are of different kinds (digit / non-digit)\n var isBorder = currentIsLast ||\n xor(currentIsDigit, isDigit(nextChar));\n if (isBorder) {\n // creating new part\n var partStr = key.slice(from, index);\n parts.push(new Part(partStr, currentIsDigit));\n from = index;\n break;\n }\n }\n // our string is over\n } else {\n completed = true;\n }\n }\n\n /**\n * Creates new Part\n * @param text\n * @param isNumber\n * @constructor\n */\n function Part(text, isNumber) {\n this.isNumber = isNumber;\n this.value = isNumber ? Number(text) : text;\n }\n // cleaning whitespace\n function trim(str) {\n return str.replace(/^\\s+|\\s+$/, \"\");\n }\n }", "function parseObject(_string){\n string = _string.slice(0);\n /*\n Orcbrew has two structures that use the {} syntax\n One uses properties as keys (:property)\n The other uses numbers as indices (0 {0 :value, 1: value} 1 {0: value, 1: value})\n */\n\n if(string[0] === '{') string = string.slice(1);\n else throw new Error('[Object Parser] String must start with {');\n\n //The payload will be an object or an array depending on the value\n let payload;\n if(isNaN(parseInt(_rgxlib.property_or_number.exec(string)[0], 10)))\n payload = {};\n else\n payload = [];\n\n //This loop will iterate through the properties of the object\n //as long as we're not at the end of the object\n objectLoop:\n while(_rgxlib.property_or_number_or_object_close.exec(string)[0] !== '}'){\n let keyLength = 0, valueLength = 0, value;\n\n //Find a key to parse and jump to it\n [string, keyLength] = findKeyOrIndex(string);\n \n //Save key\n let key = string.slice(0, keyLength);\n console.log('Key: ' + key);\n //Jump past key\n string = string.slice(keyLength);\n\n //Slice the colon off of the key\n key = string.slice(1); \n \n //Get value corresponding to key\n [string, valueLength] = findObjectValue(string);\n\n //Evaluate and store value\n [value, string] = parseByType(string.slice(0, valueLength));\n\n //Store value in object or array depending on keytypes\n if (isNaN(parseInt(key, 10))) {\n payload[key] = value;\n }else{\n payload.push(value);\n }\n }\n //Step over last curly brace\n string.slice(string.search(/}/) + 1);\n return [payload, string];\n}", "function parseArray(str) {\n var result = [], value = \"\",\n nstruct = new RegExp(/(\\[)|(\\{)/g),\n estruct = new RegExp(/(\\])|(\\})/g),\n instr = false,\n strch, eov, len, ch, pch,\n depth = 0, i = 0;\n\n // clean up the string\n str = str.replace(/\\s,*/g, \"\");\n str = str.replace(/,\\s*/g, \",\");\n str = str.substring(1, str.length - 1);\n\n len = str.length;\n\n // walk through string and pick up values\n do {\n // get chars\n pch = str.charAt(i - 1);\n ch = str.charAt(i);\n\n // check if string\n if (ch === \"'\" || ch === '\"') {\n // string char found\n if (pch !== \"\\\\\" && ch === strch) {\n // not escaped\n if (instr && ch === strch) {\n // ended a string\n instr = false;\n strch = \"\";\n } else if (!instr) {\n // entering a new string\n instr = true;\n strch = ch;\n }\n }\n }\n\n // new structure - increase depth\n if (nstruct.test(ch) && !instr) {\n depth += 1;\n }\n\n // end of structure - decrease depth\n if (estruct.test(ch) && !instr) {\n depth -= 1;\n }\n\n // end of value flagged\n eov = ((ch === \",\" || estruct.test(ch))\n && !depth // not in a structure\n && !instr); // not in a string\n\n // end of current value - unserialise it and continue\n if (eov || i === len) {\n result.push(util.unserialise(value, json));\n value = \"\";\n } else {\n // add char to current value\n value += ch;\n }\n\n // next char\n i += 1;\n } while (i <= len);\n\n return result;\n }", "function _extractType(type){\n switch(type.kind){\n // u8[] type alias\n case ts.SyntaxKind.ArrayType:\n return \"Vec<u8>\";\n case ts.SyntaxKind.VoidKeyword:\n return \"void\";\n // Strip \"Type\" suffix from the runtime types\n default:\n return polkadotTypes[type.typeName.escapedText.replace(\"Type\", \"\")];\n }\n}", "function detectType(str, t) {\n str = str.replace(/[\\,]/ig, '')\n\n let num = parseFloat(str)\n\n // 28.93\n if (!isNaN(num)) {\n for (let suffix in t.ordinal.suffix) {\n if (str.slice(-suffix.length) === suffix) return ['N', num]\n }\n return ['n', num]\n }\n\n // third\n if (t.ordinal.unit[str] != null) return ['U', t.ordinal.unit[str]]\n\n // tenth\n if (t.ordinal.ten[str]) return ['T', t.ordinal.ten[str]]\n\n // thousandth\n if (t.ordinal.magnitude[str]) return ['M', t.ordinal.magnitude[str]]\n\n // fourty\n if (t.cardinal.ten[str]) return ['t', t.cardinal.ten[str]]\n\n // three\n if (t.cardinal.unit[str] != null) return ['u', t.cardinal.unit[str]]\n\n // thousand\n if (t.cardinal.magnitude[str]) return ['m', t.cardinal.magnitude[str]]\n\n // PI etc\n if (t.constant[str]) return ['c', t.constant[str]]\n\n throw Error('Unknown part `' + str + '`')\n}", "function reconstructString(name){\n\t// if string contains a full stop or other conditions then split\n\t\t// else return string\n\tif(name.indexOf(\".\") > -1){\n\t\tvar splitter = name.split(\".\")\n\t\treturn splitter[0];\n\t} else if (name.indexOf(\"Lt\")){\n\t\tvar splitter = name.split(\"Ltd\")\n\t\treturn splitter[0];\n\t} else if (name.indexOf(\"lt\")){\n\t\tvar splitter = name.split(\"lt\")\n\t\treturn splitter[0];\n\t} else if (name.indexOf(\"lim\")){\n\t\tvar splitter = name.split(\"lim\")\n\t\treturn splitter[0];\n\t} else if (name.indexOf(\"Lim\")) {\n\t\tvar splitter = name.split(\"Lim\")\n\t\treturn splitter[0];\n\t} else{\n\t\treturn name;\n\t}\n}", "function splitSquareBrackets(str) {\n var leftIx = 0, \n rightIx = str.length,\n ix = rightIx,\n level,\n obj = { \n before: '', inside: '', after: ''\n };\n\n // look for left bracket\n while (leftIx < str.length) {\n if (str[leftIx] === '[') {\n break;\n }\n leftIx += 1;\n }\n\n // look for right bracket\n ix = leftIx + 1;\n level = 1;\n while (ix < rightIx) {\n if (str[ix] === ']') {\n level -= 1;\n } else if (str[ix] === '[') {\n level += 1;\n }\n if (level === 0) {\n break;\n }\n ix += 1;\n }\n // if we did not find the right bracket (ix === rightIx), \n // or the brackets enclose nothing (ix - leftIx === 1),\n // or the brackets enclose everything, then do not split\n if (ix === rightIx || (ix - leftIx === 1) || \n ((leftIx === 0) && (ix + 1 === rightIx))) {\n leftIx = rightIx;\n } else {\n rightIx = ix;\n }\n\n obj.before = str.substr(0, leftIx);\n obj.inside = str.substr(leftIx + 1, rightIx - leftIx - 1); \n obj.after = str.substr(rightIx+1);\n return obj;\n }", "function parse ( type ) {\n\t\treturn isArray ( type ) ? asArray ( type ) : asObject ( type );\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert github issue state to agm syntax
function convertState(state) { return (state === 'closed' ? 'Done' : 'New'); }
[ "function resolveState(state) {\n var retStr = \"\";\n if (state == \"Unseen\") {\n retStr += \"and G = \\'\\' \";\n } else if (state == \"Denied\") {\n retStr += \"and G = \\'n\\' \";\n } else if (state == \"Approved\") {\n retStr += \"and G = \\'y\\' and H != \\'y\\' \";\n } else if (state == \"Paid\") {\n retStr += \"and G = \\'y\\' and H = \\'y\\' \";\n } \n return retStr;\n}", "function convertIssue(owner, repo, raw) {\n\tconst time_to_fix = (raw.created_at && raw.closed_at) ?\n\t\t\tmoment(raw.closed_at).diff(moment(raw.created_at)) :\n\t\t\tnull;\n\treturn {\n\t\tid: raw.id,\n\t\towner: owner,\n\t\trepo: repo,\n\t\tstate: raw.state,\n\t\ttitle: raw.title,\n\t\tnumber: raw.number,\n\t\turl: raw.url,\n\t\tlocked: raw.locked,\n\t\tcomments: raw.comments,\n\t\tcreated_at: enhanceDate(raw.created_at),\n\t\tupdated_at: enhanceDate(raw.updated_at),\n\t\tclosed_at: enhanceDate(raw.closed_at),\n\t\tauthor_association: raw.author_association,\n\t\tuser: raw.user.login,\n\t\tbody: raw.body,\n\t\tlabels: raw.labels.map(label => label.name),\n\t\tis_pullrequest: !!raw.pull_request,\n\t\tassignees: !raw.assignees ? null : raw.assignees.map(a => a.login),\n\t\treviewers: !raw.reviewers ? null : raw.reviewers.map(a => a.login),\n\t\treactions: !raw.reactions ? null : {\n\t\t\ttotal: raw.reactions.total_count,\n\t\t\tupVote: raw.reactions['+1'],\n\t\t\tdownVote: raw.reactions['-1'],\n\t\t\tlaugh: raw.reactions.laugh,\n\t\t\thooray: raw.reactions.hooray,\n\t\t\tconfused: raw.reactions.confused,\n\t\t\theart: raw.reactions.hearts,\n\t\t},\n\t\ttime_to_fix: time_to_fix,\n\t};\n}", "function pr_to_issue(pr) {\n\treturn {\n\t\tsynopsis: pr.synopsis,\n\t\tstate: pr.state,\n\t\thidden: pr.confidential === 'yes'\n\t};\n}", "function Issue(issue) {\n\n var sha = /^--- Pull Request #\\d*? on commit (\\b[0-9a-f]{40}\\b) ---/;\n\n var match = sha.exec(issue.body);\n\n issue.sha = null;\n if(match) {\n issue.sha = match[1];\n issue.body = issue.body.replace(match[0], '');\n }\n\n return issue;\n}", "function drupalOrgIssueStatus(status) {\n switch (status) {\n case '1':\n return 'Active';\n case '2':\n return 'Fixed';\n case '3':\n return 'Closed (duplicate)';\n case '4':\n return 'Postponed';\n case '5':\n return \"Closed (won't fix)\";\n case '6':\n return 'Closed (works as designed)';\n case '7':\n return 'Closed (fixed)';\n case '8':\n return 'Needs review';\n case '13':\n return 'Needs work';\n case '14':\n return 'Reviewed & tested by the community';\n case '15':\n return 'Patch (to be ported)';\n case '16':\n return 'Postponed (maintainer needs more info)';\n case '18':\n return 'Closed (cannot reproduce)';\n }\n}", "function buildStatusToGithub(e, project){\n // Only set state of build when is a push or PR.\n if ([eventTypePush, eventTypePullRequest].includes(e.cause.event.type)) {\n // Set correct status\n var state = githubStateFailure\n if (e.cause.trigger == buildStatusSuccess) {\n state = githubStateSuccess\n }\n // Set the status on github.\n updateGHPRStateJob = setGithubCommitStatus(e, project, state)\n updateGHPRStateJob.run()\n } else {\n console.log(`Build finished with ${e.cause.trigger} state`)\n }\n}", "function abbrState(input, to){\n var states = [\n ['All States', 'ALL'],\n ['Arizona', 'AZ'],\n ['Alabama', 'AL'],\n ['Alaska', 'AK'],\n ['Arizona', 'AZ'],\n ['Arkansas', 'AR'],\n ['California', 'CA'],\n ['Colorado', 'CO'],\n ['Connecticut', 'CT'],\n ['Delaware', 'DE'],\n ['Florida', 'FL'],\n ['Georgia', 'GA'],\n ['Hawaii', 'HI'],\n ['Idaho', 'ID'],\n ['Illinois', 'IL'],\n ['Indiana', 'IN'],\n ['Iowa', 'IA'],\n ['Kansas', 'KS'],\n ['Kentucky', 'KY'],\n ['Kentucky', 'KY'],\n ['Louisiana', 'LA'],\n ['Maine', 'ME'],\n ['Maryland', 'MD'],\n ['Massachusetts', 'MA'],\n ['Michigan', 'MI'],\n ['Minnesota', 'MN'],\n ['Mississippi', 'MS'],\n ['Missouri', 'MO'],\n ['Montana', 'MT'],\n ['Nebraska', 'NE'],\n ['Nevada', 'NV'],\n ['New Hampshire', 'NH'],\n ['New Jersey', 'NJ'],\n ['New Mexico', 'NM'],\n ['New York', 'NY'],\n ['North Carolina', 'NC'],\n ['North Dakota', 'ND'],\n ['Ohio', 'OH'],\n ['Oklahoma', 'OK'],\n ['Oregon', 'OR'],\n ['Pennsylvania', 'PA'],\n ['Rhode Island', 'RI'],\n ['South Carolina', 'SC'],\n ['South Dakota', 'SD'],\n ['Tennessee', 'TN'],\n ['Texas', 'TX'],\n ['Utah', 'UT'],\n ['Vermont', 'VT'],\n ['Virginia', 'VA'],\n ['Washington', 'WA'],\n ['West Virginia', 'WV'],\n ['Wisconsin', 'WI'],\n ['Wyoming', 'WY'],\n ];\n\n if (to == 'abbr'){\n input = input.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n for(i = 0; i < states.length; i++){\n if(states[i][0] == input){\n return(states[i][1]);\n }\n }\n } else if (to == 'name'){\n input = input.toUpperCase();\n for(i = 0; i < states.length; i++){\n if(states[i][1] == input){\n return(states[i][0]);\n }\n }\n }\n}", "parseState(s) {\n switch (s) {\n case \"\":\n return Profile.CodeState.COMPILED;\n case \"~\":\n return Profile.CodeState.OPTIMIZABLE;\n case \"*\":\n return Profile.CodeState.OPTIMIZED;\n }\n throw new Error(\"unknown code state: \" + s);\n }", "function abbrState(input, to){\n \n var states = [\n ['Arizona', 'AZ'],\n ['Alabama', 'AL'],\n ['Alaska', 'AK'],\n ['Arizona', 'AZ'],\n ['Arkansas', 'AR'],\n ['California', 'CA'],\n ['Colorado', 'CO'],\n ['Connecticut', 'CT'],\n ['Delaware', 'DE'],\n ['Florida', 'FL'],\n ['Georgia', 'GA'],\n ['Hawaii', 'HI'],\n ['Idaho', 'ID'],\n ['Illinois', 'IL'],\n ['Indiana', 'IN'],\n ['Iowa', 'IA'],\n ['Kansas', 'KS'],\n ['Kentucky', 'KY'],\n ['Kentucky', 'KY'],\n ['Louisiana', 'LA'],\n ['Maine', 'ME'],\n ['Maryland', 'MD'],\n ['Massachusetts', 'MA'],\n ['Michigan', 'MI'],\n ['Minnesota', 'MN'],\n ['Mississippi', 'MS'],\n ['Missouri', 'MO'],\n ['Montana', 'MT'],\n ['Nebraska', 'NE'],\n ['Nevada', 'NV'],\n ['New Hampshire', 'NH'],\n ['New Jersey', 'NJ'],\n ['New Mexico', 'NM'],\n ['New York', 'NY'],\n ['North Carolina', 'NC'],\n ['North Dakota', 'ND'],\n ['Ohio', 'OH'],\n ['Oklahoma', 'OK'],\n ['Oregon', 'OR'],\n ['Pennsylvania', 'PA'],\n ['Rhode Island', 'RI'],\n ['South Carolina', 'SC'],\n ['South Dakota', 'SD'],\n ['Tennessee', 'TN'],\n ['Texas', 'TX'],\n ['Utah', 'UT'],\n ['Vermont', 'VT'],\n ['Virginia', 'VA'],\n ['Washington', 'WA'],\n ['West Virginia', 'WV'],\n ['Wisconsin', 'WI'],\n ['Wyoming', 'WY'],\n ];\n\n if (to == 'abbr'){\n input = input.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n for(i = 0; i < states.length; i++){\n if(states[i][0] == input){\n return(states[i][1]);\n }\n } \n } else if (to == 'name'){\n input = input.toUpperCase();\n for(i = 0; i < states.length; i++){\n if(states[i][1] == input){\n return(states[i][0]);\n }\n } \n }\n}", "function briefState(s) {\n return `\\\nA=${toHex2(s.a)} \\\nB=${toHex2(s.b)} \\\nSP=${toHex2(s.sp)} \\\nPSW=${toHex2(s.psw)} \\\n${s.cy ? 'C' : 'c'}${s.ov ? 'O' : 'o'}${s.ac ? 'A' : 'a'} \\\nDPTR=${toHex4(s.dptr)} \\\nR:${s.regs.map((v, x) => toHex2(v) + (x === 3 ? ' ' : '')).join(' ')}`;\n}", "function convertState(name) {\n let abbreviation = states\n .filter(state => name === state.name)\n .map(state => state.abbr);\n return abbreviation;\n}", "function getState(issueOrRequest) {\n if (issueOrRequest.state == 'open')\n return 'open';\n else if (issueOrRequest.merged_at)\n return 'merged';\n else\n return 'closed';\n }", "function badgeMarkdown() {\n return function(repo) {\n if (repo === undefined) { return \"\"; }\n var scheme = window.location.protocol;\n var host = window.location.host;\n var path = repo.host+'/'+repo.owner+'/'+repo.name;\n return '[![Build Status]('+scheme+'//'+host+'/api/badge/'+path+'/status.svg?branch=master)]('+scheme+'//'+host+'/'+path+')'\n }\n }", "function parseInternalRepoLink() {\n let url = $ctrl.internalScmRepositoryUrl;\n let protocol = url.split('://')[0];\n let base = url.split('://')[1].split('/')[0];\n let project = url.split(base + (['https', 'http'].includes(protocol) ? '/gerrit/' : '/'))[1];\n return 'https://' + base + '/gerrit/gitweb?p=' + project + ';a=summary';\n }", "function formatNotes(data){\n\treturn data.map(commit =>\n\t\t`- [:information_source:](${commit.html_url}) - ${commit.commit.message} ${commit.author ? `- [${commit.author.login}](${commit.author.html_url})` : ''}`\n\t).join('\\n')\n}", "parseMarkdownStories(source, recursive) {\n var lines = source.split(/\\r?\\n/)\n var stories = lines.map((ea, index) => {\n var result = Strings.matchDo(/^## +(.*)/, ea, title => \n new Project({isProject: true, project: title, stories: [], comments: []}))\n if (!result) result = Strings.matchDo(/^(- )(.*)/, ea, (prefix, issue) => {\n var title, rest, state;\n Strings.matchDo(/ ((#|(?:[0-9]+P)|(?:\\?+P)).*)$/, issue, (a) => {\n rest = a\n })\n if (!title) title = issue.replace(rest, \"\")\n var number;\n var labels = []\n var tags = []\n if (rest) {\n Strings.matchDo(/(#([0-9]+))/, rest, (a,b) => {\n rest = rest.replace(a,\"\") \n number = b\n })\n }\n if (rest) {\n Strings.matchDo(/(#((open)|(closed)))/, rest, (a,b) => {\n rest = rest.replace(a,\"\") \n state = b\n })\n }\n if (rest) {\n // lively.notify(\"rest \" + rest)\n Strings.matchAllDo(/(#[A-Za-z]+)/, rest, (tag) => {\n var label = this.tagToLabel(tag)\n if (label && !labels.includes(label)) {\n labels.push(label)\n }\n tags.push(tag)\n\n })\n tags.forEach(tag => {\n // lively.notify(\"replace tag \" + tag)\n rest = rest.replace(new RegExp(\" ?\" + tag, \"g\"),\"\")\n })\n\n }\n\n return new Story({\n isStory: true,\n title: title.replace(/ *$/,\"\"), \n rest: rest && rest.replace(/ *$/,\"\"),\n number: number ? parseInt(number) : undefined,\n state: state,\n labels: labels,\n items: []\n })\n })\n if (!result) result = Strings.matchDo(/^ +(- .*)/, ea, item => \n new Item({isItem: true, item: item}))\n \n if (!result) result = new Comment({isComment: true, comment: ea})\n return result\n })\n \n // now, make sense of the parsing...\n var lastProject\n var lastStory\n \n stories.forEach(ea => {\n if (ea.isProject) {\n lastProject = ea;\n lastStory = null;\n }\n if (ea.isStory) {\n lastStory = ea\n }\n if (ea.isStory && lastProject) {\n lastProject.stories.push(ea)\n lastStory.project = lastProject.project\n }\n if (ea.isItem && lastStory) {\n ea.story = lastStory; // it is not a tree any more...\n lastStory.items.push(ea)\n }\n if (ea.isComment && lastProject) {\n ea.project = lastProject\n lastProject.comments.push(ea)\n }\n if (ea.comment == \"<!--NoProject-->\") {\n ea.project = undefined;\n lastProject = undefined\n }\n })\n if (recursive) {\n stories = stories.filter(ea => \n ea.isProject ||\n (ea.isStory && !ea.project) ||\n (ea.isItem && !ea.story) ||\n ea.isComment && !ea.project\n ); // get rid of the global itmes\n }\n return stories\n }", "toAST(txt) {\r\n return new MarkdownAST(txt)\r\n }", "function abbrStateToName(state){\n state = state.toUpperCase();\n for(let i = 0; i < stateNames.length; i++){\n if(stateNames[i][1] === state){\n return(stateNames[i][0]);\n }\n }\n}", "ChangeToState(stateName) {\n if (this.state.indexOf(stateName) == -1) return 'Not Valid State Name';\n else this.group = this.file.findRows(stateName,'State');\n return this.group;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
solve function for challege 1 default challenge Find the shortest path from start to exit of the grid.
function solve(){ var grid = cGrid; var point = { row: 0, col: 0 }; stepCount = 0; //resetStep exitRow = grid.length-1; var minDistance = -1; //2. Walk through grid, loop each step do{ let nextSteps = []; let step = {}; for( var direct in directions){ step = movable(point, grid, direct); if(step.canMove){ step.direction = direct; nextSteps.push(step); } } //If no direction walkable, exit if(nextSteps.length == 0){ noExit = true; break; } //3. sort distance and take the shortest direction nextSteps.sort((a, b) => (a.minDistance - b.minDistance)); //mark current step and make the move point = markElement(point, grid, nextSteps); //5. test exit condition if (point.row == exitRow && point.col == exitCol){ exitReached = true; grid[exitRow][exitCol] = colValues.PATH; document.getElementById(`${exitRow}:${exitCol}`).setAttribute("blockValue", "step"); stepCount ++; break; } } while(true); writeResults(); }
[ "function solvePath(){\n var grid = cGrid;\n stepCount = 0; //resetStep\n startRow = 0;\n exitRow = grid.length-1;\n var point = {\n row: 0,\n col: 0\n };\n\n //1. Loop start row , find the start col and mark\n let startCol = point.col;\n for ( ;startCol < grid[startRow].length; startCol++){\n noEntry = true;\n if (grid[startRow][startCol] == colValues.OPEN){\n point.row = startRow;\n point.col = startCol;\n noEntry = false;\n break;\n }\n }\n if(noEntry){\n writeResults();\n return;\n }\n \n //2. loop and find open path and mark as walked\n do {\n let step = {};\n for( var direct in directions){\n step = movable(point, grid, direct);\n if(step.canMove && step.colValue == colValues.OPEN){\n //mark current step as walked , move and add step count\n grid[point.row][point.col] = colValues.PATH;\n document.getElementById(`${point.row}:${point.col}`).setAttribute(\"blockValue\", \"step\");\n point = getNextPoint(point, direct);\n stepCount ++;\n break;\n }\n }\n //3. Test exit condition\n if ( point.row == exitRow){\n exitReached = true;\n grid[point.row][point.col] = colValues.PATH;\n document.getElementById(`${point.row}:${point.col}`).setAttribute(\"blockValue\", \"step\");\n break;\n }\n } while(true);\n\n writeResults();\n}", "function solvePath() {\n let r = 19\n let c = 19\n shortestPath.push(board[r][c])\n while (true) {\n let parent = board[r][c].parentNode\n shortestPath.unshift(parent);\n r = parent.r\n c = parent.c\n if (r == 0 && c == 0) {\n return\n }\n }\n}", "function solve() {\n\n xLoc = xQueue.shift();\n yLoc = yQueue.shift();\n\n // Check if finished\n\n if (xLoc > 0) {\n if (tiles[xLoc - 1][yLoc].state == 'f') {\n pathFound = true;\n }\n }\n if (xLoc < tileColumnCount - 1) {\n if (tiles[xLoc + 1][yLoc].state == 'f') {\n pathFound = true;\n }\n }\n if (yLoc > 0) {\n if (tiles[xLoc][yLoc - 1].state == 'f') {\n pathFound = true;\n }\n }\n if (yLoc < tileRowCount - 1) {\n if (tiles[xLoc][yLoc + 1].state == 'f') {\n pathFound = true;\n }\n }\n\n // Check empty neighbors\n\n if (xLoc > 0) {\n if (tiles[xLoc - 1][yLoc].state == 'e') {\n xQueue.push(xLoc - 1);\n yQueue.push(yLoc);\n tiles[xLoc - 1][yLoc].state = tiles[xLoc][yLoc].state + 'l';\n }\n }\n if (xLoc < tileColumnCount - 1) {\n if (tiles[xLoc + 1][yLoc].state == 'e') {\n xQueue.push(xLoc + 1);\n yQueue.push(yLoc);\n tiles[xLoc + 1][yLoc].state = tiles[xLoc][yLoc].state + 'r';\n }\n }\n if (yLoc > 0) {\n if (tiles[xLoc][yLoc - 1].state == 'e') {\n xQueue.push(xLoc);\n yQueue.push(yLoc - 1);\n tiles[xLoc][yLoc - 1].state = tiles[xLoc][yLoc].state + 'u';\n }\n }\n if (yLoc < tileRowCount - 1) {\n if (tiles[xLoc][yLoc + 1].state == 'e') {\n xQueue.push(xLoc);\n yQueue.push(yLoc + 1);\n tiles[xLoc][yLoc + 1].state = tiles[xLoc][yLoc].state + 'd';\n }\n }\n \n\n // Output the path\n if (xQueue.length <= 0 || pathFound) {\n clearInterval(solveInterval);\n finalOutput();\n }\n \n}", "function findPath(grid, pathStart, pathEnd)\n{\n // shortcuts for speed\n\tvar\tabs = Math.abs;\n\tvar\tmax = Math.max;\n\tvar\tpow = Math.pow;\n\tvar\tsqrt = Math.sqrt;\n\n\tif(!grid) return;\n\t// keep track of the grid dimensions\n\t// Note that this A-star implementation expects the grid array to be square:\n\t// it must have equal height and width. If your game grid is rectangular,\n\t// just fill the array with dummy values to pad the empty space.\n\tvar gridWidth = grid[0].length;\n\tvar gridHeight = grid.length;\n\tvar gridSize =\tgridWidth * gridHeight;\n\n\n function ManhattanDistance(Point, Goal)\n {\t// linear movement - no diagonals - just cardinal directions (NSEW)\n return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n }\n\n function Neighbours(x, y)\n {\n var\tN = y - 1,\n S = y + 1,\n E = x + 1,\n\t\t\t\tW = x - 1,\n myN = N > -1 && canWalkHere(x, N, 'd'),\n myS = S < gridHeight && canWalkHere(x, S, 'u'),\n myE = E < gridWidth && canWalkHere(E, y, 'l'),\n myW = W > -1 && canWalkHere(W, y, 'r'),\n result = [];\n if(myN)\n result.push({x:x, y:N});\n if(myE)\n result.push({x:E, y:y});\n if(myS)\n result.push({x:x, y:S});\n if(myW)\n result.push({x:W, y:y});\n //findNeighbours(myN, myS, myE, myW, N, S, E, W, result);\n return result;\n }\n // returns boolean value (grid cell is available and open)\n function canWalkHere(x, y, direction)\n {\n return ((grid[x] != null) &&\n (grid[x][y] != null) &&\n (grid[x][y].IsDug(direction)));\n\t}\n\n\t// which heuristic should we use?\n\t// default: no diagonals (Manhattan)\n\tvar distanceFunction = ManhattanDistance;\n\tvar findNeighbours = function(){}; // empty\n\n // Node function, returns a new object with Node properties\n\t// Used in the calculatePath function to store route costs, etc.\n\tfunction Node(Parent, Point)\n\t{\n\t\tvar newNode = {\n\t\t\t// pointer to another Node object\n\t\t\tParent:Parent,\n\t\t\t// array index of this Node in the grid linear array\n\t\t\tvalue:Point.x + (Point.y * gridWidth),\n\t\t\t// the location coordinates of this Node\n\t\t\tx:Point.x,\n\t\t\ty:Point.y,\n\t\t\t// the distanceFunction cost to get\n\t\t\t// TO this Node from the START\n\t\t\tf:0,\n\t\t\t// the distanceFunction cost to get\n\t\t\t// from this Node to the GOAL\n\t\t\tg:0\n\t\t};\n\n\t\treturn newNode;\n\t}\n\n\t// Path function, executes AStar algorithm operations\n\tfunction calculatePath()\n\t{\n\t\t// create Nodes from the Start and End x,y coordinates\n\t\tvar\tmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\n\t\tvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\n\t\t// create an array that will contain all grid cells\n\t\tvar AStar = new Array(gridSize);\n\t\t// list of currently open Nodes\n\t\tvar Open = [mypathStart];\n\t\t// list of closed Nodes\n\t\tvar Closed = [];\n\t\t// list of the final output array\n\t\tvar result = [];\n\t\t// reference to a Node (that is nearby)\n\t\tvar myNeighbours;\n\t\t// reference to a Node (that we are considering now)\n\t\tvar myNode;\n\t\t// reference to a Node (that starts a path in question)\n\t\tvar myPath;\n\t\t// temp integer variables used in the calculations\n\t\tvar length, max, min, i, j;\n\t\t// iterate through the open list until none are left\n\t\twhile(length = Open.length)\n\t\t{\n\t\t\tmax = gridSize;\n\t\t\tmin = -1;\n\t\t\tfor(i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\tif(Open[i].f < max)\n\t\t\t\t{\n\t\t\t\t\tmax = Open[i].f;\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// grab the next node and remove it from Open array\n\t\t\tmyNode = Open.splice(min, 1)[0];\n\t\t\t// is it the destination node?\n\t\t\tif(myNode.value === mypathEnd.value)\n\t\t\t{\n\t\t\t\tmyPath = Closed[Closed.push(myNode) - 1];\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tresult.push([myPath.x, myPath.y]);\n\t\t\t\t}\n\t\t\t\twhile (myPath = myPath.Parent);\n\t\t\t\t// clear the working arrays\n\t\t\t\tAStar = Closed = Open = [];\n\t\t\t\t// we want to return start to finish\n\t\t\t\tresult.reverse();\n\t\t\t}\n\t\t\telse // not the destination\n\t\t\t{\n\t\t\t\t// find which nearby nodes are walkable\n\t\t\t\tmyNeighbours = Neighbours(myNode.x, myNode.y);\n\t\t\t\t// test each one that hasn't been tried already\n\t\t\t\tfor(i = 0, j = myNeighbours.length; i < j; i++)\n\t\t\t\t{\n\t\t\t\t\tmyPath = Node(myNode, myNeighbours[i]);\n\t\t\t\t\tif (!AStar[myPath.value])\n\t\t\t\t\t{\n\t\t\t\t\t\t// estimated cost of this particular route so far\n\t\t\t\t\t\tmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n\t\t\t\t\t\t// estimated cost of entire guessed route to the destination\n\t\t\t\t\t\tmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\t\t\t\t\t\t// remember this new path for testing above\n\t\t\t\t\t\tOpen.push(myPath);\n\t\t\t\t\t\t// mark this node in the grid graph as visited\n\t\t\t\t\t\tAStar[myPath.value] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// remember this route as having no more untested options\n\t\t\t\tClosed.push(myNode);\n\t\t\t}\n\t\t} // keep iterating until until the Open list is empty\n\t\treturn result;\n }\n\n return calculatePath();\n}", "solve(){\r\n\t\tif (this.solutionCount >= this.maxSolutions){\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfor (let y = 0; y < constants.GRID_SIZE; y++){\r\n\t\t\tfor (let x = 0; x < constants.GRID_SIZE; x++){\r\n\t\t\t\tif (this.grid[y][x] == constants.BLANK){\r\n\t\t\t\t\tfor (var i of this.nextNumber()){\r\n\t\t\t\t\t\tif (this.rules.isValid(this.grid, x, y, i)){\r\n\t\t\t\t\t\t\tthis.grid[y][x] = i;\r\n\t\t\t\t\t\t\tthis.lastTry = utils.toIndex(x, y);\r\n\t\t\t\t\t\t\tthis.solve();\r\n\t\t\t\t\t\t\tthis.grid[y][x] = constants.BLANK;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.solutionCount++;\r\n\t\tthis.solutions.push(this.snapshot(this.grid));\r\n\t}", "findPath() {\n let openList = [this.auxMap[this.S[0]][this.S[1]]];\n let closedList = [];\n\n while (openList.length > 0) {\n openList.forEach(element => element.f = element.distanceFromStart + element.h);\n openList.sort((a, b) => (a.f < b.f) ? 1 : -1);\n let currentNode = openList.pop();\n if (currentNode.x == this.F[0] && currentNode.y == this.F[1]) {\n this.auxMap[currentNode.x][currentNode.y] = currentNode;\n break;\n }\n this.auxMap[currentNode.x][currentNode.y] = currentNode;\n let adjacentNodes = this.map.getAdjacentNodes([currentNode.x, currentNode.y]);\n for (let i in adjacentNodes) {\n let successor_current_cost = currentNode.distanceFromStart + this.cost(currentNode.x, currentNode.y);\n let adj = this.auxMap[adjacentNodes[i][0]][adjacentNodes[i][1]];\n if (openList.map(x => { return x.id; }).indexOf(adj.id) != -1 && adj.distanceFromStart <= successor_current_cost)\n continue;\n else if (closedList.map(x => { return x.id; }).indexOf(adj.id) != -1) {\n if (adj.distanceFromStart <= successor_current_cost)\n continue;\n let index = closedList.map(x => { return x.id; }).indexOf(adj.id);\n closedList.splice(index, 1);\n openList.unshift(adj);\n }\n else {\n adj.h = this.heuristic(adj.x, adj.y, this.F);\n openList.unshift(adj);\n }\n adj.distanceFromStart = successor_current_cost;\n adj.parent = currentNode;\n this.auxMap[adj.x][adj.y] = adj;\n }\n closedList.unshift(currentNode);\n }\n\n let c = [this.F[0], this.F[1]];\n while (this.auxMap[c[0]][c[1]].parent != null) {\n this.path.unshift([c[0], c[1]]);\n let x = this.auxMap[c[0]][c[1]].parent.x;\n let y = this.auxMap[c[0]][c[1]].parent.y;\n c[0] = x;\n c[1] = y;\n }\n this.path.unshift([this.S[0], this.S[1]]);\n }", "function FindRoute( mapGrid) {\n \n var self = this;\n \n self.mapGrid = mapGrid; \n self.mapGrid.clearAllPathStep();\n\n\n /**\n * Given the begining and ending cells, return the route as an array of cells \n */\n self.getRoute = function(originCell, goalCell) {\n \n originCell.isOrigin = true;\n goalCell.isGoal = true;\n \n var routeStep = getRouteSteps(originCell, goalCell);\n routeStep--; // Point to next step\n \n var route = [];\n var cell = originCell;\n \n // Loop until the cell we're in matches the ending cell\n //\n while (routeStep > 0 && ! cell.isGoal ) {\n \n // Save the children of cell\n var northCell = self.mapGrid.cellNorth( cell );\n var eastCell = self.mapGrid.cellEast( cell );\n var southCell = self.mapGrid.cellSouth( cell );\n var westCell = self.mapGrid.cellWest( cell ); \n \n if ( northCell.pathStep === routeStep ) {\n \n route.push(northCell);\n cell = northCell;\n }\n else if ( eastCell.pathStep === routeStep ) {\n \n route.push(eastCell);\n cell = eastCell;\n }\n else if ( southCell.pathStep === routeStep ) {\n \n route.push(southCell);\n cell = southCell;\n }\n else if ( westCell.pathStep === routeStep ) {\n \n route.push(westCell);\n cell = westCell;\n }\n routeStep--;\n }\n return route;\n }\n function getRouteSteps(originCell, goalCell) {\n \n console.log('FindRoute.getRoute start originCell=',originCell);\n console.log('FindRoute.getRoute start goalCell=',goalCell);\n\n \n self.step = 1;\n\n var foundStep = 0;\n var queue = [];\n \n goalCell.pathStep = 0;\n \n // Starts at the end and searches to begining\n queue.push(goalCell); // Initialize que\n \n \n while ( foundStep === 0 && queue.length > 0 ) {\n \n // Get current cell to check\n var cell = queue.shift();\n \n console.log('FindRoute.getRoute loop cell=',cell);\n \n // Save the children of cell\n var northCell = self.mapGrid.cellNorth( cell );\n var eastCell = self.mapGrid.cellEast( cell );\n var southCell = self.mapGrid.cellSouth( cell );\n var westCell = self.mapGrid.cellWest( cell ); \n \n if ( northCell \n && ! northCell.isGoal \n && ! northCell.isWall() \n && northCell.pathStep === null ) {\n \n queue.push( northCell );\n \n if ( northCell.isOrigin ) {\n \n foundStep = self.step;\n }\n else {\n \n northCell.pathStep = self.step;\n }\n }\n if ( eastCell \n && ! eastCell.isWall() \n && ! eastCell.isGoal \n && eastCell.pathStep === null) {\n \n queue.push( eastCell );\n \n if ( eastCell.isOrigin ) {\n \n foundStep = self.step;\n }\n else {\n \n eastCell.pathStep = self.step;\n }\n }\n if ( southCell \n && ! southCell.isGoal \n && ! southCell.isWall() \n && southCell.pathStep === null ) {\n\n queue.push( southCell );\n \n if ( southCell.isOrigin ) {\n \n foundStep = self.step;\n }\n else {\n \n southCell.pathStep = self.step;\n }\n }\n if ( westCell \n && ! westCell.isGoal \n && ! westCell.isWall() \n && westCell.pathStep === null ) {\n\n queue.push( westCell );\n \n if ( westCell.isOrigin ) {\n \n foundStep = self.step;\n }\n else {\n \n westCell.pathStep = self.step;\n }\n }\n\n self.step++;\n console.log('FindRoute.getRoute loop mapGrid.dump()=' + self.mapGrid.dump());\n } \n return foundStep;\n }\n}", "GetClosestPath(grid)\n {\n //Get start end tile\n let start_end = grid.GetStartAndEndTile();\n\n let start_response = this.AStarPathFind(grid.GetTileArray(), start_end.start.GetVec(), start_end.end.GetVec());\n\n start_response.from_start = true;\n\n //Check to see if the response is a valid path, if so return it\n if (start_response.valid) return start_response;\n\n //check to see if starting from the end yields a closer result\n let end_response = this.AStarPathFind(grid.GetTileArray(), start_end.end.GetVec(), start_end.start.GetVec());\n\n end_response.from_start = false;\n\n //Return if the either path is null\n if (!start_response.path || !start_response.path[0] ) return end_response;\n if (!end_response.path || !end_response.path[0]) return start_response;\n\n //return the path closer to the goal\n return (start_response.path[0].distance_to_goal <= end_response.path[0].distance_to_goal) ? start_response : end_response;\n }", "solution() {\n if (!this.isSolvable()) return null;\n\n let sol = this.finalSearchNode;\n let path = [sol];\n\n // Traverse backwards through the known solution and store it\n while (sol.previous !== null) {\n path.push(sol.previous);\n sol = sol.previous;\n }\n\n // Traverse backwards through the path and print out the solution\n console.log(`Minimum number of moves = ${this.finalSearchNode.moves}`);\n for (let i = path.length - 1; i >= 0; i--) {\n console.log();\n console.log(`Move #${path[i].moves}`);\n path[i].board.string();\n }\n }", "calcBestWay(_lin, _col) {\n // Variaveis de controle\n let menorValHeuristico = 0; // Armazena o menor valor heuristico entre os vizinhos\n let menorLin = -1, menorCol = -1; // Armazenam as cordenadas do filho com menor valor heuristico\n\n let valorHeuristico; // Armazena a distancia do vertice filho para o destino\n\n // Valor heuristico do vertice atual(aquele que eh passado por parametro)\n let valorHeuristicoAtual = this.calcDestDistance(_lin, _col);\n\n // Os if's a seguir sempre checam se o existe um filho na direcao desejada(DIREITA, BAIXO, ESQUERDA, CIMA)\n // e tambem se esse filho nao eh um obstaculo\n\n // Filho da DIREITA\n if( (_col+1 >= 0 && _col+1 < this.map.dimension.col) && \n (this.map.fullMap[_lin][_col+1] != \"-\") && !this.alreadyVisited(_lin, _col+1)) {\n // Calcula o valor heuristico do vertice filho\n valorHeuristico = this.calcDestDistance(_lin, _col+1);\n\n // Checa se o valor do filho eh menor que o valor do vertice atual\n if(valorHeuristico < valorHeuristicoAtual) {\n // Checa se eh o menor valor dentre os demais filhos\n if(menorValHeuristico == 0 || valorHeuristico < menorValHeuristico) {\n menorValHeuristico = valorHeuristico;\n menorLin = _lin;\n menorCol = _col+1;\n } \n }\n }\n // Filho de BAIXO\n if( (_lin+1 >= 0 && _lin+1 < this.map.dimension.lin) && \n (this.map.fullMap[_lin+1][_col] != \"-\") && !this.alreadyVisited(_lin+1, _col)) {\n // Calcula o valor heuristico do vertice filho\n valorHeuristico = this.calcDestDistance(_lin+1, _col);\n\n // Checa se o valor do filho eh menor que o valor do vertice atual\n if(valorHeuristico < valorHeuristicoAtual) {\n // Checa se eh o menor valor dentre os demais filhos\n if(menorValHeuristico == 0 || valorHeuristico < menorValHeuristico) {\n menorValHeuristico = valorHeuristico;\n menorLin = _lin+1;\n menorCol = _col;\n } \n }\n }\n // Filho da ESQUERDA\n if( (_col-1 >= 0 && _col-1 < this.map.dimension.col) && \n (this.map.fullMap[_lin][_col-1] != \"-\") && !this.alreadyVisited(_lin, _col-1)) {\n // Calcula o valor heuristico do vertice filho\n valorHeuristico = this.calcDestDistance(_lin, _col-1);\n\n // Checa se o valor do filho eh menor que o valor do vertice atual\n if(valorHeuristico < valorHeuristicoAtual) {\n // Checa se eh o menor valor dentre os demais filhos\n if(menorValHeuristico == 0 || valorHeuristico < menorValHeuristico) {\n menorValHeuristico = valorHeuristico;\n menorLin = _lin;\n menorCol = _col-1;\n }\n }\n }\n // Filho de CIMA\n if( (_lin-1 >= 0 && _lin-1 < this.map.dimension.lin) && \n (this.map.fullMap[_lin-1][_col] != \"-\") && !this.alreadyVisited(_lin-1, _col)) {\n // Calcula o valor heuristico do vertice filho\n valorHeuristico = this.calcDestDistance(_lin-1, _col);\n\n // Checa se o valor do filho eh menor que o valor do vertice atual\n if(valorHeuristico < valorHeuristicoAtual) {\n // Checa se eh o menor valor dentre os demais filhos\n if(menorValHeuristico == 0 || valorHeuristico < menorValHeuristico) {\n menorValHeuristico = valorHeuristico;\n menorLin = _lin-1;\n menorCol = _col;\n } \n }\n }\n\n // Retorna as coordenadas do vizinho com menor valor heuristico em relacao ao vertice atual\n // Se n encontrar um com valor menor que o atual retorna (lim: -1, col: -1).\n return {\n lin: menorLin,\n col: menorCol,\n }\n }", "function findShortestPath() {\n console.log(\"finding shortest path\");\n // a knight can only make 8 different moves, represented by the combination of these two arrays\n var row = [2, 2, -2, -2, 1, 1, -1, -1];\n var col = [-1, 1, 1, -1, 2, -2, 2, -2];\n\n // dictionary which tracks which cells have been visited while performing BFS\n var visited = {};\n\n // queue which tracks cells which need to be looked at\n var queue = new Queue();\n queue.push(start);\n\n // search for the destination until it is found or we run out of cells to look at\n while (!queue.isEmpty()) {\n var currentNode = queue.pop();\n\n // made it to the destination\n if (currentNode.x == end.x && currentNode.y == end.y) {\n console.log(\"found the destination\");\n\n // highlight and mark the path for the user\n displayPathTo(currentNode);\n\n // return the number of hops needed\n return currentNode.dist;\n }\n\n // skip current node if it has been visited\n if (!visited[currentNode.hash()]) {\n // add this node to the list of visted nodes\n visited[currentNode.hash()];\n\n // check all 8 possible knight movements and add the valid ones to the queue\n for (var ii = 0; ii < 8; ii++) {\n var x1 = currentNode.x + row[ii];\n var y1 = currentNode.y + col[ii];\n if (isValidCell(x1, y1)) {\n // pass in the current node as a parent to the new node so we can retrace the path\n var newNode = new Node(currentNode, x1, y1, currentNode.dist + 1);\n queue.push(newNode);\n }\n }\n }\n }\n\n // if we get here, the destination was not found\n // (something went wrong, since a knight can always make it to any other space)\n console.log(\"destination was not found\");\n return Infinity;\n}", "function solve(map, miner, exit) {\r var result = [];\r if(miner.x === exit.x && miner.y === exit.y) return [];\r\r //converting the map to we can edit. We want to know if we visited a point in the graph\r var newMap = [];\r for(var i = 0; i < map.length; i++) {\r newMap[i] = [];\r for(var j = 0; j < map[i].length; j++) {\r newMap[i][j] = {};\r newMap[i][j].value = map[i][j];\r newMap[i][j].visited = false;\r newMap[i][j].x = i;\r newMap[i][j].y = j;\r }\r }\r // newMap is the our map\r\r var pathStack = new Stack();\r\r var currPosition = newMap[miner.x][miner.y];\r currPosition.visited = true;\r pathStack.push(currPosition);\r\r while(pathStack.top != 0) {\r var next = findUnvisitedAdjVertex(currPosition);\r\r if(next == null) {\r var temp = pathStack.peek();\r //backtrack here\r if(currPosition.x == temp.x && currPosition.y == temp.y) {\r pathStack.pop();\r }\r currPosition = pathStack.pop();\r result.pop(); // updating result stack to forget the move made\r } else {\r if(next.x == exit.x && next.y == exit.y) {\r console.log(\"exit found\");\r return result;\r }\r pathStack.push(next);\r currPosition = next; //updating the current position to next pos\r currPosition.visited = true;\r }\r }\r\r\r function findUnvisitedAdjVertex(pos) {\r if (pos) {\r if(pos.x >= 1 && newMap[pos.x - 1] && newMap[pos.x - 1][pos.y] && newMap[pos.x - 1][pos.y].value == true && newMap[pos.x - 1][pos.y].visited == false ) {\r //left position is free and is unvisited\r result.push(\"left\");\r return newMap[pos.x-1][pos.y];\r } else if (pos.y >= 1 && newMap[pos.x] && newMap[pos.x][pos.y-1] && newMap[pos.x][pos.y-1].value == true && newMap[pos.x][pos.y-1].visited == false ) {\r //top hasn't been visited and is free\r result.push(\"up\");\r return newMap[pos.x][pos.y-1];\r } else if(pos.x+1 < newMap.length && newMap[pos.x + 1] && newMap[pos.x + 1][pos.y] && newMap[pos.x + 1][pos.y].value == true && newMap[pos.x + 1][pos.y].visited == false ) {\r //left position is free and is unvisited\r result.push(\"right\");\r return newMap[pos.x+1][pos.y];\r } else if (pos.y+1 < newMap[0].length && newMap[pos.x] && newMap[pos.x][pos.y+1] && newMap[pos.x][pos.y+1].value == true && newMap[pos.x][pos.y+1].visited == false ) {\r //bottom hasn't been visited and is free\r result.push(\"down\");\r return newMap[pos.x][pos.y+1];\r }\r }\r return null;\r }\r return result;\r}", "solve() {\n this.board = this.solveHelper(this.board, -1, -1, 0);\n }", "function solveStep(loc,puzzleCpy,optionsCpy,numOptionsCpy,visitedCpy,difficulty){\n var result = false;\n //console.dir(loc);\n \n currX = loc.x;\n currY = loc.y;\n \n visitedCpy[currX][currY] = true;\n \n var currOptions = optionsCpy[currX][currY];\n \n //drawGrid(puzzleCpy);\n \n difficulty += numOptionsCpy[currX][currY] - 1;\n /*\n if(numValues == gridSize){\n if(numOptionsCpy[currX][currY] > 1){\n difficulty += numOptionsCpy[currX][currY] - 1;\n }\n } else{\n if(numOptionsCpy[currX][currY] >= 1){\n difficulty += numOptionsCpy[currX][currY]-0;\n }\n }\n */\n \n for(var i = 0; i < numValues;i++){\n if(currOptions&(1<<i)){\n if(!checkConstraints(letterArr[i],currX,currY,puzzleCpy)){\n continue;\n }\n var puzzleCpy2 = JSON.parse(JSON.stringify(puzzleCpy));\n var optionsCpy2 = JSON.parse(JSON.stringify(optionsCpy));\n var numOptionsCpy2 = JSON.parse(JSON.stringify(numOptionsCpy));\n var currentResult = setValueStep(letterArr[i],loc,puzzleCpy2,optionsCpy2,numOptionsCpy2,visitedCpy,difficulty);\n if(currentResult){\n result = true;\n }\n }\n }\n \n var queueCpy = getQueue(puzzleCpy,numOptionsCpy,visitedCpy);\n //console.dir(queueCpy.toArray());\n //console.dir(loc);\n //console.dir(letter);\n while(!queueCpy.isEmpty()){\n //console.dir(queueCpy.toArray());\n var nextLoc = queueCpy.dequeue();\n if(loc.x == nextLoc.x && loc.y == nextLoc.y){\n continue;\n }else{\n var difficultyCpy = difficulty;\n var visitedCpy2 = JSON.parse(JSON.stringify(visitedCpy));\n return solveStep(nextLoc,puzzleCpy,optionsCpy,numOptionsCpy,visitedCpy2,difficultyCpy);\n }\n }\n \n //console.log(\"End loc step\");\n return result;\n }", "function solution(gridarr)\n{\n\tdo\n\t{\n\t\tif (hasZeros(optgrid(gridarr)))\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tvar temparr = copyArr(gridarr);\n\t\tfor (row=0; row<9; row++)\n\t\t{\n\t\t\tfor (col=0; col<9; col++)\n\t\t\t{\n\t\t\t\tsolve(gridarr, row, col);\n\t\t\t}\n\t\t}\n\t\tif (matches(gridarr,temparr)&&hasZeros(gridarr))\n\t\t{\n\t\t\tvar coords = findmin(optgrid(gridarr));\n\t\t\tvar poss = possibilities(gridarr, coords);\n\t\t\tfor (l=0; l<poss.length; l++)\n\t\t\t{\n\t\t\t\tnewgrid = copyArr(gridarr);\n\t\t\t\tnewgrid[coords[0]][coords[1]] = poss[l];\n\t\t\t\tsolution(newgrid);\n\t\t\t}\n\t\t\tgridarr = copyArr(newgrid);\n\t\t\tupdateInput(gridarr);\n\t\t}\n\t} while (hasZeros(gridarr));\n\tupdateInput(gridarr);\n\n\t//This is a comment to see if I can use github with Atom.\n}", "function Greedy__Algorithm(grid,Visited_Nodes,Unvisited_Nodes,end,Select_Heuristic)\n {\n \n if (Unvisited_Nodes.length > 0){\n var lowestvalueIndex = 0; \n for (var i = 0 ; i< Unvisited_Nodes.length;i++){\n if(Unvisited_Nodes[i].h < Unvisited_Nodes[lowestvalueIndex].h)\n lowestvalueIndex = i ; \n }\n\nvar current_Node = Unvisited_Nodes[lowestvalueIndex];\n\nif (current_Node === end){ // === is for equal testing \n console.log(\"Searching Done!\")\n\n // now we need to find the path \n path = []; \n temp = current_Node; \n path.push(temp);\n while(temp.previous){\npath.push(temp.previous);\ntemp = temp.previous; // backtracks until it reaches to start \n\n }\n noLoop();\n // return;\n}\nremoveFromArray(Unvisited_Nodes,current_Node)\nVisited_Nodes.push(current_Node);\n\nvar neighbors = current_Node.neighbors // the neighbors of the current_Node\nfor (var i = 0 ; i<neighbors.length;i++){\n var neighbor = neighbors[i]; // checking every neighbor \n\n if (!Visited_Nodes.includes(neighbor) && !neighbor.wall){ // if Visited_Nodes does not include neighbor AND our neighbor is not wall then ...\n\nvar tempG = current_Node.g + Euclidean_Distance_heuristic(neighbor, current_Node);\n\n\n neighbor.g = tempG;\n Unvisited_Nodes.push(neighbor);\n\n\nif(Select_Heuristic == 1)\n{\n neighbor.h = Euclidean_Distance_heuristic(neighbor, end);;\n}\n\nif(Select_Heuristic == 2){\n neighbor.h = Manhattan_Distance_heuristic(neighbor, end);;\n}\n\n neighbor.previous = current_Node;\n // only for debugging \n// console.log(\" current neighbor's i : \" + neighbor.i + \" current neighbor's j : \" + neighbor.j);\n// console.log(\"h is : \" + neighbor.h);\n// console.log(\"g is : \" + neighbor.g);\n// console.log(\"f is : \" + neighbor.f);\n\n}\n\n}\n// only for debugging \n// console.log(\"________________________________\");\n} else{\n// no solution \nconsole.log(\"no_Solution\");\n}\n\n }", "function searchGrid(grid) {\r\n if (solved(grid)) {\r\n console.log(\"Solved!\");\r\n return grid;\r\n } else {\r\n // get the next empty position with fewest possible values\r\n // this is to go through the fewest possibilities\r\n var next = \"\";\r\n for (pos in grid) {\r\n if (grid[pos].length > 1) { // if position is empty\r\n if (next == \"\") {\r\n next = pos;\r\n } else if (grid[pos].length < grid[next].length) { // if current position has fewer possible values\r\n next = pos;\r\n }\r\n }\r\n }\r\n\r\n var possibleValues = grid[next];\r\n var len = possibleValues.length;\r\n // go through each possible value and see if it solves the puzzle\r\n for (var i = 0; i < len; i++) {\r\n // make a new copy of the grid\r\n var newGrid = {};\r\n for (p in grid) {\r\n newGrid[p] = grid[p];\r\n }\r\n\r\n newGrid[next] = possibleValues.charAt(i); // put next possible value into position\r\n var valid = eliminateValues(newGrid, next); // propogate constraints\r\n if (valid) valid = eliminate2(newGrid, next);\r\n\r\n // if grid is valid, continue checking other positions\r\n if (valid) {\r\n //outGrid(newGrid);\r\n valid = searchGrid(newGrid);\r\n if (typeof valid != \"boolean\") return valid; // success\r\n }\r\n // revert position\r\n }\r\n }\r\n\r\n return false;\r\n}", "function calculateBestPath() {\r\n\t\t\tvar\tpathStart = Node(null, {x:startingPosition[0], y:startingPosition[1]}); // a node from the start coordinates\r\n\t\t\tvar pathEnd = Node(null, {x:finishingPosition[0], y:finishingPosition[1]}); // a node from the end coordinates\r\n\t\t\t\t\t\r\n\t\t\tvar AStar = new Array(worldSize);\t\t\t// an array that will contain all positions in the world\r\n\t\t\tvar Open = [pathStart];\t\t\t// a list of currently open nodes\r\n\t\t\tvar Closed = [];\t\t\t// a list of closed nodes\r\n\t\t\tvar result = []; \t\t\t// the array that will be returned\r\n\t\t\tvar myNeighbours;\t\t\t// a reference to a node that is nearby\r\n\t\t\tvar currentNode;\t\t\t// a reference to a node that we are now considering taking\r\n\t\t\tvar currentPath;\t\t\t// a reference to a node that starts the current path we are considering\r\n\t\t\t\r\n\t\t\t// temporary variables used in the calculations\r\n\t\t\tvar length, max, min, a, b;\r\n\t\t\t\r\n\t\t\twhile(length = Open.length) {\t\t\t\t// iterate through the open list until there is nothing left\t\t \r\n\t\t\t\tmax = worldSize;\r\n\t\t\t\tmin = -1;\r\n\t\t\t\t\r\n\t\t\t\t// get the max and min\r\n\t\t\t\tfor(a = 0; a < length; a++) {\r\n\t\t\t\t\tif(Open[a].f < max) {\r\n\t\t\t\t\t\tmax = Open[a].f;\r\n\t\t\t\t\t\tmin = a;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tcurrentNode = Open.splice(min, 1)[0];\t\t\t// remove the next node from the open array and put it in currentNode\r\n\t\t\t\t\r\n\t\t\t\t// is it the destination node?\r\n\t\t\t\tif( currentNode.value === pathEnd.value ) {\t\t\t// if we have reached our destination node (Bugs Bunny's position)\r\n\t\t\t\t\tcurrentPath = currentNode;\r\n\t\t\t\t\tdo {\r\n\t\t\t\t\t\tresult.push([currentPath.x, currentPath.y]);\r\n\t\t\t\t\t} while (currentPath = currentPath.Parent);\r\n\t\t\t\t\tAStar = Closed = Open = [];\t\t\t// clear the arrays\r\n\t\t\t\t\tresult.reverse();\t\t\t// reverse the result so as not to return a list from finish to start instead of start to finish\r\n\t\t\t\t}\r\n\t\t\t\telse {\t\t\t// otherwise, it was not our destination\t\t\t \r\n\t\t\t\t\tmyNeighbours = Neighbours(currentNode.x, currentNode.y);\t\t\t\t// find which nearby nodes are available to move to\r\n\t\t\t\t\tfor(a = 0, b = myNeighbours.length; a < b; a++) {\t\t\t\t// test each neighbouring node that hasn't been tested already\t\t\t\t\r\n\t\t\t\t\t\tcurrentPath = Node(currentNode, myNeighbours[a]);\t\t\t\t// add to the current path we are considering\r\n\t\t\t\t\t\tif (!AStar[currentPath.value]) {\r\n\t\t\t\t\t\t\tcurrentPath.g = currentNode.g + distanceFunction(myNeighbours[a], currentNode);\t\t\t// cost of this current route so far\r\n\t\t\t\t\t\t\tcurrentPath.f = currentPath.g + distanceFunction(myNeighbours[a], pathEnd);\t\t\t// cost of the current route all the way to the destination (Bugs' position)\r\n\t\t\t\t\t\t\tOpen.push(currentPath);\t\t\t// remember this new path by placing it in the open array\r\n\t\t\t\t\t\t\tAStar[currentPath.value] = true;\t\t\t// mark this node as having been visited already so as not to have to check it again\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} // keep iterating while open is not empty\r\n\t\t\treturn result;\r\n\t\t}", "solve(grid) {\n let updated = false;\n for (let r = 0; r < 9; r++) {\n for (let c = 0; c < 9; c++) {\n if (grid[this.getIndex(r,c)] == null) {\n if(this.trySolveSquareElimination(grid,r,c)) {\n updated = true;\n }; \n if(this.trySolveByCrossGroup(grid,r,c)) {\n updated = true;\n }; \n }\n }\n }\n if (updated) {\n this.solve(grid);\n } else {\n if (!this.isSolved(grid)) {\n this.solutions = this.solveByBruteForce(grid,[]);\n } else {\n this.solutions.push(grid);\n }\n this.numberOfSolutions = this.solutions.length;\n return true\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the already selected items from the cookies and update the displayed list of components to match.
function loadSelectionsFromCookies() { // Iterate over all items, selecting those that have a cookie stored which is equal to "selected" Object.keys(allItemNames).forEach(itemName => { itemNameSafe = allItemNames[itemName] itemCookie = localStorage.getItem(itemNameSafe) if (itemCookie != null) { if (itemCookie == "selected") { // Call selectItem to add the item to the internal list of selected items without updating the display, as updating the display for each item // causes page-freezing lag selectItem(itemName) } } }) // Now that all of the selected items are displayed as pressed and listed in the selectedItems array, update the displayed list of components updateSelectedItemComponents() }
[ "populateActiveChoices() {\n /**\n * Remove children instead of clearing innerHTML, to keep change listener.\n */\n while (this.activeList_.firstElementChild) {\n this.activeList_.firstElementChild.remove();\n }\n this.activeList_.insertAdjacentHTML('beforeend', '<option></option>');\n this.numActive_ = 0;\n for (let idx = 0; idx < window.localStorage.length; idx++) {\n const key = window.localStorage.key(idx);\n if (!key.startsWith(this.ACTIVE_KEY_PREFIX_)) {\n continue;\n }\n this.numActive_++;\n const activeName = key.substr(this.ACTIVE_KEY_PREFIX_.length);\n const projectName = this.projectInActive(activeName);\n const templateName = this.templateInActive(activeName);\n this.activeList_.insertAdjacentHTML('beforeend', `\n <option\n value=\"${activeName}\">${projectName} (${templateName})</option>`);\n }\n }", "function populateFavoritesSelect() {\n\tvar currentFavorite = getCurrentFavorite();\n\tfavoritesSelect.clear();\n\tfor (var i = 0; i < favorites.length; i++) {\n\t\tfavoritesSelect.addItem(favorites[i]);\n\t}\n\tfavoritesSelect.finalize();\n\tselectItem(favoritesSelect,currentFavorite);\n}", "function recreateItems() {\n\n var selected;\n\n orig_input\n .find('option')\n .each(function (i, opt) {\n opt = $(opt);\n var $item = $('<div class=\"item item-available\" data-id=\"' + opt.attr('value') + '\">'\n + opt.text() + '</div>');\n if (opt.is(':selected')) {\n $item.addClass('selected');\n $selected_item.text($item.text());\n selected = $item[0];\n }\n available_items.append($item);\n $item.click(clickItem);\n item_count++;\n });\n\n // Scroll to the selected item.\n if (selected) {\n available_items[0].scrollTop = selected.offsetTop - 83;\n }\n }", "function persistSelection() {\n $.cookie(\"for_os\", $osMenu.val(), {path: '/'});\n $.cookie(\"for_browser\", $browserMenu.val(), {path: '/'});\n updateHashFragment();\n }", "function populateSelectedFavs() {\n // pass over to Receive Favourites modal form area the favourites currently selected\n let favList = document.getElementById(\"fav-list\");\n favList.innerHTML = localStorage.getItem('favs');\n}", "select_items(componentID, itemID, clearSelection) {\n this.set(componentID, this.add_items(componentID, itemID, clearSelection));\n }", "function loadCookies() {\n var decodedCookie = document.cookie;\n if (decodedCookie != \"\"){\n var cookieSplit = decodedCookie.split(';');\n var cookieLength = cookieSplit.length;\n var element = document.getElementById(\"cookies-dropdown\");\n\n $(element).find(\".recent-search\").remove();\n\n for (var i = 0; i < cookieLength; i++) {\n\n var currentCookie = cookieSplit[i].trim().split('=');\n\n var optionAdd = document.createElement(\"option\");\n\n if (currentCookie[0].startsWith(COOKIE_PREFIX)) {\n currentCookie[0] = currentCookie[0].replace(COOKIE_PREFIX, \"\");\n\n optionAdd.text = currentCookie[0];\n optionAdd.value = currentCookie[1];\n optionAdd.className = \"recent-search\";\n\n element.appendChild(optionAdd);\n }\n }\n }\n\n // Reset dropdown\n $(\"#cookies-dropdown\").val(\"null\");\n}", "function setupItems() {\n let items = getLocalStorage();\n\n if (items.length > 0) {\n items.forEach((item) => {\n createAllItems(item.id, item.value);\n });\n allList.classList.add(\"visible\");\n }\n}", "loadSelections() {\n this.storage.selections.forEach((s) => {\n let ele = this.querySelector(`[data-id=\"${s.id}\"]`);\n if(ele) ele.selected = s.selection;\n });\n\n this.showSaveButton();\n }", "function update_selection_list() {\n\n\t\t\t// Remove view types that are deselected.\n\t\t\t$( root_prefix + ' .vaa-combine-selection' ).each( function() {\n\t\t\t\tvar $this = $( this ),\n\t\t\t\t\ttype = $this.attr( 'vaa-view-type' );\n\t\t\t\tif ( ! selection.hasOwnProperty( type ) ) {\n\t\t\t\t\t$this.slideUp( 'fast', function() { $( this ).remove() } );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\t// Append or update view types selection.\n\t\t\t$.each( selection, function( type, data ) {\n\t\t\t\tvar text = data.el.attr( 'vaa-view-text' ) + '<span class=\"remove ab-icon dashicons dashicons-dismiss\"></span>',\n\t\t\t\t\t$existing = $( root_prefix + ' .vaa-combine-selection-' + type ),\n\t\t\t\t\tlabel = data.el.attr( 'vaa-view-type-label' );\n\t\t\t\tif ( label ) {\n\t\t\t\t\ttext = '<span class=\"ab-bold\">' + label + ':</span> ' + text;\n\t\t\t\t}\n\t\t\t\tif ( $existing.length ) {\n\t\t\t\t\t$existing.html( text );\n\t\t\t\t\tif ( 'none' === $existing.css( 'display' ) || ! $existing.is( ':visible' ) ) {\n\t\t\t\t\t\t$existing.slideDown( 'fast' );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar attr = [\n\t\t\t\t\t\t'class=\"ab-item ab-empty-item vaa-combine-selection vaa-combine-selection-' + type + '\"',\n\t\t\t\t\t\t'vaa-view-type=\"' + type + '\"',\n\t\t\t\t\t\t'style=\"display:none;\"'\n\t\t\t\t\t];\n\t\t\t\t\tvar html = '<li ' + attr.join( ' ' ) + '>' + text + '</li>';\n\t\t\t\t\t$selection_container.append( html );\n\t\t\t\t\t$( root_prefix + ' .vaa-combine-selection-' + type ).slideDown( 'fast' );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\tif ( is_active && ! $.isEmptyObject( selection ) ) {\n\t\t\t\tif ( 'none' === $selection_container.css( 'display' ) || ! $selection_container.is( ':visible' ) ) {\n\t\t\t\t\t$selection_container.slideDown( 'fast' );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$selection_container.slideUp( 'fast' );\n\t\t\t}\n\t\t}", "function updateCookies() {\n var exDate = new Date();\n exDate.setDate(exDate.getDate() + 7); // default expiration in a week\n \n var sections = window.exhibit.getCollection(\"picked-sections\").getRestrictedItems();\n var classes = window.exhibit.getCollection(\"picked-classes\").getRestrictedItems();\n \n document.cookie = 'picked-sections='+sections.toArray()+'; expires='+exDate+'; path=/';\n document.cookie = 'picked-classes='+classes.toArray()+'; expires='+exDate+'; path-/';\n \n if (window.database.getObject('user', 'userid') != null) {\n\t\t$.post(\"./scripts/post.php\",\n\t\t\t{ userid: window.database.getObject('user', 'userid'),\n\t\t\t pickedsections: sections.toArray().join(','),\n\t\t\t pickedclasses: classes.toArray().join(',')\n\t\t\t });\n }\n}", "function updateCatalogIdentifier(selected) {\n const commerceProvider = getSelectedCommerceProvider();\n const catalogs = getCatalogIdentifiers(commerceProvider);\n catalogIdentifierCoralSelectComponent.items.clear();\n const items = buildSelectItems(catalogs, selected);\n items.forEach(item => {\n catalogIdentifierCoralSelectComponent.items.add(item);\n });\n }", "function loadAnswersFromCookies()\n {\n var oldResult = getCookie();\n\n for(var key in oldResult){\n var obj = $(\"[name='\"+key+\"']\");\n if(key == settings.markOption.markedQuestionsSelector && settings.markOption.enableMarked){\n var nameQS = $(settings.markOption.markedQuestionsSelector).attr('name');\n obj = $(\"[name='\"+nameQS+\"']\");\n }\n var item = oldResult[key].split('{sep}');\n var tempV= new Array();\n var count= 0;\n //deleteCookie(key);\n for(var key2 in item){\n if(item[key2] == \"\"){// When item is empty string, ignore it\n continue;\n }\n tempV[count++] = item[key2];\n if(obj.data('alternatetype') === 'checkbox' || obj.data('alternatetype') === 'radio'){\n $(\"[name='\"+key+\"'][value='\"+item[key2]+\"']\").prop('checked', true);\n }else{\n obj.val(item[key2]);\n }\n }\n \n // If its select, set all selected value\n if(obj.data('alternatetype') === 'select'){\n obj.val(tempV);\n }\n }\n \n if(settings.quickAccessOption.enableAccessSection){\n setQuickAccessResponseForAllData();\n }\n \n if(settings.markOption.enableMarked){\n var markedValues = _getMarkedValue();\n for(var keyM in markedValues){\n // Mark button Object\n var markButton = $(settings.markOption.markSelector + '[data-question=\"'+ markedValues[keyM] +'\"]');\n // Un Mark button Object\n var unmarkButton = $(settings.markOption.unmarkSelector + '[data-question=\"'+ markedValues[keyM] +'\"]');\n \n markButton.addClass('hidden');\n unmarkButton.removeClass('hidden');\n }\n } \n }", "function selectItem(selectedItem){ //function built to select item store data of what was chosen and send what you chose to the selection.html\n Cookies.set(\"color\", selectedItem); \n location.href = \"/pages/selection.html\";//makes it so when user choses an object it goes directly to page \n}", "function updateActivePreceptors()\n\t{\n\t\t// empty the box\n\t\t$('#hiddenActivePreceptors').find('option').remove();\n\t\t\n\t\t// clone whats currently in active\n\t\t$(\"select#hiddenActivePreceptors\").append($(\"#activePreceptors option\").clone());\n\t\t\n\t\t// then select it all\n\t\t$(\"select#hiddenActivePreceptors *\").attr(\"selected\", true);\n\t}", "function populateUI() {\n const selectedSeats = JSON.parse(sessionStorage.getItem(\"selectedSeats\"));\n \n if (selectedSeats !== null && selectedSeats.length > 0) {\n seats.forEach((seat, index) => {\n if (selectedSeats.indexOf(index) > -1) {\n seat.classList.add(\"selected\");\n }\n });\n }\n //seat click event\n container.addEventListener(\"click\", e => {\n if (e.target.classList.contains(\"seat\") && !e.target.classList.contains(\"occupied\")) {\n e.target.classList.toggle(\"selected\");\n updateSelectedCount();\n }\n });\n \n // initial count and total\n updateSelectedCount(); \n }", "updateItems(e) {\n this.__tabs = this.querySelectorAll(\"a11y-tab\");\n this.__hasIcons = true;\n if (!this.id) this.id = this._generateUUID();\n if (this.__tabs && this.__tabs.length > 0)\n this.__tabs.forEach((tab, index) => {\n if (!tab.icon) this.__hasIcons = false;\n tab.order = index + 1;\n tab.total = this.__tabs.length;\n });\n this.selectTab(this.activeTab);\n }", "function setItems(state) {\n // Disable autocomplete and sorting temporarily\n disableAutocomplete();\n disableSorting();\n\n $('#nav-items').replaceWith(state);\n\n // Re-enable autocomplete and sorting\n enableAutocomplete();\n enableSorting();\n }", "updateSelectedItemsList(selectedItem, isSelected) {\n if (isSelected) this.borrowingCreationRequest.params.selectedItems.push(selectedItem);\n else this.removeItemFromSelectedItemsList(selectedItem);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
part D Create a deleteTask function: i. It receives a string as a parameter called task. ii. It removes that string from the array. iii. It prints in console a message indicating the deletion. iv. It returns the number of elements in the array after the deletion
function deleteTask(task) { var index; index = myTaskArray.indexOf(task); if (index > -1) { myTaskArray.splice(index, 1); console.log("Item " + task + " has been deleted from the array"); } else { console.log("Item " + task + " is not in the array"); } return myTaskArray.length; }
[ "function deleteTask(task) {\n // var taskIndex = array.indexOf(task);\n // if (taskIndex > -1) {\n // array.splice(taskIndex, 1);\n // console.log(`${task} deleted`);\n // }\n tasks = tasks.filter(function (t) {\n return t !== task;\n });\n console.log(task + \" deleted\");\n return tasks.length;\n}", "function deleteTask(task) {\n var index = myArray.indexOf[task];\n myArray.splice(index, 1);\n return myArray.length;\n}", "function deleteTask(){\n objectArray.object.splice(objectArray.object.indexOf(task),1);\n }", "function deleteTask() {\n 'use strict';\n var output = document.getElementById('output');\n var message = '';\n\n //prompt the task number to delete\n var deleteTask = prompt('What task number do you want to delete?');\n\n if(deleteTask != null) {\n //converts the task number to the index of the array it is at\n deleteTask = parseInt(deleteTask) - 1;\n\n //delete the task\n if((deleteTask >= 0) && (deleteTask < tasks.length)){\n tasks.splice(deleteTask, 1);\n }\n\n //make list\n message = '<h2>To-Do</h2><ol>';\n for (var i = 0, count = tasks.length; i < count; i++) {\n message += '<li>' + tasks[i] + '</li>';\n }\n message += '</ol>';\n\n //display list\n output.innerHTML = message;\n }\n }", "function removeTask(task)\r\n{\r\n\tfor(var i=0; i<tasks.length; i++)\r\n\t{\r\n\t\tif(tasks[i] == task)\r\n\t\t{\r\n\t\t\ttasks.splice(i, 1);\r\n\t\t}\r\n\t}\r\n}", "static removeTask(task) {\n for (let i = 0; i < $scope.completedTasks.length; i++) {\n let flag = false;\n for (let j = 0; j < $scope.completedTasks[i].tasksIds.length; j++) {\n if ($scope.completedTasks[i].tasksIds[j] === task.id) {\n if ($scope.completedTasks[i].tasksIds.length - 1 === 0) {\n $scope.completedTasks.splice(i, 1);\n flag = true;\n break;\n } else {\n $scope.completedTasks[i].tasksIds.splice(j, 1);\n flag = true;\n break;\n }\n }\n }\n if (flag) break;\n }\n }", "[DELETE_TASK] (state, payload) {\n state.tasks.splice(payload.index, 1);\n }", "function deleteTask() {\n let li = this.parentElement;\n let h1 = li.querySelector(\"h1\");\n removeListElementsFromArray(h1);\n li.parentElement.removeChild(li);\n taskCount--;\n updateCounter(taskCount);\n }", "function deleteTask() {\n const taskElement = this.parentNode;\n taskElement.remove();\n taskCount--;\n displayCount(taskCount);\n }", "function deleteTheTask(e) {\n\n let tempDeleteId = e.target.parentElement.innerText.toString();\n let deleteArray = tempDeleteId.split(\")\");\n tempDeleteId = deleteArray[0];\n\n\n let deleteObj = {};\n for (var a = 0; a < taskList.length; a++) {\n if (taskList[a].taskId == tempDeleteId) {\n deleteObj = taskList[a];\n break;\n }\n }\n\n\n for (var b = 0; b < taskList.length; b++) {\n if (taskList[b].taskId == deleteObj.taskId) {\n taskList.splice(b, 1);\n break;\n }\n }\n\n\n removeList();\n displayList();\n\n\n}", "function deleteTask(){\n id = event.srcElement.parentElement.getAttribute('id');\n let task = list.find(i => i.id === +id);\n task.active === true ? activeTasksCounter-- : activeTasksCounter;\n list.splice(list.indexOf(task),1);\n localStorage.setItem('tasksList', JSON.stringify(list)); \n removeTaskFromContainer(id);\n updateActiveTasksCounter();\n list.length == 0 ? hiddenButtons() : 0;\n}", "function deleteMe ($dele){\n\tvar deletedTask = { task: $dele.data('val').split('-').join(' ') , importance: $dele.find('.imp').data('val') ,done: $dele.hasClass('completed') } \n\tconsole.log('delete a task function: ' , deletedTask )\n\tcurrentUser.deletedTasks.push( deletedTask );\n\n\t// this is to get the deleted tasks out of tasks arr ;\n\tvar k ;\n\tfor ( k=0;k<currentUser.tasks.length ; k++){\n\t\tif (JSON.stringify(deletedTask) === JSON.stringify(currentUser.tasks[k])){\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (currentUser.tasks.length === 0 ){\n\t\t$('#empty').show();\n\t}\n\n\tcurrentUser.tasks.splice(k , 1 );\n\n\t$dele.remove();\n\tupdateAvg();\n}", "deleteTasks(taskId) {\n const newTasks = [];\n for (let i = 0; i < this.tasks.length; i++) {\n const task = this.tasks[i]\n if (task.id !== taskId) {\n newTasks.push(task);\n }\n }\n this.tasks = newTasks;\n }", "function removeTask(taskElement){\n //delete the element that was provided\n taskElement.remove();\n}", "function removeTask(taskID){\n for(let i = 0; i < tasks.length; i++){\n if(tasks[i].id == taskID){\n tasks.splice(i, 1);\n break;\n }\n }\n}", "deleteTaskList(t) {\n this.taskLists.splice(t, 1);\n }", "function removeTask()\n{\n //Remove Trasks from the Array\n var rID = this.getAttribute(\"id\");\n var taskList = createArray();\n taskList.splice(rID, 1);\n localStorage.setItem('itemList', JSON.stringify(taskList));\n displayTask();\n}", "function deleteTask(task) {\n const params = new URLSearchParams();\n params.append('id', task.id);\n fetch('/delete-rec', {method: 'POST', body: params});\n}", "deleteSubtask(arr, task, subtaskIndex) {\n task.subtasks.splice(subtaskIndex, 1);\n this.updateFirestore(arr);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an activity bubble for the specified commit
function createActivityBubble (commit) { var bubble = new ActivityBubble(); bubble.user.login = commit.committer.login; bubble.user.name = commit.commit.committer.name; bubble.commitUrl = commit.url; bubble.fixBugCommit = commit.commit.message.indexOf("fix") > -1 && commit.commit.message.indexOf("bug") > -1; bubble.commitSha = commit.sha; bubble.commitTime = new Date(commit.commit.committer.date).getTime(); var rangeMilliseconds = bubble.getRange().hours*3600*1000 + bubble.getRange().minutes*60*1000; bubble.beginTime = bubble.commitTime - rangeMilliseconds; bubble.endTime = bubble.commitTime + rangeMilliseconds; return bubble; }
[ "function createItem(revision) {\n\n var block = $('<div></div>').attr('class', 'commit-item2');\n var actions = $('<div></div>');\n\n var title = $('<div></div>')\n .text(revision.Message)\n .attr('class', 'commit-title2')\n .appendTo(block);\n\n $('<div></div>')\n .text(\"Revision : \" + revision.Revision + \" by \" + revision.Author + \" on \" + revision.Timestamp)\n .attr('class', 'commit-subtitle')\n .appendTo(title);\n\n $('<div></div>')\n .attr('class', 'commit-annotation-summary')\n .append($('<span class=\"label label-primary\"><i class=\"fa fa-eye\"></i> ' + revision.NumberReviewers + ' </span>'))\n .append($('<span class=\"label label-success\"><i class=\"fa fa-comment\"></i> ' + revision.NumberComments + ' </span>'))\n .append($('<span class=\"label label-warning\"><i class=\"fa fa-comments\"></i> ' + revision.NumberReplies + ' </span>'))\n .append($('<span class=\"label label-danger\"><i class=\"fa fa-heart\"></i> ' + revision.NumberLikes + ' </span>'))\n .appendTo(block);\n\n if (revision.ApprovedBy) {\n $('<div></div>')\n .text('Cool! Approved by: ' + revision.ApprovedBy)\n .appendTo(actions);\n }\n\n actions.appendTo(block);\n\n block.on('click', { revision: revision.Revision }, openForReview);\n\n $('<div></div>').attr('class', 'commit-item-footer').appendTo(block);\n\n block.appendTo(insertPoint);\n}", "newCommit() {\n\t\tconst method = `newCommit[${this.name}]`;\n\t\tlogger.debug(`${method} - start`);\n\n\t\treturn new Commit(this.chaincodeId, this.channel, this);\n\t}", "function getActivityBubbles(){\n\tvar commits = getCommits();\n\tvar activityBubbles = new Array();\n\t$.each(commits, function(index) {\n\t\tif(this.committer != null){\n\t\t\tactivityBubbles.push(createActivityBubble(this));\n\t\t}\n\t});\n\tactivityBubbles = getBubblesProductivityIndex(activityBubbles); \n\treturn activityBubbles;\n}", "addCommit(commit) {\n this.list[commit.blockHash].push(commit);\n }", "function addCommitButton(onclick) {\n\t\tvar commitButton = jQuery('<button>Commit</button>');\n\t\tcommitButton.click(function(event){\n\t\t\tif (commitEnabled === true) {\n\t\t\t\tonclick(event);\n\t\t\t}\n\t\t});\n\t\tmainControlPanel.append(commitButton);\n\t\tcommitEnabled = true;\n\t}", "static createInstance(committer, randomString, commitDateTime) {\n return new Commitment({ committer, randomString, commitDateTime});\n }", "async generateCommitNote(commit) {\n var _a;\n const subject = commit.subject\n ? commit.subject\n .split(\"\\n\")[0]\n .trim()\n .replace(\"[skip ci]\", \"\\\\[skip ci\\\\]\")\n : \"\";\n let pr = \"\";\n if ((_a = commit.pullRequest) === null || _a === void 0 ? void 0 : _a.number) {\n const prLink = url_join_1.default(this.options.baseUrl, \"pull\", commit.pullRequest.number.toString());\n pr = `[#${commit.pullRequest.number}](${prLink})`;\n }\n const user = await this.createUserLinkList(commit);\n return `- ${subject}${pr ? ` ${pr}` : \"\"}${user ? ` (${user})` : \"\"}`;\n }", "async function addCommitHistoryLink(bar) {\n\tconst parts = parseCurrentURL();\n\tparts[2] = 'commits';\n\tconst url = '/' + parts.join('/');\n\tif (await is404(url)) {\n\t\treturn;\n\t}\n\tbar.after(\n\t\t<p class=\"container\">\n\t\t\tSee also the file’s {<a href={url}>commit history</a>}\n\t\t</p>\n\t);\n}", "function play_commit(commit){\n\t//clear colors from element\n\tvar new_list = [];\n\tfor (var i = 0; i < color_classes.length; i++) {\n\t\tcommit.elem.classList.remove(color_classes[i]);\n\t}\n\t//get position\n\tvar xy = cumulativeOffset(commit.elem);\n\tvar rect = commit.elem.getBoundingClientRect();\n\txy.x += rect.width/2;\n\txy.y += rect.height/2;\n\t//get frequency (based on sha1)\n\tvar n = parseInt(commit.sha[0]+commit.sha[1], 16);\n\t//var duration = 1.0;\n\tvar duration = Math.log((commit.timestamp - last_times[commit.table_i])/10000);\n\tif(duration > 6){\n\t\tduration = 6;\n\t}\n\tif(duration < 0.5){\n\t\tduration = 0.5;\n\t}\n\tvar note = n % g_minor_432.length;\n\tvar pos_sample = new PositionSample(xy, g_minor_432[note], duration);\n\t//color it\n\tcommit.elem.classList.add(color_classes[n % 4]);\n\tused_tables[commit.table_i]++;\n\tlast_times[commit.table_i] = commit.timestamp;\n\tsetTimeout(function(ind, cla){\n\t\tused_tables[ind]--;\n\t\tif(used_tables[ind] <= 0){\n\t\t\tcommit.elem.classList.remove(cla);\n\t\t}\n\t}, duration * 1000 + 400, commit.table_i, color_classes[note % 7]);\n}", "newMessage ({commit}, msg) {\n commit(NEW_MESSAGE, msg)\n }", "commitToLink(commit) {\n const url = `https://github.com/${this.data.github.owner}/${this.data.github.name}/commit/${commit.hash}`;\n return `[${commit.shortHash}](${url})`;\n }", "function onReceiveCommits(commits) {\n render(commits);\n hideSpinner();\n hideOfflineMessage();\n /*\n * Task 7a)\n * Store data in IndexedDB\n */\n}", "function fillCommitsModal(commitSha, commitTitle, commitUrl){\n document.getElementById(\"gitLink\").setAttribute(\"onclick\", `location.href='${decodeURIComponent(commitUrl)}'`);\n repoStats.getCommitLinesChanged(commitSha, (data) => {\n document.getElementById(\"commitsModalTitle\").innerHTML = decodeURIComponent(commitTitle).replace(/>>/g, \"'\");\n let body = `<p>Lines Added: ${data.additions}</br>Lines Removed: ${data.deletions}</p>`;\n document.getElementById(\"commitsModalBody\").innerHTML = body;\n }, () => {\n\n });\n}", "createTracker ({commit}, account) {\n commit('START_LOADING')\n commit('CREATE_TRACKER')\n return createTracker().then(tracker => {\n commit('CREATE_TRACKER_OK', {account, tracker})\n return tracker\n }).catch(err => {\n commit('CREATE_TRACKER_FAIL', err)\n }).finally(() => {\n commit('STOP_LOADING')\n })\n }", "generateBubble() {\n var proto = `<a href=\"/timeline/${this.slug}/\" data-category=\"${this.category.slug}\" class=\"timeline__bubble timeline__bubble--hidden\">\n <p class=\"timeline__bubble-title\">${this.name}</p>\n <p class=\"timeline__bubble-date\">${this.dateFormated}</p>\n </a>`\n var container = document.createElement(\"fragment\");\n container.innerHTML = proto;\n this.bubble = container.firstChild;\n this.timeline.bubblesContainer.appendChild(this.bubble);\n }", "function addBubble(evt) {\r\n \r\n var position = calculBubblePosition(evt);\r\n var elt = OpenCharts.Event.element(evt); \r\n \r\n elt.parentNode.appendChild(\r\n window.renderer.createBubble(\r\n elt, \r\n position.x, \r\n position.y, \r\n bubble.size.width, \r\n bubble.size.height, \r\n {\r\n fillColor: \"white\",\r\n fillOpacity: 1, \r\n strokeColor: renderer.getAttribute('strokeColor', elt),\r\n strokeOpacity: 1,\r\n strokeWidth: 2,\r\n strokeLinecap: \"round\",\r\n strokeDashstyle: \"solid\"\r\n },\r\n window.renderer.offset\r\n )\r\n );\r\n}", "function getActivity ( options ) {\n var \n after = '--after=' + options.after,\n before = '--before=' + options.before,\n author = options.author ? ( '--author=' + options.author ) : null,\n format = options.json ? ( '--pretty=format:{ \"commit\": \"%H\", \"author\": \"%an <%ae>\", \"date\": \"%ad\", \"message\": \"%f\"}' ) : null,\n args = [ 'log', after, before ],\n git;\n\n if ( author ) args.push( author );\n if ( format ) args.push( format );\n\n git = spawn( 'git', args, options.options );\n\n return git; // return stream\n}", "function createActTimeline() {\n preparation_editor.createActTimeline();\n}", "logActivity(activity) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!activity) {\n throw new Error('Missing activity.');\n }\n const blobName = this.getBlobName(activity);\n const data = JSON.stringify(activity);\n const container = yield this.ensureContainerExists();\n const block = yield this.client.createBlockBlobFromTextAsync(container.name, blobName, data, null);\n const meta = this.client.setBlobMetadataAsync(container.name, blobName, {\n fromid: activity.from.id,\n recipientid: activity.recipient.id,\n timestamp: activity.timestamp.toJSON()\n });\n const props = this.client.setBlobPropertiesAsync(container.name, blobName, {\n contentType: 'application/json'\n });\n yield Promise.all([block, meta, props]); // Concurrent\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
.closest recurses up the DOM from the target node, checking if the current element matches the query fluent doc(target).closest(query); legacy doc.closest(target, query);
function closest(target, query){ target = getTarget(target); if(isList(target)){ target = target[0]; } while( target && target.ownerDocument && !is(target, query) ){ target = target.parentNode; } return target === doc.document && target !== query ? null : target; }
[ "closest(selectors) {\n /* eslint-disable-next-line @typescript-eslint/no-this-alias */\n let node = this;\n while (node) {\n if (node.matches(selectors)) {\n return node;\n }\n node = node.parent;\n }\n return null;\n }", "function closest(el, selector){\n\tvar tmpEl = el;\n\t\n\t// use \"!=\" for null and undefined\n\twhile (tmpEl != null && tmpEl !== document){\n\t\tif (matchesFn.call(tmpEl,selector)){\n\t\t\treturn tmpEl;\n\t\t}\n\t\ttmpEl = tmpEl.parentElement;\t\t\n\t}\n\treturn null;\n}", "closest(el, selector) {\n let parent = el.parentElement;\n while(parent) {\n if (this.matches(parent, selector)) {\n break;\n }\n parent = parent.parentElement;\n }\n\n return parent;\n }", "closest(selector) {\n let isFind = false;\n let $parentEl = this.getFirstEl().parentElement;\n while (!isFind) {\n if ($parentEl === null || $parentEl === void 0 ? void 0 : $parentEl.matches(selector)) {\n isFind = true;\n this.$elItems = [$parentEl];\n return this;\n }\n else {\n $parentEl = $parentEl.parentElement;\n }\n if ($parentEl.matches('html')) {\n isFind = true;\n return undefined;\n }\n }\n //return $parentEl;\n }", "function closest( e, classname ) {\n if( classie.has( e, classname ) ) {\n return e;\n }\n return e.parentNode && closest( e.parentNode, classname );\n }", "function getClosestNode(node, target) {\n\t\t\tvar parent = null;\n\t\t\tif (node === target) {\n\t\t\t\treturn node;\n\t\t\t}\n\t\t\twhile (node !== null) {\n\t\t\t\tparent = node.parentElement;\n\t\t\t\tif (parent !== null && parent === target) {\n\t\t\t\t\treturn parent;\n\t\t\t\t}\n\t\t\t\tnode = parent;\n\t\t\t}\n\t\t\treturn null;\n\t\t}", "function closest( e, classname ) {\n\t\tif( classie.has( e, classname ) ) {\n\t\t\treturn e;\n\t\t}\n\t\treturn e.parentNode && closest( e.parentNode, classname );\n\t}", "function closest( e, classname ) {\n if( classie.has( e, classname ) ) {\n return e;\n }\n return e.parentNode && closest( e.parentNode, classname );\n }", "function closest( e, classname ) {\n\t\tif( $(e).hasClass(classname) ) {\n\t\t\treturn e;\n\t\t}\n\t\treturn e.parentNode && closest( e.parentNode, classname );\n\t}", "function closest(e, classname) {\n\tif ($(e).hasClass(classname)) {\n\t\treturn e;\n\t}\n\treturn e.parentNode && closest(e.parentNode, classname);\n}", "function closest(el, selector) {\n while (el) {\n if (selectorMatches(el, selector)) {\n break;\n }\n el = el.parentElement;\n }\n return el;\n}", "getClosestElemByTag(sourceElem, targetTag) {\n let result = sourceElem;\n while (result !== null && result.nodeType === 1) {\n if (result.tagName.toLowerCase() === targetTag.toLowerCase()) {\n return result;\n }\n result = result.parentNode;\n }\n return null;\n }", "function closest(e, classname) {\n if ($(e).hasClass(classname)) {\n return e;\n }\n return e.parentNode && closest(e.parentNode, classname);\n }", "function closest(el, selector, self = false) {\n var matchesFn;\n ['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'].some(function (fn) {\n if (typeof document.body[fn] == 'function') {\n matchesFn = fn;\n return true;\n }\n return false;\n })\n if (self && el[matchesFn](selector)) return el;\n var parent;\n while (el) {\n parent = el.parentElement;\n if (parent && parent[matchesFn](selector)) {\n return parent;\n }\n el = parent;\n }\n return null;\n}", "function closestPolyfill(el, s) {\n var ElementProto = win.Element.prototype,\n elementMatches = ElementProto.matches ||\n ElementProto.msMatchesSelector ||\n ElementProto.webkitMatchesSelector,\n ret = null;\n if (ElementProto.closest) {\n ret = ElementProto.closest.call(el, s);\n }\n else {\n do {\n if (elementMatches.call(el, s)) {\n return el;\n }\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n }\n return ret;\n }", "function closestMatchingAncestor(node) {\n let cursor = node;\n while (cursor) {\n if (cursor.mozMatchesSelector(selector))\n return cursor;\n if (cursor instanceof Ci.nsIDOMHTMLHtmlElement)\n break;\n cursor = cursor.parentNode;\n }\n return null;\n }", "function closestByClass(el, classToFind) {\n while (!el.classList.contains(classToFind)) {\n el = el.parentNode;\n if (!el) {\n return null;\n }\n }\n return el;\n }", "function closest (el, sel) {\n if (!el) return\n if (matches(el, sel)) {\n return el\n } else {\n return closest(el.parentNode, sel)\n }\n}", "static getClosest(el, klass) {\n if (el == null)\n return null;\n let curEl = el;\n while (curEl != null) {\n if (Dom.hasClass(curEl, klass))\n return curEl;\n curEl = curEl.parentElement;\n }\n return null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens a new window with analysis result as a string
function openResultWindow(collaboratorsAnalysisResult){ var recipe = window.open("",'Analysis Result','width=800,height=600'); var html = "<html><head><title>Analysis Result</title></head><body>" + JSON.stringify(collaboratorsAnalysisResult) + "</body></html>"; recipe.document.open(); recipe.document.write(html); recipe.document.close(); }
[ "function showExecuted () {\n instrWin = new BrowserWindow({ width: 400, height: 600 })\n\n instrWin.loadFile(\"executedInstr.html\")\n\n instrWin.on('closed', () =>{\n instrWin = null\n })\n}", "function showVAASTViewer() {\n var polymode = \"\";\n var runid = getQueryVariable(\"run\");\n var genome = getQueryVariable(\"genomeId\");\n // var mode = $(\"input[name='mode']:checked\").val();\n polyFilter = $(\"#vaastPolymorphic option:selected\").attr('value');\n var dtitle = \"VAAST Viewer for Genome: \" + genome;\n if (polyFilter && polyFilter!= \"NONE\") {\n polymode = \"&no_polymorphic=1\";\n }\n var url = \"index.php?id=60&score=1\" + polymode + \"&job_id=\" + runid;\n window.open (url,\"vaastviewer\");\n}", "function evaluation(){\n var win = window.open('https://ccnsb06-iiith.vlabs.ac.in/exp6_10/aspirin/aspirin_MS_exp9.html','_blank');\n win.focus();\n}", "function openResultwin(winurl) {\n try {\n if (queryResultLayout == 'tree') {\n var winw = 300;\n var winh = 450;\n } else {\n var winw = 500;\n var winh = 200;\n }\n } catch(e) {\n var winw = 500;\n var winh = 200;\n }\n \n var w = window.open(winurl, 'resultwin', 'width=' + winw + ',height=' + winh + ',status=yes,resizable=yes,scrollbars=yes');\n w.focus();\n return w;\n}", "function resultsHelpClicked() {\n window.open(\"https://www.visualcalcs.com/support/#Results\");\n PrintToLog(\"Results Help Clicked\");\n}", "function showCalculatePopup() {\n var baseURL = 'file://' + __dirname + '/html/goldmanCalculation.html';\n resultsWindow = new BrowserWindow({\n width: 450,\n height: 450,\n show: false,\n alwaysOnTop: true,\n resizable: false,\n icon: '../images/icon.ico'\n });\n resultsWindow.on('closed', function () {\n resultsWindow.show = false;\n resultsWindow = null;\n });\n //url params: NG_RT, NG_z, KIn, KOut\n var parameters = \"?NG_RT=\" + $scope.NG_RT +\n \"&NG_z=\" + $scope.z +\n \"&KIn=\" + $scope.potassiumInside +\n \"&KOut=\" + $scope.potassiumOutside +\n \"&NaIn=\" + $scope.sodiumInside +\n \"&NaOut=\" + $scope.sodiumOutside +\n \"&KPerm=\" + $scope.potassiumPerm +\n \"&NaPerm=\" + $scope.sodiumPerm;\n\n parameters = encodeURI(parameters);\n\n resultsWindow.loadURL(baseURL + parameters);\n resultsWindow.setMenu(null);\n resultsWindow.show();\n }", "function openExecutionWindow(tc_id, tcversion_id, build_id, tplan_id, platform_id, whoiam) \n{\n var url = \"lib/execute/execSetResults.php?\" + \"version_id=\" + tcversion_id +\n \"&level=testcase&id=\" + tc_id + \"&tplan_id=\" + tplan_id +\n \"&setting_build=\" + build_id + \"&setting_platform=\" + platform_id +\n \"&caller=\" + whoiam;\n \n var width = getCookie(\"TCExecPopupWidth\");\n var height = getCookie(\"TCExecPopupHeight\");\n \n if (width == null)\n {\n var width = \"800\";\n }\n \n if (height == null)\n {\n var height = \"600\";\n }\n \n var windowCfg = \"width=\"+width+\",height=\"+height+\",resizable=yes,scrollbars=yes,dependent=yes\";\n window.open(fRoot+url, '_blank', windowCfg);\n}", "function showCalculation()\n{\n if (calculation.length != 0)\n {\n myWin = open('', '', 'width=600,height=200,resizable=yes,location=no,directories=no,toolbar=no,status=no,scrollbars=yes');\n var b = '<html><head><title>Calculation</title></head><body><center>' + calculation + '</center></body></html>';\n a = myWin.document;\n a.open();\n a.write(b);\n a.close();\n }\n}", "function createReportWindow(arg) {\n const reportWin = new BrowserWindow({\n width: 900,\n height: 650,\n x: 20,\n y: 30,\n resizable: true,\n webPreferences: {\n nodeIntegration: true\n },\n show: false\n });\n\n reportWin.loadFile(\"./src/resultsWindow/index.html\");\n reportWin.once(\"ready-to-show\", () => {\n reportWin.webContents.send(\"load_results\", arg);\n reportWin.show();\n });\n // reportWin.webContents.openDevTools();\n}", "function showCalculation()\r\n{\r\n \tif(calculation.length != 0)\r\n\t{\r\n \tmyWin=open('','','width=600,height=200,resizable=yes,location=no,directories=no,toolbar=no,status=no,scrollbars=yes');\r\n \tvar b='<html><head><title>Calculation</title></head><body><center>'+calculation+'</center></body></html>';\r\n \ta=myWin.document;\r\n \ta.open();\r\n \ta.write(b);\r\n \ta.close();\r\n\t}\r\n}", "function viewHtml() {\n var entry = ProjectManager.getSelectedItem();\n if (entry === undefined) {\n entry = DocumentManager.getCurrentDocument().file;\n }\n var path = entry.fullPath;\n var w = window.open(path);\n w.focus();\n }", "function openNewPageWithRawResults(result) {\n alert(result)\n }", "function goToAnalysis() {\n\ttargets = document.querySelectorAll('.clusterlabel')\n\tfor(i=0;i<targets.length;i++){\n\t\ttargets[i].onclick=function() {\n\t\t\tvar analysis = window.open('cluster-analysis.html', '_blank');\n\t\t\tanalysis.focus();\n\t\t}\n\t}\n}", "function showGeneInfo(geneID)\n{\n\tvar w=window.open('/transmart/details/gene/?rwg=y&altId='+geneID , 'detailsWindow', 'width=900,height=800'); \n\tw.focus(); \n}", "function openCvvWindow()\n{\n\tNewWindow = window.open('cvv.html','What is cvv','width=800,height=500,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,colyhistory=no'); \n}", "function displayTestResults() {\n // Setup the tests\n QUnit.urlParams({});\n QUnit.config(myConfig);\n QUnit.load(run_all_tests);\n\n // Run the tests\n var html = QUnit.getHtml().setWidth(1000).setHeight(600);\n SpreadsheetApp.getUi().showModalDialog(html, 'File Mapper Unit Tests');\n}", "function explainGame() {\n window.open(\"vcaballeassign3_3.html\");\n}", "function openSourceWindow(e) {\n var test = tests[e.target.href.match(/#(.+)$/)[1]],\n popWnd = window.open(\"\", \"\", \"scrollbars=1, resizable=1\"),\n innerHTML = '';\n\n innerHTML += '<b>Test </b>';\n innerHTML += '<b>' + test.id + '</b> <br /><br />\\n';\n\n if (test.description) {\n innerHTML += '<b>Description</b>';\n innerHTML += '<pre>' +\n test.description.replace(/</g, '&lt;').replace(/>/g, '&gt;') +\n ' </pre>\\n';\n }\n\n innerHTML += '<br /><br /><br /><b>Testcase</b>';\n innerHTML += '<pre>' + test.code + '</pre>\\n';\n\n innerHTML += '<br /><b>Path</b>';\n innerHTML += '<pre>' + test.path + '</pre>';\n innerHTML += '<br /><a href=\"javascript:void(window.open(\\'http://hg.ecmascript.org/tests/test262/file/tip/test/suite'\n innerHTML += test.path.replace(\"TestCases\", \"\") + '\\'));\">' + 'Hg source' + '</a> (might be newer than the testcase source shown above)\\n'\n \n popWnd.document.write(innerHTML);\n }", "function doClick2() {\n const REF = \"http://corpus.quran.com/qurandictionary.jsp\";\n let p = \"\";\n if (menu2.value) p = \"?q=\" + currentRoot()\n console.log(\"Corpus\" + p);\n window.open(REF + p, \"NewTab\") //, \"resizable,scrollbars\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The router file's path is invalid
function testRouterInvalidJsonPath() { var routerJsonPath = ".invalidJson", proxyManager = new ProxyManager(routerJsonPath, {}); A.areEqual(routerJsonPath, proxyManager.proxyConfig, 'Router jsonpath doesn\'t match'); }
[ "function testRouterValidJsonPath() {\n\n var routerJsonPath = \"./config/router.json\",\n proxyManager = new ProxyManager(routerJsonPath, {});\n A.areEqual(routerJsonPath, proxyManager.proxyConfig, 'Router jsonpath doesn\\'t match');\n }", "createRouteFile() {\n // check if `router.js` file exists already in the routes folder\n if (!fs.existsSync(`${this.route}/router.js`)) {\n const file = path.join(__dirname, '../files/router.js');\n\n fs.readFile(file, \"utf-8\", (err, data) => {\n if (err) {\n console.log(err);\n return;\n }\n\n // write `router.js` file\n fs.writeFile(`${this.route}/router.js`, data, (err) => {\n if (err) {\n console.log('Error creating router.js file');\n return;\n }\n\n console.log(\"Successfully created router.js\");\n });\n });\n\n return;\n }\n\n console.log(`router.js already exists`);\n }", "registerPath() {\n this.router.post('/import', this.import.bind(this));\n }", "function sendBadRouteMessage( res )\n{\n\tres = res.status( 404 );\n\tres.json( { message : \"That URL Path Doesn't Exist\" } );\n}", "function PathResolver() {}", "function RouterException(msg) {\n Error.call(this, msg);\n }", "function validatePath(path) {\n if (path == name)\n return true\n}", "function validPath(path) {\n if (!(path && path.length !== 0)) {\n alert(\"Please enter a valid path\");\n return false;\n } else {\n return true;\n }\n }", "[validatePath](path) {\n\t\tconst absolutePath = Path.resolve(this.rootPath, path);\n\t\tif(this.sandbox.length !== 0 && !this.sandbox.some((sandboxPath) => absolutePath.startsWith(sandboxPath)))\n\t\t\tthrow new Error(`Path is out of the sandbox: ${absolutePath}`);\n\t\treturn absolutePath;\n\t}", "function validateRoute(req,res,next){\n const body = req.body;\n !body || body === {}\n ? res.status(400).json({ message: \"post not included\" })\n : req.params.item !== global.configuration.routes[0].sourcePath.replace('/', '')\n ? res.status(404).json({message: \"sourcePath match not found\"})\n : next();\n}", "function middlewareShouldThrowOnInvalidRouter() {\n expect(() => {\n new Ginseng(this.config).middleware({ router: \"invalid\" })\n }).toThrow(\n new TypeError(\"Invalid router: 'invalid'\"))\n}", "function validatePath(ruta) {\n return path.isAbsolute(ruta); // Retorna un booleano\n}", "routerReady() { }", "function errorLoadRoute(err) {\n // On error loaded page we can redirect user to 404 page or error page.\n console.error('Loaded page failed', err);\n}", "registerRoute() {\n /**\n * Base path must always be defined\n */\n if (!this.config.basePath) {\n throw new utils_1.Exception(`Missing property \"basePath\" in \"${this.diskName}\" disk config`, 500, 'E_MISSING_LOCAL_DRIVER_BASEPATH');\n }\n const routeName = LocalFileServer.makeRouteName(this.diskName);\n const routePattern = `${this.config.basePath.replace(/\\/$/, '')}/${LocalFileServer.filePathParamName}`;\n this.logger.trace({ route: routePattern, name: routeName }, 'registering drive route');\n this.router\n .get(routePattern, async ({ response, request, logger }) => {\n const location = request.param(LocalFileServer.filePathParamName).join('/');\n const fileVisibility = await this.driver.getVisibility(location);\n const usingSignature = !!request.input('signature');\n /**\n * Deny request when not using signature and file is \"private\"\n */\n if (!usingSignature && fileVisibility === 'private') {\n response.unauthorized('Access denied');\n return;\n }\n /**\n * Deny request when using signature but its invalid. File\n * visibility doesn't play a role here.\n */\n if (usingSignature && !request.hasValidSignature()) {\n response.unauthorized('Access denied');\n return;\n }\n /**\n * Read https://datatracker.ietf.org/doc/html/rfc7234#section-4.3.5 for\n * headers management\n */\n try {\n const filePath = this.driver.makePath(location);\n const stats = await this.driver.getStats(filePath);\n /**\n * Ignore requests for directories\n */\n if (!stats.isFile) {\n return response.notFound('File not found');\n }\n /**\n * Set Last-Modified or the Cache-Control header. We pick\n * the cache control header from the query string only\n * when a valid signature is presented.\n */\n if (usingSignature && request.input('cacheControl')) {\n response.header('Cache-Control', request.input('cacheControl'));\n }\n else {\n response.header('Last-Modified', stats.modified.toUTCString());\n }\n /**\n * Set the Content-Type header. We pick the contentType header\n * from the query string only when a valid signature\n * is presented\n */\n if (usingSignature && request.input('contentType')) {\n response.header('Content-Type', request.input('contentType'));\n }\n else {\n response.type((0, path_1.extname)(filePath));\n }\n /**\n * Set the following headers by reading the query string values. Must\n * be done when a signature was presented.\n */\n if (usingSignature && request.input('contentDisposition')) {\n response.header('Content-Disposition', request.input('contentDisposition'));\n }\n if (usingSignature && request.input('contentEncoding')) {\n response.header('Content-Encoding', request.input('contentEncoding'));\n }\n if (usingSignature && request.input('contentLanguage')) {\n response.header('Content-Language', request.input('contentLanguage'));\n }\n /**\n * Define etag when present in stats\n */\n if (stats.etag) {\n response.header('etag', stats.etag);\n }\n /*\n * Do not stream files for HEAD request, but set the appropriate\n * status code.\n *\n * 200: When NOT using etags or cache is NOT fresh. This forces browser\n * to always make a GET request\n *\n * 304: When etags are used and cache is fresh\n */\n if (request.method() === 'HEAD') {\n response.status(response.fresh() ? 304 : 200);\n return;\n }\n /*\n * Regardless of request method, if cache is\n * fresh, then we must respond with 304\n */\n if (response.fresh()) {\n response.status(304);\n return;\n }\n /**\n * Set content length if serving the file\n */\n response.header('Content-length', stats.size.toString());\n /**\n * Stream file.\n */\n return response.stream(await this.driver.getStream(location));\n }\n catch (error) {\n if (error.original?.code === 'ENOENT' || error.code === 'ENOENT') {\n response.notFound('File not found');\n }\n else {\n logger.fatal(error, `drive: Unable to serve file \"${location}\" from \"${this.diskName}\" disk`);\n response.internalServerError('Cannot process file');\n }\n }\n })\n .as(routeName);\n }", "function isValidPath(p) {\n return isString(p) && /^\\/?[^\\/?#]*(\\/[^\\/?#]+)*\\/?(\\?[^#]*)?(#.*)?$/.test(p);\n }", "validateOriginPath(originPath) {\n if (core_1.Token.isUnresolved(originPath)) {\n return originPath;\n }\n if (originPath === undefined) {\n return undefined;\n }\n let path = originPath;\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n if (path.endsWith('/')) {\n path = path.slice(0, -1);\n }\n return path;\n }", "initializeRouterFromFile() {\n let input = fs.readFileSync('infile.dat', 'utf8').split('\\n');\n\n let lastRouterId = '';\n input.forEach(function (line) {\n if (line.indexOf('\\r')) {\n line = line.split('\\r')[0];\n }\n line = line.split(' ');\n if (line[0] !== '') {\n const router = new Router();\n router.id = line[0];\n router.network_name = line[1];\n this.routers.set(line[0], router);\n lastRouterId = line[0];\n } else {\n const router = this.routers.get(lastRouterId);\n let cost = line[2] ? line[2] : 1\n let connectedRouter = {\n routerId: +line[1],\n cost: +cost\n }\n router.routing_table_1.push(connectedRouter);\n router.neighbors[line[1]] = parseInt(line[2]) || 1;\n this.graph.addVertexToGraph(router.id, router.neighbors);\n router.link_cost = line.length > 2 ? line[2] : 1;\n }\n }, this);\n\n console.log(this.graph);\n this.generateRoutingTables();\n }", "_loadError(url, err) {\n this.error(\"app:error:resolve\", [err, url]);\n return { template: \" \" };\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handles the input change of the newest card
function handleCardInputChange(evt) { setNewCard({ ...newCard, [evt.target.name]: evt.target.value, }); }
[ "function cardUpdateListener(data) {\n AppData.setCardContent(data[\"card\"], data[\"newContent\"]);\n \tAppData.saveData();\n }", "function handleCardsInputChange(evt, idx) {\n const dupeCards = [...cards];\n dupeCards[idx][evt.target.name] = evt.target.value;\n setCards(dupeCards);\n }", "function newCard() {\n if (snapDeck.length === 0) {\n endGame()\n }\n const newCard = snapDeck.pop()\n currentCard.innerHTML = `Current card is ${newCard.rank} and suit ${newCard.suit}`\n if (snapPot.length >= 1) {\n const last = snapPot.length - 1\n lastCard.innerHTML = `Last card is ${snapPot[last].rank} and suit ${snapPot[last].suit}`\n }\n snapPot.push(newCard)\n deckNum.innerHTML = snapDeck.length\n snapPotNum.innerHTML = snapPot.length\n error.innerHTML = ''\n }", "addcard(){\n console.log(\"enter details pressed\");\n Actions.addcard();\n }", "function updateCard() {\n\n // 6-1 Create the payload object.\n const payload = {\n fields: {\n Name: this.name,\n Notes: this.note\n }\n }\n\n // 6-2 Edit the card:\n this.editCard(this.idToEdit, payload)\n}", "function card_update_ui() {\n\tg_dontRenderSelectedCard = true;\n\tif (g_ui.deckIdx >= 0 && g_ui.deckIdx < g_decks.length && g_ui.cardIdx >= 0 && g_ui.cardIdx < g_decks[g_ui.deckIdx].cards.length) {\n\t\tlet deck = g_decks[g_ui.deckIdx];\n\t\tlet card = deck.cards[g_ui.cardIdx];\n\n\t\t$('#card-form-container').attr('card-type', card.constructor.name);\n\t\t$('#card-type').val(card.constructor.name);\n\n\t\t$('#card-title').attr('disabled', false).val(card.title);\n\t\t$('#card-title-multiline').attr('disabled', false).prop('checked', card.title_multiline);\n\t\t$('#card-subtitle').attr('disabled', false).val(card.subtitle);\n\t\t$('#card-color').attr('disabled', false).val(card.color).change();\n\t\t$('#card-icon').attr('disabled', false).val(card.icon);\n\t\t$('#card-icon-back').attr('disabled', false).val(card.icon_back);\n\t\t$('#card-background').attr('disabled', false).val(card.background_image);\n\t\t$('#card-description').attr('disabled', false).val(card.description);\n\t\t$('#card-contents').attr('disabled', false).val(card.contents.join('\\n'));\n\t\t$('#card-tags').attr('disabled', false).val(card.tags ? card.tags.join(', ') : '');\n\t\t$('#card-reference').attr('disabled', false).val(card.reference);\n\t\t$('#card-compact').attr('disabled', false).prop('checked', card.compact);\n\n\t\tif (card.constructor === CreatureCard) {\n\t\t\t$('.creature-hide').hide();\n\t\t\t$('.item-hide').show();\n\t\t\t$('.spell-hide').show();\n\t\t\t$('.power-hide').show();\n\n\t\t\t$('.creature-only').show();\n\t\t\t$('.item-only').hide();\n\t\t\t$('.spell-only').hide();\n\t\t\t$('.power-only').hide();\n\n\t\t\t$('#card-creature-cr').val(card.cr);\n\t\t\t$('#card-creature-size').val(card.size);\n\t\t\t$('#card-creature-alignment').val(card.alignment);\n\t\t\t$('#card-creature-type').val(card.type);\n\n\t\t\t$('#card-creature-ac').val(card.ac);\n\t\t\t$('#card-creature-hp').val(card.hp);\n\t\t\t$('#card-creature-perception').val(card.perception);\n\t\t\t$('#card-creature-speed').val(card.speed);\n\n\t\t\t$('#card-creature-strength').val(card.stats[0]);\n\t\t\t$('#card-creature-dexterity').val(card.stats[1]);\n\t\t\t$('#card-creature-constitution').val(card.stats[2]);\n\t\t\t$('#card-creature-intelligence').val(card.stats[3]);\n\t\t\t$('#card-creature-wisdom').val(card.stats[4]);\n\t\t\t$('#card-creature-charisma').val(card.stats[5]);\n\n\t\t\t$('#card-creature-resistances').val(card.resistances);\n\t\t\t$('#card-creature-vulnerabilities').val(card.vulnerabilities);\n\t\t\t$('#card-creature-immunities').val(card.immunities);\n\n\t\t\t$('#card-contents').attr('rows', 17);\n\t\t} else if (card.constructor === ItemCard) {\n\t\t\t$('.creature-hide').show();\n\t\t\t$('.item-hide').hide();\n\t\t\t$('.spell-hide').show();\n\t\t\t$('.power-hide').show();\n\n\t\t\t$('.creature-only').hide();\n\t\t\t$('.item-only').show();\n\t\t\t$('.spell-only').hide();\n\t\t\t$('.power-only').hide();\n\n\t\t\t$('#card-contents').attr('rows', 27);\n\t\t} else if (card.constructor === SpellCard) {\n\t\t\t$('.creature-hide').show();\n\t\t\t$('.item-hide').show();\n\t\t\t$('.spell-hide').hide();\n\t\t\t$('.power-hide').show();\n\n\t\t\t$('.creature-only').hide();\n\t\t\t$('.item-only').hide();\n\t\t\t$('.spell-only').show();\n\t\t\t$('.power-only').hide();\n\n\t\t\t$('#card-spell-level').val(card.level);\n\t\t\t$('#card-spell-ritual').prop('checked', card.ritual);\n\t\t\t$('#card-spell-casting-time').val(card.casting_time);\n\t\t\t$('#card-spell-range').val(card.range);\n\t\t\t$('#card-spell-verbal').prop('checked', card.verbal);\n\t\t\t$('#card-spell-somatic').prop('checked', card.somatic);\n\t\t\t$('#card-spell-materials').val(card.materials);\n\t\t\t$('#card-spell-duration').val(card.duration);\n\t\t\t$('#card-spell-type').val(card.type);\n\t\t\t$('#card-spell-classes').val(card.classes);\n\t\t\t$('#card-spell-higher-levels').val(card.higherLevels);\n\n\t\t\t$('#card-contents').attr('rows', 19);\n\t\t} else if (card.constructor === PowerCard) {\n\t\t\t$('.creature-hide').show();\n\t\t\t$('.item-hide').show();\n\t\t\t$('.spell-hide').show();\n\t\t\t$('.power-hide').hide();\n\n\t\t\t$('.creature-only').hide();\n\t\t\t$('.item-only').hide();\n\t\t\t$('.spell-only').hide();\n\t\t\t$('.power-only').show();\n\n\t\t\t$('#card-contents').attr('rows', 27);\n\t\t} else {\n\t\t\t$('.creature-hide').show();\n\t\t\t$('.item-hide').show();\n\t\t\t$('.spell-hide').show();\n\t\t\t$('.power-hide').show();\n\n\t\t\t$('.creature-only').hide();\n\t\t\t$('.item-only').hide();\n\t\t\t$('.spell-only').hide();\n\t\t\t$('.power-only').hide();\n\n\t\t\t$('#card-contents').attr('rows', 27);\n\t\t}\n\n\t\tlet cardsList = $('#cards-list');\n\t\tif ((g_previousCardIdx || g_previousCardIdx === 0) && g_previousCardIdx < deck.cards.length) {\n\t\t\tlet oldCard = deck.cards[g_previousCardIdx];\n\t\t\tlet oldCardElt = cardsList[0].children[g_previousCardIdx];\n\t\t\toldCardElt.style.backgroundColor = oldCard.color ? oldCard.color + '29' : '';\n\t\t\toldCardElt.classList.remove('selected');\n\t\t}\n\t\tlet cardScrollHeight = cardsList[0].children[g_ui.cardIdx].scrollHeight;\n\t\tlet scrollPos = g_ui.cardIdx * cardScrollHeight;\n\t\tif (scrollPos < cardsList[0].scrollTop + cardScrollHeight)\n\t\t\tcardsList[0].scrollTop = scrollPos - cardScrollHeight;\n\t\telse if (scrollPos >= cardsList[0].scrollTop + cardsList[0].offsetHeight - 2 * cardScrollHeight)\n\t\t\tcardsList[0].scrollTop = scrollPos - cardsList[0].offsetHeight + 2 * cardScrollHeight;\n\t\tcardsList[0].children[g_ui.cardIdx].classList.add('selected');\n\t} else {\n\t\t$('#card-form-container').removeAttr('card-type');\n\t\t$('#card-type').val('Card');\n\n\t\t$('#card-title').attr('disabled', true).val('');\n\t\t$('#card-title-multiline').attr('disabled', true).prop('checked', false);\n\t\t$('#card-subtitle').attr('disabled', true).val('');\n\t\t$('#card-color').attr('disabled', true).val('').change();\n\t\t$('#card-icon').attr('disabled', true).val('');\n\t\t$('#card-icon-back').attr('disabled', true).val('');\n\t\t$('#card-background').attr('disabled', true).val('');\n\t\t$('#card-description').attr('disabled', true).val('');\n\t\t$('#card-contents').attr('disabled', true).val('');\n\t\t$('#card-tags').attr('disabled', true).val('');\n\t\t$('#card-reference').attr('disabled', true).val('');\n\t\t$('#card-compact').attr('disabled', true).prop('checked', false);\n\n\t\t$('.creature-hide').hide();\n\t\t$('.item-hide').hide();\n\t\t$('.spell-hide').hide();\n\t\t$('.power-hide').hide();\n\n\t\t$('.creature-only').hide();\n\t\t$('.item-only').hide();\n\t\t$('.spell-only').hide();\n\t\t$('.power-only').hide();\n\t\t\n\t\t$('#card-contents').attr('disabled', true).attr('rows', 27);\n\t}\n\n\tg_dontRenderSelectedCard = false;\n\tcard_render();\n}", "function lastcard() {\t\n\tif (i > 0) {\n\t\ti -= 1;\n\t}\n\trefresh();\n}", "function handleDeckInputChange(evt) {\n setUpdateDeck({\n ...updateDeck,\n [evt.target.name]: evt.target.value,\n });\n }", "function handleEdittedCard(newCardData, cardCollection) {\n const cardId = parseInt(newCardData.id)\n const filteredCards = cardsData.filter((card) => {\n return card.id !== cardId\n })\n newCardData[\"collection\"] = cardCollection\n const allCardsUpdated = [...filteredCards, newCardData]\n setCardsData(allCardsUpdated)\n \n }", "function changeCard () {\n let position = document.getElementById(\"card-id\").value;\n socket.emit('changeCard', position, playerNumber);\n return;\n}", "function manipulateCard(event) {\n\t// Check if there is any card already clicked\n\tif (firstClickedElement === null){\n\n\t\t// No card clicked yet => store its value (class) into firstCard variable\n\t\tfirstCard = event.target.lastElementChild.getAttribute('class');\n\n\t\t// Show the card\n\t\tshowCard(event);\n\n\t\t// Get the element of the first clicked card\n\t\tfirstClickedElement = document.querySelector('.clicked');\n\n\t} else if (firstCard === event.target.lastElementChild.getAttribute('class')) {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Since 2nd card matches the first one => change cards status to \"card match\" (both cards remain with their face up) -> with a short delay\n\t\tchangeCardsStatus(event, 'card match');\n\n\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\tother2Cards();\n\t\t\n\t\t// Increase number of matched cards\n\t\tcellNo = cellNo + 2;\n\n\t} else {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Set the 2 clicked cards attributes to wrong class -> with a short delay\n\t\tchangeCardsStatus(event, 'card open show wrong');\n\n\t\t// Set the 2 clicked cards attributes to its defaults -> with a short delay\n\t\tsetTimeout(function(){\n\t\t\tchangeCardsStatus(event, 'card');\n\n\t\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\t\tother2Cards();\n\t\t}, 300);\n\t}\n}", "function changeCardName(cname, ccard) {\r\n\t\t// Change to provide validation; no empty name (no action taken)\r\n\t\tvar name = prompt(\"Please enter a new name\",cname);\r\n\t\tif (name!=null && name!=\"\")\r\n\t\t{\r\n\t\t\t// change name\r\n\t\t\ttext = splitString(name, 12);\r\n\t\t\tnlines = text.length;\r\n\t\t\t$($(ccard).find(\"text\")[0]).text(text[0]);\r\n\t\t\t$($(ccard).find(\"text\")[1]).text(text[1]);\r\n\t\t\t$($(ccard).find(\"text\")[2]).text(text[2]);\r\n\t\t\tconsole.log(\"Card name changed\");\r\n\t\t\tconsole.log(cs.getCards());\r\n\t\t\tcs.sync();\r\n\t\t\tconsole.log(\"Card model changed\");\r\n\t\t\tconsole.log(cs.getCards());\r\n\t\t} else {\r\n\t\t\t// Nothing\r\n\t\t\tconsole.log(\"Card name not changed\");\r\n\t\t}\r\n\t}", "updateCard(event) {\n // Grab editor window textarea element\n var editorText = document.getElementById(\"editorText\");\n // Grab editor window video element\n var editorVideo = document.getElementById(\"editorVideo\");\n // grab selected card's index\n var currCardIndex = editorText.cardindex;\n\n // grab array from app.js which holds each clipcard's info\n var cardContainer = this.props.cardContainer;\n // get selected clipcard's info\n var currCardInfo = cardContainer[currCardIndex]\n console.log(\"current card state: \", currCardInfo)\n // get the current card's text and video values\n var currCardText = document.getElementById(currCardInfo['id']).children[0].children[1]\n var currCardMedia = document.getElementById(currCardInfo['id']).children[2];\n // update the card's text value to be the editor window's text's value\n currCardText.value = editorText.value\n // update the card's video source to be the editor window's video source\n currCardMedia.src = editorVideo.src\n\n var clipCard = this.state.clipCard;\n clipCard.mediaPath = currCardMedia.src;\n clipCard.text = currCardText.value\n this.setState({\n 'clipCard': clipCard,\n });\n\n console.log(\"card container: \", cardContainer)\n }", "handleCard(event) {\n const isNumber = isNaN(Number(event.target.value.split(' ').join('')));\n if (!isNumber) {\n const result = new CardUtility().formatCardNumber(event.target.value);\n if (result !== false) {\n this.value = result.value;\n this.cardType = result.cardType.type;\n this.maxLength = result.cardType.maxCardNumberLength;\n if (this.value.length === this.maxLength) {\n this.isValid = true;\n if (this.cardType === 'fake') {\n this.isValid = false;\n }\n }\n else {\n this.isValid = false;\n }\n }\n else {\n this.isValid = result;\n this.cardType = '';\n this.maxLength = 16;\n }\n }\n else {\n if (this.value.length !== 0) {\n this.value = this.value.substring(0, this.value.length - 1);\n }\n else {\n this.value = '';\n }\n }\n }", "updateDealtCards() {\n this.updateBlackjackState();\n }", "function editCard() {\n //TO DO\n console.log(\"Edit Card\");\n }", "function processLastSelection() {\n D1846.draft.hand.length = 0;\n var playerIndex = D1846.input.playerid - 1;\n D1846.draft.players[playerIndex].privates.push(D1846.privateName);\n var cash = D1846.draft.players[playerIndex].cash;\n cash -= D1846.numcost;\n D1846.draft.players[playerIndex].cash = cash; \n $(\"#lastdraft2\").remove();\n $(\"#lastdraft1\").remove();\n finishDraft();\n}", "function postInput(ev) {\n\t//var p = $.ajax({type: 'POST', url: 'http://www.tomladendorf.com/flashcards/addcard.cgi', data: \"first_name=Tom&last_name=Ladendorf\"});\n\tvar question = $(\"#questionField\").val();\n\tvar answer = $(\"#answerField\").val();\n\tvar master = ev.data;\n\tvar back = $.post(\"addcard.cgi\", \"question=\" + question + \"&answer=\" + answer + \"&id=\" + master.length + \"&tablename=\" + master.tableName, function(data) {\n\t\t//alert(\"DATA: \" + data);\n\t});\n\tvar newPair = \"<div class='pair'><div class='question'>\" + question + \"</div><div class='answer'>\" + answer + \"</div></div>\";\n\t$(\"body\").append($(newPair));\n\tmaster.add(new Card(question, answer));\n\t$(\"#addContainer\").remove();\n\t$(\"#buttons\").append($(\"<a id='add' class='button'>ADD A NEW CARD</a>\"));\n\t$(\"#add\").click(ev.data, displayInput);\n\t$(\"body\").append($(back));\n}", "function resetInput(){\n\tinCardNo='01';\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets the selected instructor in the instructor select element
function selectInstructorDropDown() { let instructorId = document.getElementById('selectedInstructorId'); if (instructorId != null) { let dropDown = document.getElementById('selectInstructor'); for (let i=0; i < dropDown.options.length; i++) { if (dropDown.options[i].value == instructorId.value) { dropDown.options[i].selected = true; return; } } } }
[ "function SetupInstructorOptions(e) {\n\tvar DEBUG_setInstructor = true;\n\tvar c,\n\t\t\tthisSelectId, thisSelect;\n\tif ( DEBUG_setInstructor ) { console.log('BEGIN SetupInstructorOptions[e.id='+e.id+']'); }\n\tvar eIdParts = e.id.split('_');\n\tvar scmId = eIdParts[1];\n\tvar campusIndex = parseInt(eIdParts[2]);\n\tvar instructorIndex = parseInt(eIdParts[3]);\n\tif ( DEBUG_setInstructor ) { console.log('ScheduleInstructor.length='+ScheduleInstructor.length); }\n\tvar InstructorIdsSelected = []; // Array of instructorIds that have been selected to this point.\n\tfor ( c=0; c<ScheduleInstructor.length; c++ ) { // Loop thru campus indexes.\n\t\tthisSelectId = 'selInstructor_'+scmId+'_'+campusIndex+'_'+c;\n\t\tif ( DEBUG_setInstructor ) { console.log('thisSelectId='+thisSelectId); }\n\t\tthisSelect = document.getElementById(thisSelectId);\n\t\tSelectedInstructorId = parseInt(thisSelect.options[thisSelect.selectedIndex].value);\n\t\tif ( DEBUG_setInstructor ) { console.log('SelectedInstructorId='+SelectedInstructorId); }\n\t\tif ( !isNaN(SelectedInstructorId) ) { InstructorIdsSelected.push(SelectedInstructorId); } // Add the instructorId to the array.\n\t} // Loop thru campus indexes.\n\tif ( DEBUG_setInstructor ) { console.log('InstructorIdsSelected='+InstructorIdsSelected); }\n\tfor ( c=0; c<ScheduleInstructor.length; c++ ) { // Loop thru campus indexes.\n\t\tthisSelectId = 'selInstructor_'+scmId+'_'+campusIndex+'_'+c;\n\t\tif ( DEBUG_setInstructor ) { console.log('thisSelectId='+thisSelectId); }\n\t\tthisSelect = document.getElementById(thisSelectId);\n\t\tconsole.log('thisSelect.selectedIndex='+thisSelect.selectedIndex);\n\t\tSelectedInstructorId = parseInt(thisSelect.options[thisSelect.selectedIndex].value);\n\t\tif ( !isNaN(SelectedInstructorId) ) {\n\t\t\tSelectedIndex = thisSelect.selectedIndex;\n\t\t} else {\n\t\t\tSelectedInstructorId = 0; SelectedIndex = 0;\n\t\t}\n\t\tif ( DEBUG_setInstructor ) { console.log('SelectedInstructorId='+SelectedInstructorId+' SelectedIndex='+SelectedIndex); }\n\t\tthisSelect.options.length = 0;\n\t\tvar opt = document.createElement('option');\n\t\topt.value = '';\n\t\topt.innerHTML = '';\n\t\tthisSelect.appendChild(opt);\n\t\t/**/\n\t\tfor ( var i=0; i<ScheduleInstructor.length; i++ ) {\n\t\t\tif ( ScheduleInstructor[i].instructorId === SelectedInstructorId || InstructorIdsSelected.indexOf(ScheduleInstructor[i].instructorId) === -1 ) { \n\t\t\t\tif ( DEBUG_setInstructor ) { console.log('Adding selInstructor_'+c+' option for '+ScheduleInstructor[i].Name+'.'); }\n\t\t\t\topt = document.createElement('option');\n\t\t\t\topt.value = ScheduleInstructor[i].instructorId;\n\t\t\t\topt.innerHTML = ScheduleInstructor[i].Name;\n\t\t\t\tthisSelect.appendChild(opt);\n\t\t\t}\n\t\t}\n\t\tif ( SelectedInstructorId ) {\n\t\t\t//thisSelect.selectedIndex = SelectedInstructorId;\n\t\t\tthisSelect.value = SelectedInstructorId;\n\t\t}\n\t} // Loop thru campus indexes.\n} // END SetupInstructorOptions.", "select()\n\t{\n\t\tthis.units.forEach((u) => u.selected.value = true);\n\t}", "function selectCourse() {\n courseSelection = document.getElementById('course').value;\n}", "function selectLeague(){\n setOption(document.getElementById('league_select'), document.getElementById('leagueid').value);\n}", "function setSelectModif(etat, poste){\n document.getElementById(\"etat\").selectedIndex = etat;\n document.getElementById(\"poste\").selectedIndex = poste;\n}", "function addNewInstructor() { //Adds the inputted instructors into an array for later user.\n\n\n if (instructorIdArray == null) instructorIdArray = []; //Testing to see if the online dtabase is empty and if so just create an empty array\n\n instructorIdArray.push(document.getElementById('instructorId').value);//pushing the inputs into the arrays\n\n document.getElementById('instructors');\n\n var opt = instructorIdArray[instructorIdArray.length - 1]; //Creating an option based off of the latest option in the instructor array\n var el = document.createElement(\"option\");//Creating an optio element\n el.textContent = opt;//Making that element have the data from the option\n el.value = opt;//Making the value have the data from the option\n document.getElementById('instructors').appendChild(el); //Adding the element to the select input\n\n var optQuery = instructorIdArray[instructorIdArray.length - 1]; //Creating an option based off of the latest option in the instructor array\n var elQuery = document.createElement(\"option\");//Creating an optio element\n elQuery.textContent = opt;//Making that element have the data from the option\n elQuery.value = opt;//Making the value have the data from the option\n document.getElementById('instructorsQuery').appendChild(elQuery); //Adding the element to the select input\n\n goToPage(pageFromInstructor); //Going back to he prevoius page\n instIDRef.update(instructorIdArray);//Updating the online databse\n\n document.getElementById(\"instructorId\").value = \"\"; //Clearing the input field\n\n}", "function loadSelectableInstructors ( )\n\t{\n\t\t$.ajax(\n\t\t{\n\n\t\t\ttype: 'GET',\n\n\t\t\turl: 'data/phps/_php.selectable.instructors.display.php', \n\n\t\t\tdataType: 'json',\n\n\t\t\tsuccess: function (data) \n\t\t\t{\n\t\t\t\t//show user data based on old id\n\t\t\t\tvar tasUserDisplaySelectHtmlElement = document.getElementById ('cinstructor');\n\t\t\t\tconsole.log(data);\n\t\t\t\tfor ( i = 0; i < data.length; i ++ )\n\t\t\t\t{\n\t\t\t\t\tvar newOption = document.createElement ( 'option' );\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tvar value = data[i].itemName;\n\t\t\t\t\tnewOption.value = value;\n\t\t\t\t\tnewOption.innerHTML = value;\n\t\t\t\t\ttasUserDisplaySelectHtmlElement.appendChild ( newOption );\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function setSubjSelect() {\n\t\n\t$('#subjects').empty();\n\t\n\tvar subjects = g_curIncident.subjects;\n\tvar len = 0;\n\t\n\tif(subjects) {\n\t\tlen = subjects.length;\n\t}\n\t\n\tif(len > 0) {\n\t\tfor(i=0;i<len;i++) {\n\t\t\t\n\t\t\tvar subject = subjects[i];\n\t\t\tvar subjectName = (!subject.fname)?\"\":subject.lname + \", \" + subject.fname;\n\t\t\t\n\t\t\t$('#subjects')\n\t .append($('<option>', { value : subject.civId })\n\t .text(subjectName)); \n\t\t\t\n\t\t\tif(g_curSubject && subject.civId == g_curSubject.civId) {\n\t\t\t\t$('#subjects')[0].selectedIndex = i;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t$('#subjects').selectmenu(\"refresh\");\n\t\t\n\t}\n\t\n}", "function selectItemByValue(elmnt, value){\n\n\t\t\tfor(var i=0; i < elmnt.options.length; i++)\n\t\t\t{\n\t\t\t\tif(elmnt.options[i].value == value)\n\t\t\t\telmnt.selectedIndex = i;\n\t\t\t}\n\t\t}", "function setCoursesDropdown(courseName) {\n let coursesDropdown = document.getElementById('coursesDropdown');\n let selectedChange = false;\n for (let i = 0; i < coursesDropdown.length; i++) {\n if (coursesDropdown.options[i].text == courseName) {\n coursesDropdown.selectedIndex = i;\n selectedChange = true;\n break;\n }\n }\n if (!selectedChange) {\n console.error(\"ERROR whilst setting selected course to:\" + courseName);\n }\n}", "function setBeauticianDocument(event){\n var Beautician = document.getElementById(\"beauticianDoc\");\n Beautician.value = BeautId[this.selectedIndex];\n}", "function autoSetPatient(elementId, name) {\r\n\tselectElement = $(elementId);\r\n\t\r\n\tif (selectElement.selectedIndex==0) {\r\n\t\tfor (iter = 0; iter < selectElement.options.length; iter++) {\r\n\t\t\tif (selectElement.options[iter].text.toLowerCase()==name.toLowerCase()) {\r\n\t\t\t\tselectElement.selectedIndex=iter;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function set_selection() {\n var sel = this;\n\n // Save note\n unsaved_notes[get_current_pair()] = document.getElementById(\"note\").value;\n \n // Not allowed to select disabled electrodes unless in setup mode\n if (sel.classList.contains(\"skeleton\") && get_control_mode() != \"setup\") return;\n\n // Unselect other screws/electrodes\n var oldsel = document.querySelectorAll(\".screw[selected], .electrode[selected]\");\n for (var i = 0; i < oldsel.length; i++) {\n oldsel[i].removeAttribute(\"selected\");\n }\n\n // Select this pair\n var newsel = document.querySelectorAll(\"[pair=\\\"\"+sel.getAttribute(\"pair\")+\"\\\"]\");\n for (var i = 0; i < newsel.length; i++) {\n newsel[i].setAttribute(\"selected\", \"1\");\n }\n if (sel.classList.contains(\"electrode\") && get_control_mode() == \"setup\") {\n setup_electrode_number(sel);\n }\n\n // Clear note\n document.getElementById(\"note\").value = unsaved_notes[get_current_pair()] || \"\";\n\n redraw_pair_info();\n}", "function studentSelectize() {\n var currentSelectizeValue;\n\n $('#edukodas_bundle_statisticsbundle_pointhistory_student').selectize({\n plugins: {\n 'no_results': { message: 'Nepavyko nieko rasti' }\n },\n onChange: function (value) {\n if (!value.length || value == currentSelectizeValue) {\n return;\n }\n },\n onBlur: function () {\n if (this.getValue() === '') {\n this.setValue(currentSelectizeValue);\n }\n },\n onFocus: function () {\n currentSelectizeValue = this.getValue();\n this.clear(true);\n }\n });\n }", "function setSelected (i) {\n selectedStudent = i;\n d3.select (\"h1\")\n .text (i == -1 ? \"No Student Selected\" : \"Test Results for \" + gStudents[i]);\n d3.selectAll (\".student\")\n .classed (\"selected\", function (junk, i2) {\n return i == i2;\n });\n draw ();\n}", "function seleccion(){\n\t\tvar seleccion = document.getElementById(\"cliente\");\n\t\tvar idCliente = seleccion.options[seleccion.selectedIndex].value;\n\t\tdocument.getElementById(\"idCliente\").value = idCliente;\n\t}", "function selectGrade() {\n var grade_menus = document.getElementsByClassName(\"grades-menu\");\n for(var i = 0; i < grade_menus.length; i++){\n var menu = grade_menus[i];\n var id = menu.getAttribute(\"data-id\");\n var camper = getCamperById(id);\n var camper_grade = camper[\"grade_code\"];\n var options = menu.childNodes;\n for(var j = 0; j < options.length; j++){\n var option = options[j];\n if(camper_grade == option.getAttribute(\"value\"))\n {\n option.setAttribute(\"selected\", \"selected\");\n }\n }\n menu.addEventListener(\"change\", onChangeGrade);\n }\n}", "function goTeacherSelect() {\n var selectTeacher = document.getElementById(\"teacherSelect\");\n selectTeacher.classList.toggle(\"selected\");\n}", "function set_selected_option (what, set_val) {\n var last =what.length -1;\n var index;\n for (index=0; index<what.length; index++) {\n if (what[index].value == set_val) {\n what.selectedIndex = index;\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructors Initialize a new instance of `PdfGridEndPageLayoutEventArgs` class.
function PdfGridEndPageLayoutEventArgs(result){return _super.call(this,result)||this;}
[ "function PdfGridBeginPageLayoutEventArgs(bounds,page,startRow){var _this=_super.call(this,bounds,page)||this;_this.startRow=startRow;return _this;}", "function PdfGridEndPageLayoutEventArgs(result) {\n return _super.call(this, result) || this;\n }", "function BeginPageLayoutEventArgs(bounds,page){var _this=_super.call(this)||this;_this.bounds=bounds;_this.pdfPage=page;return _this;}", "function PdfGridBeginPageLayoutEventArgs(bounds, page, startRow) {\n var _this = _super.call(this, bounds, page) || this;\n _this.startRow = startRow;\n return _this;\n }", "function BeginPageLayoutEventArgs(bounds, page) {\n var _this = _super.call(this) || this;\n _this.bounds = bounds;\n _this.pdfPage = page;\n return _this;\n }", "function EndPageLayoutEventArgs(result){var _this=_super.call(this)||this;_this.layoutResult=result;return _this;}", "function EndPageLayoutEventArgs(result) {\n var _this = _super.call(this) || this;\n _this.layoutResult = result;\n return _this;\n }", "function PdfGrid(){var _this=_super.call(this)||this;/**\n * @hidden\n * @private\n */_this.gridSize=new SizeF(0,0);/**\n * Check the child grid is ' split or not'\n */_this.isGridSplit=false;/**\n * @hidden\n * @private\n */_this.isRearranged=false;/**\n * @hidden\n * @private\n */_this.pageBounds=new RectangleF();/**\n * @hidden\n * @private\n */_this.listOfNavigatePages=[];/**\n * @hidden\n * @private\n */_this.parentCellIndex=0;_this.tempWidth=0;/**\n * @hidden\n * @private\n */_this.breakRow=true;_this.splitChildRowIndex=-1;/**\n * The event raised on `begin cell lay outing`.\n * @event\n * @private\n */ //public beginPageLayout : Function;\n/**\n * The event raised on `end cell lay outing`.\n * @event\n * @private\n */ //public endPageLayout : Function;\n_this.hasRowSpanSpan=false;_this.hasColumnSpan=false;_this.isSingleGrid=true;return _this;}", "function PdfGrid() {\n var _this = _super.call(this) || this;\n /**\n * @hidden\n * @private\n */\n _this.gridSize = new SizeF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.isRearranged = false;\n /**\n * @hidden\n * @private\n */\n _this.pageBounds = new RectangleF();\n /**\n * @hidden\n * @private\n */\n _this.listOfNavigatePages = [];\n /**\n * @hidden\n * @private\n */\n _this.flag = true;\n /**\n * @hidden\n * @private\n */\n _this.columnRanges = [];\n /**\n * @hidden\n * @private\n */\n _this.currentLocation = new PointF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.breakRow = true;\n return _this;\n }", "function GridCellEventArgs(graphics,rowIndex,cellIndex,bounds,value){this.gridRowIndex=rowIndex;this.gridCellIndex=cellIndex;this.internalValue=value;this.gridBounds=bounds;this.pdfGraphics=graphics;}", "function PdfGridEndCellDrawEventArgs(graphics,rowIndex,cellIndex,bounds,value,style){var _this=_super.call(this,graphics,rowIndex,cellIndex,bounds,value)||this;_this.cellStyle=style;return _this;}", "function PdfGridStyle(){var _this=_super.call(this)||this;_this.gridBorderOverlapStyle=exports.PdfBorderOverlapStyle.Overlap;_this.bAllowHorizontalOverflow=false;_this.gridHorizontalOverflowType=exports.PdfHorizontalOverflowType.LastPage;return _this;}", "function PdfLayoutResult(page,bounds){this.pdfPage=page;this.layoutBounds=bounds;}", "function GridCellEventArgs(graphics, rowIndex, cellIndex, bounds, value) {\n this.gridRowIndex = rowIndex;\n this.gridCellIndex = cellIndex;\n this.internalValue = value;\n this.gridBounds = bounds;\n this.pdfGraphics = graphics;\n }", "onFooterPage(event) {\n this.offset = event.page - 1;\n this.bodyComponent.updateOffsetY(this.offset);\n this.page.emit({\n count: this.count,\n pageSize: this.pageSize,\n limit: this.limit,\n offset: this.offset\n });\n if (this.selectAllRowsOnPage) {\n this.selected = [];\n this.select.emit({\n selected: this.selected\n });\n }\n }", "function PdfGridStyle() {\n var _this = _super.call(this) || this;\n _this.gridBorderOverlapStyle = PdfBorderOverlapStyle.Overlap;\n _this.bAllowHorizontalOverflow = false;\n _this.gridHorizontalOverflowType = PdfHorizontalOverflowType.LastPage;\n return _this;\n }", "callToScrollEndEvent() {\n const {\n scrollEnd,\n } = this.options;\n\n if (!scrollEnd) {\n return;\n }\n\n scrollEnd();\n }", "function PdfPage(){var _this=_super.call(this,new PdfDictionary())||this;/**\n * Stores the instance of `PdfAnnotationCollection` class.\n * @hidden\n * @default null\n * @private\n */_this.annotationCollection=null;/**\n * Stores the instance of `PageBeginSave` event for Page Number Field.\n * @default null\n * @private\n */_this.beginSave=null;_this.initialize();return _this;}", "_onScrollDidEnd(event: Object){\n\n let currentEvent = event.nativeEvent;\n let scrollViewWidth = currentEvent.layoutMeasurement.width;\n let currentOffset = currentEvent.contentOffset.x;\n let currentPage = Math.ceil(currentOffset/scrollViewWidth);\n\n // Validate that the onPageChangeEnd prop\n // had been set\n if(this.props.onPageChangeEnd)\n this.props.onPageChangeEnd(currentPage);\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If `range` is a proper range with a start and end, returns the original object. If missing an end, computes a new range with an end, computing it as if it were an event. TODO: make this a part of the event > eventRange system
function ensureVisibleEventRange(range) { var allDay; if (!range.end) { allDay = range.allDay; // range might be more event-ish than we think if (allDay == null) { allDay = !range.start.hasTime(); } range = $.extend({}, range); // make a copy, copying over other misc properties range.end = t.getDefaultEventEnd(allDay, range.start); } return range; }
[ "function ensureVisibleEventRange(range) {\n\t\tvar allDay;\n\n\t\tif (!range.end) {\n\n\t\t\tallDay = range.allDay; // range might be more event-ish than we think\n\t\t\tif (allDay == null) {\n\t\t\t\tallDay = !range.start.hasTime();\n\t\t\t}\n\n\t\t\trange = {\n\t\t\t\tstart: range.start,\n\t\t\t\tend: t.getDefaultEventEnd(allDay, range.start)\n\t\t\t};\n\t\t}\n\t\treturn range;\n\t}", "function ensureVisibleEventRange(range) {\n\t\tvar allDay;\n\n\t\tif (!range.end) {\n\n\t\t\tallDay = range.allDay; // range might be more event-ish than we think\n\t\t\tif (allDay == null) {\n\t\t\t\tallDay = !range.start.hasTime();\n\t\t\t}\n\n\t\t\trange = $.extend({}, range); // make a copy, copying over other misc properties\n\t\t\trange.end = t.getDefaultEventEnd(allDay, range.start);\n\t\t}\n\t\treturn range;\n\t}", "function convertRange(range) {\n return {\n startOffset: range.start,\n endOffset: range.end,\n count: 1\n }\n}", "convertRange (range) {\n return {\n startOffset: range.start,\n endOffset: range.end,\n count: 1\n }\n }", "function serializeRange(range) {\n return (!range || ((range.startContainer === range.endContainer)\n && (range.startOffset === range.endOffset)))\n ? null : {\n startContainer: range.startContainer,\n startOffset: range.startOffset,\n endContainer: range.endContainer,\n endOffset: range.endOffset\n };\n}", "function invertRange(range) {\n var start = $type.getValue(range.start);\n var end = $type.getValue(range.end);\n return {\n start: 1 - end,\n end: 1 - start\n };\n}", "function invertRange(range) {\n var start = getValue(range.start);\n var end = getValue(range.end);\n return { start: 1 - end, end: 1 - start };\n}", "function invertRange(range) {\n var start = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.start);\n\n var end = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.end);\n\n return {\n start: 1 - end,\n end: 1 - start\n };\n }", "function range(from, to) { // Use Object.create() to create an object that inherits from the \n\n let r = Object.create(range.methods);\n\n r.from = from;\n r.to = to;\n return r;\n}", "function invertRange(range) {\n var start = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.start);\n var end = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.end);\n return { start: 1 - end, end: 1 - start };\n}", "function invertRange(range) {\r\n var start = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.start);\r\n var end = _Type__WEBPACK_IMPORTED_MODULE_0__[\"getValue\"](range.end);\r\n return { start: 1 - end, end: 1 - start };\r\n}", "function invertRange(range) {\r\n var start = __WEBPACK_IMPORTED_MODULE_0__Type__[\"getValue\"](range.start);\r\n var end = __WEBPACK_IMPORTED_MODULE_0__Type__[\"getValue\"](range.end);\r\n return { start: 1 - end, end: 1 - start };\r\n}", "function normalizeRange(range) {\n // We start off by picking start and end nodes. If the start node is a text\n // node, we can just use it as is. If it's a element node, though, we need to\n // use the offset to figure out which child node is the one that's actually\n // selected.\n //\n // There's a additional hiccup that the offsets used by Range represent the\n // spaces in between child nodes, while the TreeWalker API operates on the\n // nodes directly. Because of this, we need to keep track of whether the\n // selected text starts/ends before or after the start/end node. The\n // startOffset/endOffset variables do double duty in this regard — if the\n // startNode/endNode is a text node, the startOffset/endOffset is a text\n // offset, but if the startNode/endNode is a element node, they represent\n // whether the selection starts/ends before the node (0) or after the node\n // (1).\n var makeNodeAndOffset = function (initNode, initOffset) {\n var node, offset;\n if (initNode.nodeType == TEXT_NODE || initNode.childNodes.length == 0) {\n node = initNode;\n offset = initOffset;\n }\n else {\n node = initNode.childNodes[Math.min(initOffset, initNode.childNodes.length - 1)];\n if (node.nodeType == TEXT_NODE) {\n offset = (initOffset == initNode.childNodes.length) ? node.wholeText.length : 0;\n }\n else {\n offset = (initOffset == initNode.childNodes.length) ? 1 : 0;\n }\n }\n return [node, offset];\n };\n var _a = makeNodeAndOffset(range.startContainer, range.startOffset), startNode = _a[0], startOffset = _a[1];\n var _b = makeNodeAndOffset(range.endContainer, range.endOffset), endNode = _b[0], endOffset = _b[1];\n var newRange = new Range();\n var treeWalker = document.createTreeWalker(range.commonAncestorContainer);\n // stages:\n // 0 = Looking for startNode.\n // 1 = startNode found, but it wasn't a non-empty text node — looking for a\n // non-empty text node.\n // 2 = Looking for endNode.\n var stage = 0;\n var node = treeWalker.currentNode;\n var prevEndNode = endNode;\n while (node) {\n if (stage == 0 && node == startNode) {\n if (node.nodeType != TEXT_NODE && startOffset != 0) {\n node = treeWalker.nextNode();\n if (!node) {\n return null;\n }\n }\n stage = 1;\n }\n if (node.nodeType == TEXT_NODE && node.wholeText.trim() != '') {\n if (stage == 1) {\n newRange.setStart(node, (node == startNode) ? startOffset : 0);\n stage = 2;\n }\n if (stage == 2) {\n prevEndNode = newRange.endContainer;\n newRange.setEnd(node, node.wholeText.length);\n }\n }\n if (stage == 2 && node == endNode) {\n if (node.nodeType == TEXT_NODE && node.wholeText.trim() != '') {\n newRange.setEnd(node, endOffset);\n return newRange;\n }\n if (node == newRange.endContainer && endOffset == 0) {\n newRange.setEnd(prevEndNode, prevEndNode.wholeText.length);\n }\n return newRange;\n }\n node = treeWalker.nextNode();\n }\n return null;\n}", "function $R(start, end, exclusive) {\n return new ObjectRange(start, end, exclusive);\n}", "function createRange(pos,end){if(end===void 0){end=pos;}ts.Debug.assert(end>=pos||end===-1);return{pos:pos,end:end};}", "function create_range(start, end) {\n return RangeImpl_1.RangeImpl._create(start, end);\n}", "_convertPriceToRange(range) {\n let price = {};\n price.productType = range.__typename;\n price.currency = range.minimum_price.final_price.currency;\n price.regularPrice = range.minimum_price.regular_price.value;\n price.finalPrice = range.minimum_price.final_price.value;\n price.discountAmount = range.minimum_price.discount.amount_off;\n price.discountPercent = range.minimum_price.discount.percent_off;\n\n if (range.maximum_price) {\n price.regularPriceMax = range.maximum_price.regular_price.value;\n price.finalPriceMax = range.maximum_price.final_price.value;\n price.discountAmountMax = range.maximum_price.discount.amount_off;\n price.discountPercentMax = range.maximum_price.discount.percent_off;\n }\n\n price.discounted = !!(price.discountAmount && price.discountAmount > 0);\n price.range = !!(\n price.finalPrice &&\n price.finalPriceMax &&\n Math.round(price.finalPrice * 100) != Math.round(price.finalPriceMax * 100)\n );\n\n return price;\n }", "function mapWithoutIndex (range) {\n return {\n start: range.start,\n end: range.end\n }\n}", "function range_extract(range) {\n var e_1, _a, e_2, _b, e_3, _c;\n /**\n * 1. Let fragment be a new DocumentFragment node whose node document is\n * range’s start node’s node document.\n * 2. If range is collapsed, then return fragment.\n */\n var fragment = CreateAlgorithm_1.create_documentFragment(range._startNode._nodeDocument);\n if (range_collapsed(range))\n return fragment;\n /**\n * 3. Let original start node, original start offset, original end node,\n * and original end offset be range’s start node, start offset, end node,\n * and end offset, respectively.\n */\n var originalStartNode = range._startNode;\n var originalStartOffset = range._startOffset;\n var originalEndNode = range._endNode;\n var originalEndOffset = range._endOffset;\n /**\n * 4. If original start node is original end node, and they are a Text,\n * ProcessingInstruction, or Comment node:\n * 4.1. Let clone be a clone of original start node.\n * 4.2. Set the data of clone to the result of substringing data with node\n * original start node, offset original start offset, and count original end\n * offset minus original start offset.\n * 4.3. Append clone to fragment.\n * 4.4. Replace data with node original start node, offset original start\n * offset, count original end offset minus original start offset, and data\n * the empty string.\n * 4.5. Return fragment.\n */\n if (originalStartNode === originalEndNode &&\n util_1.Guard.isCharacterDataNode(originalStartNode)) {\n var clone = NodeAlgorithm_1.node_clone(originalStartNode);\n clone._data = CharacterDataAlgorithm_1.characterData_substringData(originalStartNode, originalStartOffset, originalEndOffset - originalStartOffset);\n MutationAlgorithm_1.mutation_append(clone, fragment);\n CharacterDataAlgorithm_1.characterData_replaceData(originalStartNode, originalStartOffset, originalEndOffset - originalStartOffset, '');\n return fragment;\n }\n /**\n * 5. Let common ancestor be original start node.\n * 6. While common ancestor is not an inclusive ancestor of original end\n * node, set common ancestor to its own parent.\n */\n var commonAncestor = originalStartNode;\n while (!TreeAlgorithm_1.tree_isAncestorOf(originalEndNode, commonAncestor, true)) {\n if (commonAncestor._parent === null) {\n throw new Error(\"Parent node is null.\");\n }\n commonAncestor = commonAncestor._parent;\n }\n /**\n * 7. Let first partially contained child be null.\n * 8. If original start node is not an inclusive ancestor of original end\n * node, set first partially contained child to the first child of common\n * ancestor that is partially contained in range.\n */\n var firstPartiallyContainedChild = null;\n if (!TreeAlgorithm_1.tree_isAncestorOf(originalEndNode, originalStartNode, true)) {\n try {\n for (var _d = __values(commonAncestor._children), _e = _d.next(); !_e.done; _e = _d.next()) {\n var node = _e.value;\n if (range_isPartiallyContained(node, range)) {\n firstPartiallyContainedChild = node;\n break;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_e && !_e.done && (_a = _d.return)) _a.call(_d);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n /**\n * 9. Let last partially contained child be null.\n * 10. If original end node is not an inclusive ancestor of original start\n * node, set last partially contained child to the last child of common\n * ancestor that is partially contained in range.\n */\n var lastPartiallyContainedChild = null;\n if (!TreeAlgorithm_1.tree_isAncestorOf(originalStartNode, originalEndNode, true)) {\n var children = __spread(commonAncestor._children);\n for (var i = children.length - 1; i > 0; i--) {\n var node = children[i];\n if (range_isPartiallyContained(node, range)) {\n lastPartiallyContainedChild = node;\n break;\n }\n }\n }\n /**\n * 11. Let contained children be a list of all children of common ancestor\n * that are contained in range, in tree order.\n * 12. If any member of contained children is a doctype, then throw a\n * \"HierarchyRequestError\" DOMException.\n */\n var containedChildren = [];\n try {\n for (var _f = __values(commonAncestor._children), _g = _f.next(); !_g.done; _g = _f.next()) {\n var child = _g.value;\n if (range_isContained(child, range)) {\n if (util_1.Guard.isDocumentTypeNode(child)) {\n throw new DOMException_1.HierarchyRequestError();\n }\n containedChildren.push(child);\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_g && !_g.done && (_b = _f.return)) _b.call(_f);\n }\n finally { if (e_2) throw e_2.error; }\n }\n var newNode;\n var newOffset;\n if (TreeAlgorithm_1.tree_isAncestorOf(originalEndNode, originalStartNode, true)) {\n /**\n * 13. If original start node is an inclusive ancestor of original end node,\n * set new node to original start node and new offset to original start\n * offset.\n */\n newNode = originalStartNode;\n newOffset = originalStartOffset;\n }\n else {\n /**\n * 14. Otherwise:\n * 14.1. Let reference node equal original start node.\n * 14.2. While reference node’s parent is not null and is not an inclusive\n * ancestor of original end node, set reference node to its parent.\n * 14.3. Set new node to the parent of reference node, and new offset to\n * one plus reference node’s index.\n */\n var referenceNode = originalStartNode;\n while (referenceNode._parent !== null &&\n !TreeAlgorithm_1.tree_isAncestorOf(originalEndNode, referenceNode._parent)) {\n referenceNode = referenceNode._parent;\n }\n /* istanbul ignore next */\n if (referenceNode._parent === null) {\n /**\n * If reference node’s parent is null, it would be the root of range,\n * so would be an inclusive ancestor of original end node, and we could\n * not reach this point.\n */\n throw new Error(\"Parent node is null.\");\n }\n newNode = referenceNode._parent;\n newOffset = 1 + TreeAlgorithm_1.tree_index(referenceNode);\n }\n if (util_1.Guard.isCharacterDataNode(firstPartiallyContainedChild)) {\n /**\n * 15. If first partially contained child is a Text, ProcessingInstruction,\n * or Comment node:\n * 15.1. Let clone be a clone of original start node.\n * 15.2. Set the data of clone to the result of substringing data with\n * node original start node, offset original start offset, and count\n * original start node’s length minus original start offset.\n * 15.3. Append clone to fragment.\n * 15.4. Replace data with node original start node, offset original\n * start offset, count original start node’s length minus original start\n * offset, and data the empty string.\n */\n var clone = NodeAlgorithm_1.node_clone(originalStartNode);\n clone._data = CharacterDataAlgorithm_1.characterData_substringData(originalStartNode, originalStartOffset, TreeAlgorithm_1.tree_nodeLength(originalStartNode) - originalStartOffset);\n MutationAlgorithm_1.mutation_append(clone, fragment);\n CharacterDataAlgorithm_1.characterData_replaceData(originalStartNode, originalStartOffset, TreeAlgorithm_1.tree_nodeLength(originalStartNode) - originalStartOffset, '');\n }\n else if (firstPartiallyContainedChild !== null) {\n /**\n * 16. Otherwise, if first partially contained child is not null:\n * 16.1. Let clone be a clone of first partially contained child.\n * 16.2. Append clone to fragment.\n * 16.3. Let subrange be a new live range whose start is (original start\n * node, original start offset) and whose end is (first partially\n * contained child, first partially contained child’s length).\n * 16.4. Let subfragment be the result of extracting subrange.\n * 16.5. Append subfragment to clone.\n */\n var clone = NodeAlgorithm_1.node_clone(firstPartiallyContainedChild);\n MutationAlgorithm_1.mutation_append(clone, fragment);\n var subrange = CreateAlgorithm_1.create_range([originalStartNode, originalStartOffset], [firstPartiallyContainedChild, TreeAlgorithm_1.tree_nodeLength(firstPartiallyContainedChild)]);\n var subfragment = range_extract(subrange);\n MutationAlgorithm_1.mutation_append(subfragment, clone);\n }\n try {\n /**\n * 17. For each contained child in contained children, append contained\n * child to fragment.\n */\n for (var containedChildren_1 = __values(containedChildren), containedChildren_1_1 = containedChildren_1.next(); !containedChildren_1_1.done; containedChildren_1_1 = containedChildren_1.next()) {\n var child = containedChildren_1_1.value;\n MutationAlgorithm_1.mutation_append(child, fragment);\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (containedChildren_1_1 && !containedChildren_1_1.done && (_c = containedChildren_1.return)) _c.call(containedChildren_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n if (util_1.Guard.isCharacterDataNode(lastPartiallyContainedChild)) {\n /**\n * 18. If last partially contained child is a Text, ProcessingInstruction,\n * or Comment node:\n * 18.1. Let clone be a clone of original end node.\n * 18.2. Set the data of clone to the result of substringing data with\n * node original end node, offset 0, and count original end offset.\n * 18.3. Append clone to fragment.\n * 18.4. Replace data with node original end node, offset 0, count\n * original end offset, and data the empty string.\n */\n var clone = NodeAlgorithm_1.node_clone(originalEndNode);\n clone._data = CharacterDataAlgorithm_1.characterData_substringData(originalEndNode, 0, originalEndOffset);\n MutationAlgorithm_1.mutation_append(clone, fragment);\n CharacterDataAlgorithm_1.characterData_replaceData(originalEndNode, 0, originalEndOffset, '');\n }\n else if (lastPartiallyContainedChild !== null) {\n /**\n * 19. Otherwise, if last partially contained child is not null:\n * 19.1. Let clone be a clone of last partially contained child.\n * 19.2. Append clone to fragment.\n * 19.3. Let subrange be a new live range whose start is (last partially\n * contained child, 0) and whose end is (original end node, original\n * end offset).\n * 19.4. Let subfragment be the result of extracting subrange.\n * 19.5. Append subfragment to clone.\n */\n var clone = NodeAlgorithm_1.node_clone(lastPartiallyContainedChild);\n MutationAlgorithm_1.mutation_append(clone, fragment);\n var subrange = CreateAlgorithm_1.create_range([lastPartiallyContainedChild, 0], [originalEndNode, originalEndOffset]);\n var subfragment = range_extract(subrange);\n MutationAlgorithm_1.mutation_append(subfragment, clone);\n }\n /**\n * 20. Set range’s start and end to (new node, new offset).\n */\n range._start = [newNode, newOffset];\n range._end = [newNode, newOffset];\n /**\n * 21. Return fragment.\n */\n return fragment;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splits a string of text into chunks.
function splitText(text) { let parts = textchunk.chunk(text, maxCharacterCount); var i = 0; parts = parts.map(str => { // Compress whitespace. // console.log("-----"); // console.log(str); // console.log("-----"); return str.replace(/\s+/g, ' '); }).map(str => { // Trim whitespace from the ends. return str.trim(); }); return Promise.resolve(parts); }
[ "function splitTextIntoChunks(text, chunksize, delimiter){\n\n delimiter = typeof(delimiter) === 'undefined' ? \" \" : delimiter;\n\n var letter_counter = 0;\n var word_counter = 0;\n var text_chunks = new Array();\n var current_chunk = \"\";\n\n while(letter_counter < text.length){\n\n if(text[letter_counter] === delimiter && word_counter === chunksize - 1){\n\n text_chunks.push(current_chunk);\n current_chunk = \"\";\n word_counter = 0;\n\n }else if(text[letter_counter] === delimiter && word_counter < chunksize - 1){\n\n ++word_counter;\n current_chunk += text[letter_counter];\n }else{\n current_chunk += text[letter_counter];\n }\n\n if(letter_counter === text.length - 1){\n\n text_chunks.push(current_chunk);\n }\n\n ++letter_counter;\n }\n\n return text_chunks;\n}", "function chunk(text) {\n //185 characters seems to be longest discord tts reads\n let ii, lastSpaceIndex;\n const maxChunkSize = 184;\n let chunks = [];\n if (text.length > maxChunkSize) {\n for (ii = 0; ii < text.length; ii += lastSpaceIndex) {\n let temp = text.substring(ii, ii + maxChunkSize);\n lastSpaceIndex = temp.lastIndexOf(\" \");\n // need to check for the last \"part\" otherwise last index of space\n // will mean ii is always less than text.length\n if (ii + maxChunkSize > text.length) {\n chunks.push(text.substring(ii, ii + maxChunkSize));\n break;\n } else {\n chunks.push(text.substring(ii, ii + lastSpaceIndex));\n }\n }\n } else {\n chunks.push(text);\n }\n return chunks;\n}", "function breakInChunks(text, sizeOfChunks) {\r\n const collection = [];\r\n const startingIndex = 0;\r\n let index = sizeOfChunks;\r\n while (text.length > sizeOfChunks) {\r\n if (text[index] === ' ') {\r\n const start = text.slice(startingIndex, index);\r\n collection.push(start);\r\n text = text.slice(index + 1);\r\n index = startingIndex + sizeOfChunks;\r\n } else {\r\n index--;\r\n }\r\n }\r\n\r\n // Add remaining string\r\n if (text.length <= sizeOfChunks && text.length != 0) {\r\n collection.push(text);\r\n }\r\n \r\n return collection\r\n}", "function split(_delimiter, _string) \r\n{\r\n \tvar theArray = new Array();\r\n \r\n\twhile (_string != \"\") \r\n\t{\r\n \t\tendOfChunk = _string.indexOf(_delimiter); \t// Find the delimiter.\r\n\r\n \t\tif (endOfChunk == -1) endOfChunk = _string.length; \t// If delimiter not found, find end of string.\r\n \t\tvar thisChunk = _string.substring(0, endOfChunk); \t// Get the next chunk of text.\r\n \t\t_string = _string.substring(endOfChunk + 1, _string.length); \t // Remove the chunk we got from the original string.\r\n \t\ttheArray[theArray.length] = thisChunk; \t// Add this chunk to the array.\r\n \t}\r\n \r\n\treturn theArray;\r\n}", "function chunkString(str, size) {\r\n const numChunks = Math.ceil(str.length / size)\r\n const chunks = new Array(numChunks)\r\n \r\n for (let i = 0, o = 0; i < numChunks; ++i, o += size) {\r\n chunks[i] = str.substr(o, size)\r\n }\r\n \r\n return chunks\r\n }", "chunks(html) {\n // https://stackoverflow.com/a/42559116/794111\n return html\n .replace(/\\n\\r/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n .split(/\\n{2,}/g);\n }", "function chunkString(str, size) {\n const numChunks = Math.ceil(str.length / size),\n chunks = new Array(numChunks);\n\n for (let i = 0, o = 0; i < numChunks; ++i, o += size) {\n chunks[i] = str.substr(o, size);\n }\n\n return chunks;\n}", "function str_split (string, split_length) {\n if (split_length === null) {\n split_length = 1;\n }\n if (string === null || split_length < 1) {\n return false;\n }\n string += '';\n var chunks = [],\n pos = 0,\n len = string.length;\n while (pos < len) {\n chunks.push(string.slice(pos, pos += split_length));\n }\n \n return chunks;\n}", "function split (str, delimiter) {\nlet resultArray = []\n\nlet delimiterIdx = str.indexOf(delimiter)\nwhile (delimiterIdx !== -1) {\n const chunk = str.substring(0, delimiterIdx)\n resultArray.push(chunk)\n \n str = str.substring(chunk.length)\n str = str.substring(delimiter.length)\n\n delimiterIdx = str.indexOf(delimiter)\n}\nresultArray.push(str)\n\nreturn resultArray\n}", "chunk (str, width) {\n const chunks = []\n let chunk\n let ansiDiff\n let index\n let noAnsi\n let attempts = 0\n while (str && ++attempts <= 999) {\n noAnsi = this.utils.stripAnsi(str)\n index = noAnsi.length <= width ? width : this.lastIndexOfRegex(noAnsi, this.split, width)\n if (index < 1) index = Math.max(width, 1)\n // TODO this ain't cutting it for ansi reconstitution\n chunk = str.slice(0, index).trim()\n ansiDiff = chunk.length - this.utils.stripAnsi(chunk).length\n if (ansiDiff > 0) {\n index += ansiDiff\n chunk = str.slice(0, index).trim()\n }\n chunks.push(chunk)\n // prep for next iteration\n str = str.slice(index)\n }\n return chunks\n }", "function chunkString(str, len) {\n\tvar _size = Math.ceil(str.length / len),\n\t _ret = new Array(_size),\n\t _offset;\n\n\tfor (var _i = 0; _i < _size; _i++) {\n\t\t_offset = _i * len;\n\t\t_ret[_i] = str.substring(_offset, _offset + len);\n\t}\n\n\treturn _ret;\n}", "function chunkString(str, len) {\n\tvar _size = Math.ceil(str.length/len),\n\t_ret = new Array(_size),\n\t_offset\n\t;\n\n\tfor (var _i=0; _i<_size; _i++) {\n\t\t_offset = _i * len;\n\t\t_ret[_i] = str.substring(_offset, _offset + len);\n\t}\n\n\treturn _ret;\n}", "function splitText(text, maxLength) {\n var parts = []\n if (text.length > maxLength) {\n var splitChars = ['?', '!', '.', ',', ' ', '@', '#', '\"', ';']\n var i = Math.abs(maxLength / 2)\n var found = false\n var offSet = 0\n //tired, not seeing straight. doing stupid shit now\n\n\n do {\n\n\n if (splitChars.indexOf(text.charAt(i)) > -1) {\n found = true\n }\n i++\n } while ((i < text.length) && (!found))\n //console.log(i + '/' + text.length + ' offset' + offSet)\n //no obvious splits\n if (!found) {\n i = Math.abs(text.length / 2)\n }\n\n\n parts[0] = text.substring(0, i)\n parts[1] = text.substring(i, text.length)\n } else {\n parts[0] = text\n }\n return parts\n }", "function splitLines(text) {\n return text.split(/\\r?\\n/);\n}", "splitText(text) {\n return text.split(\" \");\n }", "function split (string, delimiter) {\n let results = [];\n let delimiterLength = delimeter.length;\n for (var index=0; index < string.length; index++) {\n let characters = string.substr(index, delimeterLength);\n // let chunkStart =\n // let chunkEnd\n //console.log(characters, index)\n if (characters === delimiter) {\n //console.log(string.substr(0,index))\n }\n }\n return results\n}", "function splitText(text) {\n \t\t\t \tconst [column, row] = getColumnAndRow(text.length);\n\t \t\t\tfor (let i = 0; i <= row; i += 1) {\n\t\t\t\t\tnewArray.push(text.substr(column * i, column));\n\t \t\t\t\tdocument.getElementById(\"output2\").innerHTML += text.substr(column * i, column) + '<br>';\t\n\t \t\t\t}\n // displays chunked texts by column size #3\n\t\t\t\tfor (let i = 0; i < newArray.length; i++) {\n\t\t\t\t\t//newString += i > 0 ? ' ' : '';\n\t\t\t\t \tfor (let j = 0; j < row; j++) {\n\t\t\t\t\t\tconst string = newArray[j] && newArray[j][i] ? newArray[j][i] : ''; \n\t\t\t\t\t\tnewString += string;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdocument.getElementById(\"output3\").innerHTML = newString;\n\t\t\t}", "function splitText(text, start = 0, end = text.length) {\n const pre = text.slice(0, start);\n const middle = text.slice(start, end);\n const next = text.slice(end);\n return [pre, middle, next];\n}", "function stringChunk(str, n) {\n var a = [];\n if(n==0) return a\n for(var i=0;i<str.length/n;i++){\n a.push(str.substring(n*i,n*i+n))\n }\n return a\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the state to off when the pump disables itself.
function pumpStateOff(triggerFunc) { Object.assign(state, { isOn: false, deviceSequence: state.deviceSequence + 1 }); triggerFunc(); }
[ "setOff() {\n this.setFrame(0);\n this.on = false;\n }", "switchOff () {\n if (!this._isOn()) { return }\n\n if (!this._eventDispatched('SwitchToggledOff')) { return }\n\n this._setOffState()\n }", "function off() {\n gpio.write(pin, 0, (err) => {\n if (err) throw err;\n console.log('LED is OFF');\n state = 'off';\n });\n}", "powerOff() {\n if (!state.busy && state.power === 'on') {\n this.emit('change', (state = Object.assign({}, state, {\n power: 'off'\n })));\n }\n }", "function turnDeviceOff() {\n clearInterval(blinkingModule); \n led.writeSync(0); \n }", "disable() {\n\t\tif (this.initiated) {\n\t\t\tthis.enabled = false;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.awake();\n\t\tthis.enabled = false;\n\t}", "suppress () {\n this.state = this.STATE.NONE;\n this.active = false;\n }", "setMotorOff () {\n this._parent._send('motorOff', {motorIndex: this._index});\n this._isOn = false;\n }", "powerOff() {\n if (this.setStatusLedsCallback) {\n this.setStatusLedsCallback(false);\n }\n if (this.setWaitLedCallback) {\n this.setWaitLedCallback(true);\n }\n if (this.setAddressLedsCallback) {\n this.setAddressLedsCallback(new Array(16).fill(0));\n }\n if (this.setDataLedsCallback) {\n this.setDataLedsCallback(new Array(8).fill(0));\n }\n if (this.dumpCpuCallback) {\n this.dumpCpuCallback('');\n }\n if (this.dumpMemCallback) {\n this.dumpMemCallback('');\n }\n this.isPoweredOn = false;\n }", "disable() {\n this._status = false;\n }", "switchOff() {\n this.setIllumination(false);\n }", "async function off (pin) {\n return set(pin, OFF)\n}", "disable() {\n this._is_enabled = false;\n }", "disable() {\n disconnect(this._mergerBinaural, this._summingBus);\n this._active = false;\n }", "emergencyOff() {\n this.emergencyStatus = false;\n }", "async off() {\n\t\tthis.logger.log('Powering off DUT');\n\t\tawait doRequest({method: 'POST', uri: `${this.url}/dut/off`});\n\t\tthis.logger.log('DUT powered off');\n\t}", "disable() {\n disconnect(this._binauralMerger, this._outputGain);\n this._active = false;\n }", "function ledProcessOff(){\n //Write signal to down\n ledProcess.write(0);\n}", "function modesOff() {\n\ttilling = false;\n\tplanting = false;\n\tweeding = false;\n\tharvesting = false;\n\twatering = false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fill the array with the content of the name attribute of the images
function fill_array() { for(var i=0;i<16;i++){ array.push(document.images[i].name); clicked.push(false); } }
[ "function init() {\r\n\tlet images = document.querySelectorAll(\"img\");\r\n\tfor (let i=0; i<16; i++) {\r\n\t\tarray[i]=images[i].getAttribute(\"name\");\r\n\t}\r\n}", "function fill_array() {\n\tvar div = document.getElementById(\"grid\");\n\tvar img = div.getElementsByTagName(\"img\");\n\tfor (var i = 0; i < img.length; i++) {\n\t\tarray[i] = img[i].name;\n\t}\n}", "function produceListOfImgNamesARRAY() {\n\n for(var imgNum = 1; imgNum < imgMax + 1; imgNum++) {\n\n // Images 1 .. 9 need a different URL structure\n if (imgNum < 10) {\n images.push(\"/../../static/images/pdxcg_0\" + imgNum + \".jpg\");\n } else {\n // Images 10 .. 60 need a different URL structure\n images.push(\"/../../static/images/pdxcg_\" + imgNum + \".jpg\");\n }\n }\n // console.log(images);\n}", "function getCurryImageNameArray(){\n //grabbing current page's curry name, cutting out all whitespaces and converting it to lower case\n var curryName = document.getElementById(\"curryName\").innerHTML.replace(/\\s+/g, '').toLowerCase();\n //concatenating curry name and putting it into array\n curryImagesURL = [curryName+\"Med.png\", curryName+\"Small.png\", curryName+\"Large.png\"];\n}", "initImagesName()\n {\n let tileSet = this.mapJSON.tilesets;\n //console.log(tileSet);\n for(let i = 0; i < tileSet.length; i++)\n {\n let firstgid = tileSet[i].firstgid;\n let tileSetImages = tileSet[i].tiles;\n\n for (let key in tileSetImages)\n {\n let gid = firstgid + parseInt(key);\n this.imagePathArray[gid] = tileSetImages[key].image;\n }\n\n }\n //console.log(this.imagePathArray);\n }", "initImageDimensionInfoArray() {\n for(let i = 0; i < this.shlideImgEls.length; i++) {\n let tmpObj = {};\n tmpObj.src = this.shlideImgEls[i].src;\n this.imageDimensionInfoArray.push(tmpObj);\n }\n\n // console.log(this.imageDimensionInfoArray);\n }", "function getImageNamesFromGenre(data, name) {\n var names = [];\n for (var i = 0; i < data.length; i++) {\n if (data[i].genre.indexOf(name) != -1) { \n var imageObj = {\n \"imgName\": './data/images/' + data[i].imdbID + '.jpg',\n \"rank\": data[i].rank\n }\n names.push(imageObj); \n }\n }\n return names;\n }", "function loadAllImages(temple_image_names) {\n //var temple_images = [];\n var temple_images_objects = [];\n for (i = 0; i < temple_image_names.length; i ++) {\n //console.log('temple_images/' + temple_image_names[i] + '_large.webp');\n var oneTemple = new Image();\n oneTemple.src = 'temple_images/' + temple_image_names[i] + '_large.webp';\n //temple_images.push(oneTemple);\n var temple_image_object = {\n image: oneTemple,\n currentX: -1,\n currentY: -1,\n currentSize: -1,\n lastX: -1,\n lastY: -1,\n lastSize: -1,\n };\n temple_images_objects.push(temple_image_object);\n\n }\n //return temple_images;\n return temple_images_objects;\n}", "getImageName(state){\n const images = state.fishesListe.map( fish => fish.file_id );\n return images;\n }", "function getArrayPhotoNames() {\n // Get the required elements from the page to create a slideshow.\n var slideShowButton = document.getElementById(\"slideShow\");\n var display = document.getElementById(\"imageDisplay\");\n var pathFolder = document.getElementById(\"folder\").value;\n var commonName = document.getElementById(\"name\").value;\n var startNum = document.getElementById(\"startNum\");\n var endNum = document.getElementById(\"endNum\");\n var imagesource = pathFolder + commonName;\n // Local vairables\n var imageNumber = startNum.value;\n // For debugging purposes.\n console.log(\"Image source val: \" + imagesource);\n // Calculate the array size.\n arraySize = endNum.value - startNum.value + 1;\n // only alert when the start number is greater than the end\n if (arraySize < 1 || endNum.value == \"\" || startNum.value == \"\") {\n alert(\"Invalid Numbers!\");\n console.log(\"Error\");\n return false;\n }\n // Create the array of image srcs.\n photos = new Array(arraySize);\n for (i = 1; i <= arraySize; i++) {\n photos[i] = imagesource + \"\" + imageNumber + \".jpg\";\n imageNumber++;\n }\n console.log(\"Photo src value: \" + photos[1]);\n // Update the image src.\n display.setAttribute(\"src\", photos[1]);\n }", "function makeChartDataArrays(){\n for(var i = 0; i < allImages.length; i++){\n nameData[i] = allImages[i].name;\n clickedData[i] = allImages[i].clicked;\n }\n}", "function getAllImages()\n{\n\n for (var i = 0; i < g_imageList.length; i++)\n {\n var img = new Image();\n img.src = \"img/companyPhotos/\" + g_imageList[i];\n g_images.push(img);\n \n }\n}", "function formArrayToLoadTextures(name, term) {\n var toR = [];\n var len = 3; for (i = 0; i < len; i++) toR.push({});\n toR[0][\"name\"] = name + \"_aoMap\";\n toR[0][\"url\"] = \"res/\" + name + \"/\" + name + \"_aoMap.\" + term;\n toR[1][\"name\"] = name + \"_map\";\n toR[1][\"url\"] = \"res/\" + name + \"/\" + name + \"_map.\" + term;\n toR[2][\"name\"] = name + \"_normalMap\";\n toR[2][\"url\"] = \"res/\" + name + \"/\" + name + \"_normalMap.\" + term;\n // toR[3][\"name\"] = name + \"_displacementMap\";\n // toR[3][\"url\"] = \"res/\" + name + \"/\" + name + \"_displacementMap.\" + term\n return toR;\n }", "function initImgList() {\r\n\t var imgEls = store.rootEl.querySelectorAll('img');\r\n\t store.totalIndex = imgEls.length;\r\n\t store.imgList = new Array(store.totalIndex);\r\n\t for (var i = 0, len = store.totalIndex; i < len; i++) {\r\n\t var element = imgEls[i];\r\n\t setDataset(element, 'index', String(i));\r\n\t store.imgList[i] = element;\r\n\t }\r\n\t }", "function getImageFiles(elem) {\n\tvar pic_set = [];\t\n\tfor (var j = 1; j <= NUM_PICS; j++) {\n\t\tpic_set.push('final-images/' + elem.noun + '_' + elem.order[j-1] + '.png');\n\t\t\t}\n\t\n\n return pic_set;\n}", "function populateFigures() {\n var filename;\n var currentFig;\n /*loop through the jpgs in the images folder and assign to a corresponding img element in the\n photoOrder array */\n for (var i = 1; i < 4; i++)\t{\t\n filename = \"https://cdn.glitch.com/60727fd5-6722-4373-b04f-8543cf0cb884%2FIMG_0\" + photoOrder[i] + \"sm.jpg\";\n currentFig = document.getElementsByTagName(\"img\")[i-1]; //subtract 1 from the counter to match the array value \n currentFig.src = filename;\n }\n}", "function createAristArray (artistName, lastName) {\n\n var artistArray = [];//return different arrays for each artist?\n //only load first 6 now. how to pick 6 of 6-10 paintings in the folder?\n for( i=1; i<=6;i++){\n artistArray.push('img/' + artistName + '/' + lastName + i +'.jpg');\n }\n return artistArray\n}", "function createArray()\n{\n var counter = 0; //simple Counter\n for(var i = 1; i <= 3; i++) //Row\n {\n for(var j = 1; j <= 4; j++) //Column\n {\n var iString = new String(i);\n var jString = new String(j);\n var imgSource = new String(iString+jString+\".jpg\"); //String of image source\n \n imgAry[counter] = imgSource; //Put the string into the array\n counter++;\n }\n }\n}", "function buildArray() {\r\n for (var x = 1; x < 9; x++) {\r\n tileImages.push(x + '.png');\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to update last online activity
function updateLastActivity(){ var handlerUrl = runtime.handlerUrl(element, 'updateLastOnline'); $.ajax({ type: "POST", url: handlerUrl, data: JSON.stringify({"hello": "world"}), success: function(result){ console.log("updating last online activity",result); }, error: function (request, status, error) { console.log(error); console.log(status); console.log(request.responseText); } }); }
[ "static updateActivity() {\n let numStreams = Object.keys(this.onlineChannels).length;\n let activity = `${numStreams} stream${numStreams == 1 ? \"\" : \"s\"}`;\n this.discordClient.user.setActivity(activity, {\n \"type\": \"WATCHING\"\n });\n\n console.log('[StreamActivity]', `Update current activity: watching ${activity}.`);\n }", "function updateActivity(id)\n{\n var index = findClientByID(id);\n clients[index].lastActivity = timestamp.timestamp();\n refreshClients();\n}", "function updateUsersActivity() {\n SBF.updateUsersActivity(agent_online ? SB_ACTIVE_AGENT['id'] : -1, activeUser() != false ? activeUser().id : -1, function (response) {\n if (response == 'online') {\n if (!SBChat.user_online) {\n $(conversations_area).find('.sb-conversation .sb-top > .sb-labels').prepend(`<span class=\"sb-status-online\">${sb_('Online')}</span>`);\n SBChat.user_online = true;\n }\n } else {\n $(conversations_area).find('.sb-conversation .sb-top .sb-status-online').remove();\n SBChat.user_online = false;\n }\n });\n }", "function activityHandler()\n {\n var now = new Date();\n lastActivityTime = now.getTime();\n }", "function activityHandler() {\n\t\t\tvar now = new Date();\n\t\t\tlastActivityTime = now.getTime();\n\t\t}", "_updateSessionActivity(_lastActivity = new Date().getTime()) {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }", "function setLastOnline() {\n let today = new Date();\n activeProfile.lastOnline = new Date(today.getTime());\n // Set profile object to save changes in monthlyIn/Out && balance.\n setValue(userStorage, activeProfile.name, JSON.stringify(activeProfile));\n}", "function onlineTime() {\r\n\tONLINETIME++;\r\n}", "function updateLastSeen(user) {\n\tif (user.presence.status != \"offline\") {\n\t\tseen[user.id] = Date.now();\n\t}\n}", "function updateAPIStatus (activity, age, isLive) {\n let d = new Date()\n let tf = moment(d).format('hh:mm a')\n if (isLive) {\n d3.select(activity).attr('src', '/images/icons/activity.svg')\n d3.select(age)\n .text('Live @ ' + tf)\n } else {\n d3.select(activity).attr('src', '/images/icons/alert-triangle.svg')\n d3.select(age)\n .text('No data @ ' + tf)\n }\n}", "function updateActiveTime() {\n\twindow._lact = Date.now();\n\ttry {\n\t\twindow.yt.util.activity.getTimeSinceActive = () => Date.now();\n\t} catch (e) {\n\t\tconsole.log('[ANTI-PAUSE] Unable to replace getTimeSinceActive()');\n\t}\n}", "function dynupd_last_ticker()\r\n{\r\n // update vp_last div\r\n if (dynupd_on==1) {\r\n \t$(\"#du_last\").html('Online ('+Math.round((Date.now()-last_tick)/1000)+')');\r\n } else {\r\n \t$(\"#du_last\").html('Offline');\r\n }\r\n}", "function onlineTime() {\n\tUSERONLINE++;\n\tvar h = Math.floor(USERONLINE/60);\n\tvar m = USERONLINE-h*60;\n\tm<10 ? m=\"0\"+m : '';\n\tonlinetime.html(h+\":\"+m);\n}", "function updateLastVisited() {\n chrome.tabs.onActivated.addListener(function(activeInfo) {\n chrome.storage.local.get(null, function(results) {\n if (results.toggle2 == true) {\n let currentTab = activeInfo.tabId;\n console.log('Switched to Tab: ', currentTab);\n results.lastVisited[currentTab] = (new Date()).toJSON();\n chrome.storage.local.set({\n lastVisited: results.lastVisited\n });\n\n }\n })\n })\n}", "static pullLeaderboardUpdate () {\n\n this.setLastUpdateTime(true, false)\n }", "function refreshRecentlyUsed(l) { Home.RecentlyUsed.download(l); }", "function setLastSeenTime(data){\r\n var lastDateObj = new Date(eval(data.lastSeen));\r\n var year = lastDateObj.getFullYear();\r\n var month = lastDateObj.getMonth();\r\n var date = lastDateObj.getDate();\r\n var lastSeenTime = '';\r\n var today = new Date();\r\n\r\n // Create time and add leading zeros if needed\r\n var hours = (lastDateObj.getHours().toString().length==2)?lastDateObj.getHours():('0'+lastDateObj.getHours());\r\n var minutes = (lastDateObj.getMinutes().toString().length==2)?lastDateObj.getMinutes():('0'+lastDateObj.getMinutes());\r\n\r\n if((today.getDate()==date)&&(today.getMonth()==month)&&(today.getFullYear()==year)){\r\n\r\n lastSeenTime ='today at '+ hours +':'+minutes;\r\n\r\n }else{\r\n if(today.getDate()!=date){\r\n var day = lastDateObj.toString().split(' ')[0];\r\n var dateNo = (lastDateObj.getDate().toString().length==2)?lastDateObj.getDate():('0'+lastDateObj.getDate());\r\n lastSeenTime += (day + ' '+dateNo);\r\n }\r\n if(today.getMonth()!=month){\r\n var monthString = lastDateObj.toString().split(' ')[1];\r\n lastSeenTime+= (' '+monthString);\r\n }\r\n if(today.getFullYear()!=year){\r\n lastSeenTime += (' '+ year);\r\n }\r\n\r\n lastSeenTime += (', '+ hours +':'+ minutes);\r\n }\r\n\r\n if(data.lastSeen == undefined){\r\n $('.online-stat').html('');\r\n }else{\r\n $('.online-stat').html('Last seen '+lastSeenTime);\r\n }\r\n }", "function updateTotalTime() {\n var currDomain = getActiveWebsite(); \n if(isUserActiveNow() && isWatchedWebsite(currDomain)){\n totalTimeOnWebsites += 1; \n }\n}", "activityForNumber(number) {\n\t\t\n\t\tvar session = this.sessionForNumber(number);\t\t\n\t\tsession.lastActivity = Date.now();\t\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update card probabilities in table
function updateProbTable() { console.log("update probability table"); var table = document.getElementById("probabilityTable").rows; // get probability table, collection of all rows // update suspect probabilities var i, d; for(i = 1; i < 7; i++) // iterate through rows, row header at 0, 6 suspects { d = table[i].cells; // d is the collection of cells in row i d[1].innerHTML = suspectList[i-1].prob; // suspect probabilities in column 1 } // update weapon probabilities for(i = 1; i < 7; i++) // iterate through rows, row header at 0, 6 weapons { d = table[i].cells; // d is the collection of cells in row i d[3].innerHTML = weaponList[i-1].prob; // weapon probabilities in column 3 } // update room probabilities for(i = 1; i < 10; i++) // iterate through rows, row header at 0, 6 weapons { d = table[i].cells; // d is the collection of cells in row i d[5].innerHTML = roomList[i-1].prob; // weapon probabilities in column 3 } }
[ "function updateCapacitiesForCard(card) {\n\n\tfor (var model_number= 0; model_number<card.models.length; model_number++ ) {\n\t\tmodel = card.models[model_number];\n\t\tfor (var i=0; i<model.capacities.length; i++ ) {\n\t\t\tmodel_capa = model.capacities[i];\n\t\t\t// search in capacities\n\t\t\tif (model_capa._id) { // case model_capa is bad data\n\t\t\t\tvar $capa = capacities_map[model_capa._id.$oid];\n\t\t\t\tmodel_capa._title = $capa._title;\n\t\t\t\tmodel_capa._type = $capa._type;\n\t\t\t\tmodel_capa.__text = $capa.__text;\n\t\t\t}\n\t\t}\n\t}\n\t\n}", "updatePhotoProb(probabilities, uid, photoCount) {\n probabilities.forEach(probability => {\n let userLabelRef = firebase.database().ref(`users/${uid}/${probability.label}`);\n userLabelRef.transaction(currentProb => {\n return (currentProb + probability.probability) / photoCount;\n });\n });\n }", "function updateImpliedProbabilites() {\n $(\".athlete_fight_row\").each(function(index) {\n var moneyline = $(this).find(\".moneyline\").text();\n var impliedProb = 1 / convertMoneylineToDecimal(moneyline);\n $(this).find(\".implied_prob\").text((100 * impliedProb).toFixed(2) + \"%\");\n });\n}", "function updateTableCellProbTables(advancer) {\n let myBoard = advancer.node.board;\n let mySpray = advancer.getSpray();\n let totalPossibilities = 0;\n for (let i = 0; i<4; i++) {\n totalPossibilities = totalPossibilities + mySpray[0][0][i];\n }\n for (let i = 0; i<3; i++) {\n for (let j=0; j<4; j++) {\n for (let k=0; k<4; k++) {\n let n = mySpray[j][i][k];\n tableCellProbs[i][j][k].textContent = roundToProb(n/totalPossibilities);\n tableCells[i][j][k].style.backgroundColor = percColor(n,totalPossibilities);\n }\n if (myBoard.board[j][i] !== EMPTY) {\n probabilityUndertables[i][j].style.visibility=\"hidden\";\n } else {\n probabilityUndertables[i][j].style.visibility=\"visible\";\n }\n }\n }\n}", "function calcProb(c)\n{\n\tconsole.log(\"calculate probability for \" + c.name);\n\tc.prob = (1 - (c.Ny)) / ((Np + 1) - (Np - c.Nm));\t// calculate probability for card\n\tc.probGuessed = (1 - (c.Ny)) / ((Np + 1) - (Np - c.NmGuessed));\t// calc prob for card with player guesses taken into account\n}", "function update_cards() {\n var table = $(card_table);\n cards = [];\n table.find('label.card_id')\n .each(function (i, e) {\n var card_no = $(e)\n .closest('tr')\n .find('input.card_no')\n .val(),\n card_psw = $(e)\n .closest('tr')\n .find('input.card_psw')\n .val();\n if (card_no != '') cards.push({\n index: i,\n card_no: card_no,\n card_psw: card_psw\n });\n });\n}", "update() {\n let totalRating = this.getTotalRating_();\n\n totalRating.score = totalRating.score.map((grade, i) =>\n totalRating.scoreCount[i] >= MIN_SCORE_COUNT ?\n grade :\n 0\n );\n\n if (totalRating.score.every(grade => grade) &&\n totalRating.reviewCount >= MIN_REVIEW_COUNT\n ) {\n totalRating.totalScore = ratingService.calculateTotalScore(\n totalRating.score\n );\n } else {\n totalRating.totalScore = 0;\n }\n\n this.updateTable_(totalRating);\n }", "update (chosenArm, reward) {\n this.counts[chosenArm] = this.counts[chosenArm] + 1\n const n = this.counts[chosenArm]\n const value = this.values[chosenArm]\n const newValue = ((n - 1) / n * value) + (1 / n) * reward\n this.values[chosenArm] = newValue\n }", "function updateCard(player) {\n // The playe's name\n var name = player.getAttribute(\"name\");\n\n // The card element\n var card = $(\".card[player='\"+ name +\"']\");\n\n // The table row containing all the informations needed\n var row = $(\"tr[name='\" + name + \"']\");\n\n // The total amount\n var total = row.find(\"td[data-type='total']\").html();\n\n // Update the value\n var newTotal = parseInt(card.find(\".amount\").html()) + parseInt(total);\n card.find(\".amount\").html(newTotal);\n\n // Reset the player's points\n clearValues(name);\n\n\n // Save stats\n var stats = {};\n stats['fees'] = newTotal;\n _stats[name] = stats;\n}", "setPlayerCharacterCardAbilityApplied(characterCard) {\r\n this.ccsArray.forEach((element) => {\r\n if (element.rank === characterCard.rank) {\r\n element.ability = true;\r\n }\r\n });\r\n }", "function updateProbs() {\n for (var i = 0; i < board_len; i++) {\n for (var j = 0; j < board_len; j++) {\n probs[i][j] = updateCoordProb(i + 1, j + 1);\n }\n }\n}", "function updateChanceCard() {\n var rn;\n\n rn = Math.floor((Math.random() * 40) + 1);\n if (debug == 1) {\n console.log(\"Generating chance case scenario\");\n }\n switch (rn) {\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n case 10:\n case 11:\n case 12:\n case 13:\n case 14:\n case 15:\n case 16:\n case 17:\n case 18:\n case 19:\n case 20:\n case 21:\n case 22:\n case 23:\n case 24:\n case 25:\n case 26:\n case 27:\n case 28:\n case 29:\n case 30:\n case 31:\n case 32:\n case 33:\n case 34:\n case 35:\n case 36:\n case 37:\n case 38:\n case 39:\n case 40:\n }\n\n}", "function updateScore (prize, numGuess, Bankrupt) {\n\tif(Bankrupt) {\n\t}\n}", "makeProbs() {\n for (let [hypo, odds] of this.items()) {\n this.set(hypo, probability(odds));\n }\n }", "function policyNumberUpdate(assistant){\n\tvar req = request.body.result.parameters.acctNum;\n\tvar newVal = request.body.result.parameters.policyNum;\n\tdb.ref(\"transamerica-dummy-data/accounts/\"+req).update({policyNum: newVal});\n\tassistant.ask('Done!');\n}", "function computeProbs(prob_table){\n p_fbg_given_kg = prob_table[idx_fbg_given_kg];\n p_fbi_given_kg = prob_table[idx_fbi_given_kg];\n p_fbg_given_ki = prob_table[idx_fbg_given_ki];\n p_fbi_given_ki = prob_table[idx_fbi_given_ki];\n p_kbg_given_kg = prob_table[idx_kbg_given_kg];\n p_kbi_given_kg = prob_table[idx_kbi_given_kg];\n p_kbg_given_ki = prob_table[idx_kbg_given_ki];\n p_kbi_given_ki = prob_table[idx_kbi_given_ki];\n p_ftc_given_fbg = prob_table[idx_ftc_given_fbg];\n p_fnt_given_fbg = prob_table[idx_fnt_given_fbg];\n p_ftc_given_fbi = prob_table[idx_ftc_given_fbi];\n p_fnt_given_fbi = prob_table[idx_fnt_given_fbi];\n p_kta_given_kbg = prob_table[idx_kta_given_kbg];\n p_ktc_given_kbg = prob_table[idx_ktc_given_kbg];\n p_kta_given_kbi = prob_table[idx_kta_given_kbi];\n p_ktc_given_kbi = prob_table[idx_ktc_given_kbi];\n p_kg = prob_table[idx_kg];\n\t//console.log(\"p_kg: \" + p_kg)\n p_ki = prob_table[idx_ki];\n\n p_fbg = p_fbg_given_kg * p_kg + p_fbg_given_ki * p_ki\n p_fbi = p_fbi_given_kg * p_kg + p_fbi_given_ki * p_ki\n\n p_kbg = p_kbg_given_kg * p_kg + p_kbg_given_ki * p_ki\n p_kbi = p_kbi_given_kg * p_kg + p_kbi_given_ki * p_ki\n\n p_ftc = p_ftc_given_fbg * p_fbg + p_ftc_given_fbi * p_fbi\n p_ftc_given_kg = p_ftc_given_fbg * p_fbg_given_kg + p_ftc_given_fbi * p_fbi_given_kg\n p_ftc_given_ki = p_ftc_given_fbg * p_fbg_given_ki + p_ftc_given_fbi * p_fbi_given_ki\n\n p_fnt = p_fnt_given_fbg * p_fbg + p_fnt_given_fbi * p_fbi\n p_fnt_given_kg = p_fnt_given_fbg * p_fbg_given_kg + p_fnt_given_fbi * p_fbi_given_kg\n p_fnt_given_ki = p_fnt_given_fbg * p_fbg_given_ki + p_fnt_given_fbi * p_fbi_given_ki\n \n p_kta = p_kta_given_kbg * p_kbg + p_kta_given_kbi * p_kbi\n p_kta_given_kg = p_kta_given_kbg * p_kbg_given_kg + p_kta_given_kbi * p_kbi_given_kg\n p_kta_given_ki = p_kta_given_kbg * p_kbg_given_ki + p_kta_given_kbi * p_kbi_given_ki\n \n p_ktc = p_ktc_given_kbg * p_kbg + p_ktc_given_kbi * p_kbi\n p_ktc_given_kg = p_ktc_given_kbg * p_kbg_given_kg + p_ktc_given_kbi * p_kbi_given_kg\n p_ktc_given_ki = p_ktc_given_kbg * p_kbg_given_ki + p_ktc_given_kbi * p_kbi_given_ki\n\n\tp_ftc = Math.max(p_ftc, .0000001)\n\tp_kta = Math.max(p_kta, .0000001)\n\tp_ktc = Math.max(p_ktc, .0000001)\n p_kg_given_ftc = p_ftc_given_kg * p_kg / p_ftc\n p_ki_given_ftc = p_ftc_given_ki * p_ki / p_ftc\n p_kg_given_kta = p_kta_given_kg * p_kg / p_kta\n p_ki_given_kta = p_kta_given_ki * p_ki / p_kta\n p_kg_given_ktc = p_ktc_given_kg * p_kg / p_ktc\n p_ki_given_ktc = p_ktc_given_ki * p_ki / p_ktc\n\n p_ftc_and_kta_given_kg = p_ftc_given_kg * p_kta_given_kg\n p_ftc_and_kta_given_ki = p_ftc_given_ki * p_kta_given_ki\n p_ftc_and_ktc_given_kg = p_ftc_given_kg * p_ktc_given_kg\n p_ftc_and_ktc_given_ki = p_ftc_given_ki * p_ktc_given_ki\n\n p_ftc_and_kta = p_ftc_given_kg * p_kta_given_kg * p_kg + p_ftc_given_ki * p_kta_given_ki * p_ki\n p_ftc_and_ktc = p_ftc_given_kg * p_ktc_given_kg * p_kg + p_ftc_given_ki * p_ktc_given_ki * p_ki\n p_fnt_and_kta = p_fnt_given_kg * p_kta_given_kg * p_kg + p_fnt_given_ki * p_kta_given_ki * p_ki\n p_fnt_and_ktc = p_fnt_given_kg * p_ktc_given_kg * p_kg + p_fnt_given_ki * p_ktc_given_ki * p_ki\n\n\tp_ftc_and_kta = Math.max(p_ftc_and_kta, .0000001)\n\tp_ftc_and_ktc = Math.max(p_ftc_and_ktc, .0000001)\n p_kg_given_ftc_and_kta = p_ftc_and_kta_given_kg * p_kg / p_ftc_and_kta\n p_ki_given_ftc_and_kta = p_ftc_and_kta_given_ki * p_ki / p_ftc_and_kta\n p_kg_given_ftc_and_ktc = p_ftc_and_ktc_given_kg * p_kg / p_ftc_and_ktc\n p_ki_given_ftc_and_ktc = p_ftc_and_ktc_given_ki * p_ki / p_ftc_and_ktc\n\n p_ftc_and_kta_given_kg = p_ftc_given_kg * p_kta_given_kg\n p_ftc_and_ktc_given_kg = p_ftc_given_kg * p_ktc_given_kg\n p_fnt_and_kta_given_kg = p_fnt_given_kg * p_kta_given_kg\n p_fnt_and_ktc_given_kg = p_fnt_given_kg * p_ktc_given_kg\n\n p_ftc_and_kta_given_ki = p_ftc_given_ki * p_kta_given_ki\n p_ftc_and_ktc_given_ki = p_ftc_given_ki * p_ktc_given_ki\n p_fnt_and_kta_given_ki = p_fnt_given_ki * p_kta_given_ki\n p_fnt_and_ktc_given_ki = p_fnt_given_ki * p_ktc_given_ki\n\n\tprob_table[idx_fbg] = p_fbg;\n\tprob_table[idx_fbi] = p_fbi;\n\tprob_table[idx_kbg] = p_kbg;\n\tprob_table[idx_kbi] = p_kbi;\n\tprob_table[idx_ftc] = p_ftc;\n\tprob_table[idx_ftc_given_kg] = p_ftc_given_kg;\n\tprob_table[idx_ftc_given_ki] = p_ftc_given_ki;\n\tprob_table[idx_fnt] = p_fnt;\n\tprob_table[idx_fnt_given_kg] = p_fnt_given_kg;\n\tprob_table[idx_fnt_given_ki] = p_fnt_given_ki;\n\n\tprob_table[idx_kta] = p_kta;\n\tprob_table[idx_kta_given_kg] = p_kta_given_kg;\n\tprob_table[idx_kta_given_ki] = p_kta_given_ki;\n\n\tprob_table[idx_ktc] = p_ktc;\n\tprob_table[idx_ktc_given_kg] = p_ktc_given_kg;\n\tprob_table[idx_ktc_given_ki] = p_ktc_given_ki;\n\n\tprob_table[idx_kg_given_ftc] = p_kg_given_ftc;\n\tprob_table[idx_ki_given_ftc] = p_ki_given_ftc;\n\tprob_table[idx_kg_given_kta] = p_kg_given_kta;\n\tprob_table[idx_ki_given_kta] = p_ki_given_kta;\n\tprob_table[idx_kg_given_ktc] = p_kg_given_ktc;\n\tprob_table[idx_ki_given_ktc] = p_ki_given_ktc;\n\n\tprob_table[idx_ftc_and_kta_given_kg] = p_ftc_and_kta_given_kg;\n\tprob_table[idx_ftc_and_kta_given_ki] = p_ftc_and_kta_given_ki;\n\tprob_table[idx_ftc_and_ktc_given_kg] = p_ftc_and_ktc_given_kg;\n\tprob_table[idx_ftc_and_ktc_given_ki] = p_ftc_and_ktc_given_ki;\n\n\tprob_table[idx_ftc_and_kta] = p_ftc_and_kta;\n\tprob_table[idx_ftc_and_ktc] = p_ftc_and_ktc;\n\tprob_table[idx_fnt_and_kta] = p_fnt_and_kta;\n\tprob_table[idx_fnt_and_ktc] = p_fnt_and_ktc;\n\n\tprob_table[idx_kg_given_ftc_and_kta] = p_kg_given_ftc_and_kta;\n\tprob_table[idx_kg_given_ftc_and_kta_vert] = p_kg_given_ftc_and_kta; //show vert slider as well\n\tprob_table[idx_ki_given_ftc_and_kta] = p_ki_given_ftc_and_kta;\n\tprob_table[idx_kg_given_ftc_and_ktc] = p_kg_given_ftc_and_ktc;\n\tprob_table[idx_ki_given_ftc_and_ktc] = p_ki_given_ftc_and_ktc;\n\n\tprob_table[idx_ftc_and_kta_given_kg] = p_ftc_and_kta_given_kg;\n\tprob_table[idx_ftc_and_ktc_given_kg] = p_ftc_and_ktc_given_kg;\n\tprob_table[idx_fnt_and_kta_given_kg] = p_fnt_and_kta_given_kg;\n\tprob_table[idx_fnt_and_ktc_given_kg] = p_fnt_and_ktc_given_kg;\n\n\tprob_table[idx_ftc_and_kta_given_ki] = p_ftc_and_kta_given_ki;\n\tprob_table[idx_ftc_and_ktc_given_ki] = p_ftc_and_ktc_given_ki;\n\tprob_table[idx_fnt_and_kta_given_ki] = p_fnt_and_kta_given_ki;\n\tprob_table[idx_fnt_and_ktc_given_ki] = p_fnt_and_ktc_given_ki;\n\n\t//console.log(\"prob kg_given_ftc_and_kta: \" + p_kg_given_ftc_and_kta);\n}", "updateDealtCards() {\n this.updateBlackjackState();\n }", "_donationPointsUpdate()\n{\n donations = 1 //Get values from database for number of donations\n for (i = 1; i <= donations; i++) //for each donation -> add 50 points\n {\n this.state.points.donationPoints = this.state.points.donationPoints + 50;\n this.forceUpdate();\n }\n \n //--->UPDATE THE donationPoints VALUE IN DB-->\n }", "updatePerishableProducts()\n {\n this.items = this.items.filter(\n function (product) {\n if (typeof product === \"undefined\") {\n return false;\n }\n\n const initPerishable = GAME.model.base.products\n .filter((prod) => prod.name == product.name)\n .shift().values.perishable - 1;\n\n product.values.perishable = product.values.perishable - 1;\n product.values.percentage = 100 * product.values.perishable / initPerishable;\n\n // empty container does not have defined products. Else: product needs to be perishable,\n // and needs to have perished.\n return !(product.values.isPerishable && product.values.perishable <= 0)\n }\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SEND LOGIN ////////////////////////////////////////// triggered by: the submission of the add_login form, or a reconnect if global user data are set or cordova login arguemnts: user and password as string what it does: send the data UNDCODED TODO why: ... ///////////////////////////////////////// SEND LOGIN
function send_login(user,pw){ $("#login_node").remove(); if((user=="" || pw=="") || (user=="nongoodlogin" && pw=="nongoodlogin")){ // empty form send add_login("please enter a user name and a password"); } else { // store to reconnect without prompt g_user=user; g_pw=pw; // hash the password, combine it with the challange and submit the hash of the result var hash_pw = CryptoJS.MD5(pw).toString(CryptoJS.enc.Hex); var hash = CryptoJS.MD5(hash_pw+prelogin).toString(CryptoJS.enc.Hex); //console.log("received pw="+pw+" as hash="+hash_pw+" and prelogin="+prelogin+" and generated hash="+hash); var cmd_data = { "cmd":"login", "login":user, "client_pw":hash, "alarm_view":0}; con.send(JSON.stringify(cmd_data)); $("#welcome_loading").remove(); // vertically and horizontally center box var l=$("<div></div>"); l.addClass("center_hor").addClass("center").attr("id","welcome_loading"); l.insertAfter("#clients"); l.append(get_loading("wli","Login in...")); }; }
[ "function submitLogin(type, data, extra, callback) {\n console.log(\"Logging in with \" + type);\n setTitle(TITLE_POST_AUTH);\n\n // Add the login type.\n data.type = type;\n\n // Add the device information, if it was provided.\n if (extra.device_id) {\n data.device_id = extra.device_id;\n }\n if (extra.initial_device_display_name) {\n data.initial_device_display_name = extra.initial_device_display_name;\n }\n\n $.post(matrixLogin.endpoint, JSON.stringify(data), function(response) {\n if (callback) {\n callback();\n }\n matrixLogin.onLogin(response);\n }).fail(errorFunc);\n}", "initLogin() {\n this.send({\n id: 10000,\n magic: '0x1234',\n method: 'global.login',\n params: {\n clientType: '',\n ipAddr: '(null)',\n loginType: 'Direct',\n password: '',\n userName: this.dahua_username,\n },\n session: 0,\n });\n }", "function login(){\n var username = getFormValue('loginuser');\n var password = getFormValue('loginpass');\n\n if (username && password){\n sendAjax(USER_FUNCTIONS+'login.php', loginCallback, {\n username: username,\n password: password\n });\n }\n}", "function login(){\n var cred = {\n username: document.getElementById(\"username\").value,\n password: document.getElementById(\"password\").value\n }\n con.emit(\"login\", cred); // Send login info to the server\n}", "function login_from_params(usr, pwd) {\n if (isMobileDevice()) {\n setUnsupportedDevice();\n } else {\n USER_NAME = usr;\n USER_PWD = pwd;\n send(json_get_login_message(usr, pwd));\n }\n}", "function submitLogin ( event ) {\n\tif ( event && event.preventDefault && typeof event.preventDefault == \"function\") { event.preventDefault(); }\n\tconsole.log ( \"call to: submitLogin\");\n\tvar data = {\n\t \t \"username\"\t\t: $(\"#username\").val()\n\t\t, \"password\"\t\t: $(\"#password\").val()\n\t\t, \"__method__\"\t\t: \"POST\"\n\t\t, \"_ran_\" \t\t\t: ( Math.random() * 10000000 ) % 10000000\n\t};\n\tsubmitItData ( event, data, \"/api/v2/login\", function(data){\n\t\tconsole.log( \"data=\", data );\n\t\tuser_id = data.user_id; // sample: -- see bottom of file: www/js/pdoc-form02.js\n\t\tg_user_id = data.user_id; // sample: -- see bottom of file: www/js/pdoc-form02.js\n\t\tg_username = $(\"#username\").val();\n\t\tif ( data[\"real_name\"] ) {\n\t\t\t$(\"#user_real_name\").text(\": \"+data[\"real_name\"]);\n\t\t}\n\t\tif ( data.Auth2faEnabled === \"Yes\" ) {\n\t\t\trenderX2faPin();\n\t\t} else {\n\t\t\tif ( window.localStorage ) {\n\t\t\t\tlocalStorage.setItem(\"jwt_token\",data.jwt_token);\n\t\t\t}\n\t\t\tLoggInDone( data.jwt_token, true );\n\t\t}\n\t}, function(data) {\n\t\tconsole.log( \"ERROR: \", data );\n\t\trenderError( \"Failed to Login - Network communication failed.\", \"Failed to communicate with the server.\" );\n\t});\n}", "function onSendLoginClick() {\n if (vm.email === '') {\n vm.warning = 'Veuillez indiquer votre email';\n return;\n }\n if (vm.password === '') {\n vm.warning = 'Veuillez indiquer votre mot de passe';\n return;\n }\n if (!vm.email.match(/^[a-z]+[a-z0-9._]+@[a-z]+\\.[a-z.]{2,5}$/)) {\n vm.warning = 'Adresse email incorrecte';\n return;\n }\n\n authentication(vm.email, vm.password);\n }", "function seeLogin() {\n // clear #seeForm (we may write an error there)\n $(\"#seeForm\").html(\"\");\n\n var username = $(\"#seeLoginUsername\").val();\n var password = $(\"#seeLoginPassword\").val();\n\n player.UserRegistration.login({\n method: \"Userpwd\",\n username: username,\n password: password,\n persist: 0,\n });\n}", "function login_to_server(){\n\t$.CurrentUser.UserName=document.forms[\"frmLogin\"][\"userName\"].value;\n\t$.CurrentUser.UserPassword=document.forms[\"frmLogin\"][\"userPassword\"].value;\n\t\n\t//Goal1.id = userObj.userName+'_Goal1';\t//Send User Name\n\tsocket.emit('UserAuthorize', $.CurrentUser);\n}", "onLogin() {\n let channelName = (($channel.val() || this._defaultChannel) || '').trim()\n toggleSpinner(true);\n pulseChannelWindow(channelName, true);\n this.connect($nickname.val(), $password.val(), channelName);\n }", "function loginUser(form) {\n // Send the text values in the form's \"email\" and \"password\" fields\n sendLogin(form.email.value, form.password.value);\n }", "function seeLogin()\r\n{\r\n // clear #seeForm (we may write an error there)\r\n $( '#seeForm' ).html('');\r\n\r\n var username = $( \"#seeLoginUsername\" ).val();\r\n var password = $( \"#seeLoginPassword\" ).val();\r\n\r\n player.UserRegistration.login(\r\n {method: 'Userpwd', username: username, password: password, persist: 0}\r\n );\r\n\r\n}", "function doLoginRequest() {\n\tnew Ajax.Request('/sim/login',{\n\t\tmethod: 'post',\n\t\tparameters: {user: $('f1').value, password: $('f2').value},\n\t\trequestHeaders: {Accept: 'application/json'},\n\t\tonSuccess: function(transport){\n\t\t\tconsole.log(transport.responseJSON.status);\n\t\t\tif (transport.responseJSON.status == 'ok') {\n\t\t\t\tvar user = $('f1').value;\n\t\t\t\tvar user_password = $('f2').value;\n\t\t\t\tgotoAfterSuccessLogin(user, user_password);\n\t\t\t} else {\n//\t\t\t\t$('td-error').innerHTML = \"User name or Password are invalid.<br/>Please try again.\";\n\t\t\t\tnew WarningBox(\"User name or Password are invalid.<br/>Please try again.\");\n\t\t\t}\n\t\t}\n\t});\n}", "function loginHandler(email, password) { API.triggerServerEvent(\"clientLogin\", email, password); }", "function login(){\n\t\tCloud.Users.login({\n\t\t login: username,\n\t\t password: password\n\t\t}, function (e) {\n\t\t if (e.success) {\n\t\t var user = e.users[0].id;\n\t\t Ti.App.Properties.setString(\"cloud_user_id\", user);\n\t\t Ti.API.info('Login OK');\n\t\t subscribeToServerPush();\n\t\t } else {\n\t\t Ti.API.info('Error:\\\\n' + ((e.error && e.message) || JSON.stringify(e)));\n\t\t }\n\t\t});\n\t}", "function login() {\n // parse input fields and validate them\n parseAndValidateForm(loginBox, function (userData) {\n // hide the login box and display the content or fetch it\n loginBox.clear();\n loginBox.hide();\n setUserBar(userData.name);\n T.user.login(userData);\n });\n return false;\n }", "function postLogin(username, password, regId, devicePlatform, imei){\n var requestUrl=webUrl; \n $.ajax({\n url: requestUrl,\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n\t data:\"ID=\"+username+\"&PW=\"+password+\"&RID=\"+regId+\"&IMEIID=\"+imei+\"&PLATFORM=\"+devicePlatform,\n\t\ttimeout: apiTimeout, \n\t\tsuccess: function(data){\n\t\t\tif(data.message == 'Logon Success')\n\t\t\t{\n\t\t\t\tstoreProfile(username, password);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//alert(data.message);\n\t\t\t\tnavigator.notification.alert(data.message, function(){}, \"Mewah Group\", \"Ok\");\n\t\t\t}\n\t\t\tloading.endLoading();\n\t\t},\n\t\terror: function(xhr, status, error) {\n\t\t alert(status);\n\t\t loading.endLoading();\n\t\t}\n });\n}", "function loginOk(r) {\n console.log(JSON.stringify(r));\n if (r.validacion == \"ok\") {\n if (r.Activo == 1) {\n idSesion = r.id_user; // Id de la sesión con la que realizaremos todas las peticiones a los ws\n $(\"#lbmiCuentaNombre\").text(r.Nombre + \" \" + r.Apellidos);\n $(\"#lbmiCuentaDireccion\").text(r.Direccion);\n $(\"#lbmiCuentaPoblacion\").text(r.Poblacion);\n $(\"#lbmiCuentaProvincia\").text(r.Provincia);\n $(\"#lbmiCuentaTelefono\").text(r.TelefonoContacto);\n $(\"#lbmiCuentaEmail\").text(r.Email);\n $(\"#lbmiCuentaPaypal\").text(r.CuentaPaypal);\n $(\"#lbmiCuentaBloqueado\").text(r.Bloqueado);\n moneda = r.Moneda;\n cambio = r.Cambio;\n if (r.Pais == 1) {\n $(\"#lbmiCuentaPais\").text(\"España\");\n } else {\n $(\"#lbmiCuentaPais\").text(\"Indeterminado\");\n }\n if (r.Bloqueado == \"Bloqueado\") { // si el usuario está bloquado puede acceder, pero no publicar ningún anuncio\n usuarioBloqueado = 1;\n } else {\n usuarioBloqueado = 0;\n }\n traducir(r.Pais); // funcion para traducir la app (Falta por realizar muchas cosas)\n creditosDisponibles = r.Creditos; // \n $.mobile.changePage('#app');\n register(); // intentamos registrar el dispositivo (si es Android se registrara)\n displayMainMenu();\n } else {\n $(\"#lbPopUpLogin\").text(\"Tu usuario esté temporalmente inactivo\");\n $(\"#loginPopUp\").popup(\"open\");\n }\n } else {\n $(\"#lbPopUpLogin\").text(\"Usuario/Password incorrecto\");\n $(\"#loginPopUp\").popup(\"open\");\n }\n\n}", "function chatLogin() {\n sendWebSocketMessage(v_chatWebSocket, v_chatRequestCodes.Login, v_session_key, false);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make sure a colors number is valid
function isValidColorsNumber(colors) { return colors > 2 && colors < Infinity && !isNaN(colors) && colors % 1 === 0; }
[ "function validateColorInput(value) {\n // #000 or #000000 is acceptable\n if (value.length !== 7 && value.length !== 4) { return false; }\n if (value[0] !== '#') { return false; }\n return true;\n }", "function validateColorField(value) {\n\tvar regex = '^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$';\n\t\n\treturn value.match(regex) != null;\n}", "function ColorValid (color) {\n\t//I didn't make this\n\t//http://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation\n\tvar test = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color);\n\tif (test)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}", "validateColors(colors) {\n for (let color of colors) {\n let style = new Option().style;\n style.color = color;\n if (\n style.color === \"\" ||\n style.color === \"white\" ||\n style.color === \"transparent\"\n ) {\n alert(\"Please enter valid colors.\")\n return false;\n } else if (this.numPlayers === \"1\" && style.color === this.p2.color) {\n alert(`You can't use ${this.p2.color} for single player.`);\n return false;\n }\n }\n return true;\n }", "function checkValidColor(color) {\n let RegExp = /(^[0-9A-Fa-f]{6}$)|(^[0-9A-F]{3}$)/i;\n return RegExp.test(color);\n }", "function validateColor(val) {\n\tif (val === 'random') {\n\t\treturn getRandomColor();\n\t} else {\n\t\treturn val;\n\t}\n}", "function isValidColor(text) {\n return hexColorRegEx.test(text);\n}", "function check_color_type(color, err_handler) {\n var hex_regex = /^#((((\\d|[a-fA-F])){3})|(((\\d|[a-fA-F])){6}))$/;\n var rgb_regex = /^((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))$/;\n var type = 'unvalid';\n function rgb_valid(val) {\n return rgb_regex.test(val);\n }\n\n if (hex_regex.test(color.begin) && hex_regex.test(color.end)) {\n type = 'hex';\n } else if($.isArray(color.begin) && $.isArray(color.end) &&\n color.begin.length === 3 && color.end.length === 3 &&\n color.begin.every(rgb_valid) && color.end.every(rgb_valid)){\n type = 'rgb';\n } else {\n err_handler && err_handler();\n }\n return type;\n }", "function colorCheck() {\r\n var r = 0;\r\n var g = 0;\r\n var b = 0;\r\n var redInput = 0;\r\n var greenInput = 0;\r\n var blueInput = 0;\r\n var bValid = false;\r\n\r\n redInput = document.querySelector(\"#RedColorText\");\r\n r = parseInt(redInput.value);\r\n\r\n greenInput = document.querySelector(\"#GreenColorText\");\r\n g = parseInt(greenInput.value);\r\n\r\n blueInput = document.querySelector(\"#BlueColorText\");\r\n b = parseInt(blueInput.value);\r\n\r\n if (validate(r) && validate(g) && validate(b)) {\r\n bValid = \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\r\n }\r\n\r\n return bValid;\r\n\r\n}", "function isValidColor(color) {\r\n if (!color || color.match(/px/g)) return false;\r\n if (color.match(/colorPalette|fade/g)) return true;\r\n if (color.charAt(0) === \"#\") {\r\n color = color.substring(1);\r\n return (\r\n [3, 4, 6, 8].indexOf(color.length) > -1 && !isNaN(parseInt(color, 16))\r\n );\r\n }\r\n return /^(rgb|hsl)a?\\((\\d+%?(deg|rad|grad|turn)?[,\\s]+){2,3}[\\s\\/]*[\\d\\.]+%?\\)$/i.test(\r\n color\r\n );\r\n}", "validateInput(input) {\n\n function isValidRGBComponent(component) {\n if (isNaN(component)) {\n return false;\n } else {\n const numericalValue = parseInt(component);\n return numericalValue >= 0 && numericalValue <= 255;\n }\n }\n\n // trim surrounding whitespace\n const triple = input.trim();\n const components = triple.split(/\\s+/).map(component => parseInt(component));\n if ((components.length !== 3) ||\n (!components.every(isValidRGBComponent))) {\n return { error: true };\n } else {\n const [ r, g, b ] = components;\n return { color: tinycolor({r, g, b}) };\n }\n }", "function checkDigits(color) {\n if (color.length === 1) {\n color = '0' + color\n }\n return color\n }", "static isRgb(color){return color&&\"number\"===typeof color.r&&\"number\"===typeof color.g&&\"number\"===typeof color.b}", "function validColor(command){\n\tvar valid = true;\n\t//check that the command is only 2 words\n\tif (command.length > 2){\n\t\tvalid = false;\n\t}\n\treturn valid;\n}", "function isColorCode( fieldValue ) {\r\n\tvar checkOK = \"#0123456789ABCDEFabcdef\";\r\n\tvar checkStr = fieldValue;\r\n\tvar allValid = true;\r\n\tvar allNum = \"\";\r\n\r\n\tfor (i = 0; i < checkStr.length; i++)\r\n\t{\r\n\t\tch = checkStr.charAt(i);\r\n\r\n\t\tfor (j = 0; j < checkOK.length; j++)\r\n\t\t\tif (ch == checkOK.charAt(j))\r\n\t\t\t\tbreak;\r\n\r\n\t\tif (j == checkOK.length)\r\n\t\t{\r\n\t\t\tallValid = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\tif (ch != \",\")\r\n\t\t\tallNum += ch;\r\n\t}\r\n\r\n\t// now check length and that only first letter is # symbol\r\n\tif ( fieldValue.length != 7 || fieldValue.lastIndexOf( '#' ) != 0 )\r\n\t\tallValid = false;\r\n\r\n\treturn allValid;\r\n}", "function isValidColorCode(str) {\r\n\treturn /^\\#[0-9a-fA-F]{6}$/.test(str);\r\n}", "function colorMatchCheck (one, two, three, four) \n{\n return (one === two && one === three && one === four && one !== 'rgb(116, 104, 104)' && one !== undefined);\n}", "function validateColor (requestedColor) { \n var color = requestedColor || '';\n if (color.indexOf('0x') === 0) {\n return color.substring(2);\n } else if (color.indexOf('#') === 0) {\n return color.substring(1);\n } else { \n return colorList.getColor(color) || color;\n }\n}", "function checkPaletteValid(name, map) { // 3401\n var missingColors = VALID_HUE_VALUES.filter(function(field) { // 3402\n return !map[field]; // 3403\n }); // 3404\n if (missingColors.length) { // 3405\n throw new Error(\"Missing colors %1 in palette %2!\" // 3406\n .replace('%1', missingColors.join(', ')) // 3407\n .replace('%2', name)); // 3408\n } // 3409\n // 3410\n return map; // 3411\n } // 3412" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets appropriate value for the temperature given returns a number between the limits low and high
function getColorValue(temp, low, high) { // make sure that the temperature doesn't fall out of bounds temp = (temp < LOW_TEMP) ? LOW_TEMP : temp; temp = (temp > HIGH_TEMP) ? HIGH_TEMP : temp; // the (|| 1) is to make sure divisor is not 0 let divisor = (HIGH_TEMP - LOW_TEMP) || 1; let color = low + (temp - LOW_TEMP) * ((high - low) / divisor); return color; }
[ "function getTemperatureEval(low, high){\n if (high < 5){\n return 1;\n } else if (high < 10){\n return 2;\n } else if (high < 17){\n return 3;\n } else if (high < 24){\n return 4;\n } else {\n return 5;\n }\n}", "function temperature(fr) {\n return maxTemp * (1 - fr) + 0.0001;\n }", "function temperature(getTemperature) {\n return getTemperature * 9/5 + 32;\n}", "get temperature() {\n // C = 5/9 * (F - 32);\n return 5/9 * (this.fahrenheit - 32); \n }", "get temperature() {\n return (5 / 9) * (this.fahrenheit - 32);\n }", "function getTemperature() {\n local supplyVoltage = hardware.voltage();\n local voltage = supplyVoltage * Temperature.read() / 65535.0;\n local c = (voltage - 0.5) * 100 ;\n local celsius = format(\"%.01f\", c);\n return(celsius);\n}", "function getTemperature(errors) {\n if (errors >= 50) {\n return 2;\n } else if (errors >= 40) {\n return 1;\n } else if (errors >= 20) {\n return 0.75;\n } else if (errors >= 10) {\n return 0.4;\n }\n return 0.35;\n}", "function randomTemperature(max, min) {\n return Math.round((Math.random() * (max - min) + min) * 10) / 10;\n}", "function temperature() {\n var roll = dice.d(20);\n // Its a normal day\n if (roll < 15) {\n return 90 + dice.d(9);\n }\n // extreme heat\n if (roll > 17) {\n return 100 + dice.d(10);\n }\n // random heavy cold front\n if (roll > 14 && roll < 18) {\n return 95 - (dice.d(4) * 10);\n }\n}", "getWaterTemp() {\n var temp = 520;\n return temp;\n }", "function inTemperatureBoundaries(temp) {\n temp = parseFloat(temp);\n return ( temp >= MinTemperature && temp <= MaxTemperature);\n}", "function tempToMetric(tempF){\n return parseInt( (tempF - 32) * (5 / 9) );\n}", "function getTemperature(value){\n\tvar stg1 = ((1023.0/value) - 1);\n\tvar stg2 = ((mathjs.log(stg1, 10))/3975.0);\n\tvar stg3 = (stg2 + (1/298.15));\n\tvar stg4 = ((1/stg3) - 275.15);\n\t//console.log(value+\" Temperature ----> \"+stg4.toString().substring(0,5));\n\treturn stg4.toString().substring(0,2);\n}", "function convertTemp(temperature, type) {\n if (temperature > 0){\n console.log((temperature - 32) * 5/9 + type);\n} else {\n console.log((temperature * 9/5) + 32 + type);\n}\n}", "function getDanceability(temp, isReWeather) {\n var tempToDance;\n var danceability;\n\n\tif(isReWeather) {\n\t\tdanceability = ($('input[name=\"danceability\"]')[0]['valueAsNumber']/10);\n\t\tif (danceability >= .6) {\n\t\t\tdanceability = .5; //for range .8-1, which is max range\n\t\t}\n\t}\n\telse {\n\t\tif (temp > 100) {\n\t\t\ttempToDance = 100;\n\t\t} else if (temp < 0) {\n\t\t\ttempToDance = 0;\n\t\t} else tempToDance = temp;\n\n\t\tdanceability = (tempToDance * .5) / 100; // where min danceability is .6, max will be 1\n\t\t$(\"input[name='danceability']\").val((temp + .2)/10.0) // set value of slider\n\t}\n\treturn danceability;\n}", "function temperature(getTemperature) {\n // the Celsius degrees will be converted into Fahrenheit, and return\n return getTemperature * 9/5 + 32;\n}", "function get_max(){\r\n\tvar high=temp[temp.length-1];\r\n\tconsole.log('Maxmium temperature '+high);\r\n}", "function GetSelectedTemperatureValue()\n{\n\treturn $(\"#id_tmp_slider\").is(\":checked\") ? 0.50 : 0.00;\n}", "function getTempColor(value) {\n var sRes = \"white\";\n var iValue = parseFloat(value);\n\n\n if (iValue >= 35) {\n sRes = \"#EF0F06\";\n } else if (iValue >= 27) {\n sRes = \"#E6940F\";\n } else if (iValue >= 22) {\n sRes = \"#ABCD23\";\n } else if (iValue >= 15) {\n sRes = \"#CCE566\";\n } else if (iValue >= 10) {\n sRes = \"#73E265\";\n } else if (iValue >= 3) {\n sRes = \"#C9F4C3\";\n } else if (iValue >= -5) {\n sRes = \"#E8EEF8\";\n } else if (iValue >= -10) {\n sRes = \"#B5C9E8\";\n } else if (iValue >= -20) {\n sRes = \"#6F95D3\";\n }\n\n return sRes;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }