query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Function that shuffles cards based on css order | function shuffle(cards) {
cards.forEach(card => {
let randomize = Math.floor(Math.random() * 10);
card.style.order = randomize;
});
} | [
"function shuffle() {\n cards.forEach(card => {\n let randPos = Math.floor(Math.random() * 12);\n card.style.order = randPos;\n })\n}",
"function shuffleCards() {\n removeCards();\n const shuffleArray = cards.sort(() => Math.random() - 0.5);\n displayCards(shuffleArray);\n styleCards();\n}",
"function rearrange() {\n cards = shuffle(cards);\n for (var i = 0; i < cards.length; i++) {\n deck.innerHTML = \"\";\n [].forEach.call(cards, function(item) {\n deck.appendChild(item);\n });\n cards[i].classList.remove(\"show\", \"open\", \"match\", \"disabled\");\n }\n}",
"shuffleCards(cards, checkNames) {\n let j = 0;\n cards.forEach((card, index) => {\n let random = Math.floor(Math.random() * 12);\n\n card.style.order = random;\n index % 2 == 0 ? j++ : (j = j);\n card.type = checkNames[j];\n });\n }",
"function shuffleCards() {\n var shuffledCards = shuffle(cards);\n $(shuffledCards).each(function(index, value) {\n $(\".cards\").append($(value));\n });\n }",
"function shuffleDeckFrench() {\n $(\".game-card-fr\").each(function () {\n let shuffleDeckFrench = Math.floor(Math.random() * 21);\n this.style.order = shuffleDeckFrench;\n });\n }",
"function shuffle_Cards(){\n symbols = shuffle(symbols);\n\n // to make the shuffling appear in Markup also not just inside the symbols array\n let i=0;\n allcards.forEach(card => {\n let icon = card.children[0];\n icon.className = symbols[i];\n i++;\n });\n }",
"function shuffle(x) {\n var tarjetas = document.querySelectorAll('.tarjetas');\n\n for (i = 0; i < x; i++) {\n posicion = Math.floor(Math.random() * 16);\n tarjetas[i].style.order = posicion;\n }\n}",
"shuffle() {\n for (let i = this.cards.length - 1; i > 0; i--) {\n const newIndex = Math.floor(Math.random() * (i + 1)); //get random index before the current card to swap with\n const oldValue = this.cards[newIndex];\n this.cards[newIndex] = this.cards[i];\n this.cards[i] = oldValue;\n //Looping through all of our cards and swapping them with another card to get a random shuffle\n }\n }",
"shuffle() {\n this.activeCards = _.shuffle(this.activeCards);\n }",
"function shuffleCards() {\n\t\t\tvar curr_index = cards.length, \n\t\t\t\ttemp_value, \n\t\t\t\trand_index;\n\t\t\twhile (0 !== curr_index){\n\t\t\t\t// Pick random value\n\t\t\t\trand_index = Math.floor(Math.random() * curr_index);\n\t\t\t\tcurr_index--;\n\t\t\t\t// Swap the randomly picked value with the current one\n\t\t\t\ttemp_value = cards[curr_index];\n\t\t\t\tcards[curr_index] = cards[rand_index];\n\t\t\t\tcards[rand_index] = temp_value;\n\t\t\t}\n\t\t}",
"function shuffleDeck() {\n const shuffleCards = shuffle(cardsList);\n for(card of shuffleCards) {\n deck.appendChild(card);\n }\n}",
"function randomOrder(){\n for(let i = 0; i < flipCard.length; i++){ \n randomNum = Math.floor(Math.random() * 16);\n flipCard[i].style.order = randomNum;\n }\n }",
"function shufflePlayCards() {\r\n shuffle(numArray4);\r\n shuffle(numArray6);\r\n shuffle(iconArray4);\r\n shuffle(iconArray6);\r\n}",
"function arrangeCards() {\n shuffledCards = shuffle(cards);\n const fragment = document.createDocumentFragment();\n for(let card of shuffledCards) {\n let li = document.createElement(`li`);\n li.setAttribute(`class`,`card`);\n li.setAttribute(`data-card`,`${card}`)\n cardcounter++;\n li.setAttribute(`index`,`${cardcounter}`);\n let i = document.createElement(`i`);\n i.setAttribute(`class`,`fa ${card}` );\n li.appendChild(i);\n fragment.appendChild(li);\n }\n cardcounter = 0;\n\n // Removing the existing cards in the deck and re populating the shuffled\n // cards\n const deck = document.querySelector(`.deck`);\n deck.remove();\n const containerDiv = document.querySelector(`.container`);\n let ul = document.createElement(`ul`);\n ul.setAttribute(`class`,`deck`);\n containerDiv.insertAdjacentElement(`beforeend`,ul);\n const newDeck = document.querySelector(`.deck`);\n newDeck.appendChild(fragment);\n}",
"shuffleItems() {\r\n this.items.sort(() => Math.random() - 0.5);\r\n this.items.forEach((item, index) => {\r\n item.div.style.order = index;\r\n });\r\n }",
"function randomGenerateCards() {\n $(\".cards\").html($(\".cards .card\").sort(function () {\n return Math.random() - 0.5;\n }));\n }",
"function shuffleCards(ulElement)\n{\n\t// get the number of elements present in the list(i.e. number of cards).\n\tvar length = ulElement.children.length;\n\t\n\t/*\n\t\tCreate an array containing all the cards. \n\t\tchildNodes returns a NodeList and we cannot manipulate it.\n\t\tHence we need an array to swap the positions.\n\t*/\n\tvar liArray = Array.from(ulElement.childNodes);\n\t\n\t//Iterate through the array and swap the ith element with random element.\n\tfor(var i = 0; i < length; i++)\n\t{\n\t\t//Generate a random number between i and the length of array.\n\t\tvar randomNumber = Math.floor(Math.random() * (length - i)) + i;\n\t\t\n\t\t//Perform the swapping\n\t\tvar temp = liArray[i];\n\t\tliArray[i] = liArray[randomNumber];\n\t\tliArray[randomNumber] = temp;\n\t}\n\t\n\t//Create a new unordered list\n\tvar newULElement = document.createElement(\"UL\");\n\tnewULElement.classList.add(\"deck\");\n\t\n\t//Add all the array elements to the unordered list.\n\tliArray.forEach(function(li) {\n\t\tnewULElement.appendChild(li);\n\t})\n\treturn newULElement\n}",
"function shuffle(card) {\n TweenLite.fromTo(\n card, // target element\n 0.5, // time\n {\n // sets first position\n x:410, \n y:-15, \n ease: Expo.easeOut}, // animation configuraton\n {\n // final position\n x:0,\n y:0,\n ease: Expo.easeIn});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sort the deliquents by percentLogged | function percentLoggedDesc(a,b) {
if (a.percentLogged < b.percentLogged) {
return -1;
} else if (a.percentLogged > b.percentLogged) {
return 1;
} else {
return 0;
}
} | [
"function sortChartData() {\n chartData.sort((element1, element2) => {\n return element2.percentUnique - element1.percentUnique;\n });\n }",
"function filterAndSort(langs) {\n return langs.filter(function(e) { return e.language })\n .sort(function(a,b) { return b.percent - a.percent })\n}",
"function sortByImportance(e) {\n sorting(\"importent\");\n}",
"function sortByPopularity() {\n let list = Trackster.list;\n\n if(Trackster.filter.listeners ==='ascending'){\n var $t = list.sort((a, b) => a.listeners - b.listeners); // For ascending sort\n Trackster.filter.listeners = 'descending';\n $('#sortButton3b').show();\n $('#sortButton3a').hide();\n }\n else if (Trackster.filter.listeners ==='descending'){\n var $t = list.sort((a, b) => b.listeners - a.listeners); // For descending sort \n Trackster.filter.listeners = 'ascending';\n $('#sortButton3a').show();\n $('#sortButton3b').hide();\n }\n Trackster.list = $t; // add newly sorted list to the current list.\n $('#track-list').empty(); // empty the DOM list items.\n Trackster.PopulateTrackRows(Trackster.list);\n}",
"function sortItems(items) {\n\titems.sort(function (a, b) {\n\t\treturn (a.percentage < b.percentage) ?\n\t\t\t// if percentage A is less than B return -1\n\t\t\t-1 :\n\t\t\t// if percentage A is NOT less than B we make another comparation\n\t\t\t((a.percentage > b.percentage) ?\n\t\t\t\t// if percentage A is more than B return 1\n\t\t\t\t1 :\n\t\t\t\t// if percentage A is NOT more than B means that are equials\n\t\t\t\t// We make another comparation, we take in count the counter value\n\t\t\t\t(a.counter < b.counter ? -1 : 1));\n\t});\n\treturn items;\n}",
"function ratioSort(user1, user2){\n\t\t\tif (user1[1] > user2[1]) return 1;\n\t\t\telse if (user2[1] > user1[1]) return -1;\n\t\t\telse return 0;\n\t\t}",
"function sortTrackCount()\n{\n\ttracks.sort( function(a,b) { if (a.playCount < b.playCount) return -1; else return 1; } );\n\tclearTable();\n\tfillTracksTable();\n}",
"function sortPlayers(){\n parsedlclStrgObjArr.sort(function(a, b) {\n if (a.totalPoints === b.totalPoints) {\n return (b.percentWon) - (a.percentWon);\n } else {\n return (b.totalPoints) - (a.totalPoints);\n }\n });\n}",
"static sortFloors(floors) {\n const sorted = [...floors];\n sorted.sort(\n (a, b) => parseInt(b.iabp_name, 10) - parseInt(a.iabp_name, 10),\n );\n\n return sorted;\n }",
"function sortByWealth() {\r\n data = data.sort((a, b) => b.money - a.money);\r\n\r\n updateDOM();\r\n}",
"sortCaptured() {\n this.aiCaptured.sort(sortPieces);\n this.playerCaptured.sort(sortPieces);\n }",
"function sortByWealth() {\n data = data.sort((a, b) => b.money - a.money);\n updateDOM();\n}",
"function percentile(products, perc){\n\n if (products.length>0){\n //first order the products by descending price\n products.sort(price_desc);\n //get the index of needed product\n let index=Math.trunc(products.length/100*perc); //returns the integer truncature of a number\n return products[index].price;}\n}",
"function TOP10 (arr, percentage){\n const salarioOrder = arr.sort ((a,b) => a - b )\n console.log (salarioOrder)\n const space = (percentage/100) * salarioOrder.length;\n const top10Salary = salarioOrder.slice ( -space );\n const MedianaTOP10 = MedianaSalarios (top10Salary)\n return MedianaTOP10\n}",
"function histSorter(a,b) {\n if (a.outcome > b.outcome) { return 1; }\n else if (a.outcome < b.outcome) { return -1; }\n else if (a.trial > b.trial) { return 1; }\n else if (a.trial < b.trial) { return -1 }\n else { return 0; }\n }",
"mostEngagedTable() {\r\n this.stats.mostEngaged = this.members.sort(compareMissed);\r\n\r\n for (var i = 0; i < this.members.length * this.stats.showTablePercent; i++) {\r\n this.stats.engagedTop.push(this.stats.mostEngaged[i]);\r\n };\r\n }",
"function sortData() {\n\tattractions.sort((a,b) => a[\"Visitors\"] - b[\"Visitors\"]);\n\n\t// creates bar chart with the top five attractions\n\tlet data = attractions.slice(-5);\n\trenderBarChart(data);\n}",
"function percentile(arr,index){\n\tvar x = (arr.length*index)/100;\n\tvar ordArr = arr.slice(0);\n\tordArr = ordArr.sort(sortNumber);\n\tif(x%1==0){\n\t\treturn ordArr[Math.floor(x)+1];\n\t}else{\n\t\treturn (ordArr[Math.floor(x)]+ordArr[Math.floor(x)+1])/2;\n\t}\n}",
"sortAndPrint() {\n /*Resets the errand container*/\n $(\"#errandContainer\").empty();\n\n /*Sorts errand by time*/\n this.activeErrands.sort(function (a, b) {\n return Number(a.getElementsByTagName(\"div\")[2].innerHTML.replace(/[^0-9]/g, '')) - Number(b.getElementsByTagName(\"div\")[2].innerHTML.replace(/[^0-9]/g, ''));\n });\n\n /*Sorts errand by date*/\n this.activeErrands.sort(function (a, b) {\n return Number(a.getElementsByTagName(\"div\")[1].innerHTML.replace(/[^0-9]/g, '')) - Number(b.getElementsByTagName(\"div\")[1].innerHTML.replace(/[^0-9]/g, ''));\n });\n\n /*Apends errand to the errand container*/\n for (let errand of this.activeErrands) {\n $(\"#errandContainer\").append(errand);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the debug window exists, then close it | function hideDebug() {
if (window.top.debugWindow && ! window.top.debugWindow.closed) {
window.top.debugWindow.close();
window.top.debugWindow = null;
}
} | [
"function closeHelpDesk() {\n window.close();\n}",
"function __zdbCloseWorkWindow(myWindowId){\n if(myWindowId == null) return false;\n application.activeWindow.close();\n application.activateWindow(myWindowId);\n return;\n}",
"function onClose() {\n\tdebug( 'Window closed. Dereferencing window object to allow for GC...' );\n\tmainWindow = null;\n}",
"function CloseWindow() {\n if( satellite != null && satellite.open ) {\n satellite.close();\n satellite = null;\n }\n}",
"function closeDetail() {\n\n\tif (!currentDetailWindow) {\n\t\treturn;\n\t}\n\n\t$.tab.close(currentDetailWindow);\n\n\tcurrentDetailWindow = null;\n}",
"function onClosed() {\n\t// Dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}",
"function closeWindow(){\n\tipcRenderer.send('close:window');\n}",
"function mainWindowClose () {\n module.exports.internal.mainWindow = null\n}",
"hideWindow() {\n\t\tfin.desktop.Window.getCurrent().hide();\n\t}",
"function onClosed() {\n\tmainWindow = null;\n}",
"function CloseWin () \n{\n\tif (WindowID)\n\t\tif (!WindowID.closed)\n\t\t\tWindowID.close ();\n\tWindowID = '';\n}",
"function exit () {\n windowStack.forEach(function(window){\n window.hide();\n });\n}",
"closeWindow() {\n console.log('Canceling gitignore creation...')\n this.panel.hide()\n }",
"function close() {\n\tif (Navigator === null) return;\n\n\twindows = {};\n\twindowsId = [];\n\tNavigator.close();\n}",
"function closeWindow() {\n\tif (confirm(\"Do you really want to close window and exit program ?\")) {\n\t\tclose();\n\t}\n}",
"function closeWin(s) {\n dir = exec(\"ps -ef | grep ./gl | grep -v grep | awk '{print $2}' | xargs kill \", function(err, stdout, stderr) { console.log(stderr); });\n if (calWindow)\n calWindow.close();\n status = s;\n size();\n}",
"function onClosed() {\n mainWindow = null;\n}",
"function closeWindow(win = BrowserWindow.getFocusedWindow()) {\n if (!win) throw new Error('No focused window.');\n else win.close();\n}",
"function closeDetails() {\n\n\tif (!Alloy.Globals.detailsWindow) {\n\t\treturn;\n\t}\n\n\t$.tab.closeWindow(Alloy.Globals.detailsWindow);\n\n\tAlloy.Globals.detailsWindow = null;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that gets the number input | function getNumber() {
// store the input as an integer in num
num = parseInt(input.value());
} | [
"function getInputNumber(input){\n if(inputNum == undefined){\n inputNum = input;\n }else{\n inputNum = (inputNum * 10) + (input * 1);\n }\n calcDisplay.value = inputNum; \n }",
"function getInputNumber(id){\n const Amount = document.getElementById(id).value;\n const AmountNumber = parseFloat(Amount);\n return AmountNumber;\n}",
"function numero(){\n var input = prompt('Introduzca un numero decimal')\n input = parseFloat(input);\n input = Math.ceil(input);\n return input;\n}",
"function getNumber(num){\n const number = document.getElementById(\"num\"+num);\n const parsed = parseInt(number.innerText);\n return parsed\n}",
"function getNumber()\n\t{\n\t\tif(this.value == \".\" && acc.includes(\".\"))\n\t\t\treturn;\n\t\t\n\t\tacc = acc + this.value;\n\t\tdocument.getElementById(\"output\").value = acc;\n\t}",
"function readNumber() { //Repeat until the input is a number\n \n let num;\n do {\n const input = prompt(\"Enter a number please?\", 0);\n num = parseFloat(input);\n } while ( isNaN(num) );\n return num;\n }",
"function numberOne() {\n return parseInt(userNumber.value);}",
"function getNumberInput() {\r\n let pH = READLINE.question(\"Enter in a phone number! \");\r\n\r\n while (checkNumber(pH) == false) {\r\n pH = READLINE.question(\"Enter in a VALID phone number! \");\r\n }\r\n return pH;\r\n}",
"function getNumber(id){\r\n return Number(document.getElementById(id).value);\r\n}",
"function getNum(question) {\n\n //Ask out question for our number\n var num = prompt(question);\n\n //Validate it!\n while(true) {\n if(isNaN(num) || num === \"\") {\n num = prompt(\"Invalid Input! \" + question);\n } else {\n break;\n }\n }\n\n //return our number\n return parseInt(num);\n}",
"function convertInputToNum(expression){\n\treturn math.compile(prompt(expression)).evaluate();\n}",
"function validateNumberInput(input){\n\tif(isNaN(+input))\n\t{\n\t\tgenerateError(\"Please enter a number!\");\n\t\treturn false;\n\t}\n\tvar num=Number(input); //get an int value from text input\n\tif(num<0||num>200)\n\t{\n\t\tgenerateError(\"Please enter a number between 0-200!\");\n\t\treturn false;\n\t}\n\treturn num;\t\t\n\n}",
"function askNumber(question){\n let res = read.questionInt(question + \"\\n\");\n if(isNaN(res) == true) {\n\t aff('ERROR '+ res +' isn\\'t a number');\n }\n return parseInt(res);\n}",
"function getNum() {\n if (afterCalc) {\n displayStr.lower = this.value;\n display.value = displayStr.lower;\n displayStr.upper = \"\";\n display_upper.value = displayStr.upper;\n afterCalc = false;\n }\n if (this.value === \"+/-\") {\n (displayStr.lower.includes(\"-\")) ? displayStr.lower = displayStr.lower.slice(1, displayStr.lower.length): displayStr.lower = \"-\" + displayStr.lower;\n display.value = displayStr.lower;\n } else if (display.value === \"0\" || display.value === \"\" || clear || display.value === ERROR) {\n displayStr.lower = this.value;\n display.value = displayStr.lower; // first digit when user clicked\n if (this.value === \".\") {\n displayStr.lower = \"0.\";\n // when user clicked \".\", make it to \"0.\"\n display.value = \"0.\";\n }\n clear = false;\n } else if (validation.number.test(display.value + this.value)) {\n // when user contructed a valid number, add it to it\n displayStr.lower += this.value;\n display.value = displayStr.lower;\n currentValue = display.value;\n } else {\n // otherwise, replace it with pervious value\n display.value = currentValue;\n }\n // disableButton(/\\./, \".\");\n}",
"function input(n){\n // make sure n is Valid\n if(!String(n).match(/^[1-3]$/)){\n throw new Error('invalid arguments - pbs.input() requires one argument - 1, 2, or 3');\n }\n\n var rawVal = parent.$('#pbs_input_' + n).val();\n if(rawVal.length){\n return rawVal;\n }\n return undefined;\n }",
"function inputNumBees() {\n beeN = document.getElementById('beeInput').value;\n}",
"get inputNumber () { \n return $('#number'); \n }",
"function getUserInput() {\n\tvar rawValue = document.getElementById('userInput').value.trim();\n\n //evaluates for any input\n\tif (rawValue.length === 0) {\n\t\tthrow \"You must enter a number.\"\n\t}\n //evaluates if input is a number, if not, error is thrown via an alert box.\n\tvar num = Number(rawValue);\n\tif (isNaN(num)) {\n\t\tthrow rawValue + \" is not a number.\"\n\t}\n\n\treturn num;\n}",
"function getInputValue(inputId) {\n const currentValue = document.getElementById(inputId).value;\n const currentValueNum = parseInt(currentValue);\n return currentValueNum;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
$g by JoeSimmons. Supports ID, Class, and XPath (full with types) in one query Supports multiple id/class grabs in one query (split by spaces), and the ability to remove all nodes regardless of type See script page for syntax examples: | function $g(que, obj) {
if(!que || !(que=que.replace(/^\s+/,''))) return;
var obj=(obj?obj:({del:false,type:6,node:document})), r,
class_re=/^\.[A-Za-z0-9-_]/, id_re=/^\#[^\s]/, xp_re=/^\.?(\/\/|count|id)\(?[A-Za-z0-9\'\"]/;
if(!que || typeof que!='string' || que=='') return false;
else if(id_re.test(que)) {
var s=que.split(' '), r=new Array();
for(var n=0;n<s.length;n++) r.push(document.getElementById(s[n].substring(1)));
if(r.length==1) r=r[0];
} else if(xp_re.test(que)) {
r = document.evaluate(que,(obj['node']||document),null,(obj['type']||6),null);
switch((obj['type']||6)){case 1:r=r.numberValue;break;case 2: r=r.stringValue;break;case 3:r=r.booleanValue;break;case 8:case 9:r=r.singleNodeValue;break;}
} else if(class_re.test(que)) {
var expr='', s=que.split(' ');
for(var n=0;n<s.length && s[n].indexOf('.')==0;n++) expr+="@class='"+s[n].substring(1)+"' or ";
r = document.evaluate("//*["+expr.replace(/( or )$/,'')+"]",document,null,6,null);
if(r.snapshotLength==1) r=r.snapshotItem(0);
} else return null;
if(obj['del']===true && r) {
if(r.nodeType==1) r.parentNode.removeChild(r);
else if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);
else if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);
} else return r;
} | [
"function removeNodes (cssClass) {\n let selector = 'div.' + cssClass;\n let elements = document.querySelectorAll(selector);\n Array.prototype.forEach.call(elements, function (element) {\n document.body.removeChild(element);\n });\n}",
"function $g(que, O) {\r\nif(!que||typeof(que)!='string'||que==''||!(que=que.replace(/^\\s+/,''))) return false;\r\nvar obj=O||({del:false,type:6,node:document}), r, t,\r\n\tidclass_re=/^[#\\.](?!\\/)[^\\/]/, xp_re=/^\\.?(\\/{1,2}|count|id)/;\r\nif(idclass_re.test(que)) {\r\nvar s=que.split(' '), r=new Array(), c;\r\nfor(var n=0; n<s.length; n++) {\r\nswitch(s[n].substring(0,1)) {\r\ncase '#': r.push(document.getElementById(s[n].substring(1))); break;\r\ncase '.': c=document.getElementsByClassName(s[n].substring(1));\r\n\t\t if(c.length>0) for(var i=0; i<c.length; i++) r.push(c[i]); break;\r\n}\r\n}\r\nif(r.length==1) r=r[0];\r\n} else if(xp_re.test(que)) {\r\nr = (obj['doc']||document).evaluate(que,(obj['node']||document),null,((t=obj['type'])||6),null);\r\nif(typeof t==\"number\" && /[12389]/.test(t)) r=r[(t==1?\"number\":(t==2?\"string\":(t==3?\"boolean\":\"singleNode\")))+\"Value\"];\r\n}\r\nif(r && obj['del']===true) {\r\nif(r.nodeType==1) r.parentNode.removeChild(r);\r\nelse if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\nelse if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);\r\n} return r;\r\n}",
"function removeElemByClass(cl, tag) {\r\nif(array=document.evaluate(\"//\"+(tag||'*')+\"[@class='\"+cl+\"']\", document, null, 6, null))\r\nfor(var i=array.snapshotLength-1; (item=array.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\n}",
"function BuildXPath(tag_val, id_val, class_val, attr_name, attr_val){\r\n\tvar\ttag = '';\r\n\tvar\tquery = '';\r\n\tvar\tcount = 0;\r\n\tvar\tcond = new Array(3);\r\n\r\nLOG.output(\"tag_val:\"+tag_val);\r\n\tif(tag_val) {\r\n\t\ttag = tag_val;\r\n\t} else {\r\n\t\ttag = '*';\r\n\t}\r\nLOG.output(\"id_val:\"+id_val);\r\n\tif(id_val) {\r\n\t\tcond[count] = '@id=\"'+id_val+'\"';\r\n\t\tcount++;\r\n\t}\r\nLOG.output(\"class_val:\"+class_val);\r\n\tif(class_val) {\r\n\t\tcond[count] = '@class=\"'+class_val+'\"';\r\n\t\tcount++;\r\n\t}\r\nLOG.output(\"attr_name:\"+attr_name);\r\nLOG.output(\"attr_val:\"+attr_val);\r\n\tif(attr_name) {\r\n\t\tcond[count] = '@'+attr_name+'='+\"'\"+attr_val+\"'\";\r\n\t\tcount++;\r\n\t}\r\n\tquery = '//'+tag;\r\n\tif(count) {\r\n\t\tquery = query + '[';\r\n\t\tfor(var i = 0; i < count; i++) {\r\n\t\t\tquery = query + cond[i];\r\n\t\t\tif(i+1 < count) {\r\n\t\t\t\tquery = query + ' and ';\r\n\t\t\t}\r\n\t\t}\r\n\t\tquery = query + ']';\r\n\t}\r\nLOG.output(\"query:\"+query);\r\n\treturn query;\r\n}",
"function $g(que, obj) {\r\nif(!que || !(que=que.replace(/^\\s+/,''))) return;\r\nvar obj=obj||({del:false,type:6,node:document}), r,\r\n\tidclass_re=/^[#\\.][^\\/]/, xp_re=/^\\.?(\\/\\/|count|id)/;\r\nif(typeof que!='string' || que=='') return false;\r\nelse if(idclass_re.test(que)) {\r\nvar s=que.split(' '), r=new Array(), c;\r\nfor(var n=0; n<s.length; n++) {\r\nswitch(s[n].substring(0,1)) {\r\ncase '#': r.push(document.getElementById(s[n].substring(1))); break;\r\ncase '.': c=document.getElementsByClassName(s[n].substring(1));\r\n\t\t if(c.length>0) for(var i=0; i<c.length; i++) r.push(c[i]); break;\r\n}\r\n}\r\nif(r.length==1) r=r[0];\r\n} else if(xp_re.test(que)) {\r\nr = document.evaluate(que,(obj['node']||document),null,(obj['type']||6),null);\r\nswitch((obj['type']||6)){\r\ncase 1: r=r.numberValue; break;\r\ncase 2: r=r.stringValue; break;\r\ncase 3: r=r.booleanValue; break;\r\ncase 8: case 9: r=r.singleNodeValue; break;\r\n}\r\n}\r\nif(r && obj['del']===true) {\r\nif(r.nodeType==1) r.parentNode.removeChild(r);\r\nelse if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\nelse if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);\r\n} return r;\r\n}",
"function deldiv(id) {\r\n\tdelitem('//div[@id=\\\"' + id + '\\\"]' );\r\n}",
"removeItemsByClass (className, exceptID=null) {\n // console.log(exceptID)\n for (var i of $(`.${className}`)) {\n if ( $(i).attr(\"id\") != exceptID) {\n $(i).remove();\n }\n }\n }",
"function remove_class_all(class_name) {\n\n var elm_arr = document.getElementsByClassName(class_name);\n var i;\n elm_arr = [].slice.call(elm_arr);\n for (i = 0; i < elm_arr.length; i++) {\n remove_class(class_name,elm_arr[i].id)\n }\n}",
"function _cleanUp (){\n $('.json2htmlIdAdded').each( function(index){\n \t\tvar classname = $(this).attr('class') ;\n \t\tif(classname == 'json2htmlIdAdded'){\n \t\t\t$(this).removeAttr(\"class\");\n \t\t}else{\n \t\t\t$(this).removeClass('json2htmlIdAdded');\n \t\t}\n \t\t$(this).removeAttr('id');\n \t});\n }",
"function removeClasses(theElements, ...theClasses){\n // Test to see if \"theElements\" is a single node or a node list. Credit to Tim Pietrusky https://twitter.com/jackrugile/status/435539724774547456. NodeList has a method called item() that node does not. If the type of something.item is undefined, then you're not dealing with a NodeList.\n if( typeof theElements.item === 'undefined' ) {\n // Iterate over the \"theClasses\" rest parameter\n for(const theClass of theClasses){\n // Use classList.remove() to remove each class\n theElements.classList.remove(theClass);\n } \n } else {\n // When dealing with a node list, iterate over each node\n for(const theElement of theElements){\n // Iterate over the \"theClasses\" rest parameter\n for(const theClass of theClasses){\n // Use classList.remove() to remove each class\n theElement.classList.remove(theClass);\n }\n }\n }\n}",
"function querySelectorParser(selector){\n var first, second, third;\n //check to see what the first element in the string is\n switch(selector[0]){\n case \".\" : //if class, check if it has an id element # in the string\n var result = setClassAndIDObject(selector, \"#\", first, second)\n first = result.first;\n second = result.second;\n break;\n case \"#\" :\n var result = setClassAndIDObject(selector, \".\", first, second)\n first = result.first;\n second = result.second;\n break;\n default: //assumption: you know that it starts with a tag\n //check to see if string has both class and id\n if(selector.indexOf(\"#\") !== -1 && selector.indexOf(\".\") !== -1){\n //determine which comes first\n var firstElemToSplit, secondElemToSplit, thirdElemName, secondElemName;\n var classIndex = selector.indexOf(\".\");\n var idIndex = selector.indexOf(\"#\");\n if(classIndex < idIndex){\n firstElemToSplit= \"#\", thirdElemName = \"id\", secondElemToSplit = \".\", secondElemName = \"class\";\n }else{\n firstElemToSplit = \".\"; thirdElemName = \"class\"; secondElemToSplit = \"#\"; secondElemName = \"id\"\n }\n // to-do: set the right first, second, third object\n var firstSplitArr = selector.split(firstElemToSplit)\n third = { name: firstElemToSplit + firstSplitArr[1], element: thirdElemName };\n var secondSplitArr = firstSplitArr[0].split(secondElemToSplit);\n second = {name: secondElemToSplit + secondSplitArr[1], element: secondElemName}\n first = {name : secondSplitArr[0], element: \"tag\"}\n }else if(selector.indexOf(\".\") !== -1){\n //parse string based on .\n var selectorArr = selector.split(\".\");\n first = { name : selectorArr[0] , element: \"tag\"};\n second = { name : \".\" + selectorArr[1], element: \"class\"}\n } else if (selector.indexOf(\"#\") !== -1){\n var selectorArr = selector.split(\"#\");\n first = { name : selectorArr[0] , element: \"tag\"};\n second = { name : \"#\" + selectorArr[1], element: \"id\"}\n } else {\n first = {name : selector, element: \"tag\"}\n }; break;\n }\n\n var resultObj = {\n first: first, second: second, third: third\n };\n console.log(\"Selector parser for \"+ selector +\":\", resultObj);\n return resultObj\n}",
"function removeCssClassForID(elementID, cssClass) {\n var realID = checkIfID(elementID);\n if (cssClass.constructor === Array) {\n cssClass.forEach(function(element) {\n $(realID).removeClass(element);\n });\n } else {\n $(realID).removeClass(cssClass);\n }\n }",
"function deleteNodes(xPath, params) {\r\n\t\t\tparams = params || {};\r\n\t\t\tvar o = selectNodes(xPath, params);\r\n\t\t\tif (o) {\r\n\t\t\t\tif (o.snapshotItem)\r\n\t\t\t\t\tfor (var i = o.snapshotLength - 1; (item = o.snapshotItem(i)); i--)\r\n\t\t\t\t\t\titem.parentNode.removeChild(item);\r\n\t\t\t\telse\r\n\t\t\t\t\tfor (var i = o.length - 1; i >= 0; i--)\r\n\t\t\t\t\t\tif (o[i])\r\n\t\t\t\t\t\t\to[i].parentNode.removeChild(o[i]);\r\n\t\t\t}\r\n\t\t\to = null;\r\n\t\t}",
"function SelectByID(type, endPart) {\n return element = $(type + \"[id$=\" + endPart + \"]\");\n}",
"function remCssO(c,objetos){\n\tvar i=1;\n\twhile (i<arguments.length){\n\t\tdocument.querySelector(arguments[i]).classList.remove(c);\n\t\ti++;\n\t}\n}",
"function remove(id) {\n return db('classes').where({ id }).delete()\n}",
"function process()\r\n\r\n{\r\n\r\n\tvar xpath;\r\n\r\n xpath ='//div[starts-with(@id,\"ad\")]';\r\n killAds(xpath);\r\n xpath ='//div[starts-with(@id,\"google_ads\")]';\r\n\r\n \tkillAds(xpath);\r\n xpath ='//div[starts-with(@class,\"ad\")]';\r\n killAds(xpath);\r\n xpath ='//div[contains(@class,\" ad\")]';\r\n killAds(xpath);\r\n xpath='//div[contains(@class,\"topic_ad\")]';\r\n killAds(xpath);\r\n\r\n xpath = '//div[contains(@id,\"divplay\")]';\t\r\n killAds(xpath);\r\n\r\n}",
"function removeXPath(xpathexpr) {\n dactyl.open(`javascript:var elts=document.evaluate(${xpathexpr},document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for (var i=0; i < elts.snapshotLength; i++){var elt=elts.snapshotItem(i);elt.parentNode.removeChild(elt);}; void(0)`)\n}",
"function deleteClass(id) {\n return db(\"classes\").where({ id }).del();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch to the video to the right in the playlist from the current one. | function shiftRight() {
right_video = current_video - 1;
if(right_video < 1) {
right_video = vid_array.length-1;
}
switchToVideo(right_video);
} | [
"function shiftLeft() {\n\tleft_video = current_video + 1;\n\tif (left_video >= vid_array.length) {\n\t\tleft_video = 1;\n\t}\n\tswitchToVideo(left_video);\n}",
"function forwardButtonTrigger() {\n if (window.currentVideoSelectedForPlayback) {\n setCurrentlyPlaying(false)\n const currentNode = window.currentVideoSelectedForPlayback\n const currentTime = currentNode.data.videoCore.currentTime\n const currentVideoEnd = currentNode.data.metadata.endTime\n\n if (currentTime + 1 < currentVideoEnd) {\n currentNode.data.videoCore.currentTime += 1\n } else if (currentNode.next) {\n const remainingTime = 1 - currentTime\n window.currentVideoSelectedForPlayback = currentNode.next\n const nextStartTime = window.currentVideoSelectedForPlayback.data.metadata.startTime\n window.currentVideoSelectedForPlayback.data.videoCore.currentTime = nextStartTime + remainingTime\n } else {\n window.currentVideoSelectedForPlayback.data.videoCore.currentTime = currentVideoEnd\n }\n renderUIAfterFrameChange(window.currentVideoSelectedForPlayback)\n }\n}",
"function NextVideo()\n{\n // subtract 0 to cast currentVideoIndex as a number - otherwise it concatenates with \"1\" as a string.\n ChangeVideoToTarget(currentPlaylist[(currentVideoIndex - 0) + 1].url);\n currentVideoIndex++;\n\n CheckPrevAndNext(currentVideoIndex);\n}",
"function PreviousVideo()\n{\n ChangeVideoToTarget(currentPlaylist[currentVideoIndex - 1].url);\n currentVideoIndex--;\n\n CheckPrevAndNext(currentVideoIndex);\n}",
"function gotoAndPlayNextSong() {\n if (playlist.length > 1) {\n playlist.shift();\n player.loadVideoById(playlist[0]);\n } else {\n player.clearVideo();\n }\n}",
"function playNextVideo() {\n if (firstTime) {\n loadPlaylist();\n firstTime = false;\n } else {\n if (currentVideoIndex >= playlistLength - 1) {\n playlistDone = true;\n }\n myPlayer.playlist.currentItem(currentVideoIndex);\n myPlayer.play();\n }\n currentVideoIndex += 1;\n }",
"_playPreviousVideo(){\n var currentVideo = this.state.videoIndex;\n if (currentVideo - 1 > -1){\n this.setState({\n videoIndex: (currentVideo - 1),\n videoPaused: false\n });\n }\n }",
"function rewindTwoSeconds() {\n var video = $(\".main-video\").get(0);\n video.currentTime = video.currentTime - 2;\n}",
"jumpBackward() {\n\t\t\tvar videoContainer = paella.player.videoContainer;\n\t\t\tvideoContainer.currentTime().then(function(currentTime) {\n\t\t\t\tpaella.player.videoContainer.seekToTime(currentTime - 10);\n\t\t\t});\n\t\t}",
"function setCurrentVideo() {\n if (videos.length > 0) {\n player.loadVideoById(videos[currentVideo].id, 0, \"large\");\n selectNthPlaylistElement(currentVideo);\n sendCurrentVideo(currentVideo, videos[currentVideo]);\n }\n}",
"function playPrevVideo() {\n var index\n if (position < 0) {\n position = position + 62\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition =\"all 1s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n } else if (position === 0) {\n position = (ids.length-1) * (-62)\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition = \"left 0.5s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n }\n}",
"function playNextVideo() {\n // remove current video\n const $oldVideo = videoElements[0];\n $oldVideo.off('ended'); // sometimes it gets called again\n $oldVideo.off('timeupdate');\n $oldVideo.remove();\n\n if (earlyFail()) {\n submitData(); // fail\n return;\n }\n\n // play next video\n videoElements.shift();\n window.focus()\n if (videoElements.length > 0) {\n // queue up another video\n if (counter < videos.length) {\n newVideo(videos[counter]);\n }\n counter += 1;\n checked = false;\n // play the next video\n playWhenReady(videoElements[0]);\n // update progress bar\n $progressBar.progress(\"set progress\", counter - NUM_LOAD_AHEAD);\n // update state\n } else {\n submitData(); // done\n }\n }",
"function playCurrentVideo() {\n \tisPlaying = true;\n \tvideo.playVideo();\n }",
"previousChannel() {\n const newIndex =\n this.currentIndex > 0 ? this.currentIndex - 1 : this.playlist.length - 1;\n\n this.playChannel(newIndex);\n }",
"function GoToVideoByPlaylistId(id)\n{\n ChangeVideoToTarget(currentPlaylist[id].url);\n CheckPrevAndNext(id);\n}",
"playFirstVideo() {\n this.currentPos_ = 0;\n this.reloadCurrentVideo_(this.onFirstVideoReady_.bind(this));\n }",
"nextChannel() {\n const newIndex =\n this.currentIndex < (this.playlist.length - 1) ? (this.currentIndex + 1) : 0;\n\n this.playChannel(newIndex);\n }",
"function playNextVideo() {\n var index\n if (position === (ids.length-1) * (-62)) {\n position = 0\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition = \"left 0.5s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n } else if (position <= 0) {\n position = position - 62\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition =\"all 1s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n }\n}",
"function landingPlayVideo(e) {\n\n\t\t\t// play all videos\n\t\t\tvideoOne.play();\n\t\t\tvideoTwo.play();\n\t\t\tvideoThree.play();\n\n\t\t\taudioThree.play();\n\t\t\taudioOne.play();\n\n\t\t\taudioThree.volume = 0.15;\n\n\t\t\tvideoWindow.classList.add(\"move-content\");\n\n\t\t\t// change videoPlay button text to pause\n\t\t\tvideoPlay.innerHTML = \"Pause\";\n\t\t\t// add \"playing\" class to video play button\n\t\t\tvideoPlay.classList.add(\"playing\");\n\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find closest panel and scroll to it | function findClosestPanel() {
var differences = [],
lowestDiff = Infinity
if (lowestDiff !== 0) {
// work out closest element
for (var i = 0; i < sections.length; i++) {
var difference = window.scrollY - sections[i].offsetTop
if (difference < 0) {
// turn any negative number into a positive
negativeDiff = true
difference = Math.abs(difference)
}
else {
negativeDiff = false
}
// if less than the last number, compare this with lowestDiff
// if smaller, updated difference and closestPanel
if (difference < lowestDiff) {
lowestDiff = difference
closestPanel = sections[i]
}
// briefly remove scrollInit
window.onscroll = null
scroll()
setTimeout(function(){
scrollInit()
}, 500)
}
}
} | [
"function panelScroll() {\n\t\"use strict\";\n\t$('.panel-group').one('shown.bs.collapse', function () {\n\t\tvar panelExpanded = $(this).find('.in');\n\t\t\n\t\t$('html, body').animate({\n\t\t\tscrollTop: panelExpanded.offset().top - 105\n\t\t}, 400);\n\t});\n}",
"function scrollSub(id){\n var topPos = document.getElementById(id).parentNode.parentNode.offsetTop;\n $(\".panel\").animate({\n scrollTop : topPos\n },250)\n}",
"function scrollToPanel(panel)\n{\n\tvar parent = $(\".right\");\n\tif($(panel).size() > 0)\n\t{\n\t\t$(parent).scrollTo(panel, 350, {easing:'easeInOutBack', onAfter: function(){\n\t\t\t$(panel).scrollTo(0, 250);\n\t\t}});\n\t}\n\telse\n\t{\n\t\t//default panel\n\t\tvar defaultPanel = $(\".panel#about\");\n\t\tscrollToPanel(defaultPanel);\n\t\treturn false;\n\t}\n\t\n\tvar selectedId = $(panel).attr(\"id\");\n\tupdateNav(selectedId);\n}",
"function onPanelExpanded() {\n // if necessary, re-position panel to account for the larger size\n positionPanel();\n\n // if necessary, scroll down to bring first highlighted element into view\n $(\"#options-list\").animate({\n scrollTop: computeScrollOffset()\n }, 300)\n }",
"function scrollMenuTo(panelToScroll, targetY) {\n console.log(\"Scrolling \" + panelToScroll + \" to: \" + targetY);\n $(panelToScroll).scrollTop(targetY);\n }",
"function treeMenuScroll() {\n\tif(currentItem == null)\n\t\treturn;\n\tvar trObj = showTreeWindow.document.getElementById(currentItem.index);\t\n\tif(trObj == null)\n\t\treturn;\n\ttrObj.scrollIntoView(false);\n}",
"function _slideToElement() {\n var module_name = this.getAttribute('data-module');\n\n $('html, body').animate({\n scrollTop: $('#' + module_name).offset().top\n }, 500);\n}",
"function set_scroll(){\n\t\tvar parent_row = this.current_details_box.previousSibling,\n\t\t\tscroll_amount = parent_row.offsetTop;\n\t\tif(scroll_amount)\n\t\t\twindow.scrollTo(0,scroll_amount);\n\t\t//TODO Add smooth scrolling here\n\t}",
"function scrollToWebElement(el){\r\n return browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());\r\n}",
"function scrollToCurrentlySelectedMatch_() {\n let match = getCurrentSelectedMatch_();\n if (!match) {\n return;\n }\n\n match.nodes[0].scrollIntoView({block: \"center\", inline: \"center\"});\n}",
"function scrollToElement()\n{\n // after creating the tree, we need to go give the selected node focus\n if(selectedNodeId != null)\n {\n var sElement = getLinkElement(escapeQuotes(selectedNodeId));\n\t if(sElement != null)\n\t \tsElement.focus();\n }\n}",
"function scrollWindowTo()\n {\n if (targetRow === null) return;\n var offsetY = 0;\n var element = targetRow;\n if (element.offsetParent)\n {\n offsetY = element.offsetTop;\n while (element = element.offsetParent)\n {\n offsetY += element.offsetTop;\n }\n }\n window.scrollTo(0, offsetY);\n }",
"function lsd_scrollToContentName(name) {\n\tvar body = document.getElementById('body');\n\tvar target = document.getElementById('content_'+lsd_alphaNumericOnly(name));\n\tvar container = document.getElementById(\"lsd_contentPanel\");\n\t\n\tif(target) {\n\t\tif( $(body).outerWidth() == $(container).outerWidth() ) {\n\t\t\t// Mobile mode? : Scroll the window itself\n\t\t\twindow.scrollTo( 0, target.offsetTop - 10 + container.offsetTop );\n\t\t} else {\n\t\t\t// Desktop mode? : Scroll the container\n\t\t\tcontainer.scrollTop = target.offsetTop - 10;\n\t\t}\n\t}\n\n\t// var scrollTopTarget = $(\"#content_\"+lsd_alphaNumericOnly(name)).offset().top; // - $('#lsd_contentBox').offset().top;\n\t// console.log(scrollTopTarget);\n\t// $('#lsd_contentPanel').animate({\n\t// \tscrollTop: scrollTopTarget\n\t// }, 2000);\n}",
"function scrollPage(e,el,o) {\n\t// get the element we're basing the scroll on (the target)\n\tvar el = Ext.get(this.dom.hash.replace(/#/,''));\n\t// get the container\n\tvar ct = Ext.query(\"#bodypanel .x-panel-body\")[0];\n\tct = Ext.get(ct);\n\t// calculate y position of target element; this is how far we need to scroll\n\tvar yoffset = el.getOffsetsTo(ct)[1];\n\t// do the scroll\n\tct.scrollTo(\"top\",yoffset,true);\n\t// call preventDefault on the original click event to prevent anchor jump\n\te.preventDefault();\n}",
"scrollToTopOfDiscussion() {\n const scrollPaneTop = ELEMENT_DISCUSSION.offsetTop;\n const elementTop = this.offsetTop;\n const offset = elementTop - scrollPaneTop;\n ELEMENT_DISCUSSION.scrollTop = offset;\n }",
"function goToDivScroll(id){\n\t\t // Scroll\n\t\t $('html,body').animate({\n\t\t \tscrollTop: $(\"#tabs\").offset().top\n\t\t \t}, 'slow');\n\t\t}",
"function updateScroll() {\n var elements = container.getElementsByClassName(\"selected\");\n if (elements.length > 0) {\n var element = elements[0];\n // make group visible\n var previous = element.previousElementSibling;\n if (previous && previous.className.indexOf(\"group\") !== -1 && !previous.previousElementSibling) {\n element = previous;\n }\n if (element.offsetTop < container.scrollTop) {\n container.scrollTop = element.offsetTop;\n }\n else {\n var selectBottom = element.offsetTop + element.offsetHeight;\n var containerBottom = container.scrollTop + container.offsetHeight;\n if (selectBottom > containerBottom) {\n container.scrollTop += selectBottom - containerBottom;\n }\n }\n }\n }",
"function faqScrolltodiv(divname) {\n\t\t\tvar element = document.getElementById(\"physiotherapy\");\n\t element.scrollIntoView();\n\t\t}",
"_scrollToSelected() {\n let form = $('.form.list-form-constructor .panel-wrapper');\n let selectColumn = $('.fd-selected:first');\n let firstSelectedOffsetLeft = selectColumn.length > 0 ? selectColumn.offset().left : 0;\n let scrollLeft = firstSelectedOffsetLeft + form.scrollLeft() - (form.offset().left + 10);\n\n form.animate({ scrollLeft });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get date and time to start according to service window for current workrequest Calls WFR AbBldgOpsHelpDeskgetServiceWindowStartFromSLA Fills in date and time started | function getDateAndTimeStarted(){
var panel = View.panels.get('tool_form');
var wrId = panel.getFieldValue("wrtl.wr_id");
var result = {};
try {
result = Workflow.callMethod("AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA", 'wr','wr_id',wrId);
}
catch (e) {
Workflow.handleError(e);
}
if (result.code == 'executed') {
var start = eval('(' + result.jsonExpression + ')');
//split isodate yyyy-mm-dd
temp = start.date_start.substring(1, start.date_start.length - 1).split("-");
date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);
//split isotime hh:mm:ss
tmp = start.time_start.substring(1, start.time_start.length - 1).split(":");
if (tmp[0] > 12) {
time = FormattingTime(tmp[0], tmp[1], "PM", timePattern);
}
else {
time = FormattingTime(tmp[0], tmp[1], "AM", timePattern);
}
$("tool_form_wrtl.date_start").value = date;
$("tool_form_wrtl.time_start").value = time;
$("Storedtool_form_wrtl.time_start").value = tmp[0] + ":" + tmp[1] + ".00.000";
}
else {
Workflow.handleError(result);
}
} | [
"function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_cf_cf_form');\n var wrId = panel.getFieldValue(\"wrcf.wr_id\");\n\n //kb:3024805\n\tvar result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n try {\n result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n catch (e) {\n Workflow.handleError(e);\n }\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"sched_wr_cf_cf_form_wrcf.date_start\").value = date;\n $(\"sched_wr_cf_cf_form_wrcf.time_start\").value = time;\n \n $(\"Storedsched_wr_cf_cf_form_wrcf.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}",
"function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_tl_tool_form');\n var wrId = panel.getFieldValue(\"wrtl.wr_id\");\n var result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n try {\n result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n catch (e) {\n Workflow.handleError(e);\n }\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"sched_wr_tl_tool_form_wrtl.date_start\").value = date;\n $(\"sched_wr_tl_tool_form_wrtl.time_start\").value = time;\n $(\"Storedsched_wr_tl_tool_form_wrtl.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}",
"function setServiceWindow(){\n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_days\") == \"\") { // new, set default values\n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_days\", \"0,1,1,1,1,1,0\");\n }\n \n var serv_days = responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_days\");\n var days = serv_days.split(\",\", 7);\n for (var i = 0; i < 7; i++) {\n if (days[i] == 1) {\n var check = document.getElementById(\"days\" + i);\n check.checked = true;\n }\n }\n \n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_start\") == \"\") \n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_start\", \"09:00\");\n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_end\") == \"\") \n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_end\", \"17:00\");\n}",
"function getStartTime() {\n if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {\n Office.cast.item.toItemCompose(item).start.getAsync(\n function (asyncResult) {\n if (asyncResult.status == Office.AsyncResultStatus.Failed) {\n app.showNotification(asyncResult.error.message);\n }\n else {\n // Successfully got the start time, display it, first in UTC and \n // then convert the Date object to local time and display that.\n app.showNotification('The start time in UTC is: ' + asyncResult.value.toString());\n app.showNotification('The start time in local time is: ' + asyncResult.value.toLocaleString());\n }\n });\n }\n else {\n app.showNotification(\"Message items don't have start times.\");\n }\n }",
"function getNewClockingStartTime() {\n // Start time inside dialog depends upon current clocking status\n var currentClockingStatus = JSONData.getCurrentClockingStatus( null );\n var startTime = null;\n if ( currentClockingStatus === \"technicianStatusLoggedIn\" ) {\n startTime = JSONData.getCurrentClockingStartTime( null );\n } else {\n startTime = Util.getISOCurrentTime();\n }\n debug && console.log( \"JSONData.getNewClockingStartTime: New clocking start time = \" + startTime );\n return startTime;\n }",
"get windowStart () {\n\t\treturn this._windowStart;\n\t}",
"function getThisWeekStart() {\r\n const weekStart = new Date()\r\n weekStart.setDate(weekStart.getDate() - weekStart.getDay())\r\n weekStart.setHours(0, 0, 0, 0)\r\n return weekStart\r\n}",
"function windowStart(num) {\n if (num < 12) {\n timeStart = num + \":00 AM\"; //Morning\n } else if (num == 12) {\n timeStart = num + \":00 PM\"; //Midday\n } else if (num > 12) {\n num = num - 12;\n timeStart = num + \":00 PM\"; //afternoon\n }\n return timeStart;\n}",
"function updateCalendarStart(){\n //alert(max_time_range);\n updateCalendarOpts(owgis.constants.startcal);\n // When updateing the 'current' layer by changing the start cal, we should\n // close the popup\n owgis.ol3.popup.closePopUp();\n}",
"function mondayMetricsStart(){\n var windowDeputy = window.open(\"https://2390fa18082540.na.deputy.com/#report\");\n var windowSalesforce = window.open(\"https://na74.salesforce.com/00O1J000005qXny?cancelURL=%2F00O1J000005qXny\");\n var windowTalkdesk = window.open(\"https://campaignmonitor.mytalkdesk.com/#monitoring/schedules/5b9bad188fd0250009ff4431/executions\");\n var windowReportSheet = window.open(\"https://docs.google.com/spreadsheets/d/1tfMcQE9C-hOnw0YWYVwVCyoRtlfcGOcFEqllgk16mPk/edit?usp=drive_web&ouid=108962795010392363253\");\n windowInstructions.focus;\n}",
"static getCurrentWeekStartDate() {\n try {\n let currentDate = new Date();\n let firstDayOfWeek = currentDate.getDate() - currentDate.getDay();\n currentDate.setDate(firstDayOfWeek-7);//added -7 to fetch the test data remove it later\n return libSup.formatDate(currentDate);\n } catch (error) {\n alert(\"getCurrentWeekStartDate-\" + error)\n }\n }",
"StartAppt(s){\n if(!s){\n this.started = new Date()\n } else {\n let duration = this.secondsToTime((new Date().getTime() - this.started.getTime()) / 1000)\n console.log(\"HOUR: \" + duration.h + \" MIN: \" + duration.m + \" SEC: \" + duration.s)\n }\n }",
"function onChangeToolType(){\n //get estimation\n getEstimationFromToolType();\n //fill in date and time started according to service window\n getDateAndTimeStarted();\n}",
"function sendLaunchTimeRequest() {\n\t// wrap the summand and addend as XAL doubles and send the request to the server\n\tmessage_session.sendRequest( \"getLaunchTime\", function( response ) {\n\t\tvar result = response.result;\t\t// get the result\n\t\tvar launch_time_elem = document.getElementById( \"launchtime\" );\t// get the output HTML field\n\t\tlaunch_time_elem.innerHTML = result.from_xal();\n\t} );\n}",
"function mondayMetricsStartSecond() {\n var windowStaffingCalc = window.open(\"https://docs.google.com/spreadsheets/d/16SQoyuG6OZFXiys5yISt0IvNYRD3-eL8pE9Xp20Udkc/edit#gid=0\");\n var surveyResponses = window.open(\"https://www.getfeedback.com/surveys/677515/summary\");\n var managerSlides = window.open(\"https://docs.google.com/presentation/d/1uvvDSunbkUNSS2eU0pjZRqBvJRVBjf3UG-YoMcpZ-pA/edit\");\n var windowDeputy = window.open(\"https://2390fa18082540.na.deputy.com/#roster\");\n var windowCasesClosed = window.open(\"https://campaignmonitor.my.salesforce.com/00O1J000005qXny?cancelURL=%2F00O1J000005qXny\");\n windowInstructions.focus;\n}",
"get startTimeToShow() {\n\t\tvar time = this.eventClass.start.dateTime ? moment(this.eventClass.start.dateTime) : moment(this.eventClass.start.date).startOf('day')\n\t\tif (moment(time).isBefore(moment().startOf('day')))\n\t\t\treturn moment().startOf('day')\n\t\telse return time\n\t}",
"function determineMonitorStartDateTime( dbp, centosMoment, aixMoment ) {\n\n var workDateTime;\n\n // On start up look at last processed entry and if found start monitoring from there.\n\n pdfprocessqueue.getLatestQueueEntry( dbp, function( err, result ) {\n\n if ( err ) {\n\n log.e( 'Unable to access the F559811 for last processed entry' + err );\n unexpectedDatabaseError( err );\n\n } else {\n\n // If table Empty then use System Date and Time from Oracle Host to begin Monitoring\n if ( result === null ) {\n\n lastJdeJob = 'unknown'; \n monitorFromDate = audit.getJdeJulianDateFromMoment( aixMoment );\n monitorFromTime = aixMoment.format( 'HHmmss' );\n \n\n } else {\n\n // Track last PDF procesed and its last Activity Date and Time i.e. when the UBE Job finished\n lastJdeJob = result[ 0 ];\n workDateTime = result[ 1 ].split(' ');\n monitorFromDate = workDateTime[ 0 ];\n monitorFromTime = workDateTime[ 1 ];\n\n }\n\n // Found latest entry in F559811 JDE Post PDF Handling Process Queue - so start monitoring from there\n log.d( 'Begin Monitoring from : ' + monitorFromDate + ' ' + monitorFromTime ); \n\n pollJdePdfQueue( dbp );\n\n }\n });\n}",
"function getTaskStart () {\n return taskSetting.features[0].properties.task_start;\n }",
"function wmsTimeSpan() {\r\n\ttimeSpan();\r\n\tif (td > 604800) {\r\n\t alert(\"Time span for WMS has been reduced to 1 week\");\r\n\t $(\"#duration\").val(\"604800\");\r\n\t timeSpan();\r\n\t}\r\n\tvar wmsStart = new Date(t0);\r\n\tvar wmsEnd = new Date(t1);\r\n\t /// !!!Currently for HFR, only takes time w/ mins, secs set to zero\r\n wmsStart.setUTCMinutes(0);\r\n wmsStart.setUTCSeconds(0);\r\n wmsStart.setUTCMilliseconds(0);\r\n wmsEnd.setUTCMinutes(0);\r\n wmsEnd.setUTCSeconds(0);\r\n wmsEnd.setUTCMilliseconds(0);\r\n\tvar wmsTimeStr = wmsStart.toISOString()+'/'+wmsEnd.toISOString(); \r\n\t// console.log(wmsTimeStr);\r\n\treturn wmsTimeStr;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the jsTree for the given selector | function updateTreeStructure(selector) {
$.getJSON(tree_url + '?dir=' + dir_url, function(data) {
if (data.html) {
/*
* Remove the existing tree, update the content and build the new tree.
* Need to do it this way, otherwise the tree doesn't open to the correct folder.
*/
$(selector).jstree('destroy');
$(selector).html(data.html);
createTree(selector);
}
});
} | [
"updateTreeSelection_() {\n if (angular.isUndefined(this.tree_)) {\n return;\n }\n\n this.tree_['deselect_all']();\n this.tree_['select_node'](this.selectionName_);\n }",
"function updateJSTree( updateJSTreeAction ) {\n //alert(\"JSTreeAction : \" + updateJSTreeAction);\n\n var objClassValue, nodeTitle, nodeId;\n\n if ( top.details.document.forms.nodeForm ) {\n objClassValue = top.details.document.forms.nodeForm.elements.objectClass.value;\n }\n\n if ( objClassValue && objClassValue != \"\" && top.details.detailsMainFrame.document.forms[objClassValue] ) {\n nodeTitle = top.details.detailsMainFrame.document.forms[objClassValue].elements.cn.value;\n nodeID = top.details.detailsMainFrame.document.forms[objClassValue].elements.nodeDN.value;\n }\n\n var actionData = top.navigation.jQuery.tree.plugins.arcorectxmenu.privdata;\n \n switch ( updateJSTreeAction ) {\n\n case \"create\" :\n if ( objClassValue === \"propertyObject\") { \n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/key-icon.png'} }, actionData.REF_NODE, actionData.TYPE);\n } else {\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle } }, actionData.REF_NODE, actionData.TYPE);\n } \n break;\n\n case \"move\" :\n if ( objClassValue === \"propertyObject\") { \n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/key-icon.png'} }, actionData.REF_NODE, actionData.TYPE);\n } else {\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle } }, actionData.REF_NODE, actionData.TYPE);\n }\n actionData.TREE_OBJ.remove(actionData.NODE);\n break;\n\n case \"link\" :\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'link', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/link.png'} }, actionData.REF_NODE, actionData.TYPE);\n break;\n\n case \"remove\" :\n actionData.TREE_OBJ.remove(actionData.NODE);\n break;\n }\n}",
"function updateTree(data, select_node_id)\n {\n function initTree(data, select_node_id) {\n $tree.treeview({\n data: data,\n expandIcon: 'glyphicon glyphicon-folder-close',\n collapseIcon: 'glyphicon glyphicon-folder-open',\n emptyIcon: 'glyphicon glyphicon-file'\n });\n\n $tree.treeview('expandAll');\n $tree.on('nodeSelected', onSelect);\n $tree.on('nodeUnselected', onUnselect);\n\n if (typeof(select_node_id) !== 'undefined')\n {\n $tree.treeview('selectNode', select_node_id);\n if (!options['readOnly'])\n {\n updateControls();\n }\n }\n\n if (!options['readOnly'])\n {\n initMovable();\n }\n\n if ( typeof(options['onTreeUpdate']) === 'function' )\n {\n options['onTreeUpdate']($tree);\n }\n\n }\n\n enableControls();\n\n if (typeof(data) !== 'undefined')\n {\n $tree.treeview('remove');\n initTree(data, select_node_id);\n }\n else\n {\n request('refresh', null, function(data)\n {\n if ($tree.hasClass('treeview'))\n {\n $tree.treeview('remove');\n }\n initTree(data);\n });\n }\n }",
"function updateDOM() {\n\tvar newTree = render(data);\n\tvar patches = diff(tree, newTree);\n\trootNode = patch(rootNode, patches);\n\ttree = newTree;\n}",
"function TreeView_UpdateContent(theHTML, theObject)\n{\n\t//now recreate the TreeView Data\n\ttheHTML.TreeData = new TreeViewData_TreeViewData(theObject);\n\t//finally select the data\n\ttheHTML.TreeData.Select(theObject.Properties[__NEMESIS_PROPERTY_SELECTION]);\n}",
"function _updateSelectedObject() {\n var data = $('.listTree').data('listTree');\n // Filter the context to the selected parents.\n var selected = _.filter($.extend(true, {}, data.context), function (parent) {\n return $('.listTree > ul > li > span > input[value=\"' + parent.key + '\"]').prop('checked')\n });\n // For each parent in the working context...\n _.each(selected, function (parent) {\n // Filter the children to the selected children.\n parent.values = _.filter(parent.values, function (child) {\n return $('.listTree > ul > li > ul > li > span > input[value=\"' + child.key +'\"]').prop('checked');\n });\n });\n // Update the plugin's selected object.\n $('.listTree').data('listTree', {\n \"target\": data.target,\n \"context\": data.context,\n \"options\": data.options,\n \"selected\": selected\n });\n }",
"function reloadTreeWithData(jsonData){\n $('#jsTree').tree('loadData', []);\n $('#jsTree').tree('loadData',jsonData);\n}",
"_updateTreeData() {\n let dataTree = this.get('model.rightTreeNodes');\n restorationNodeTree(dataTree, {}, A(['folder', 'desk']), true);\n\n this.get('jstreeActionReceiverRight').send('redraw');\n }",
"function _updateSelectedObject() {\n var data = $('.listTree').data('listTree');\n\n // Filter the context to the selected parents.\n var selected = _.filter($.extend(true, {}, data.context), function(parent) {\n return $('.listTree > ul > li > span > input[value=\"' + parent.key + '\"]').prop('checked')\n });\n \n // For each parent in the working context...\n _.each(selected, function(parent) {\n\n // Filter the children to the selected children.\n parent.values = _.filter(parent.values, function(child) {\n return $('.listTree > ul > li > ul > li > span > input[value=\"' + child.key + '\"]').prop('checked');\n });\n });\n\n // Update the plugin's selected object.\n $('.listTree').data('listTree', {\n \"target\": data.target,\n \"context\": data.context,\n \"options\": data.options,\n \"selected\": selected\n });\n }",
"update() {\n this.lifecycleListeners.beforeUpdate.call(this, this.context);\n if (!this.lifecycleListeners.shouldUpdate.call(this, this.context)) {\n return;\n }\n const vtree = this.render();\n patch(this.node, this.tree, vtree);\n this.lifecycleListeners.afterUpdate.call(this, this.context);\n }",
"function updateRulesFileTree() {\n\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\turl: \"/getJsonRulesTree\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: \"json\"\n\t\t})\n\n\t\t.done(function(d) {\n\t\t\t$('#rulesContainer').jstree(true).settings.core.data = d.rulesTree;\n\t\t\t$('#rulesContainer').jstree(true).refresh();\n\t\t\tgetTotalRulesCount();\n\t\t\tchartTypeRules();\n\t\t})\n\n\t\t.fail(function(d) {\n\t\t\tconsole.log(\"updateRulesFileTree - fail!\")\n\t\t\tconsole.log(d)\n\t\t});\n\t}",
"function pwi_tree_select(path) {\n\tif (pwi_current_path) {\n\t\tlet selected = document.getElementById(pwi_current_path);\n\t\tif (selected) selected.classList.remove(\"filelist-selected\");\n\t}\n\t\n\tlet tree = document.getElementById(\"phpwebide_tree\");\n\tlet node = pwi_find_node(path, tree);\n\tconsole.log(\"pwi_tree_select \"+path+\" found node\");\n\tconsole.log(node);\n\tif (node) node.classList.add(\"filelist-selected\");\n\tpwi_current_path = path;\n}",
"function updateCompiledSelectorView(fileSearch, selection, callback) {\n var hasText = selectionHasText(selection);\n var compiledSelectors = hasText ? getCompiledSelector(fileSearch, selection) : [];\n\n if (!hasText) {\n getCompiledSelector(false);\n }\n\n callback(compiledSelectors);\n}",
"function refreshCurrentTreeNode() {\n var node = $(\"#collection-tree-tree\").dynatree(\"getActiveNode\");\n\trefreshTreeNode(node);\n}",
"function updateInnerHTML(selector, newValue) {\n document.querySelector(selector).innerHTML = newValue;\n}",
"function changeNode() {\n if (selectedCacheNode) {\n var node = cachedTree.findNode(selectedCacheNode);\n if (node && !node.isElementDeleted) {\n //var node = cachedTree.findNode(selectedCacheNode);\n var value = document.getElementById('changingValue').value;\n value.trim() != '' ? node.setData(value) : alert('Please, input smth');\n render(cachedTree, \"CachedTreeView\");\n document.getElementById('addon').innerHTML = node.value + ' value change to: ';\n document.getElementById('addonAdd').innerHTML = 'Add child to ' + node.value + ':';\n document.getElementById('changingValue').value = '';\n } else if (node.isElementDeleted)\n alert('Element has been deleted, you cannot change its value');\n } else\n alert('You should select a node to change')\n}",
"function updateControls()\n {\n $tree.find('.node-selected').each(function(index, element) {\n addUpdateControls($(element));\n });\n }",
"function selectNodeById(id, old_id){\n if (typeof old_id != \"undefined\") { // remove old node if requested to do so\n $('#tree_'+old_id).removeClass('selected');\n }\n build.selected_node = id; // store new node in master array\n var $new_node = $('#tree_'+id); // ...and select the actual tree node\n $new_node.addClass('selected');\n build.tree_actions.appendTo($new_node).show();\n}",
"function updateInnerHTML(selector, newValue) {\n document.querySelector(selector).innerHTML = newValue;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the image (get the buffer and offset) into a new zipLoaderInstance | function parseImageFromZip(doSkipJPG, offsetInReader) {
return new Promise(function(resolve){
var zipLoaderInstance2 = ZipLoader.unzip( MLJ.core.Scene._zipFileArrayBuffer, doSkipJPG, offsetInReader );
resolve(zipLoaderInstance2);
});
} | [
"zipParser(blob){\n var zip = O.esri.zip;\n var _this = this;\n /*O.esri.*/zip.createReader(new /*O.esri.*/zip.BlobReader(blob), function (zipReader) {\n zipReader.getEntries(function (entries) {\n _this.initMap(entries);\n //if(entries)alert(\"TPK downloaded and unzipped!\");\n zipReader.close(function(evt){\n console.log(\"Done reading zip file.\" + evt);\n _this.set(\"loading\", false);\n });\n }, function (err) {\n alert(\"There was a problem reading the file!: \" + err);\n });\n });\n }",
"async function skinParser(zipFileBuffer, JSZip) {\n const zip = await JSZip.loadAsync(zipFileBuffer);\n\n const [\n colors,\n playlistStyle,\n images,\n cursors,\n region,\n genTextSprites,\n genExColors\n ] = await Promise.all([\n genVizColors(zip),\n genPlaylistStyle(zip),\n genImages(zip),\n genCursors(zip),\n genRegion(zip),\n genGenTextSprites(zip),\n genGenExColors(zip)\n ]);\n\n const [genLetterWidths, genTextImages] = genTextSprites || [null, {}];\n\n return {\n colors,\n playlistStyle,\n images: { ...images, ...genTextImages },\n genLetterWidths,\n cursors,\n region,\n genExColors\n };\n}",
"function extract(imageBuffer) {\n return Promise\n .fromCallback((cb) => new exif.ExifImage({image: imageBuffer}, cb))\n .then(pickFields);\n}",
"parseImg() {\n var height = this.mapHead.readUInt32LE(12);\n var width = this.mapHead.readUInt32LE(16);\n let pixels = {\n floor: [],\n obstacle_strong: [],\n rooms: {}\n };\n if (height > 0 && width > 0) {\n for (let i = 0; i < height * width; i++) {\n const val = this.buf.readUInt8(this.offset++);\n let coords;\n if (val !== 0) {\n coords = [i % width, height - 1 - Math.floor(i / width)];\n switch (val) {\n case 0:\n // non-floor, do nothing\n break;\n case 255:\n pixels.obstacle_strong.push(coords[0], coords[1]);\n break;\n case 1: // non-room\n pixels.floor.push(coords[0], coords[1]);\n break;\n default:\n if (!Array.isArray(pixels.rooms[val])) {\n pixels.rooms[val] = [];\n }\n\n pixels.rooms[val].push(coords[0], coords[1]);\n pixels.floor.push(coords[0], coords[1]);\n }\n }\n }\n }\n this.img = {\n position: {\n top: 0,\n left: 0,\n },\n dimensions: {\n height: height,\n width: width,\n },\n pixels: pixels,\n };\n }",
"function GraFlicArchive(zipDataUint8, paramz){\n\t//'this' object will be returned to the caller with contents of the ZIP.\n\tthis.f = {};//each file will have potentially .d (data) containing the files, extracted and decompressed. The filename will be the key to access the file object in files. JSON will have .json containing the reconstituted JSON object. Text will have .t (text) containing the text string. JSON and text do not currently fill the .d property because it would not be very useful and would waste resources.\n\tthis.j = {};//short links to .json ( JS-parsed and ready live JSON for stuff.json would be accessed at .j.stuff )\n\t//Images(PNG/JPG/GIF/WEBP) will have their raw binary appear in files in case metadata needs examining, and will also have an ObjectURL put here in images for easy loading by DOM elements in .b (blob link).\n\t//Other properties may be added to this result object later if needed.\n\t\n\tGraFlicArchive.archives.push(this);//Each archive created will be tracked here so that a file can be looked up if the path exists in any archive in memory with static getFileFromAny()\n\t\n\tvar v_loadedFilename = '**__Unknown__**';\n\tif(paramz){\n\t\tif(paramz.filename){\n\t\t//If the filename is provided, it can be used to check for the common ZIP repackaging mistake of packaging the extracted folder inside of itself and correct it.\n\t\t//This often happens because ZIP extractors will extract the contents into a folder with the folder name based on the filename(without extension). 'A_file.zip' extracts into folder 'A_file/'. Naturally, after editing some of the ZIP contents, the user may context-click the folder and choose to compress. This seems like how it should work, but that will put everything in the new ZIP file into another layer of extra folder that was not in the original. A contained file 'images/example.png' would become 'A_file/images/example.png';\n\t\tv_loadedFilename = paramz.filename.replace(/\\.[^\\.\\/]+$/, '');\n\t\t//TODO: Another approach that may be more reliable since the user may rename the zip after doing this: Detect if the root is empty except for one folder. If that is the case, then strip off the first folder from the extracted filename strings. Do note however, if the developer for some reason designed a save format to have a root that is empty except one folder, this could mess it up.\n\t\t}\n\t\t/*\n\t\tif(paramz.globalAsset){\n\t\t\t//being called with globalAsset true will tell it to keep the files in memory and set up the linkage so that the file can be used to fill custom zip links within the page with the images once they are extracted.\n\t\t\t//This is used when the custom:link rel=\"archive\" element is detected to say that the page uses images/files stored in a zip file.\n\t\t}\n\t\t*/\n\t}//end if paramz defined.\n\tif(!zipDataUint8){\n\t\t//If called without a binary ZIP to load, make a blank GraFlicArchive that can be filled with files programmatically and saved.\n\t\treturn;\n\t}\n//Note when reading, other ZIP builders may insert data descriptor after local file header and payload, which apparently may or may not use a signature...\n\t//Writing data descriptors is turned of in the save function used here with general purpose bit 3 set to 0.\n\tvar v_oct = zipDataUint8;\n\tvar v_pos;\n\tvar v_i;\n\tvar v_entrySize;\n\tvar v_filename;\n\tvar v_filenameSize;\n\tvar v_cdFilenameSize;\n\tvar v_extraFieldSize;\n\tvar v_cdExtraFieldSize;\n\tvar v_commentSize;\n\tvar v_payloadCompression;\n\tvar v_payloadSize;\n\tvar v_extractedBytes;\n\tvar v_fileHeadStart;\n\tvar v_startCRC;\n\tvar v_calcCRC32;\n\tvar v_readCRC32;\n\tvar v_decompressor;\n\tvar v_compSig;//component signature\n\tvar v_bitFlags;\n\tvar v_relOffset;\n\tvar v_offsetMode = 0;//0 for normal, 1 for undocumented mode some writers use that store the offset from the start of the file.\n\tconsole.log('Starting ZIP read. size: ' + v_oct.length);\n\t//First find the start of the end of central directory, it has a variable length comment field so may not be in a set spot.\n\tvar v_cdPos = v_oct.length - 1;//Read the zip starting with the central directory at the end. This is more reliable, since the length and CRC may not be available in the local file header.\n\t//IT MUST start by reading the End of Central Directory section. since there is only a comment field with in the EoCD the chances of collisions with the signature are near-zero when going in reverse to find the start of it.\n\t//reading thru the files from the start will not work because the length fields are not guaranteed to be filled in. In that case, one would have to scan for the start of Data Descriptor signature after the file to get the length. With large sections of binary there are high chances of collisions with the Data Descriptor signature.\n\tvar v_cdSig = 0;\n\twhile(v_cdSig != 0x06054B50){\n\t\tv_cdPos--;\n\t\tv_cdSig = GraFlicEncoder.readUint32(v_oct, v_cdPos, true);\n\t\t//console.log(v_cdSig.toString(16));\n\t}\n\tvar v_filesCountZIP = GraFlicEncoder.readUint16(v_oct, v_cdPos + 10, true);//Number of entries in central directory.\n\tvar v_filesRead = 0;\n\tvar v_cdStart = GraFlicEncoder.readUint32(v_oct, v_cdPos + 16, true);//Where the central directory starts\n\tv_cdPos = v_cdStart;\n\twhile(v_filesRead < v_filesCountZIP){\n\t\tconsole.log('CentDir pos: ' + v_cdPos + ' sig: ' + GraFlicEncoder.readUint32(v_oct, v_cdPos, true).toString(16));\n\t\tv_relOffset = GraFlicEncoder.readUint32(v_oct, v_cdPos + 42, true);\n\t\tif(v_relOffset == 0){v_offsetMode = 1;}\n\t\t//0 is never valid for the offset from central directory defined in the spec. If the first offset is 0, it must use the undocumented mode that uses the offset from the start of the file.\n\t\tif(v_offsetMode == 1){\n\t\t\tv_fileHeadStart = v_relOffset;\n\t\t}else{\n\t\t\tv_fileHeadStart = v_cdPos - v_relOffset;//go backwards by the offset bytes to locate the local file header.\n\t\t}\n\t\tconsole.log('version made by, version: ' + v_oct[v_cdPos + 4] + ' OS: ' + v_oct[v_cdPos + 5]);\n\t\tconsole.log('version needed to extract, version: ' + v_oct[v_cdPos + 6] + ' OS: ' + v_oct[v_cdPos + 7]);\n\t\tconsole.log('rel offset: ' + v_relOffset + ' starting at: ' + v_fileHeadStart);\n\t\tv_pos = v_fileHeadStart;\n\t\tv_payloadSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 20, true);//Read size out of central directory where it should be calculated. In the local file header it may be undefined if bit 3 of the flags is set. So far, this seems to reliably work to get payload size.\n\t\tv_cdFilenameSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 28, true);\n\t\tv_cdExtraFieldSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 30, true);//The extra field on central directory might be different from local file header.\n\t\tv_commentSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 32, true);//Comment ONLY appears on central directory header, NOT the local file header.\n\n\t\tconsole.log('local file header sig: ' + GraFlicEncoder.readUint32(v_oct, v_pos, true).toString(16));\n\t\tv_bitFlags = GraFlicEncoder.readUint16(v_oct, v_pos + 6, true);\n\t\tv_payloadCompression = GraFlicEncoder.readUint16(v_oct, v_pos + 8, true);\n\t\tv_filenameSize = GraFlicEncoder.readUint16(v_oct, v_pos + 26, true);\n\t\tv_extraFieldSize = GraFlicEncoder.readUint16(v_oct, v_pos + 28, true);\n\t\tv_pos += 30;\n\t\t\n\t\tv_filename = GraFlicEncoder.readStringUTF8(v_oct, v_pos, v_filenameSize);\n\t\t//OLD only ASCII compatible: v_filename = String.fromCharCode.apply(null, v_oct.subarray(v_pos, v_pos + v_filenameSize));\n\t\tv_pos += v_filenameSize;\n\t\tv_pos += v_extraFieldSize;//This app does not use extra field, but check for it in case the ZIP was edited and repackaged by another ZIP writer.\n\t\t\n\t\tv_cdPos += 46 + v_cdFilenameSize + v_cdExtraFieldSize + v_commentSize;//Advance to the next central directory header for the next file.\n\t\t\n\t\tconsole.log('Central Directory sizes: filename: ' + v_cdFilenameSize + ' comment: ' + v_commentSize + ' extra: ' + v_cdExtraFieldSize);\n\t\tconsole.log('Reading ' + v_filename + ' out of ZIP.');\n\t\tconsole.log('Local File Header sizes: payload: ' + v_payloadSize + ' filename: ' + v_filenameSize + ' extra: ' + v_extraFieldSize);\n\t\tconsole.log('bit flags: 0x' + v_bitFlags.toString(16));\n\t\tv_decompressor = GraFlicUtil.noCompression;//default to 0, no compression\n\t\tconsole.log('compression mode: ' + v_payloadCompression);\n\t\tif(v_payloadCompression == 8){//DEFLATE\n\t\t\tv_decompressor = window.pako.inflateRaw;\n\t\t}\n\t\tif(v_filename.match(/(^|\\/)\\./)){ // || v_filename.match(/\\..*\\./)){\n\t\t\t//Throw out files that start with a dot.\n\t\t\t//These are probably system generated junk files, the save format does not use files named this way.\n\t\t\t//In *nix operating systems starting with a dot(.) is a hidden file, often some kind of system file.\n\t\t\tconsole.log('Skipping apparent junk file: ' + v_filename);\n\t\t}else{\n\t\t\tv_extractedBytes = v_oct.subarray(v_pos, v_pos + v_payloadSize);\n\t\t\tif(v_filename.match(/\\//) && v_filename.split('/')[0].indexOf(v_loadedFilename) == 0){\n\t\t\t\t\t\t\t//(Remember, extra things like (2) may get appended to the filename if it gets renamed due to existing file that it was extracted from.)\n\t\t\t\t//If the files are in a folder with the same name as the loaded file, the user probably re-packed them\n\t\t\t\t//incorrectly which is easy to do, given the unintuitive way ZIPs extract out to a folder, but if you\n\t\t\t\t//compress the folder again, it puts the folder within the ZIP, so in that case, strip these out.\n\t\t\t\tv_filename = v_filename.replace(/^[^\\/]+\\//, '');\n\t\t\t\tconsole.log('The folder was repackaged inside of itself it seems. Filename fixed to: ' + v_filename);\n\t\t\t}\n\t\t\tvar xFile = {};\n\t\t\txFile.p = v_filename;//keep a reference for what the path is in case object referenced elsewhere.\n\t\t\ttry{//-----------------------------------------------------------------------------------\n\t\t\tif(v_filename.match(/\\.gz$/i)){\n\t\t\t\t//If .gz first decompress it with whatever compression method is defined in the ZIP entry (usually 0 none),\n\t\t\t\t//then set the decompressor to ungzip because .gz has internal compression of its own.\n\t\t\t\tv_extractedBytes = v_decompressor(v_extractedBytes);\n\t\t\t\tv_decompressor = window.pako.ungzip;\n\t\t\t\tconsole.log('.gz file, setting decompression to GZip, gz payload size: ' + v_extractedBytes.length);\n\t\t\t}\n\t\t\t//JSON and text will not have .d (data) populated since it is pretty useless in most cases and would waste resources.\n\t\t\tif(v_filename.match(/\\.json(\\.gz)?$/i)){\n\t\t\t\t//JSON needs extra logic to JSONize it into memory.\n\t\t\t\txFile.j = JSON.parse(v_decompressor(v_extractedBytes, {'to':'string'}));\n\t\t\t\t//alert('extracted JSON(' + v_filename + '): ' + JSON.stringify(xFile));\n\t\t\t\tthis.j[v_filename.replace(/\\.json(\\.gz)?$/i, '')] = xFile.j;//Set up a quick link for accessing JSON.\n\t\t\t\t\t\t\t//JSON files will typically contain the main configuration, parameters, and settings of a format\n\t\t\t\t\t\t\t//and need to be accessed often so .j.config.valX is less cluttered than: .f['config.json'].valX\n\t\t\t\t\t\t\t//do this after the file was successfully extracted\n\t\t\t}else if(v_filename.match(/\\.txt(\\.gz)?$/i)){\n\t\t\t\txFile.t = v_decompressor(v_extractedBytes, {'to':'string'});\n\t\t\t}else{\n\t\t\t\txFile.d = v_decompressor(v_extractedBytes);\n\t\t\t\t//Some browser may truncate the array text when tracing to debug and look like all zeroes.\n\t\t\t\tconsole.log('extracted U8Array(' + v_filename + '): ' + xFile + ' size: ' + xFile.d.length);\n\t\t\t}\n\t\t\t}catch(fileError){\n\t\t\t\tconsole.log('error reconstituting ' + v_filename + ', it may be a junk or auto-generated file.');\n\t\t\t}//-------------------------------- end try/catch ----------------------------------------\n\n\t\t\t//else if(v_filename.match(/\\.(a*png|jpe*g|giff*|webp)(\\.gz)?$/i)){\n\t\t\t//}\n\t\t\t\t//Keep image Uint8Array linked in case it needs to be examined for metadata such as EXIF rotation.\n\t\t\t\t//Also make a loadable BLOB ObjectURL so it can easily be loaded into images in the DOM.\n\t\t\t\t//Since the Uint8Array is used to build the BLOB for the ObjectURL, it would seem that dereferencing\n\t\t\t\t//it would probably not save any runtime resources, may as well keep it alive for analysis if needed.\n\t\t\t//make BLOBs for all files too\n\t\t\txFile.d = v_decompressor(v_extractedBytes);\n\t\t\tthis.fileToBLOB(xFile);\n\t\t\tthis.f[v_filename] = xFile;//if completed with no errors, include it in the files object\n\t\t\tconsole.log('----------------------');\n\t\t}\n\t\tv_filesRead++;\n\t}//end while\n}",
"async parseExifBlock() {\n\t\tif (this.exifOffset === undefined) return\n\t\tthis.exif = await this.parseTiffTags(this.tiffOffset + this.exifOffset, tags.exif)\n\t}",
"function Image2DParser() {\n _super.call(this, URLLoaderDataFormat.BLOB);\n }",
"async function parseFramesFromZip(name, fwidth, fheight, zip, nframes){\n\n if (name + \"-Anim.png\" in zip.files){ //check if the file exists\n let b64 = await zip.file(name + \"-Anim.png\").async(\"base64\")\n let img = await getImgfromB64(b64);\n\n //sanity check file size\n if (img.width != nframes * fwidth || !(img.height == fheight || img.height == fheight * 8)){\n addWarning(\"Warning\", \"sprite\", \"The file \" + name + \"-Anim.png has different dimensions than expected, check the frame sizes or the image dimesions. Sprites in that animation may look wrong or some might be missing.\");\n }\n\n return await parseFramesfromIMG(fwidth, fheight, img, nframes);\n }else {\n\n addWarning(\"Error\", \"sprite\", \"The file \" + name + \"-Anim.png is missing or broken (name is Case Sensitive). Generating an empty/transparent spritesheet.\");\n frames = generateEmptyFrames(fwidth, fheight, nframes, 8);\n return null;\n }\n}",
"function Image2DParser() {\n return _super.call(this, URLLoaderDataFormat.BLOB) || this;\n }",
"parse(buffer){\r\n this.buffer = buffer;\r\n this.type = buffer.toString('utf-8', 0, 2);\r\n this.pixelOffset = buffer.readInt32LE(_PIXEL_OFFSET);\r\n this.colorArray = buffer.slice(_COLOR_TABLE_OFFSET, Bitmap.pixelOffset);\r\n }",
"_insertFromCbz(){\n var self = this;\n self._zip = new StreamZip({\n file: self._comic,\n storeEntries: true\n });\n self._zip.on('error', function(err) {\n self._callError(err);\n });\n\n self._zip.on('ready', function() {\n var files = self._zip.entries();\n var total = self._zip.entriesCount, index = 0;\n var q = queue();\n q.concurrency = 1;\n for (let prop in files) {\n\n if (!files.hasOwnProperty(prop)) {\n continue;\n }\n\n let ext = path.extname(prop);\n let name = path.basename(prop)\n if( ext == \".jpg\" || ext == \".png\" ){\n q.push(function(cb) {\n self._data.images.push({\n \"file\" : name,\n \"page\" : (index < 10)?0+index:index\n })\n self._zip.stream(prop, function(err, stream) {\n if ( err) self._callError(err);\n var imageSizeStream = ImageSizeStream()\n .on('size', function(dimensions) {\n self._data.images[index].mimeType = mime.lookup(dimensions.type);\n self._data.images[index].width = dimensions.width;\n self._data.images[index].height = dimensions.height;\n });\n stream.pipe(imageSizeStream);\n self._archive.entry(stream, { name: path.join(self._model.imagePath,name) , date: self._date}, function(err) {\n index++;\n if ( err) self._callError(err);\n cb();\n });\n });\n })\n }\n }\n q.start(function(err) {\n if ( err) self._callError(err);\n if(self._data.images.length < 1){\n self._callError(\"No images found\");\n }else{\n self._insertInteractive(0, 0);\n }\n });\n })\n }",
"function loader(func,str,arr,exp,cb) {\n var\n p=function(){return func([],str(pakoOffsetStart,pakoOffsetEnd))();},\n z=function(){return func([],exp.pako.inflate(arr(JSZipOffsetStart,JSZipOffsetEnd),{to:'string'}))();};\n try {\n p();\n z();\n var zip = new exp.JSZip();\n zip.loadAsync(arr(ZipFileOffsetStart,ZipFileOffsetEnd))\n .then(function(zip){cb(null,zip);})\n .catch(cb);\n } catch(err) {\n cb(err);\n }\n p=z=null;\n }",
"function GraFlicArchive(zipDataUint8, paramz){\n\t//'this' object will be returned to the caller with contents of the ZIP.\n\tthis.files = {};//each file will have potentially .d (data) containing the files, extracted and decompressed. The filename will be the key to access the file object in files. JSON will have .json containing the reconstituted JSON object. Text will have .t (text) containing the text string. JSON and text do not currently fill the .d property because it would not be very useful and would waste resources.\n\t//Images(PNG/JPG/GIF/WEBP) will have their raw binary appear in files in case metadata needs examining, and will also have an ObjectURL put here in images for easy loading by DOM elements in .b (blob link).\n\t//Other properties may be added to this result object later if needed.\n\t\n\tGraFlicArchive.archives.push(this);//Each archive created will be tracked here so that a file can be looked up if the path exists in any archive in memory with static getFileFromAny()\n\tvar jAM = null;//will be populated if archive-metadata.json type validator found.\n\tvar bloatFolder = null;//null for N/A, will be used to fix a common packaging mistake that wraps an extra folder around everything.\n\tif(!paramz){\n\t\tparamz = {};//makes handling undefined vars easier if paramz.x is undefined it can just send undefined for optional x if needed without getting 'paramz is undefined'\n\t}\n\t\t/*\n\t\tif(paramz.globalAsset){\n\t\t\t//being called with globalAsset true will tell it to keep the files in memory and set up the linkage so that the file can be used to fill custom zip links within the page with the images once they are extracted.\n\t\t\t//This is used when the custom:link rel=\"archive\" element is detected to say that the page uses images/files stored in a zip file.\n\t\t}\n\t\t*/\n\tif(!zipDataUint8){\n\t\t//If called without a binary ZIP to load, make a blank GraFlicArchive that can be filled with files programmatically and saved.\n\t\t/*\n\t\tvar paramApps = undefined;\n\t\tif(paramz.app){//Single app string, convert to array for archive-metadata.json\n\t\t\tparamApps = [paramz.app];\n\t\t}\n\t\tif(paramz.apps){\n\t\t\tparamApps = paramz.apps;//.apps plural sent should be sent as array\n\t\t}\n\t\t//Note that these extra parameters and logic may not be needed. It may be better to just set the properties of the archive-metadata.json object after the GraFlicArchive is initialized to match what the given software or format needs. This would simplify the constructor. Falling back to the generic application/octet-stream type will probably not be devastating if properties are not customized after creation.\n\t\t\t//paramz.mime, paramz.type, paramApps);\n\t\t*/\n\t\tthis.addArchiveMetadata();\n\t\treturn;\n\t}\n//Note when reading, other ZIP builders may insert data descriptor after local file header and payload, which apparently may or may not use a signature...\n\t//Writing data descriptors is turned of in the save function used here with general purpose bit 3 set to 0.\n\tvar v_oct = zipDataUint8;\n\tvar v_pos;\n\tvar v_i;\n\tvar v_entrySize;\n\tvar v_filename;\n\tvar v_filenameSize;\n\tvar v_cdFilenameSize;\n\tvar v_extraFieldSize;\n\tvar v_cdExtraFieldSize;\n\tvar v_commentSize;\n\tvar v_payloadCompression;\n\tvar v_payloadSize;\n\tvar v_payloadUncompressedSize;\n\tvar v_extractedBytes;\n\tvar v_fileHeadStart;\n\t//var v_calcCRC32;\n\tvar v_readCRC32;\n\tvar v_compSig;//component signature\n\tvar v_bitFlags;\n\tvar v_relOffset;\n\t//OLD, incorrect: var v_offsetMode = 0;//0 for normal, 1 for undocumented mode some writers use that store the offset from the start of the file.\n\tconsole.log('Starting ZIP read. size: ' + v_oct.length);\n\t//First find the start of the end of central directory, it has a variable length comment field so may not be in a set spot.\n\tvar v_cdPos = v_oct.length - 1;//Read the zip starting with the central directory at the end. This is more reliable, since the length and CRC may not be available in the local file header.\n\t//IT MUST start by reading the End of Central Directory section. since there is only a comment field with in the EoCD the chances of collisions with the signature are near-zero when going in reverse to find the start of it.\n\t//reading thru the files from the start will not work because the length fields are not guaranteed to be filled in. In that case, one would have to scan for the start of Data Descriptor signature after the file to get the length. With large sections of binary there are high chances of collisions with the Data Descriptor signature.\n\tvar v_cdSig = 0;\n\twhile(v_cdSig != 0x06054B50){\n\t\tv_cdPos--;\n\t\tv_cdSig = GraFlicEncoder.readUint32(v_oct, v_cdPos, true);\n\t\t//console.log(v_cdSig.toString(16));\n\t}\n\tvar v_filesCountZIP = GraFlicEncoder.readUint16(v_oct, v_cdPos + 10, true);//Number of entries in central directory.\n\tvar v_filesRead = 0;\n\tvar v_cdStart = GraFlicEncoder.readUint32(v_oct, v_cdPos + 16, true);//Where the central directory starts\n\tv_cdPos = v_cdStart;\n\twhile(v_filesRead < v_filesCountZIP){\n\t\tconsole.log('CentDir pos: ' + v_cdPos + ' sig: ' + GraFlicEncoder.readUint32(v_oct, v_cdPos, true).toString(16));\n\t\tv_relOffset = GraFlicEncoder.readUint32(v_oct, v_cdPos + 42, true);\n\t\t//if(v_relOffset == 0){v_offsetMode = 1;}\n\t\t//0 is never valid for the offset from central directory defined in the spec. If the first offset is 0, it must use the undocumented mode that uses the offset from the start of the file.\n\t\t//if(v_offsetMode == 1){\n\t\tv_fileHeadStart = v_relOffset;//In ZIP 2.0, it is always the position from the beginning of the file, the other way was incorrect.\n\t\t//}else{\n\t\t//\tv_fileHeadStart = v_cdPos - v_relOffset;//go backwards by the offset bytes to locate the local file header.\n\t\t//}\n\t\tconsole.log('version made by, version: ' + v_oct[v_cdPos + 4] + ' OS: ' + v_oct[v_cdPos + 5]);\n\t\tconsole.log('version needed to extract, version: ' + v_oct[v_cdPos + 6] + ' OS: ' + v_oct[v_cdPos + 7]);\n\t\tconsole.log('rel offset: ' + v_relOffset + ' starting at: ' + v_fileHeadStart);\n\t\tv_pos = v_fileHeadStart;\n\t\tv_readCRC32 = GraFlicEncoder.readInt32(v_oct, v_cdPos + 16, true);\n\t\tv_payloadSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 20, true);//Read size out of central directory where it should be calculated. In the local file header it may be undefined if bit 3 of the flags is set. So far, this seems to reliably work to get payload size.\n\t\tv_payloadUncompressedSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 24, true);\n\n\t\tv_cdFilenameSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 28, true);\n\t\tv_cdExtraFieldSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 30, true);//The extra field on central directory might be different from local file header.\n\t\tv_commentSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 32, true);//Comment ONLY appears on central directory header, NOT the local file header.\n\n\t\t//console.log('i att(L): ' + GraFlicEncoder.readUint16(v_oct, v_cdPos + 36, true).toString(2));\n\t\t//console.log('x att(L): ' + GraFlicEncoder.readUint32(v_oct, v_cdPos + 38, true).toString(2));\n\n\t\tconsole.log('local file header sig: ' + GraFlicEncoder.readUint32(v_oct, v_pos, true).toString(16));\n\t\tv_bitFlags = GraFlicEncoder.readUint16(v_oct, v_pos + 6, true);\n\t\tv_payloadCompression = GraFlicEncoder.readUint16(v_oct, v_pos + 8, true);\n\t\tv_filenameSize = GraFlicEncoder.readUint16(v_oct, v_pos + 26, true);\n\t\tv_extraFieldSize = GraFlicEncoder.readUint16(v_oct, v_pos + 28, true);\n\t\tv_pos += 30;\n\t\t\n\t\tv_filename = GraFlicEncoder.readStringUTF8(v_oct, v_pos, v_filenameSize);\n\t\t//OLD only ASCII compatible: v_filename = String.fromCharCode.apply(null, v_oct.subarray(v_pos, v_pos + v_filenameSize));\n\t\tv_pos += v_filenameSize;\n\t\tv_pos += v_extraFieldSize;//This app does not use extra field, but check for it in case the ZIP was edited and repackaged by another ZIP writer.\n\t\t\n\t\tv_cdPos += 46 + v_cdFilenameSize + v_cdExtraFieldSize + v_commentSize;//Advance to the next central directory header for the next file.\n\t\t\n\t\tconsole.log('Central Directory sizes: filename: ' + v_cdFilenameSize + ' comment: ' + v_commentSize + ' extra: ' + v_cdExtraFieldSize);\n\t\tconsole.log('Reading ' + v_filename + ' out of ZIP.');\n\t\tconsole.log('Local File Header sizes: payload: ' + v_payloadSize + ' filename: ' + v_filenameSize + ' extra: ' + v_extraFieldSize);\n\t\tconsole.log('bit flags: 0x' + v_bitFlags.toString(16));\n\t\t\n\t\t\n\t\tif(v_filename.match(/desktop\\.ini$/) || v_filename.match(/__MACOSX\\//) || v_filename.match(/\\.DS_Store$/)){\n\t\t\t\t// || v_filename.match(/(^|\\/)\\./)){ // || v_filename.match(/\\..*\\./)){\n\t\t\t//Detect and throw out apparent non-user, OS-generated files.\n\t\t\t//If a user repackages or builds a ZIP-based file with another packaging tool, these can end up creeping into the archive and they are not needed for the ZIP-based formats.\n\t\t\t//Throw out files that start with a dot??\n\t\t\t//These are probably system generated junk files, the save format does not use files named this way.\n\t\t\t//However some users may have designed archives specifically using these types of files for some reason...\n\t\t\t//In *nix operating systems starting with a dot(.) is a hidden file, often some kind of system file.\n\t\t\tconsole.log('Skipping apparently irrelevant file: ' + v_filename);\n\t\t}else{\n\t\t\tv_extractedBytes = v_oct.subarray(v_pos, v_pos + v_payloadSize);\n\t\t\t\t//CRC is based on BEFORE being compressed, it will not be uncompressed until accessed...\n\t\t\t\t//incorrect v_calcCRC32 = GraFlicEncoder.getCRC32(v_extractedBytes, 0, v_payloadSize);\n\t\t\t\t//console.log('CRC calculated: ' + v_calcCRC32 + ' CRC read: ' + v_readCRC32);\n\t\t\tvar xFile = {};\n\t\t\txFile.reconst = false;//Has not been reconstituted. This will be done as needed if the file is accessed via .f('filepath'). That way resources are saved by not making every file live on load when not all files may be used right away, if even used at all.\n\t\t\txFile.compression = v_payloadCompression;//Compression method code as defined by ZIP.\n\t\t\txFile.uncompressed_size = v_payloadUncompressedSize;//Will need to know what size the original file is if re-packaging it.\n\t\t\txFile.zip_crc = v_readCRC32;//save the CRC that was generated over the full uncompressed payload by the ZIP packager.\n\t\t\t//console.log('uncompressed size: ' + uncompressed_size);\n\t\t\txFile.p = v_filename;//keep a reference for what the path is in case object referenced elsewhere.\n\t\t\t\n\t\t\txFile.d = v_extractedBytes;//These bytes will be decompressed later if the archived file entry is reconstituted.\n\t\t\tthis.files[v_filename] = xFile;//if completed with no errors, include it in the files object\n\t\t\tconsole.log('----------------------');\n\t\t\t\n\t\t\tvar partsAM = v_filename.match(/^(.*\\/)archive-metadata\\.json$/);//detect a bloat folder if packaging mistake was made.\n\t\t\tif(partsAM){//If matches at all\n\t\t\t\tconsole.log('.-.-.-.-. archive metadata (validate file type) .-.-.-.-.-.');\n\t\t\t\tjAM = this.f(v_filename).j;\n\t\t\t\t//The archive-metadata.json filename is long and unique enough that it out to block most collisions with other files out there on its own.\n\t\t\t\t//however, an additional check can optionally be done with .signature in case some archive somewhere has an archive-metadata.json that does something different.\n\t\t\t\tif(jAM.archiveMetadata && jAM.archiveMetadata.signature == 'archive metadata'){//verify it is for this purpose\n\t\t\t\t\tconsole.log('confirmed to be metadata/type validator: archive-metadata.json');\t\n\t\t\t\t\tif(jAM.archiveMetadata.version){//Already checked .archiveMetadata in previous if.\n\t\t\t\t\t\t//The version number is optional and merely a hint for what properties might be defined.\n\t\t\t\t\t\tconsole.log('archive-metadata.json version: ' + jAM.archiveMetadata.version);\n\t\t\t\t\t}\n\t\t\t\t\tif(partsAM && partsAM[1] && partsAM[1].length){\n\t\t\t\t\t\tbloatFolder = partsAM[1];\n\t\t\t\t\t\tconsole.log('User apparently made common mistake of packaging everything wrapped in an extra bloat folder. The bloat folder(' + bloatFolder + ') will be stripped from paths.');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconsole.log('.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.');\n\t\t\t}\n\t\t}\n\t\tv_filesRead++;\n\t}//end while\n\tif(bloatFolder){//Remove the bloat folder portion from paths if a packaging mistake resulted in things being wrapped in a bloat folder. The next time this is saved by an app using GraFlicArchive, it will be properly packaged without the bloat folder.\n\t\tvar unbloatedFiles = {};\n\t\tfor(var key in this.files){\n\t\t\tvar bRepFile = this.files[key];\n\t\t\tbRepFile.p = bRepFile.p.replace(new RegExp('^' + bloatFolder), '');\n\t\t\tunbloatedFiles[bRepFile.p] = bRepFile;\n\t\t}\n\t\tthis.files = unbloatedFiles;\n\t}\n}",
"function zillowRunner(zip) {\n zillowGetter(zip);\n }",
"constructor(packData) {\n this.name = name;\n if (packData instanceof ArrayBuffer) {\n // zip with bops uses Uint8Array data view\n packData = new Uint8Array(packData);\n }\n this.zip = new ZIP.Reader(packData);\n\n this.zipEntries = {};\n this.zip.forEach((entry) => {\n this.zipEntries[entry.getName()] = entry;\n });\n\n this.namespaces = this.scanNamespaces();\n }",
"function readZipFile(codeVar){\r\n\r\n\tvar zip = new JSUnzip(window.atob(codeVar));\r\n\t//read archive\r\n\tzip.readEntries();\r\n\r\n\t// read files\r\n\tfor (var i = 0; i < zip.entries.length; i++) {\r\n\t\tvar entry = zip.entries[i];\r\n\t\tstimuliAllInfo[i] = imageProcess(entry);\r\n\t}\r\n\r\n}",
"async function parseToImage(arrayBuffer, options) {\n // Note: image parsing requires conversion to Blob (for createObjectURL).\n // Potentially inefficient for not using `response.blob()` (and for File / Blob inputs)...\n // But presumably not worth adding 'blob' flag to loader objects?\n\n // TODO - how to determine mime type? Param? Sniff here?\n const mimeType = 'image/jpeg';\n const blob = new Blob([arrayBuffer], {type: mimeType});\n const URL = self.URL || self.webkitURL;\n const objectUrl = URL.createObjectURL(blob);\n try {\n return await loadToImage(objectUrl, options);\n } finally {\n URL.revokeObjectURL(objectUrl);\n }\n}",
"function Image2DParser(factory, alphaChannel) {\n if (factory === void 0) { factory = null; }\n if (alphaChannel === void 0) { alphaChannel = null; }\n var _this = _super.call(this, _awayjs_core__WEBPACK_IMPORTED_MODULE_1__[\"URLLoaderDataFormat\"].BLOB) || this;\n _this._factory = factory || new _factories_DefaultGraphicsFactory__WEBPACK_IMPORTED_MODULE_4__[\"DefaultGraphicsFactory\"]();\n _this._alphaChannel = alphaChannel;\n return _this;\n }",
"*buildImageMetadata(){\n if(this.type !== 'image') return;\n\n const image = yield _p(lwip.open)(lwip, this.path);\n this.width = image.width();\n this.height = image.height();\n this.size = fs.lstatSync(this.path).size;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets if the provided structure is a JSDocableNodeStructure. | static isJSDocable(structure) {
switch (structure.kind) {
case StructureKind_1.StructureKind.Class:
case StructureKind_1.StructureKind.Constructor:
case StructureKind_1.StructureKind.ConstructorOverload:
case StructureKind_1.StructureKind.GetAccessor:
case StructureKind_1.StructureKind.Method:
case StructureKind_1.StructureKind.MethodOverload:
case StructureKind_1.StructureKind.Property:
case StructureKind_1.StructureKind.SetAccessor:
case StructureKind_1.StructureKind.Enum:
case StructureKind_1.StructureKind.EnumMember:
case StructureKind_1.StructureKind.Function:
case StructureKind_1.StructureKind.FunctionOverload:
case StructureKind_1.StructureKind.CallSignature:
case StructureKind_1.StructureKind.ConstructSignature:
case StructureKind_1.StructureKind.IndexSignature:
case StructureKind_1.StructureKind.Interface:
case StructureKind_1.StructureKind.MethodSignature:
case StructureKind_1.StructureKind.PropertySignature:
case StructureKind_1.StructureKind.Namespace:
case StructureKind_1.StructureKind.VariableStatement:
case StructureKind_1.StructureKind.TypeAlias:
return true;
default:
return false;
}
} | [
"static isJSDoc(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JSDoc;\r\n }",
"static isJSDocableNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.ClassDeclaration:\r\n case typescript_1.SyntaxKind.ClassExpression:\r\n case typescript_1.SyntaxKind.Constructor:\r\n case typescript_1.SyntaxKind.GetAccessor:\r\n case typescript_1.SyntaxKind.MethodDeclaration:\r\n case typescript_1.SyntaxKind.PropertyDeclaration:\r\n case typescript_1.SyntaxKind.SetAccessor:\r\n case typescript_1.SyntaxKind.EnumDeclaration:\r\n case typescript_1.SyntaxKind.EnumMember:\r\n case typescript_1.SyntaxKind.ArrowFunction:\r\n case typescript_1.SyntaxKind.FunctionDeclaration:\r\n case typescript_1.SyntaxKind.FunctionExpression:\r\n case typescript_1.SyntaxKind.CallSignature:\r\n case typescript_1.SyntaxKind.ConstructSignature:\r\n case typescript_1.SyntaxKind.IndexSignature:\r\n case typescript_1.SyntaxKind.InterfaceDeclaration:\r\n case typescript_1.SyntaxKind.MethodSignature:\r\n case typescript_1.SyntaxKind.PropertySignature:\r\n case typescript_1.SyntaxKind.ImportEqualsDeclaration:\r\n case typescript_1.SyntaxKind.ModuleDeclaration:\r\n case typescript_1.SyntaxKind.ExpressionStatement:\r\n case typescript_1.SyntaxKind.LabeledStatement:\r\n case typescript_1.SyntaxKind.VariableStatement:\r\n case typescript_1.SyntaxKind.TypeAliasDeclaration:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isJSDocType(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JSDocFunctionType:\r\n case typescript_1.SyntaxKind.JSDocSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"function hasJSDocNodes(node) {\n return !!node.jsDoc && node.jsDoc.length > 0;\n }",
"function hasJSDocNodes(node) {\n return !!node.jsDoc && node.jsDoc.length > 0;\n }",
"static isJSDocTag(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JSDocAugmentsTag:\r\n case typescript_1.SyntaxKind.JSDocClassTag:\r\n case typescript_1.SyntaxKind.JSDocParameterTag:\r\n case typescript_1.SyntaxKind.JSDocPropertyTag:\r\n case typescript_1.SyntaxKind.JSDocReturnTag:\r\n case typescript_1.SyntaxKind.JSDocTypedefTag:\r\n case typescript_1.SyntaxKind.JSDocTypeTag:\r\n case typescript_1.SyntaxKind.JSDocTag:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isJSDoc(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.JSDocComment;\r\n }",
"function isJSDocNode(node) {\n return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */;\n }",
"function isJSDocNode(node) {\n return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */;\n }",
"static isNode(obj) {\n\t\treturn obj.type;\n\t}",
"static isJSDocTypeTag(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.JSDocTypeTag;\r\n }",
"static isJsxElement(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JsxElement;\r\n }",
"function sc_isStruct(o) {\n return (o instanceof sc_Struct);\n}",
"function isNode(o){\n return (\n typeof Node === \"object\" ? o instanceof Node :\n o && typeof o === \"object\" && typeof o.nodeType === \"number\" && typeof o.nodeName===\"string\"\n );\n}",
"function _isNode(x){\n\treturn !!(x.tree && x.statusNodeType !== undefined);\n}",
"function isJSDocCommentContainingNode(node) {\n return node.kind === 279 /* JSDocComment */ || isJSDocTag(node);\n }",
"function getJSDocNode(node, ts) {\n var _a, _b, _c;\n var parent = (_b = (_a = ts.getJSDocTags(node)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.parent;\n if (parent != null && ts.isJSDoc(parent)) {\n return parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (_c = node.jsDoc) === null || _c === void 0 ? void 0 : _c.find(function (n) { return ts.isJSDoc(n); });\n}",
"function isNodeLike(obj) {\n return obj && (obj.nodeType === 1 || obj.nodeType === 9);\n }",
"static isTyped(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.Parameter:\r\n case StructureKind_1.StructureKind.PropertySignature:\r\n case StructureKind_1.StructureKind.VariableDeclaration:\r\n case StructureKind_1.StructureKind.TypeAlias:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
do invoice transition on save activity | function saveActivityAndDoTransition() {
Y.doccirrus.jsonrpc.api.activity.read( { query: { _id: ko.unwrap( activities[0] ) } } )
.then(function( res ) {
var
data = res.data && res.data[0],
isCorrectTransition = false;
// checking if transition is allowed
if( 'INVOICEREF' === data.actType || 'INVOICE' === data.actType ) {
fsm[data.status].forEach(function( item ) {
if( item.transition === transition.transition ) {
isCorrectTransition = true;
}
});
}
if( !isCorrectTransition ) {
Y.doccirrus.DCWindow.notice( {
type: 'info',
message: i18n( 'InCaseMojit.ActivityDetailsVM.error.not_correct_status' ),
window: {
width: 'medium'
}
} );
return null;
}
return data;
}).then(function( res ) {
if( res ) {
// test transition
activityDetailsVM.saveAttachmentsAndTransition( transitionArgs )
.then(function( res ) {
return res;
}).then(function() {
roundReceiptAmount = parseFloat( currentActivity && currentActivity.amount ? currentActivity.amount() : 0 ).toFixed( 2 );
roundOutstanding = parseFloat( res.totalReceiptsOutstanding ).toFixed( 2 );
if ( currentActivity && ( roundReceiptAmount !== roundOutstanding ) && ( 'pay' === transition.transition || 'derecognize' === transition.transition ) ) {
willBalanceInvoice = true;
}
if( !willBalanceInvoice ) {
Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: true
} );
}
}).then(function() {
if( !willBalanceInvoice ) {
res.notCreateNew = true;
return Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: false
} ).then( function() {
var patientId = unwrap( currentPatient._id() );
if( patientId ) {
caseFolders.load( { patientId: patientId } );
}
});
}
});
}
}).fail( function( error ) {
Y.Array.invoke( Y.doccirrus.errorTable.getErrorsFromResponse( error ), 'display' );
} );
} | [
"function saveInvoiceNumber( itcb ) {\n // this step only applies to invoices\n if ( 'INVOICE' !== activity.actType && 'RECEIPT' !== activity.actType ) { return itcb( null ); }\n\n var\n setArgs = {\n 'content': activity.content,\n 'timestamp': activity.timestamp\n };\n\n if ( 'INVOICE' === activity.actType ) {\n setArgs.invoiceNo = activity.invoiceNo;\n mapFields.invoiceNo = activity.invoiceNo;\n mapFields.date = moment( activity.timestamp + '' ).format( 'DD.MM.YY' );\n }\n\n if ( Y.doccirrus.schemas.activity.isInvoiceCommunicationActType( activity.actType ) ) {\n setArgs.receiptNo = activity.receiptNo || '';\n mapFields.receiptNo = activity.receiptNo || '';\n mapFields.invoiceNo = activity.invoiceNo || '';\n mapFields.content = activity.content || '';\n mapFields.date = moment( activity.timestamp + '' ).format( 'DD.MM.YY' );\n }\n\n // NOTE: these always have a form, so reporting will be updated with these fields during the full\n // save when the PDF is complete.\n\n Y.doccirrus.mongodb.runDb( {\n user,\n action: 'update',\n model: 'activity',\n query: { _id: activity._id + '' },\n data: { $set: setArgs },\n options: { multi: false }\n }, itcb );\n }",
"onSaving() {\n if (this._saving) {\n this._saving.raise();\n }\n }",
"onSaved() {\n this.saved.raise();\n }",
"function continueSave() {\n notify(_L('Address successfully saved.'));\n $.customer_address.fireEvent('route', {\n page : 'addresses'\n });\n}",
"finishSave() {\n }",
"function saveClicked() {\n _save(false);\n }",
"onSaved() {\n if (this._saved) {\n this._saved.raise();\n }\n }",
"function doSave() {\n //This is a new 'virtual object' that has not been persisted\n // yet.\n if (!domainObject.getModel().persisted){\n return getParent(domainObject)\n .then(doWizardSave)\n .then(persistObject)\n .then(getParent)//Parent may have changed based\n // on user selection\n .then(locateObjectInParent)\n .then(persistObject)\n .then(function(){\n return fetchObject(domainObject.getId());\n })\n .catch(doNothing);\n } else {\n return domainObject.getCapability(\"editor\").save()\n .then(resolveWith(domainObject.getOriginalObject()));\n }\n }",
"async save() {\n const transaction = this.openmct.objects.getActiveTransaction();\n await transaction.commit();\n this.editing = false;\n this.emit('isEditing', false);\n this.openmct.objects.endTransaction();\n }",
"handleSave() {\n this.showLoadingSpinner = true;\n //Set ScheduleC Doc Complete if no value is entered in Line 12 and ScheduleC\n if ((this.objInputFields.dLine12 === null || this.objInputFields.dLine12 === undefined) &&\n (this.dLine3Total === 0) && (this.dLine31Total === 0)) {\n this.objInputFields.bScheduleCDocComplete = true;\n }\n this.objInputFields.idCareApp = this.idCareApp;\n this.objInputFields.idCareHouseholdDetail = this.idHouseholdMember;\n this.objInputFields.idCareHouseholdmemberIncome = this.idMemberIncome;\n this.objInputFields.dDiscountLength = this.dDiscountLength;\n this.objInputFields.sIncomeSourceType = this.sIncomeSource;\n this.objInputFields.sDocumentType = this.sDocumentType;\n this.objInputFields.sFormType = this.sFormType;\n this.objInputFields.listHouseholdMemberIncomeC = this.scheduleCList;\n\n saveHouseholdIncome({\n objWrapperFormInput: this.objInputFields\n })\n .then(result => {\n if (result) {\n this.showToastMessage(this.label.SuccessHeader, this.label.IncomeDocSuccessMsg, 'success');\n this.refreshData(); //refresh document section \n this.showLoadingSpinner = false;\n this.refreshIncomeInfo(); //refresh Parent income info section \n } else {\n this.showToastMessage(this.label.ErrorHeader, this.label.TransactionErrorMsg, 'error');\n this.showLoadingSpinner = false;\n console.log('error' + error);\n }\n })\n .catch(error => {\n this.showToastMessage(this.label.SuccessHeader, this.label.TransactionErrorMsg, 'error');\n this.showLoadingSpinner = false;\n });\n }",
"function onSave() {\n\tdispatcher.on(\"closeAdd\", function onCloseAdd() {\n\t\tdispatcher.off(\"closeAdd\", onCloseAdd);\n\t\tanimateClose();\n\t});\n\tvar eventStr = \"saveAlarm\";\n\tif (isEdit) {\n\t\teventStr = \"updateAlarm\";\n\t}\n\tmainCont.trigger(eventStr, {\n\t\tlabel : label,\n\t\tsnooze : snooze,\n\t\tduration : duration,\n\t\tvibration : vibration,\n\t\tsounds : sounds,\n\t\tshuffle : shuffle,\n\t\tisEdit : isEdit,\n\t});\n}",
"function saveDraft() {\n showNotification('The draft is saved.');\n draftIsSaved = true;\n}",
"function saveItem() {\n\t\t\t// here's some code for that\n\t\t}",
"function onInvoiceApproved() {\n\n Y.log('invoice approved, loading new invoice number...', 'debug', NAME);\n\n function onActivityReloaded(err, data) {\n if (err || !data) {\n Y.log('Could not load new invoice number of approved activity: ' + currentActivity._id, 'warn', NAME);\n return;\n }\n\n data = data.data ? data.data : data;\n\n Y.log('New invoice number: ' + data[0].invoiceNo, 'debug', NAME);\n\n // this may be a quotation, which would not have an invoice number\n\n mapData = {\n 'invoiceNo': (data[0].invoiceNo || ''),\n 'date': _moment( data[0].timestamp ).format( 'DD.MM.YY' )\n };\n\n // update the loaded form, do not rerender yet, doing so uses settimeout which breaks event order\n template.map(mapData, false, onMapInvoiceNo );\n }\n\n function onMapInvoiceNo(err) {\n if (err) {\n Y.log('Could not map invoice number: ' + JSON.stringify(err), 'warn', NAME);\n }\n\n context.attachments.updateFormDoc( context, template, onFormDocUpdated );\n }\n\n function onFormDocUpdated(err) {\n if (err) {\n Y.log('Could not update form document: ' + currentActivity._id, 'warn', NAME);\n return;\n }\n\n template.render(onReRender);\n }\n\n function onReRender() {\n template.raise('mapcomplete', template.toDict());\n }\n\n var mapData;\n Y.doccirrus.comctl.privateGet('1/activity/' + _k.unwrap( currentActivity._id ), {}, onActivityReloaded);\n }",
"function onInvoiceSave(doc) {\n //getLineItems, it will have delete, inserted and noChange, and updated\n //user should make a query to find required values\n\n\n var invoice = {no:12, lineitems:[\n {deliveryid:\"xxx\"},\n {delivery:\"yyyyy\"},\n {_id:\"l11\", deliveryid:\"xxxx\"},\n {_id:\"xxx\", __type__:\"delete\"}\n ]}\n\n var requiredREsult = [\n {deliveryid:\"xxx\", productuid:{accountid:{account:\"cash\"}}},\n {_id:\"l11\", deliveryid:\"xxxx\", productid:{}}\n ]\n\n\n }",
"function assignAndSaveInvoiceNumber( itcb ) {\n Y.doccirrus.invoiceserverutils.assignAndSaveInvoiceNumber( user, activity, currState, itcb );\n }",
"function save() {\n\t\tsources.userFood.save({\n\t\t\tonSuccess: function(event) {\n\t\t\t\t$comp.hide();\n\t\t\t\tWAKL.qtyAddArea.setAndGotoQty();\n\t\t\t},\n\t\t\tonError: function(event) {\n\t\t\t\tcancel();\n\t\t\t\tWAKL.err.handler(event);\n\t\t\t}\n\t\t});\n\t}",
"updateCreatedInvoice(invoice) {\n this.createdInvoice = invoice;\n this.emit('change');\n }",
"function onSave() {\n const saveData = {\n id: new Date().getTime(),\n hospitalName,\n doctorName,\n reason,\n doctorStatement,\n dateOfVisit: dateOfVisit.getTime(),\n medication,\n };\n props.addVisit(saveData);\n Realm.write(() => {\n const visitInfo = Realm.create('Visit', saveData);\n console.log(`Data written successfully ${visitInfo}`);\n props.navigation.goBack();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize the map of all resources in JSON | entitiesToJSON(){
let res = {
"id": this.id,
"resources": {}
};
(this.entitiesByID||{})::entries().forEach(([id,obj]) => res.resources[id] = (obj instanceof Resource) ? obj.toJSON(): obj);
return res;
} | [
"toJSON(depth = 0, initDepth = depth){\n\n /**\n * Converts a resource object into serializable JSON.\n * May fail to serialize recursive objects which are not instances of Resource\n * @param value - resource object\n * @param depth - depth of nested resources to output\n * @param initDepth - initial depth of nested resources used in a recursive call to compute the remaining depth\n * @returns {*} JSON object without circular references *\n */\n function valueToJSON(value, depth, initDepth) { return (value instanceof Resource)? ((depth > 0)? value.toJSON(depth - 1, initDepth): value.id): value.id? value.id: value }\n\n /**\n * Serializes field value: array or object\n * @param value - resource field value\n * @param depth - depth of nested resources to output\n * @param initDepth - initial depth of nested resources used in a recursive call to compute the remaining depth\n * @returns {*} JSON object or an array of JSON objects without circular references\n */\n function fieldToJSON(value, depth, initDepth) { return value::isArray()? value.filter(e => !!e).map(e => valueToJSON(e, depth, initDepth)): valueToJSON(value, depth, initDepth); }\n\n let omitKeys = this::keys()::difference(this.constructor.Model.fieldNames).concat([\"viewObjects\", \"infoFields\", \"labels\"]);\n let res = {};\n this::keys().filter(key => !!this[key] && !omitKeys.includes(key)).forEach(key => {\n let fieldDepth = (key === \"border\" || key === \"borders\")? initDepth: depth;\n res[key] = fieldToJSON(this[key], fieldDepth, initDepth);\n });\n return res;\n }",
"function serializeMap(map) {\n\t\t\t\tif (map === null || map === undefined) return null;\n\n\t\t\t\tvar meta = {\n\t\t\t\t\tgeometries: {},\n\t\t\t\t\tmaterials: {},\n\t\t\t\t\ttextures: {},\n\t\t\t\t\timages: {}\n\t\t\t\t};\n\n\t\t\t\tvar json = map.toJSON(meta);\n\t\t\t\tvar images = extractFromCache(meta.images);\n\t\t\t\tif (images.length > 0) json.images = images;\n\t\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\t\treturn json;\n\t\t\t}",
"function serializeMap( map ) {\n\n\t\t\tif ( map === null || map === undefined ) return null;\n\n\t\t\tconst meta = {\n\t\t\t\tgeometries: {},\n\t\t\t\tmaterials: {},\n\t\t\t\ttextures: {},\n\t\t\t\timages: {}\n\t\t\t};\n\n\t\t\tconst json = map.toJSON( meta );\n\t\t\tconst images = extractFromCache( meta.images );\n\t\t\tif ( images.length > 0 ) json.images = images;\n\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\treturn json;\n\n\t\t}",
"serializeJSON() {\n\n let nodes = [];\n let serializer = new SceneSerializer();\n\n for (let child of this.children) {\n child.walkAll(function (node) {\n nodes.push(node.serializeJSON(serializer));\n });\n }\n\n let resources = serializer.resources.map(x => x[0].name +\";\" + x[1]);\n\n return {\n background: Serialize.color(this.background),\n ambientColor: Serialize.color(this.ambientColor),\n\n fogEnabled: this.fogEnabled,\n fogMode: this.fogMode,\n fogColor: Serialize.color(this.fogColor),\n fogStart: this.fogStart,\n fogDistance: this.fogDistance,\n\n resources: resources,\n nodes: nodes,\n };\n }",
"function serializeMap(map) {\r\n\t\t\t\tif (map === null || map === undefined) return null;\r\n\r\n\t\t\t\tvar meta = {\r\n\t\t\t\t\tgeometries: {},\r\n\t\t\t\t\tmaterials: {},\r\n\t\t\t\t\ttextures: {},\r\n\t\t\t\t\timages: {}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar json = map.toJSON(meta);\r\n\t\t\t\tvar images = extractFromCache(meta.images);\r\n\t\t\t\tif (images.length > 0) json.images = images;\r\n\t\t\t\tjson.sourceFile = map.sourceFile;\r\n\r\n\t\t\t\treturn json;\r\n\t\t\t}",
"function serializeMap(map) {\n if (map === null || map === undefined) return null;\n\n var meta = {\n geometries: {},\n materials: {},\n textures: {},\n images: {}\n };\n\n var json = map.toJSON(meta);\n var images = extractFromCache(meta.images);\n if (images.length > 0) json.images = images;\n json.sourceFile = map.sourceFile;\n\n return json;\n }",
"toJson() {\n const map = {\n concepts: [],\n propositions: []\n };\n // Efforts to avoid id collisions - not sure whether necessary :/\n const ids = new Set();\n const conceptIDs = new Map();\n this.concepts.forEach(c => {\n let id = this.getID();\n while (ids.has(id)) {\n id = this.getID();\n }\n ids.add(id);\n conceptIDs.set(c, id);\n map.concepts.push({ text: c.text, x: c.x, y: c.y, id: id, resources: c.resources });\n });\n this.propositions.forEach(p => {\n map.propositions.push({\n text: p.text,\n from: conceptIDs.get(p.from),\n to: conceptIDs.get(p.to)\n });\n });\n return JSON.stringify(map);\n }",
"getAllResources() {\n return Object.values(this._resources);\n }",
"function serializeMap(map) {\n\t if (map === null || map === undefined) return null;\n\t var meta = {\n\t geometries: {},\n\t materials: {},\n\t textures: {},\n\t images: {}\n\t };\n\t var json = map.toJSON(meta);\n\t var images = extractFromCache(meta.images);\n\t if (images.length > 0) json.images = images;\n\t json.sourceFile = map.sourceFile;\n\t return json;\n\t } // Note: The function 'extractFromCache' is copied from Object3D.toJSON()",
"get resources() {\n return this._resource.copy();\n }",
"function serializeResource(resource, api) {\n var resourceJson = {};\n if (resource.description())\n resourceJson[\"description\"] = \"\" + resource.description().value();\n if (resource.relativeUri()) {\n resourceJson[\"relativeUri\"] = \"\" + resource.relativeUri().value();\n }\n if (resource.relativeUri()) {\n var relativeUriPathSegments = resource.relativeUri().value().split('/');\n var segments = relativeUriPathSegments.splice(1, relativeUriPathSegments.length);\n if (segments) {\n var pathSegments = [];\n for (var s = 0; s < segments.length; s++) {\n if (segments[s] != \"\")\n pathSegments.push(segments[s]);\n }\n resourceJson[\"relativeUriPathSegments\"] = pathSegments;\n }\n }\n serializeNodeDisplayName(resource, resourceJson);\n if (resource.type()) {\n serializeTypeProperty(resource.type(), resourceJson);\n }\n if (resource.is()) {\n if (resource.is().length > 0) {\n var values = [];\n for (var k = 0; k < resource.is().length; k++) {\n var is = resource.is()[k].value();\n var traitParameters = {};\n is.toHighLevel().attrs().forEach(function (attribute) {\n if (isKeyAttribute(attribute))\n return;\n traitParameters[\"\" + attribute.name()] = \"\" + attribute.value();\n });\n if (Object.keys(traitParameters).length > 0) {\n var isJson = {};\n isJson[\"\" + is.valueName()] = traitParameters;\n values.push(isJson);\n }\n else\n values.push(is.valueName());\n }\n resourceJson[\"is\"] = values;\n }\n }\n if (resource.securedBy()) {\n var values = [];\n if (resource.securedBy().length > 0) {\n resource.securedBy().forEach(function (x) {\n if (x.value().valueName() == \"null\" || x.value().valueName() == null)\n values.push(null);\n else\n values.push(\"\" + x.value().valueName());\n });\n resourceJson[\"securedBy\"] = values;\n }\n }\n var params = serializeParameters(resource.allUriParameters(), 'uriParameters');\n if (Object.keys(params).length > 0) {\n resourceJson[\"uriParameters\"] = params;\n }\n //var baseUriParams = serializeParameters(resource.baseUriParameters(),\"uriParameters\");\n //if (Object.keys(baseUriParams).length > 0){\n // resourceJson[\"baseUriParameters\"] = baseUriParams;\n //}\n //else{\n // var isBaseUriParams = isDefined(resource, 'baseUriParameters');\n // if (isBaseUriParams) {\n // resourceJson[\"baseUriParameters\"] = null ;\n // }\n //}\n serializeBaseUriParameters(resource, resourceJson);\n if (resource.methods().length > 0) {\n resourceJson[\"methods\"] = serializeActions(resource.methods(), api, true);\n }\n if (resource.resources().length > 0) {\n resourceJson[\"resources\"] = serializeResources(resource.resources(), api);\n }\n return resourceJson;\n}",
"function JsonGenerate(rootJson) {\n //console.log(rootJson['resources'][0]['methods'][0]['securedBy'][0]['settings']['scopes'])\n\n for (var i in rootJson['resources']) {\n\tif (debug) console.error('top resource '+i+': '+rootJson['resources'][i]);\n\tresource = rootJson['resources'][i];\n\tResource(resource);\n }\n\n console.log(JSON.stringify(scopeMap));\n}",
"serialize() {\n let data = {};\n\n // save area's metadata\n data = Object.assign(data, {\n title: this.title,\n script: this.script,\n metadata: this.metadata\n });\n\n // serialize rooms\n if (this.rooms instanceof Map) {\n for (let [ id, room ] of this.rooms) {\n // serialize each room\n data[id] = room.serialize();\n }\n }\n\n // serialize behaviors\n let behaviors = {};\n for (const [key, val] of this.behaviors) {\n // serialize each behavior\n behaviors[key] = val;\n }\n data.behaviors = behaviors;\n\n return data;\n }",
"get resources() {\n return this.getListAttribute('resources');\n }",
"async write_resources(file, resources) {\n const file_content = _.map(resources, resource => JSON.stringify(resource)).join('\\n');\n await fs.promises.writeFile(file, file_content);\n }",
"renderResources(){\n let rsc = []\n for(let key in this.resources){\n rsc.push(`${key}: ${this.resources[key]}<br> `)\n }\n return rsc.map(e => e).join('')\n }",
"static populateResources(resources) {\n let result = {};\n _.each(resources, (resource, name) => {\n // Only include the resource if it's NOT disabled\n if (!resource.disable) {\n delete resource.disable;\n let config = {};\n _.extend(config, resource);\n result[name] = { config: config };\n }\n });\n return result;\n }",
"toJSON() {\n\n var json = {\n name: this.name,\n content: this.content,\n contentType: this.contentType\n };\n\n if (this.contentId) {\n json.contentId = this.contentId;\n }\n \n if (this.customHeaders.length > 0) {\n var _ch = [];\n this.customHeaders.forEach(element => { \n _ch.push(toCustomHeader.convert(element).toJSON()); \n });\n json.customHeaders = _ch; \n } \n \n return json;\n }",
"getAll() {\n return this._resources !== undefined ? _.map(this._resources, resource => resource) : this._loadAll();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Byteswap an arbitrary buffer, flipping from one endian to the other, returning a new buffer with the resultant data | function byteswap64(buf) {
var swap = Buffer.alloc(buf.length);
for (var i = 0; i < buf.length; i++) {
swap[i] = buf[buf.length -1 - i];
}
return swap;
} | [
"function byteswap64(buf) {\n var swap = new Buffer(buf.length);\n for (var i = 0; i < buf.length; i++) {\n swap[i] = buf[buf.length -1 - i];\n }\n return swap;\n}",
"function to_little_endian(){\n\tbinary_input.reverse();\n\tbinary_key.reverse();\n}",
"function _swapEndian(val, length) {\n if (length <= 8) {\n return val\n } else if (length <= 16) {\n return (val & 0xFF00) >> 8 | (val & 0xFF) << 8\n } else if (length <= 32) {\n return ((val & 0xFF000000) >> 24 |\n (val & 0x00FF0000) >> 8 |\n (val & 0x0000FF00) << 8 |\n (val & 0x000000FF) << 24)\n }\n throw new Error('Cannot swap endianness for length ' + length)\n}",
"function _reverseBuffer(buffer) {\n var tmp, len = buffer.length - 1, half = Math.floor(buffer.length / 2);\n for (var i = len; i >= half; i--) {\n tmp = buffer[i];\n buffer[i] = buffer[len - i];\n buffer[len - i] = tmp;\n }\n }",
"function flipEndianness( array, chunkSize ) {\n\n \t\t\tvar u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );\n \t\t\tfor ( var i = 0; i < array.byteLength; i += chunkSize ) {\n\n \t\t\t\tfor ( var j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {\n\n \t\t\t\t\tvar tmp = u8[ k ];\n \t\t\t\t\tu8[ k ] = u8[ j ];\n \t\t\t\t\tu8[ j ] = tmp;\n\n \t\t\t\t}\n\n \t\t\t}\n\n \t\t\treturn array;\n\n \t\t}",
"reverseBits(buf) {\n for (let x = 0; x < buf.length; x++) {\n let newByte = 0;\n newByte += buf[x] & 128 ? 1 : 0;\n newByte += buf[x] & 64 ? 2 : 0;\n newByte += buf[x] & 32 ? 4 : 0;\n newByte += buf[x] & 16 ? 8 : 0;\n newByte += buf[x] & 8 ? 16 : 0;\n newByte += buf[x] & 4 ? 32 : 0;\n newByte += buf[x] & 2 ? 64 : 0;\n newByte += buf[x] & 1 ? 128 : 0;\n buf[x] = newByte;\n }\n }",
"function flipEndianness( array, chunkSize ) {\n\n\t\t\tvar u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );\n\t\t\tfor ( var i = 0; i < array.byteLength; i += chunkSize ) {\n\n\t\t\t\tfor ( var j = i + chunkSize - 1, k = i; j > k; j--, k++ ) {\n\t\t\t\t\tvar tmp = u8[ k ];\n\t\t\t\t\tu8[ k ] = u8[ j ];\n\t\t\t\t\tu8[ j ] = tmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn array;\n\t\t}",
"function swap32(b) {\n return ((b & 0xff) << 24)\n | ((b & 0xff00) << 8)\n | ((b >> 8) & 0xff00)\n | ((b >> 24) & 0xff);\n }",
"function endianSwap(hexStr, lengthInBytes)\n{\n while (hexStr.length < 2 * lengthInBytes)\n {\n\thexStr = '0' + hexStr;\n }\n if (hexStr.length >= 4)\n\thexStr = hexStr.substring(2, 4) + hexStr.substring(0, 2);\n if (hexStr.length >= 8)\n\thexStr = hexStr.substring(6, 8) + hexStr.substring(4, 6);\n if (hexStr.length >= 12)\n\tlogger.warn(\"endianSwap() not implemented for 12 bytes\");\n return hexStr.toUpperCase();\n}",
"function byteSwap16(val) {\n return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);\n }",
"reverseBytes() {\n\t\t//region Reverse bits order in each byte in the stream\n\t\tfor (let i = 0; i < this.view.length; i++) {\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[i] = (this.view[i] * 0x0802 & 0x22110 | this.view[i] * 0x8020 & 0x88440) * 0x10101 >> 16;\n\t\t}\n\t\t//endregion\n\n\t\t//region Shift \"most significant\" byte\n\t\tif (this.bitsCount % 8) {\n\t\t\t// noinspection ConditionalExpressionJS\n\t\t\tconst currentLength = (this.bitsCount >> 3) + (this.bitsCount % 8 ? 1 : 0);\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[this.view.length - currentLength] >>= 8 - (this.bitsCount & 0x07);\n\t\t}\n\t\t//endregion\n\t}",
"reverseBytes()\n\t{\n\t\t//region Reverse bits order in each byte in the stream\n\t\tfor(let i = 0; i < this.view.length; i++)\n\t\t{\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[i] = ((this.view[i] * 0x0802 & 0x22110) | (this.view[i] * 0x8020 & 0x88440)) * 0x10101 >> 16;\n\t\t}\n\t\t//endregion\n\t\t\n\t\t//region Shift \"most significant\" byte\n\t\tif(this.bitsCount % 8)\n\t\t{\n\t\t\t// noinspection ConditionalExpressionJS\n\t\t\tconst currentLength = (this.bitsCount >> 3) + ((this.bitsCount % 8) ? 1 : 0);\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[this.view.length - currentLength] >>= (8 - (this.bitsCount & 0x07));\n\t\t}\n\t\t//endregion\n\t}",
"function swapBuffers() {\n swapReprojectBuffer();\n swapGBuffer();\n swapHdrBuffer();\n }",
"function invert_endian(a, inpl) {\n var t = inpl ? a : Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n\tvar t1 = (a[i] & 0xff) << 24;\n\tvar t2 = ((a[i] >> 8) & 0xff) << 16;\n\tvar t3 = ((a[i] >> 16) & 0xff) << 8;\n\tvar t4 = (a[i] >> 24) & 0xff;\n\tt[i] = t1 | t2 | t3 | t4;\n }\n return t;\n}",
"converseToBuffer(): Buffer {\n const bign = this._bn.toArrayLike(Buffer);\n if (bign.length === 32) {\n return bign;\n }\n\n const zeroPad = Buffer.alloc(32);\n bign.copy(zeroPad, 32 - bign.length);\n return zeroPad;\n }",
"function reverse (buffer, target) {\n validate(buffer);\n\n if (target) {\n validate(target);\n copy(buffer, target);\n }\n else {\n target = buffer;\n }\n\n for (var i = 0, c = target.numberOfChannels; i < c; ++i) {\n target.getChannelData(i).reverse();\n }\n\n return target;\n}",
"function swapEndianC(string){\n var data = \"\";\n for (var i = 1; i <= string.length; i++){\n data += string.substr(0 - i, 1);\n }\n return data;\n}",
"get endian()\n {\n\t\tvar b = new ArrayBuffer(4);\n\t\tvar a = new Uint32Array(b);\n\t\tvar c = new Uint8Array(b);\n\t\ta[0] = 0xdeadbeef;\n\t\tif (c[0] === 0xef) return Endian.LITTLE_ENDIAN;\n\t\tif (c[0] === 0xde) return Endian.BIG_ENDIAN;\n }",
"function swapEndianC(string) {\n var data = \"\";\n for (var i = 1; i <= string.length; i++) {\n data += string.substr(0 - i, 1);\n }\n return data;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the selected values are allowed, IE we have resources named after it | function check_allowed() {
var material = $(select_div+" "+"#pd-material-type").find("option[selected]").attr("value");
var material_dict = get_material_dict(data, material);
var allowed = material_dict.allowed;
for(var i = 0; i < allowed.length; i++) {
var good = true;
var chem = allowed[i];
for(var j = 0; j < elements_nums.length; j++) {
if(chem[elements_nums[0]] != elements_nums[1]){
good = false;
break;
}
}
if(good){
return true
}
}
return false
} | [
"function validation_for_select_boxes(element){\n\tif(element.value != \"Default\")\n\t\treturn true;\n\telse{\n\t\talert(\"please select \"+ element.name);\n\t\treturn false;\n\t}\n}",
"function requireSelects ( form, requiredSelect ) {\n for ( var i = 0; i < requiredSelect.length; i++ ) {\n element = requiredSelect[i];\n if ( form[element].selectedIndex <= 0 ) {\n alert( \"Please select a value for \" + element + \".\" );\n return false;\n }\n }\n return true;\n}",
"function validateSelect(select) {\n var selectedValue = getSelectedValue(select);\n return (typeof(selectedValue) == 'string' && selectedValue != '') ? true : false;\n}",
"function getOptionsVisibilityRuleValues() {\n return [\"alfresco/forms/controls/Select\",\"alfresco/forms/controls/RadioButtons\"];\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 isValidDropDownListSelection(element)\n {\n var isValidDDLSelection = false;\n try {\n if (parseInt(element.val(), 10) != -1) {\n isValidDDLSelection = true;\n }\n }\n catch (exception)\n {\n isValidDDLSelection = true; // means a wording selection on ddl\n } \n return isValidDDLSelection;\n }",
"function enableSelectorItems(validValuesRange, selector) {\n for (var i = 0; i < selector.options.length; ++i) {\n if (($.grep(validValuesRange, function (e) {\n return e == selector.options[i].innerText;\n }).length) != 0) {\n selector[i].style.color = \"Black\";\n selector[i].disabled = false;\n } else {\n selector[i].style.color = \"LightGrey\";\n selector[i].disabled = true;\n }\n }\n var selectedStr = selector[selector.selectedIndex].innerText;\n if (($.grep(validValuesRange, function (e) {\n return e == selectedStr;\n }).length) == 0) {\n selector.selectedIndex = 0;\n // we should call this functions to update controls\n // as programmaticality change selector's value not cause change event\n executionInstructionChanged(null);\n orderDurationChanged(null);\n }\n}",
"function validateSelects(formObj){\r\n\tvSSResult = true;\r\n\tfor(vSSCounter=1; vSSCounter<arguments.length; vSSCounter++){\r\n\t\tvSSObj = formObj[arguments[vSSCounter]];\r\n\t\tif( vSSObj && vSSObj.selectedIndex == 0 ){\r\n\t\t\talert( \"Please choose another option from '\" +convertVariable(vSSObj.name)+ \"'\" );\r\n\t\t\tvSSObj.focus();\r\n\t\t\tvSSResult = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn vSSResult;\r\n}",
"function checkRestrictedFields(q) {\n\t\tvar attemptedSet = ' ';\n\t\tvar unmodifiable = sncStdChg.unmodifiable;\n\t\tif (q && unmodifiable) {\n\t\t\tfor (var i = 0; i < q.names.length; i++) {\n\t\t\t\tvar f = q.names[i];\n\t\t\t\tvar idx = containsName(unmodifiable, f);\n\t\t\t\tif (idx !== -1)\n\t\t\t\t\tattemptedSet = attemptedSet + unmodifiable[idx].label + ', ';\n\t\t\t}\n\t\t}\n\t\tif (attemptedSet !== ' ') {\n\t\t\tvar msg = formatMessage(getMessage('The following \"Change Request values\" are not allowed to be set in a template:{0}'), attemptedSet.substring(0, attemptedSet.length - 2));\n\t\t\talert(msg);\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}",
"function validatePersonSupportSelection(){\n\tvar msg='';\n\tif($('#personId').val() == ''){\n\t\tmsg += 'You must select a person from the dropdown.';\n\t}\n\tif($('#supportRole').val() == ''){\n\t\tmsg += 'You must select a support role from the dropdown.';\n\t}\n\tif(msg != ''){\n\t\talert(msg);\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}",
"function test_ownership_dropdown_values() {}",
"requiredSelect(val) {\n const typeOfValue = typeof val;\n let value;\n switch (typeOfValue) {\n case 'string':\n value = val.replace(/^\\s+|\\s+$/g, '');\n return !(value === '-1' || value === '');\n\n case 'number':\n return val !== -1;\n\n default:\n return false;\n }\n }",
"isSelectionValid(selection) {\n return selection === null\n || (this.virtDir && selection.hasOwnProperty('value') && selection.hasOwnProperty('index'))\n || (selection instanceof IgxDropDownItemComponent && !selection.isHeader);\n }",
"function validateSelections()\n {\n var isValid = false;\n \n isValid = validateDDLsOnProductSearch($('#selectCategory'), 'product category');\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectCondition'), 'product condition') : isValid;\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectBrand'), 'brand') : isValid;\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectModel'), 'model') : isValid;\n \n return isValid;\n }",
"function restrictResources(uncheck){\n\t\tvar selectedLocation=getSelectedLocation(),\n\t\trows=$(\"#resourceTable\").find(\"td[data-restrict]\");\n\t\trows.find(\"input\").attr({\"disabled\": true});\n\t\tif(uncheck){\n\t\t\trows.find(\"input\").attr({\"checked\": false});\n\t\t}\n\t\t$.each(rows, function(i, val){\n\t\t\tvar restrict=$(val).data(\"restrict\");\n\t\t\tif(restrict.length > 1){\n\t\t\t\tif ($.inArray(selectedLocation, restrict.replace(/,\\s+/g, ',').split(',')) >= 0) {\n\t\t\t\t\t$(val).find(\"input\").attr({\"disabled\": false});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function validateForm() {\n let validCandidates = 0;\n optionNames.forEach((e) => {\n if (e !== null || e !== undefined || e !== \"\") validCandidates += 1;\n });\n return validCandidates >= 2;\n }",
"function validate_form_multiple_csv_essources(){\n console.log(\"validate_form_multiple_csv_essources()\");\n\n var err = false; \n existing_categories_csv_text = $(\"#existing_categories_csv :selected\").text();\n //if( existing_categories_csv_text.includes(\"cat_id\")){ unsupported by IE\n if( existing_categories_csv_text.indexOf(\"cat_id\") !== -1){\n console.log(\"ok. cat_id exists.\");\n } else {\n console.log(\"BAD. cat_id does not exist.\");\n //colour dropdown box\n $(\"#existing_categories_csv\").css('background-color', 'yellow');\n err = true; \n\t}\n\n //check if global array of files is empty\n console.log(csv_values.length);\n if(csv_values.length == 0){\n console.log(\"no file loaded or file empty.\");\n $(\"#label_filename\").css('background-color', 'yellow');\n err = true;\n }\n\n if(err){alert(\"Sorry some fields not filled.\");\n return \"no\";\n } else {return \"ok\";}\n \n}",
"function hasSelectedValue(object, value)\n{\n\tvalue = trim(value);\n\tif ((value.length == 0) || (value == '-136'))\n\t\treturn false;\n\n\treturn true;\n}",
"function ValidateSel( Inp, name, def=-1 )\n {\n var val = Inp.val();\n\n var sErr = \"\";\n if( val == null ) sErr = \"Debe seleccionar \";\n else if( val == def ) sErr = \"Debe cambiar \";\n else return true;\n\n alert( sErr + name );\n Inp.focus();\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if this relates to the active query being executed then immediately send the cancel, else the query can be removed from the queue and never submitted to the driver. | function cancel (notify, callback) {
const qid = notify.getQueryId()
if (workQueue.length() === 0) {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (empty queue) id ${qid}`))
})
return
}
const first = workQueue.first((_idx, currentItem) => {
if (currentItem.commandType !== driverCommandEnum.QUERY) {
return false
}
const args = currentItem.args
const not = args[0]
const currentQueryId = not.getQueryId()
return qid === currentQueryId
})
if (first) {
if (first.paused) {
execCancel(qid, first, () => {
freeStatement(notify, () => {
workQueue.dropItem(first)
callback(null)
})
})
} else {
execCancel(qid, first, callback)
}
} else {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (not found) id ${qid}`))
})
}
} | [
"function cancelQuery() {\n// console.log(\"Cancelling query, currentQuery: \" + qwQueryService.currentQueryRequest);\n if (qwQueryService.currentQueryRequest != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(qwQueryService.currentQueryRequest);\n queryInFly && queryInFly.canceler(\"test\");\n\n //\n // also submit a new query to delete the running query on the server\n //\n\n var query = 'delete from system:active_requests where clientContextID = \"' +\n qwQueryService.currentQueryRequestID + '\";';\n\n// console.log(\" queryInFly: \" + queryInFly + \"\\n query: \" + query);\n\n executeQueryUtil(query,false)\n\n// .success(function(data, status, headers, config) {\n// console.log(\"Success cancelling query.\");\n// console.log(\" Data: \" + JSON.stringify(data));\n// console.log(\" Status: \" + JSON.stringify(status));\n// })\n\n\n // sanity check - if there was an error put a message in the console.\n .error(function(data, status, headers, config) {\n console.log(\"Error cancelling query.\");\n console.log(\" Data: \" + JSON.stringify(data));\n console.log(\" Status: \" + JSON.stringify(status));\n });\n\n }\n }",
"function cancelQuery(queryResult) {\n // if this is a batch query, with multiple child queries, we need to find which one\n // is currently running, and cancel that.\n if (queryResult.batch_results)\n for (i=0; i<queryResult.batch_results.length; i++) if (queryResult.batch_results[i].busy) {\n queryResult = queryResult.batch_results[i]; // cancel this child\n break;\n }\n\n //console.log(\"Cancelling query, currentQuery: \" + queryResult.client_context_id);\n if (queryResult && queryResult.client_context_id != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(queryResult.client_context_id);\n queryInFly && queryInFly.canceler(\"test\");\n\n //\n // also submit a new query to delete the running query on the server\n //\n\n var query = 'delete from system:active_requests where clientContextID = \"' +\n queryResult.client_context_id + '\";';\n\n executeQueryUtil(query,false)\n\n .then(function success() {\n// console.log(\"Success cancelling query.\");\n },\n\n // sanity check - if there was an error put a message in the console.\n function error(resp) {\n logWorkbenchError(\"Error cancelling query: \" + JSON.stringify(resp));\n// console.log(\"Error cancelling query.\");\n });\n\n }\n }",
"cancelQuery()\t{ this._behavior('cancel query'); }",
"function cancelQuery() {\n if (!timer) return;\n\n clearTimeout(timer);\n timer = null;\n }",
"cancel() {\n this.end();\n queryManager.cancelQuery(this);\n return this;\n }",
"cancelExecution(queryToken) {}",
"cancel(req, err) {\n\t\tif (typeof req === 'object') {\n\t\t\treq = req.request_id; // unwrap request\n\t\t}\n\t\terr = wrap_error(err, 'user cancelled');\n\t\tconst query = this.req_map[req];\n\t\tif (!query) return;\n\t\tthis.reject_query(query, err);\n\t\tthis.schedule_idle();\n\t\treturn query.sent;\n\t}",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n\t /**\n\t We need to check both Running and Cancelled status\n\t Tasks can be Cancelled but still Running\n\t **/\n\t if (iterator._isRunning && !iterator._isCancelled) {\n\t iterator._isCancelled = true;\n\t taskQueue.cancelAll();\n\t /**\n\t Ending with a Never result will propagate the Cancellation to all joiners\n\t **/\n\n\t end(TASK_CANCEL);\n\t }\n\t }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"abort () {\n while (this.length > 0) {\n const dial = this._queue.shift()\n dial.callback(DIAL_ABORTED())\n }\n this.stop()\n }",
"function cancel() {\n\t /**\n\t We need to check both Running and Cancelled status\n\t Tasks can be Cancelled but still Running\n\t **/\n\t if (iterator._isRunning && !iterator._isCancelled) {\n\t iterator._isCancelled = true;\n\t taskQueue.cancelAll();\n\t /**\n\t Ending with a Never result will propagate the Cancellation to all joiners\n\t **/\n\t end(TASK_CANCEL);\n\t }\n\t }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"cancel () {\r\n this.cancelRequested = true;\r\n this.append('Cancel requested.');\r\n if (this.state === 'waiting') {\r\n this.setState('cancelled');\r\n this.append('Job cancelled.');\r\n } else {\r\n state.port.postMessage({\r\n topic: 'cancel-job',\r\n data: {\r\n jobId: this.id,\r\n }\r\n }); \r\n } \r\n }",
"abort () {\n while (this.length > 0) {\n let dial = this._queue.shift()\n dial.callback(DIAL_ABORTED())\n }\n this.stop()\n }",
"abort() {\n while (this.length > 0) {\n let dial = this._queue.shift();\n\n dial.callback(DIAL_ABORTED());\n }\n\n this.stop();\n }",
"cancel() {\n if (this._activeSearch) {\n this._activeSearch.abort();\n }\n\n this._cancelSearch = true;\n later(() => (this._cancelSearch = false), 400);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns memory usage as a percentage of total memory available (0100) | function getMemUsage() {
var total = os.totalmem(),
usage = total - os.freemem(),
perc = usage / total * 100;
return {
usage : usage
, total : total
, percentage : perc
};
} | [
"function calcPhysicalMem()\n{\n\tvar os = require('os');\n\n\tvar totalm = (os.totalmem() / 1024 / 1024).toFixed(2);\n\tvar freem = (os.freemem() / 1024 / 1024).toFixed(2) ;\n\tvar usedm = (totalm - freem);\n\n\n\tmetrics[\"phys_mem_used\"].value = usedm;\n\tmetrics[\"phys_mem_free\"].value = freem;\n\tmetrics[\"phys_mem_usage\"].value = (100*usedm/totalm).toFixed(2);\n\n\n\toutput();\n}",
"function available_memory() {\n // var value = process.memoryUsage().heapUsed / 1000000;\n const percentageMemUsed = (os.freemem() / os.totalmem()) * 100.0\n return percentageMemUsed\n}",
"memoryStats() {\n const total = Math.round(osUtils.totalmem());\n const percentUse = Math.round(100 - (osUtils.freememPercentage() * 100));\n this.manager.logger.detail(`Memory stats checked - ${percentUse}% of ${total}MB used.`);\n return {percentUse, total};\n }",
"metricMemoryUtilization(props) {\n return this.metric('MemoryUtilization', props);\n }",
"metricMemoryUtilization(props) {\n return this.cannedMetric(ecs_canned_metrics_generated_1.ECSMetrics.memoryUtilizationAverage, props);\n }",
"function calculateBasedMem() {\n\t//var theForm = document.forms[\"capacity_form\"];\n var qtyAppNode = document.getElementById('qtyAppNode').value;\n var appNodeMem = document.getElementById('memNodeSize').value;\n var memPodSize = document.getElementById('memPodSize').value;\n var totalAppNodeMem = appNodeMem * qtyAppNode;\n var totalPodPerMem = totalAppNodeMem / memPodSize;\n return totalPodPerMem;\n\t//display the result\n //document.getElementById('ccapacity').innerHTML = \"Total pod por Mem: \"+totalPodPerMem;\n}",
"function getUsageLinux(cb) {\n // TODO: throw error\n if (!isFunction(cb)) { return; }\n\n function calcFree(data) {\n return (data[\"cached\"] + data[\"buffers\"] + data[\"memfree\"]) / data[\"memtotal\"];\n }\n\n function calcUsage(data) {\n return 1 - calcFree(data);\n }\n\n fs.readFile(\"/proc/meminfo\", function(err, data) {\n if (err) { return cb(err); }\n\n var meminfo = data.toString().split(\"\\n\");\n var data = {};\n\n for (var i in meminfo) {\n var line = meminfo[i].split(\":\");\n // Ignore invalid lines, if any\n if (line.length == 2) {\n data[line[0].trim().toLowerCase()] = parseInt(line[1].trim(), 10);\n }\n }\n\n cb(null, calcUsage(data) * 100);\n });\n}",
"function getTotalMemory(prof) {\n return d3.max(prof, function(d) { return d.memalloc; });\n }",
"function collectMemoryStats() {\n var memUsage = process.memoryUsage();\n metrics.gauge('memory.rss', memUsage.rss);\n metrics.gauge('memory.heapTotal', memUsage.heapTotal);\n metrics.gauge('memory.heapUsed', memUsage.heapUsed);\n metrics.increment('memory.statsReported');\n}",
"function getStats() {\n var procMem = process.memoryUsage();\n var stats = {\n mem: {\n total: os.totalmem(),\n free: os.freemem(),\n heap: procMem.rss\n },\n cpu: os.loadavg()\n };\n for(var i=0; i < stats.cpu.length; i++) {\n stats.cpu[i] = stats.cpu[i].toFixed(3);\n }\n stats.cpu = stats.cpu.join(\",\");\n // We convert from bytes to mb\n stats.mem.total = Math.ceil(stats.mem.total / 1000000) + \"MB\";\n stats.mem.free = Math.ceil(stats.mem.free / 1000000) + \"MB\";\n stats.mem.heap = (stats.mem.heap / 1000000).toFixed(3) + \"MB\";\n return stats;\n}",
"function getCpuUsage() {\n return cpu.getCpuUsage();\n}",
"function populateMemoryStatus(){\n settingsMemoryTotal.innerHTML = Number((os.totalmem()-1073741824)/1073741824).toFixed(1) + 'G'\n settingsMemoryAvail.innerHTML = Number(os.freemem()/1073741824).toFixed(1) + 'G'\n}",
"function populateMemoryStatus(){\n settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'\n settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'\n}",
"function getUsageWin32(cb) {\n // TODO: throw error\n if (!isFunction(cb)) { return; }\n\n var wmicCommand = [\n \"wmic os get TotalVisibleMemorySize\",\n \"wmic os get FreePhysicalMemory\"\n ];\n\n function calcUsage(data) {\n return (data[\"TotalVisibleMemorySize\"] - data[\"FreePhysicalMemory\"]) / data[\"TotalVisibleMemorySize\"];\n }\n\n exec(concatWmicCommands(wmicCommand), function(error, stdout, stderr) {\n if (error || stderr) { return cb(error || stderr); }\n\n var meminfo = stdout.split(\"\\r\\r\\n\");\n var data = {};\n var key = null;\n\n for (var i in meminfo) {\n var value = meminfo[i].trim();\n if (!isNaN(value) && +value > 0) {\n data[key] = +value;\n } else if (value.length > 0) {\n key = value;\n }\n }\n\n cb(null, calcUsage(data) * 100);\n });\n}",
"function memory() {\n if (!u.isNode())\n return {};\n return process.memoryUsage();\n}",
"function jvmTotalMemory_macro(param) {\n var m = java.lang.Runtime.getRuntime().totalMemory();\n return (param && param.hr) ? formatBytes(m) : m;\n}",
"function getHeapUsage() {\n return process.memoryUsage().heapUsed / 1024 / 1024;\n}",
"function mem(callback) {\n\tif (_windows) {\n\t\tcallback(NOT_SUPPORTED);\n\t}\n\n\tvar result = {\n\t\ttotal : os.totalmem(),\n\t\tfree : os.freemem(),\n\t\tused : os.totalmem() - os.freemem(),\n\n\t\tactive : os.totalmem() - os.freemem(),\n\t\tbuffcache : 0,\n\n\t\tswaptotal : 0,\n\t\tswapused : 0,\n\t\tswapfree : 0\n\t};\n\n\tif (_linux) {\n\t\texec(\"free -b\", function(error, stdout) {\n\t\t\tif (!error) {\n\t\t\t\tvar lines = stdout.toString().split('\\n');\n\n\t\t\t\tvar mem = lines[1].replace(/ +/g, \" \").split(' ');\n\t\t\t\tresult.total = parseInt(mem[1]);\n\t\t\t\tresult.free = parseInt(mem[3]);\n\t\t\t\tresult.buffcache = parseInt(mem[5]) + parseInt(mem[6]);\n\t\t\t\tresult.active = result.total - result.free - result.buffcache;\n\n\t\t\t\tmem = lines[3].replace(/ +/g, \" \").split(' ');\n\t\t\t\tresult.swaptotal = parseInt(mem[1]);\n\t\t\t\tresult.swapfree = parseInt(mem[3]);\n\t\t\t\tresult.swapused = parseInt(mem[2]);\n\n\t\t\t}\n\t\t\tcallback(result);\n\t\t});\n\t}\n\tif (_darwin) {\n\t\texec(\"vm_stat | grep 'Pages active'\", function(error, stdout) {\n\t\t\tif (!error) {\n\t\t\t\tvar lines = stdout.toString().split('\\n');\n\n\t\t\t\tresult.active = parseInt(lines[0].split(':')[1]) * 4096;\n\t\t\t\tresult.buffcache = result.used - result.active;\n\t\t\t}\n\t\t\texec(\"sysctl -n vm.swapusage\", function(error, stdout) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tvar lines = stdout.toString().split('\\n');\n\t\t\t\t\tif (lines.length > 0) {\n\t\t\t\t\t\tvar line = lines[0].replace(/,/g, \".\").replace(/M/g, \"\");\n\t\t\t\t\t\tline = line.trim().split(' ');\n\t\t\t\t\t\tfor (var i = 0; i < line.length; i++) {\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('total') != -1) result.swaptotal = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('used') != -1) result.swapused = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('free') != -1) result.swapfree = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcallback(result);\n\t\t\t});\n\t\t});\n\t}\n}",
"function totalToMemory(){\n addHistoryItem(\"total to memory\",total);\n memory = total;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates, or attempts to evaluate, a ForInStatement | function evaluateForInStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {
// Compute the 'of' part
const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);
// Ensure that the initializer is a proper VariableDeclarationList
if (!typescript.isVariableDeclarationList(node.initializer)) {
throw new UnexpectedNodeError({ node: node.initializer, typescript });
}
// Only 1 declaration is allowed in a ForOfStatement
else if (node.initializer.declarations.length > 1) {
throw new UnexpectedNodeError({ node: node.initializer.declarations[1], typescript });
}
for (const literal in expressionResult) {
// Prepare a lexical environment for the current iteration
const localEnvironment = cloneLexicalEnvironment(environment);
// Define a new binding for a break symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });
// Define a new binding for a continue symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });
// Evaluate the VariableDeclaration and manually pass in the current literal as the initializer for the variable assignment
evaluate.nodeWithArgument(node.initializer.declarations[0], localEnvironment, literal, statementTraversalStack);
// Evaluate the Statement
evaluate.statement(node.statement, localEnvironment);
// Check if a 'break' statement has been encountered and break if so
if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) {
logger.logBreak(node, typescript);
break;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) {
logger.logContinue(node, typescript);
// noinspection UnnecessaryContinueJS
continue;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) {
logger.logReturn(node, typescript);
return;
}
}
} | [
"function ForInStatement() {\n}",
"function evaluateForOfStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {\n // Compute the 'of' part\n const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);\n // Ensure that the initializer is a proper VariableDeclarationList\n if (!typescript.isVariableDeclarationList(node.initializer)) {\n throw new UnexpectedNodeError({ node: node.initializer, typescript });\n }\n // Only 1 declaration is allowed in a ForOfStatement\n else if (node.initializer.declarations.length > 1) {\n throw new UnexpectedNodeError({ node: node.initializer.declarations[1], typescript });\n }\n // As long as we only offer a synchronous API, there's no way to evaluate an async iterator in a synchronous fashion\n if (node.awaitModifier != null) {\n throw new AsyncIteratorNotSupportedError({ typescript });\n }\n else {\n for (const literal of expressionResult) {\n // Prepare a lexical environment for the current iteration\n const localEnvironment = cloneLexicalEnvironment(environment);\n // Define a new binding for a break symbol within the environment\n setInLexicalEnvironment({ env: localEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });\n // Define a new binding for a continue symbol within the environment\n setInLexicalEnvironment({ env: localEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });\n // Evaluate the VariableDeclaration and manually pass in the current literal as the initializer for the variable assignment\n evaluate.nodeWithArgument(node.initializer.declarations[0], localEnvironment, literal, statementTraversalStack);\n // Evaluate the Statement\n evaluate.statement(node.statement, localEnvironment);\n // Check if a 'break' statement has been encountered and break if so\n if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) {\n logger.logBreak(node, typescript);\n break;\n }\n else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) {\n logger.logContinue(node, typescript);\n // noinspection UnnecessaryContinueJS\n continue;\n }\n else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) {\n logger.logReturn(node, typescript);\n return;\n }\n }\n }\n}",
"function evaluateForStatement({ node, environment, evaluate, reporting, statementTraversalStack, typescript }) {\n // Prepare a lexical environment for the ForStatement\n const forEnvironment = cloneLexicalEnvironment(environment);\n // Evaluate the initializer if it is given\n if (node.initializer !== undefined) {\n if (typescript.isVariableDeclarationList(node.initializer)) {\n for (const declaration of node.initializer.declarations) {\n evaluate.declaration(declaration, forEnvironment, statementTraversalStack);\n }\n }\n else {\n evaluate.expression(node.initializer, forEnvironment, statementTraversalStack);\n }\n }\n while (true) {\n // Prepare a lexical environment for the current iteration\n const iterationEnvironment = cloneLexicalEnvironment(forEnvironment);\n // Define a new binding for a break symbol within the environment\n setInLexicalEnvironment({ env: iterationEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });\n // Define a new binding for a continue symbol within the environment\n setInLexicalEnvironment({ env: iterationEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });\n // Evaluate the condition. It may be truthy always\n const conditionResult = node.condition == null ? true : evaluate.expression(node.condition, forEnvironment, statementTraversalStack);\n // If the condition doesn't hold, return immediately\n if (!conditionResult)\n return;\n // Execute the Statement\n evaluate.statement(node.statement, iterationEnvironment);\n // Check if a 'break' statement has been encountered and break if so\n if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, BREAK_SYMBOL)) {\n break;\n }\n else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, RETURN_SYMBOL)) {\n return;\n }\n // Run the incrementor\n if (node.incrementor != null) {\n evaluate.expression(node.incrementor, forEnvironment, statementTraversalStack);\n }\n // Always run the incrementor before continuing\n else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, CONTINUE_SYMBOL)) {\n // noinspection UnnecessaryContinueJS\n continue;\n }\n }\n}",
"function visitForInStatement(node){var savedEnclosingBlockScopedContainer=enclosingBlockScopedContainer;enclosingBlockScopedContainer=node;node=ts.updateForIn(node,visitForInitializer(node.initializer),ts.visitNode(node.expression,destructuringAndImportCallVisitor,ts.isExpression),ts.visitNode(node.statement,nestedElementVisitor,ts.isStatement,ts.liftToBlock));enclosingBlockScopedContainer=savedEnclosingBlockScopedContainer;return node;}",
"function forstatementnode(state, node, ast){\n\t switch(ast[0]){\n\t case 'FORNODE':\n\t\t\t if(eval(state, node, ast[2])==true){\n\t\t\t temp = funceval(state, node, ast[4]);\n\t\t\t if(temp == \"EXIT\"){\n\t\t\t\t return;\n\t\t\t\t} else if(temp != undefined){\n\t\t\t\t return temp;\n\t\t\t } else {\n\t\t\t\t valasgn(state, node, ast[3]);\n\t\t\t\t forstatementnode(state, node, ast);\n\t\t\t }\n\t\t\t }\n\t\t\t break;\n\t }\n\t}",
"visitForInStatement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/false, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function iterizeForOf(node,path) {\n node.type = 'ForStatement';\n if (node.body.type!=='BlockStatement') {\n node.body = {type:'BlockStatement',body:[node.body]} ;\n }\n \n var index,iterator,initIterator = {\n \"type\": \"ArrayExpression\",\n \"elements\":[{\n \"type\": \"CallExpression\",\n \"callee\": {\n \"type\": \"MemberExpression\",\n \"object\": node.right,\n \"property\": {\n \"type\": \"MemberExpression\",\n \"object\": ident(\"Symbol\"),\n \"property\": ident(\"iterator\"),\n \"computed\": false\n },\n \"computed\": true\n },\n \"arguments\": []\n }]} ;\n \n if (node.left.type==='VariableDeclaration') {\n index = node.left.declarations[0].id ;\n iterator = ident(\"$iterator_\"+index.name) ;\n node.left.declarations.push({\n type:\"VariableDeclarator\",\n id:iterator,\n init:initIterator\n }) ;\n node.init = node.left ;\n } else {\n index = node.left ;\n iterator = ident(\"$iterator_\"+index.name) ;\n var declaration = {\n type:'VariableDeclaration',\n kind:'var',\n declarations:[{\n type:\"VariableDeclarator\",\n id:iterator,\n init:initIterator\n }]\n } ;\n path[0].parent.body.splice(path[0].index,0,declaration) ;\n node.init = null;\n }\n \n node.test = {\n \"type\": \"LogicalExpression\",\n \"left\": {\n \"type\": \"UnaryExpression\",\n \"operator\": \"!\",\n \"prefix\": true,\n \"argument\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"AssignmentExpression\",\n \"operator\": \"=\",\n \"left\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(1),\n \"computed\": true\n },\n \"right\": {\n \"type\": \"CallExpression\",\n \"callee\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(0),\n \"computed\": true\n },\n \"property\": ident('next'),\n \"computed\": false\n },\n \"arguments\": []\n }\n },\n \"property\": ident('done'),\n \"computed\": false\n }\n },\n \"operator\": \"&&\",\n \"right\": {\n type:'LogicalExpression',\n \"operator\": \"||\",\n left:{\n \"type\": \"AssignmentExpression\",\n \"operator\": \"=\",\n \"left\": index,\n \"right\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(1),\n \"computed\": true\n },\n \"property\": ident('value'),\n \"computed\": false\n }\n },\n right:literal(true)\n }\n } ;\n \n delete node.left ;\n delete node.right ;\n }",
"function _ForInStatementEmitter() {\n}",
"static isForInStatement(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.ForInStatement;\r\n }",
"function noassignmentsallowedinforinhead() {\n try {\n eval('for (var i = 0 in {}) {}');\n }\n catch(e) {\n return true;\n }\n}",
"function ForStatement() {\n}",
"function visitForOfStatement(node,outermostLabeledStatement){var ancestorFacts=enterSubtree(0/* IterationStatementExcludes */,2/* IterationStatementIncludes */);if(node.initializer.transformFlags&16384/* ContainsObjectRestOrSpread */){node=transformForOfStatementWithObjectRest(node);}var result=node.awaitModifier?transformForAwaitOfStatement(node,outermostLabeledStatement,ancestorFacts):ts.restoreEnclosingLabel(ts.visitEachChild(node,visitor,context),outermostLabeledStatement);exitSubtree(ancestorFacts);return result;}",
"function ForStatement(init, test, update, body) {\n this.type = \"ForStatement\";\n this.init = init;\n this.test = test;\n this.update = update\n this.body = body;\n \n if (test.typeof !== 'bool' || test.isArray)\n error('boolean expression expected');\n}",
"function parseForStatement(node) {\n\t next();\n\t labels.push(loopLabel);\n\t expect(_parenL);\n\t if (tokType === _semi) return parseFor(node, null);\n\t if (tokType === _var || tokType === _let) {\n\t var init = startNode(), varKind = tokType.keyword, isLet = tokType === _let;\n\t next();\n\t parseVar(init, true, varKind);\n\t finishNode(init, \"VariableDeclaration\");\n\t if ((tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === \"of\")) && init.declarations.length === 1 &&\n\t !(isLet && init.declarations[0].init))\n\t return parseForIn(node, init);\n\t return parseFor(node, init);\n\t }\n\t var init = parseExpression(false, true);\n\t if (tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === \"of\")) {\n\t checkLVal(init);\n\t return parseForIn(node, init);\n\t }\n\t return parseFor(node, init);\n\t }",
"function ForIn_1( object) {\n with ( object ) {\n for ( property in object ) {\n new TestCase(\n\tSECTION,\n\t\"with loop in a for...in loop. (\"+object+\")[\"+property +\"] == \"+\n\t\"eval ( \" + property +\" )\",\n\ttrue,\n\tobject[property] == eval(property) );\n }\n }\n}",
"function testForInOfLoop(node) {\n if (node.left && node.left.kind === 'let') {\n context.report(node.left, msg);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
yesterday(thisDate) / /All my troubles seemed so far away. | function yesterday(thisDate) {
// adjustForLeapYears(thisDate);
if (thisDate[2]!=1) {
return [thisDate[0],thisDate[1],thisDate[2]-1];
} else if (thisDate[1]!=0) {
return [thisDate[0],thisDate[1]-1,monthLength[thisDate[1]-1]];
} else {
var tempYear = thisDate[0]-1;
adjustForLeapYears('yesterday()',tempYear);
return [tempYear,11,31];
}
} | [
"function getYesterday(){\n\treturn getDate(-1);\n}",
"getYesterday() {\n let yesterday = new Date();\n yesterday.setDate(yesterday.getDate() - 1);\n return this.format(yesterday);\n }",
"function dateForYesterday() {\n var date = new Date().toMidnight();\n date.setDate(date.getDate() - 1);\n return date;\n}",
"function getYesterday() {\n \n var now = new Date()\n var yesterday = new Date(now.getTime() - (24 * 3600 * 1000))\n yesterday.setHours(12)\n return yesterday\n \n} // DateTime_.getYesterday()",
"function getMixpanelDateYesterday(){\n var today = new Date();\n var yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n \n //Logger.log(yesterday);\n var dd = yesterday.getDate();\n //Logger.log(yesterday);\n var mm = yesterday.getMonth() + 1;\n var yyyy = yesterday.getFullYear();\n \n if (dd < 10) {\n dd = '0' + dd;\n }\n if (mm < 10) {\n mm = '0' + mm;\n }\n \n yesterday = yyyy + '-' + mm + '-' + dd;\n //Logger.log(yesterday);\n return yesterday;\n}",
"checkIfYesterday(timestamp) {\n let other_date = new Date(timestamp);\n if ((this.today.getDate() - 1) == other_date.getDate()) {\n return true;\n } else {\n return false;\n }\n }",
"function yesterdayDateTime()\n\n {\n\n var date=new Date();//object of Date\n\n date.setHours(date.getHours()-24)//setHours() -24\n\n //display yesterday date and time\n\n alert(\"Yesterday date and time is \"+date.toLocaleString());\n\n }",
"setDate() {\n this.yesterday = new Date(this.today.setDate(this.today.getDate() - 1));\n if (this.past) {\n this.pastString = \"Past \";\n }\n }",
"function is_yesterday(lw_date) {\n is_yesterday_bool = false;\n if (lw_date === undefined || lw_date === \"\" || typeof lw_date != \"object\") {\n console.log(\"last_workout_date not defined\")\n return is_yesterday_bool\n }\n\n let today = new Date();\n let yesterday_epoch_seconds = Math.floor(today.getTime() / 1000.0) - 86400 //getTime gets epoch time in millisonds; 86400 is seconds in a day\n let yesterday = new Date(yesterday_epoch_seconds * 1000)\n\n if (parseInt(lw_date.month) === yesterday.getMonth() &&\n parseInt(lw_date.day) === yesterday.getDate() &&\n parseInt(lw_date.year) === yesterday.getFullYear()) {\n is_yesterday_bool = true\n console.log(\"good. you worked out yesterday\")\n }\n\n return is_yesterday_bool;\n\n}",
"function getYesterday() {\n const start = moment().subtract(1, \"day\").startOf(\"day\").unix();\n const end = start + ONE_DAY_SEC;\n return { start, end };\n}",
"function isYesterday(date)\r\n\t{\r\n\t\tvar yesterday = new com.actional.util.TDate();\r\n\t\tyesterday.setDate(yesterday.getDate() - 1);\r\n\r\n\t\treturn (yesterday.getFullYear() == date.getFullYear()\r\n\t\t\t\t&& yesterday.getMonth() == date.getMonth()\r\n\t\t\t\t&& yesterday.getDate() == date.getDate());\r\n\t}",
"function checkBeforeToday(date) {\n var today = new Date();\n var yesterday = new Date();\n yesterday.setDate(today.getDate() - 1);\n yesterday.setHours(23, 59, 59, 999);\n return date < yesterday;\n}",
"function isYesterday(date) {\n var today = new Date();\n var yesterday = new Date();\n yesterday.setDate(today.getDate() - 1);\n return date.getFullYear() == yesterday.getFullYear() &&\n date.getMonth() == yesterday.getMonth() &&\n date.getDate() == yesterday.getDate();\n}",
"function setHeaderPrevDate(date){\n var currentDate = moment(date);\n currentDate.subtract(1, \"day\");\n var year = currentDate.get(\"year\");\n var month = parseInt(currentDate.get(\"month\")) +1;\n var day = currentDate.get(\"date\");\n\n // Check to see if the month and day have a length of 1\n if(month.toString().length ==1){\n month = \"0\" + month;\n }\n\n if(day.toString().length == 1){\n day = \"0\" + day;\n }\n\n\n var yesterdayDate = year + \"\" + month + \"\" + day;\n var yesterdayButton = document.getElementById(\"prevDayButton\");\n\n // we can get the different formats from moment js - format\n var dateDay = currentDate.format('dddd');\n var dateMonth = currentDate.format('MMMM');\n var dateNumber = currentDate.format('Do');\n\n yesterdayButton.innerHTML = dateDay + \" \" + dateMonth + \" \" + dateNumber;\n yesterdayButton.href = \"/schedule/\" + yesterdayDate;\n\n}",
"function getYesterdaysDate() {\n const d = new Date();\n d.setDate(d.getDate() - 1);\n\n let month = (d.getMonth() + 1);\n let day = d.getDate();\n const year = d.getFullYear();\n\n if (month.length < 2) month = `0${month}`;\n if (day.length < 2) day = `0${day}`;\n\n return [year, month, day].join('-');\n}",
"function isValidDate(current) {\n let yesterday = DateTime.moment().subtract(1, 'day');\n return current.isBefore(yesterday);\n}",
"function handlePrevDay() {\n setDate(subDays(date, 1));\n }",
"function getMixpanelDateLastWeek(){\n var today = new Date();\n var yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 7);\n \n //Logger.log(yesterday);\n var dd = yesterday.getDate();\n //Logger.log(yesterday);\n var mm = yesterday.getMonth() + 1;\n var yyyy = yesterday.getFullYear();\n \n if (dd < 10) {\n dd = '0' + dd;\n }\n if (mm < 10) {\n mm = '0' + mm;\n }\n \n yesterday = yyyy + '-' + mm + '-' + dd;\n //Logger.log(yesterday);\n return yesterday;\n}",
"dateHandler(date) {\n const product_date = new Date(date);\n const current_date = new Date();\n const difference_time = Math.abs(current_date - product_date);\n const difference_days = Math.ceil(difference_time / (1000 * 60 * 60 * 24)); \n if (difference_days < 7){\n return difference_days +\" days ago\"\n }\n return date.substr(0, 15);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 8